UNPKG

@glue42/desktop

Version:

Glue42 desktop library

1,324 lines (1,292 loc) 861 kB
(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.desktop = factory()); })(this, (function () { 'use strict'; /****************************************************************************** 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 extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } 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 __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } 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) { var serializedMetrics = {}; var type = getMetricTypeByValue(metric); if (type === "object") { var values = Object.keys(metric.value).reduce(function (memo, key) { var innerType = getTypeByValue(metric.value[key]); if (innerType === "object") { var composite = defineNestedComposite(metric.value[key]); memo[key] = { type: "object", description: "", context: {}, composite: 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(function (memo, key) { var type = getTypeByValue(values[key]); if (type === "object") { memo[key] = { type: "object", description: "", context: {}, composite: defineNestedComposite(values[key]), }; } else { memo[key] = { type: 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) { var 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(function (memo, key) { var 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(function (flat, toFlatten) { return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten); }, []); } function getHighestState(arr) { return arr.sort(function (a, b) { if (!a.state) { return 1; } if (!b.state) { return -1; } return b.state - a.state; })[0]; } function aggregateDescription(arr) { var msg = ""; arr.forEach(function (m, idx, a) { var 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) { var aggregatedState = system.root.getAggregateState(); var merged = flatten(aggregatedState); var highestState = getHighestState(merged); var aggregateDesc = aggregateDescription(merged); return { description: aggregateDesc, value: highestState.state, }; } function gw3 (connection, config) { var _this = this; if (!connection || typeof connection !== "object") { throw new Error("Connection is required parameter"); } var joinPromise; var session; var init = function (repo) { var resolveReadyPromise; joinPromise = new Promise(function (resolve) { resolveReadyPromise = resolve; }); session = connection.domain("metrics"); session.onJoined(function (reconnect) { if (!reconnect && resolveReadyPromise) { resolveReadyPromise(); resolveReadyPromise = undefined; } var rootStateMetric = { name: "/State", type: "object", composite: { Description: { type: "string", description: "", }, Value: { type: "number", description: "", }, }, description: "System state", context: {}, }; var defineRootMetricsMsg = { type: "define", metrics: [rootStateMetric], }; session.send(defineRootMetricsMsg); if (reconnect) { replayRepo(repo); } }); session.join({ system: config.system, service: config.service, instance: config.instance }); }; var replayRepo = function (repo) { replaySystem(repo.root); }; var replaySystem = function (system) { createSystem(system); system.metrics.forEach(function (m) { createMetric(m); }); system.subSystems.forEach(function (ss) { replaySystem(ss); }); }; var createSystem = function (system) { return __awaiter(_this, void 0, void 0, function () { var metric, createMetricsMsg; return __generator(this, function (_a) { switch (_a.label) { case 0: if (system.parent === undefined) { return [2]; } return [4, joinPromise]; case 1: _a.sent(); metric = { name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), type: "object", composite: { Description: { type: "string", description: "", }, Value: { type: "number", description: "", }, }, description: "System state", context: {}, }; createMetricsMsg = { type: "define", metrics: [metric], }; session.send(createMetricsMsg); return [2]; } }); }); }; var updateSystem = function (system, state) { return __awaiter(_this, void 0, void 0, function () { var shadowedUpdateMetric, stateObj, rootMetric; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4, joinPromise]; case 1: _a.sent(); shadowedUpdateMetric = { type: "publish", values: [{ name: normalizeMetricName(system.path.join("/") + "/" + system.name + "/State"), value: { Description: state.description, Value: state.state, }, timestamp: Date.now(), }], }; session.send(shadowedUpdateMetric); stateObj = composeMsgForRootStateMetric(system); rootMetric = { type: "publish", peer_id: connection.peerId, values: [{ name: "/State", value: { Description: stateObj.description, Value: stateObj.value, }, timestamp: Date.now(), }], }; session.send(rootMetric); return [2]; } }); }); }; var createMetric = function (metric) { return __awaiter(_this, void 0, void 0, function () { var metricClone, m, createMetricsMsg; return __generator(this, function (_a) { switch (_a.label) { case 0: metricClone = cloneMetric(metric); return [4, joinPromise]; case 1: _a.sent(); m = serializeMetric(metricClone); createMetricsMsg = { type: "define", metrics: [m], }; session.send(createMetricsMsg); if (typeof metricClone.value !== "undefined") { updateMetricCore(metricClone); } return [2]; } }); }); }; var updateMetric = function (metric) { return __awaiter(_this, void 0, void 0, function () { var metricClone; return __generator(this, function (_a) { switch (_a.label) { case 0: metricClone = cloneMetric(metric); return [4, joinPromise]; case 1: _a.sent(); updateMetricCore(metricClone); return [2]; } }); }); }; var updateMetricCore = function (metric) { if (canUpdate()) { var value = getMetricValueByType(metric); var publishMetricsMsg = { type: "publish", values: [{ name: normalizeMetricName(metric.path.join("/") + "/" + metric.name), value: value, timestamp: Date.now(), }], }; return session.sendFireAndForget(publishMetricsMsg); } return Promise.resolve(); }; var cloneMetric = function (metric) { var metricClone = __assign({}, metric); if (typeof metric.value === "object" && metric.value !== null) { metricClone.value = __assign({}, metric.value); } return metricClone; }; var canUpdate = function () { var _a; try { var func = (_a = config.canUpdateMetric) !== null && _a !== void 0 ? _a : (function () { return true; }); return func(); } catch (_b) { return true; } }; return { init: init, createSystem: createSystem, updateSystem: updateSystem, createMetric: createMetric, updateMetric: updateMetric, }; } var Helpers = { validate: function (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"); } }, }; var BaseMetric = (function () { function BaseMetric(definition, system, transport, value, type) { this.definition = definition; this.system = system; this.transport = transport; this.value = value; this.type = type; this.path = []; 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); } Object.defineProperty(BaseMetric.prototype, "repo", { get: function () { var _a; return (_a = this.system) === null || _a === void 0 ? void 0 : _a.repo; }, enumerable: false, configurable: true }); Object.defineProperty(BaseMetric.prototype, "id", { get: function () { return "".concat(this.system.path, "/").concat(name); }, enumerable: false, configurable: true }); BaseMetric.prototype.update = function (newValue) { this.value = newValue; return this.transport.updateMetric(this); }; return BaseMetric; }()); var NumberMetric = (function (_super) { __extends(NumberMetric, _super); function NumberMetric(definition, system, transport, value) { return _super.call(this, definition, system, transport, value, MetricTypes.NUMBER) || this; } NumberMetric.prototype.incrementBy = function (num) { this.update(this.value + num); }; NumberMetric.prototype.increment = function () { this.incrementBy(1); }; NumberMetric.prototype.decrement = function () { this.incrementBy(-1); }; NumberMetric.prototype.decrementBy = function (num) { this.incrementBy(num * -1); }; return NumberMetric; }(BaseMetric)); var ObjectMetric = (function (_super) { __extends(ObjectMetric, _super); function ObjectMetric(definition, system, transport, value) { return _super.call(this, definition, system, transport, value, MetricTypes.OBJECT) || this; } ObjectMetric.prototype.update = function (newValue) { this.mergeValues(newValue); return this.transport.updateMetric(this); }; ObjectMetric.prototype.mergeValues = function (values) { var _this = this; return Object.keys(this.value).forEach(function (k) { if (typeof values[k] !== "undefined") { _this.value[k] = values[k]; } }); }; return ObjectMetric; }(BaseMetric)); var StringMetric = (function (_super) { __extends(StringMetric, _super); function StringMetric(definition, system, transport, value) { return _super.call(this, definition, system, transport, value, MetricTypes.STRING) || this; } return StringMetric; }(BaseMetric)); var TimestampMetric = (function (_super) { __extends(TimestampMetric, _super); function TimestampMetric(definition, system, transport, value) { return _super.call(this, definition, system, transport, value, MetricTypes.TIMESTAMP) || this; } TimestampMetric.prototype.now = function () { this.update(new Date()); }; return TimestampMetric; }(BaseMetric)); function system(name, repo, protocol, parent, description) { if (!repo) { throw new Error("Repository is required"); } if (!protocol) { throw new Error("Transport is required"); } var _transport = protocol; var _name = name; var _description = description || ""; var _repo = repo; var _parent = parent; var _path = _buildPath(parent); var _state = {}; var id = _arrayToString(_path, "/") + name; var root = repo.root; var _subSystems = []; var _metrics = []; function subSystem(nameSystem, descriptionSystem) { if (!nameSystem || nameSystem.length === 0) { throw new Error("name is required"); } var match = _subSystems.filter(function (s) { return s.name === nameSystem; }); if (match.length > 0) { return match[0]; } var _system = system(nameSystem, _repo, _transport, me, descriptionSystem); _subSystems.push(_system); return _system; } function setState(state, stateDescription) { _state = { state: state, description: stateDescription }; _transport.updateSystem(me, _state); } function stringMetric(definition, value) { return _getOrCreateMetric(definition, MetricTypes.STRING, value, function (metricDef) { return new StringMetric(metricDef, me, _transport, value); }); } function numberMetric(definition, value) { return _getOrCreateMetric(definition, MetricTypes.NUMBER, value, function (metricDef) { return new NumberMetric(metricDef, me, _transport, value); }); } function objectMetric(definition, value) { return _getOrCreateMetric(definition, MetricTypes.OBJECT, value, function (metricDef) { return new ObjectMetric(metricDef, me, _transport, value); }); } function timestampMetric(definition, value) { return _getOrCreateMetric(definition, MetricTypes.TIMESTAMP, value, function (metricDef) { return new TimestampMetric(metricDef, me, _transport, value); }); } function _getOrCreateMetric(metricObject, expectedType, value, createMetric) { var metricDef = { name: "" }; if (typeof metricObject === "string") { metricDef = { name: metricObject }; } else { metricDef = metricObject; } var matching = _metrics.filter(function (shadowedMetric) { return shadowedMetric.name === metricDef.name; }); if (matching.length > 0) { var existing = matching[0]; if (existing.type !== expectedType) { throw new Error("A metric named ".concat(metricDef.name, " is already defined with different type.")); } if (typeof value !== "undefined") { existing .update(value) .catch(function () { }); } return existing; } var metric = createMetric(metricDef); _metrics.push(metric); return metric; } function _buildPath(shadowedSystem) { if (!shadowedSystem || !shadowedSystem.parent) { return []; } var path = _buildPath(shadowedSystem.parent); path.push(shadowedSystem.name); return path; } function _arrayToString(path, separator) { return ((path && path.length > 0) ? path.join(separator) : ""); } function getAggregateState() { var aggState = []; if (Object.keys(_state).length > 0) { aggState.push({ name: _name, path: _path, state: _state.state, description: _state.description, }); } _subSystems.forEach(function (shadowedSubSystem) { var result = shadowedSubSystem.getAggregateState(); if (result.length > 0) { aggState.push.apply(aggState, result); } }); return aggState; } var me = { get name() { return _name; }, get description() { return _description; }, get repo() { return _repo; }, get parent() { return _parent; }, path: _path, id: id, root: root, get subSystems() { return _subSystems; }, get metrics() { return _metrics; }, subSystem: subSystem, getState: function () { return _state; }, setState: setState, stringMetric: stringMetric, timestampMetric: timestampMetric, objectMetric: objectMetric, numberMetric: numberMetric, getAggregateState: getAggregateState, }; _transport.createSystem(me); return me; } var Repository = (function () { function Repository(options, protocol) { protocol.init(this); this.root = system("", this, protocol); this.addSystemMetrics(this.root, options.clickStream || options.clickStream === undefined); } Repository.prototype.addSystemMetrics = function (rootSystem, useClickStream) { if (typeof navigator !== "undefined") { rootSystem.stringMetric("UserAgent", navigator.userAgent); } if (useClickStream && typeof document !== "undefined") { var clickStream_1 = rootSystem.subSystem("ClickStream"); var documentClickHandler = function (e) { var _a; if (!e.target) { return; } var target = e.target; var className = target ? (_a = target.getAttribute("class")) !== null && _a !== void 0 ? _a : "" : ""; clickStream_1.objectMetric("LastBrowserEvent", { type: "click", timestamp: new Date(), target: { className: className, id: target.id, type: "<" + target.tagName.toLowerCase() + ">", href: target.href || "", }, }); }; clickStream_1.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()); var urlMetric = rootSystem.stringMetric("StartURL", ""); var appNameMetric = rootSystem.stringMetric("AppName", ""); if (typeof window !== "undefined") { if (typeof window.location !== "undefined") { var startUrl = window.location.href; urlMetric.update(startUrl); } if (typeof window.glue42gd !== "undefined") { appNameMetric.update(window.glue42gd.appName); } } }; return Repository; }()); var NullProtocol = (function () { function NullProtocol() { } NullProtocol.prototype.init = function (repo) { }; NullProtocol.prototype.createSystem = function (system) { return Promise.resolve(); }; NullProtocol.prototype.updateSystem = function (metric, state) { return Promise.resolve(); }; NullProtocol.prototype.createMetric = function (metric) { return Promise.resolve(); }; NullProtocol.prototype.updateMetric = function (metric) { return Promise.resolve(); }; return NullProtocol; }()); var PerfTracker = (function () { function PerfTracker(api, initialPublishTimeout, publishInterval) { this.api = api; this.lastCount = 0; this.initialPublishTimeout = 10 * 1000; this.publishInterval = 60 * 1000; this.initialPublishTimeout = initialPublishTimeout !== null && initialPublishTimeout !== void 0 ? initialPublishTimeout : this.initialPublishTimeout; this.publishInterval = publishInterval !== null && publishInterval !== void 0 ? publishInterval : this.publishInterval; this.scheduleCollection(); this.system = this.api.subSystem("performance", "Performance data published by the web application"); } PerfTracker.prototype.scheduleCollection = function () { var _this = this; setTimeout(function () { _this.collect(); setInterval(function () { _this.collect(); }, _this.publishInterval); }, this.initialPublishTimeout); }; PerfTracker.prototype.collect = function () { try { this.collectMemory(); this.collectEntries(); } catch (_a) { } }; PerfTracker.prototype.collectMemory = function () { var memory = window.performance.memory; this.system.stringMetric("memory", JSON.stringify({ totalJSHeapSize: memory.totalJSHeapSize, usedJSHeapSize: memory.usedJSHeapSize })); }; PerfTracker.prototype.collectEntries = function () { var allEntries = window.performance.getEntries(); if (allEntries.length <= this.lastCount) { return; } this.lastCount = allEntries.length; var jsonfiedEntries = allEntries.map(function (i) { return i.toJSON(); }); this.system.stringMetric("entries", JSON.stringify(jsonfiedEntries)); }; return PerfTracker; }()); var metrics = (function (options) { var protocol; if (!options.connection || typeof options.connection !== "object") { protocol = new NullProtocol(); } else { protocol = gw3(options.connection, options); } var repo = new Repository(options, protocol); var rootSystem = repo.root; if (!options.disableAutoAppSystem) { rootSystem = rootSystem.subSystem("App"); } var api = addFAVSupport(rootSystem); initPerf(api, options.pagePerformanceMetrics); return api; }); function initPerf(api, config) { var _a, _b; if (typeof window === "undefined") { return; } var perfConfig = (_b = (_a = window === null || window === void 0 ? void 0 : window.glue42gd) === null || _a === void 0 ? void 0 : _a.metrics) === null || _b === void 0 ? void 0 : _b.pagePerformanceMetrics; if (perfConfig) { config = perfConfig; } if (config === null || config === void 0 ? void 0 : config.enabled) { new PerfTracker(api, config.initialPublishTimeout, config.publishInterval); } } function addFAVSupport(system) { var reportingSystem = system.subSystem("reporting"); var def = { name: "features" }; var featureMetric; var featureMetricFunc = function (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: name, action: action, payload: payload }); } else { featureMetric.update({ name: name, action: action, payload: 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$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$1 = createRegistry$1; var InProcTransport = (function () { function InProcTransport(settings, logger) { var _this = this; this.registry = lib$1$1(); this.gw = settings.facade; this.gw.connect(function (_client, message) { _this.messageHandler(message); }).then(function (client) { _this.client = client; }); } Object.defineProperty(InProcTransport.prototype, "isObjectBasedTransport", { get: function () { return true; }, enumerable: false, configurable: true }); InProcTransport.prototype.sendObject = function (msg) { if (this.client) { this.client.send(msg); return Promise.resolve(undefined); } else { return Promise.reject("not connected"); } }; InProcTransport.prototype.send = function (_msg) { return Promise.reject("not supported"); }; InProcTransport.prototype.onMessage = function (callback) { return this.registry.add("onMessage", callback); }; InProcTransport.prototype.onConnectedChanged = function (callback) { callback(true); return function () { }; }; InProcTransport.prototype.close = function () { return Promise.resolve(); }; InProcTransport.prototype.open = function () { return Promise.resolve(); }; InProcTransport.prototype.name = function () { return "in-memory"; }; InProcTransport.prototype.reconnect = function () { return Promise.resolve(); }; InProcTransport.prototype.messageHandler = function (msg) { this.registry.execute("onMessage", msg); }; return InProcTransport; }()); var SharedWorkerTransport = (function () { function SharedWorkerTransport(workerFile, logger) { var _this = this; this.logger = logger; this.registry = lib$1$1(); this.worker = new SharedWorker(workerFile); this.worker.port.onmessage = function (e) { _this.messageHandler(e.data); }; } Object.defineProperty(SharedWorkerTransport.prototype, "isObjectBasedTransport", { get: function () { return true; }, enumerable: false, configurable: true }); SharedWorkerTransport.prototype.sendObject = function (msg) { this.worker.port.postMessage(msg); return Promise.resolve(); }; SharedWorkerTransport.prototype.send = function (_msg) { return Promise.reject("not supported"); }; SharedWorkerTransport.prototype.onMessage = function (callback) { return this.registry.add("onMessage", callback); }; SharedWorkerTransport.prototype.onConnectedChanged = function (callback) { callback(true); return function () { }; }; SharedWorkerTransport.prototype.close = function () { return Promise.resolve(); }; SharedWorkerTransport.prototype.open = function () { return Promise.resolve(); }; SharedWorkerTransport.prototype.name = function () { return "shared-worker"; }; SharedWorkerTransport.prototype.reconnect = function () { return Promise.resolve(); }; SharedWorkerTransport.prototype.messageHandler = function (msg) { this.registry.execute("onMessage", msg); }; return SharedWorkerTransport; }()); var Utils$1 = (function () { function Utils() { } Utils.isNode = function () { 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; }; return Utils; }()); var PromiseWrapper = (function () { function PromiseWrapper() { var _this = this; this.rejected = false; this.resolved = false; this.promise = new Promise(function (resolve, reject) { _this.resolve = function (t) { _this.resolved = true; resolve(t); }; _this.reject = function (err) { _this.rejected = true; reject(err); }; }); } PromiseWrapper.delay = function (time) { return new Promise(function (resolve) { return setTimeout(resolve, time); }); }; Object.defineProperty(PromiseWrapper.prototype, "ended", { get: function () { return this.rejected || this.resolved; }, enumerable: false, configurable: true }); return PromiseWrapper; }()); var timers = {}; function getAllTimers() { return timers; } function timer (timerName) { var existing = timers[timerName]; if (existing) { return existing; } var marks = []; function now() { return new Date().getTime(); } var startTime = now(); mark("start", startTime); var endTime; var period; function stop() { endTime = now(); mark("end", endTime); period = endTime - startTime; return period; } function mark(name, time) { var currentTime = time !== null && time !== void 0 ? time : now(); var diff = 0; if (marks.length > 0) { diff = currentTime - marks[marks.length - 1].time; } marks.push({ name: name, time: currentTime, diff: diff }); } var timerObj = { get startTime() { return startTime; }, get endTime() { return endTime; }, get period() { return period; }, stop: stop, mark: mark, marks: marks }; timers[timerName] = timerObj; return timerObj; } var WebSocketConstructor = Utils$1.isNode() ? require("ws") : window.WebSocket; var WS = (function () { function WS(settings, logger) { this.startupTimer = timer("connection"); this._running = true; this._registry = lib$1$1(); this.wsRequests = []; this.settings = settings; this.logger = logger; if (!this.settings.ws) { throw new Error("ws is missing"); } } WS.prototype.onMessage = function (callback) { return this._registry.add("onMessage", callback); }; WS.prototype.send = function (msg, options) { var _this = this; return new Promise(function (resolve, reject) { _this.waitForSocketConnection(function () { var _a; try { (_a = _this.ws) === null || _a === void 0 ? void 0 : _a.send(msg); resolve(); } catch (e) { reject(e); } }, reject); }); }; WS.prototype.open = function () { var _this = this; this.logger.info("opening ws..."); this._running = true; return new Promise(function (resolve, reject) { _this.waitForSocketConnection(resolve, reject); }); }; WS.prototype.close = function () { this._running = false; if (this.ws) { this.ws.close(); } return Promise.resolve(); }; WS.prototype.onConnectedChanged = function (callback) { return this._registry.add("onConnectedChanged", callback); }; WS.prototype.name = function () { return this.settings.ws; }; WS.prototype.reconnect = function () { var _a; (_a = this.ws) === null || _a === void 0 ? void 0 : _a.close(); var pw = new PromiseWrapper(); this.waitForSocketConnection(function () { pw.resolve(); }); return pw.promise; }; WS.prototype.waitForSocketConnection = function (callback, failed) { var _a; failed = failed !== null && failed !== void 0 ? failed : (function () { }); if (!this._running) { failed("wait for socket on ".concat(this.settings.ws, " failed - socket closed by user")); return; } if (((_a = this.ws) === null || _a === void 0 ? void 0 : _a.readyState) === 1) { callback(); return; } this.wsRequests.push({ callback: callback, failed: failed }); if (this.wsRequests.length > 1) { return; } this.openSocket(); }; WS.prototype.openSocket = function (retryInterval, retriesLeft) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_b) { switch (_b.label) { case 0: this.startupTimer.