(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@iotize/device-client.js'), require('@iotize/device-client.js/client/impl'), require('rxjs'), require('@iotize/testing-grammar.js'), require('rxjs/operators')) :
    typeof define === 'function' && define.amd ? define('@iotize/device-client.js/config/iotize-studio', ['@iotize/device-client.js', '@iotize/device-client.js/client/impl', 'rxjs', '@iotize/testing-grammar.js', 'rxjs/operators'], factory) :
    (global = global || self, (global.iotize = global.iotize || {}, global.iotize['device-client'] = global.iotize['device-client'] || {}, global.iotize['device-client'].js = global.iotize['device-client'].js || {}, global.iotize['device-client'].js.config = global.iotize['device-client'].js.config || {}, global.iotize['device-client'].js.config['iotize-studio'] = factory(global.iotize['device-client'].js, global.iotize['device-client'].js.client.impl, global.rxjs, global.testingGrammar, global.rxjs.operators)));
}(this, (function (deviceClient, impl, rxjs, testingGrammar, operators) { 'use strict';

    deviceClient = deviceClient && deviceClient.hasOwnProperty('default') ? deviceClient['default'] : deviceClient;
    impl = impl && impl.hasOwnProperty('default') ? impl['default'] : impl;
    rxjs = rxjs && rxjs.hasOwnProperty('default') ? rxjs['default'] : rxjs;
    testingGrammar = testingGrammar && testingGrammar.hasOwnProperty('default') ? testingGrammar['default'] : testingGrammar;
    operators = operators && operators.hasOwnProperty('default') ? operators['default'] : operators;

    var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

    function commonjsRequire () {
    	throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
    }

    function unwrapExports (x) {
    	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
    }

    function createCommonjsModule(fn, module) {
    	return module = { exports: {} }, fn(module, module.exports), module.exports;
    }

    function getCjsExportFromNamespace (n) {
    	return n && n['default'] || n;
    }

    var definitions = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ByteOrder32Bits;
    (function (ByteOrder32Bits) {
        ByteOrder32Bits[ByteOrder32Bits["B3_B2_B1_B0"] = 0] = "B3_B2_B1_B0";
        ByteOrder32Bits[ByteOrder32Bits["B1_B0_B3_B2"] = 1] = "B1_B0_B3_B2";
        ByteOrder32Bits[ByteOrder32Bits["B2_B3_B0_B1"] = 2] = "B2_B3_B0_B1";
        ByteOrder32Bits[ByteOrder32Bits["B0_B1_B2_B3"] = 3] = "B0_B1_B2_B3";
    })(ByteOrder32Bits = exports.ByteOrder32Bits || (exports.ByteOrder32Bits = {}));
    var ByteOrder16Bits;
    (function (ByteOrder16Bits) {
        ByteOrder16Bits[ByteOrder16Bits["B1_B0"] = 0] = "B1_B0";
        ByteOrder16Bits[ByteOrder16Bits["B0_B1"] = 1] = "B0_B1";
    })(ByteOrder16Bits = exports.ByteOrder16Bits || (exports.ByteOrder16Bits = {}));

    });

    var definitions$1 = unwrapExports(definitions);
    var definitions_1 = definitions.ByteOrder32Bits;
    var definitions_2 = definitions.ByteOrder16Bits;

    var util = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function toEnumFromValue(mapping, value) {
        var values = Object.keys(mapping).map(function (key) { return mapping[key]; });
        if (values.find(function (v) { return v.toString() === value; }) ===
            undefined) {
            throw new Error("Missing value \"" + value + "\" in enum. Available keys are " + values.join(', '));
        }
        if (value in mapping) {
            // For string to number convertion
            return mapping[mapping[value]];
        }
        return value;
    }
    exports.toEnumFromValue = toEnumFromValue;
    // export function toEnumFromKey<T>(mapping: any, key: string): T {
    //     if (!(key in mapping)) {
    //         throw new Error(`Missing key "${key}" in enum. Available keys are ${Object.keys(mapping).join(', ')}`);
    //     }
    //     return mapping[mapping[key]];
    // }

    });

    var util$1 = unwrapExports(util);
    var util_1 = util.toEnumFromValue;

    var variableDataTypes = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */
    var VariableDataTypes;
    (function (VariableDataTypes) {
        VariableDataTypes[VariableDataTypes["int"] = 0] = "int";
        VariableDataTypes[VariableDataTypes["unsigned_int"] = 1] = "unsigned_int";
        VariableDataTypes[VariableDataTypes["float"] = 2] = "float";
    })(VariableDataTypes = exports.VariableDataTypes || (exports.VariableDataTypes = {}));

    });

    var variableDataTypes$1 = unwrapExports(variableDataTypes);
    var variableDataTypes_1 = variableDataTypes.VariableDataTypes;

    var iotizeVariableModel = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */




    var IotizeVariableModel = /** @class */ (function () {
        function IotizeVariableModel(data, iotizeModule, bundle) {
            this.data = data;
            this.iotizeModule = iotizeModule;
            if (bundle) {
                this._bundle = bundle;
            }
        }
        IotizeVariableModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeVariableModel.prototype.module = function () {
            return this.iotizeModule;
        };
        /**
         * Size (int bits) of one element
         */
        IotizeVariableModel.prototype.valueSize = function () {
            return IotizeVariableModel.unitSizeToBitSize(parseInt(this.data.$.Unit));
        };
        IotizeVariableModel.prototype.valueQuantity = function () {
            return Number(this.data.$.Quantity);
        };
        IotizeVariableModel.prototype.name = function () {
            return this.data.$.GUI_Name;
        };
        IotizeVariableModel.prototype.id = function () {
            return this.data.$.Id;
        };
        IotizeVariableModel.prototype.alias = function () {
            return this.data.$.GUI_Alias;
        };
        IotizeVariableModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeVariableModel.prototype.unit = function () {
            return this.data.$.GUI_DispUnit;
        };
        IotizeVariableModel.prototype.bundle = function () {
            return this._bundle;
        };
        IotizeVariableModel.prototype.type = function () {
            if (this.data.$.GUI_float && this.data.$.GUI_float == 1) {
                return variableDataTypes.VariableDataTypes.float;
            }
            else if (this.data.$.GUI_unsigned && this.data.$.GUI_unsigned == 1) {
                return variableDataTypes.VariableDataTypes.unsigned_int;
            }
            else {
                return variableDataTypes.VariableDataTypes.int;
            }
        };
        IotizeVariableModel.prototype.dataType = function () {
            if (this.data.$.GUI_float && this.data.$.GUI_float == 1) {
                return deviceClient.VariableType.FLOAT32;
            }
            else if (this.data.$.GUI_unsigned && this.data.$.GUI_unsigned == 1) {
                switch (this.data.$.Unit) {
                    case 0:
                        return deviceClient.VariableType.BOOLEAN;
                    case 1:
                        return deviceClient.VariableType.UINT8;
                    case 2:
                        return deviceClient.VariableType.UINT16;
                    case 3:
                        return deviceClient.VariableType.UINT32;
                    default:
                        throw new Error("Invalid data size for variable " + this.name());
                }
            }
            else {
                switch (this.data.$.Unit) {
                    case 0:
                        return deviceClient.VariableType.BOOLEAN;
                    case 1:
                        return deviceClient.VariableType.INT8;
                    case 2:
                        return deviceClient.VariableType.INT16;
                    case 3:
                        return deviceClient.VariableType.INT32;
                    default:
                        throw new Error("Invalid data size for variable " + this.name());
                }
            }
        };
        /**
         * Return attribute by name
         */
        IotizeVariableModel.prototype.attribute = function (name) {
            return this.data.$[name];
        };
        IotizeVariableModel.prototype.byteOrder = function () {
            var guiCoding = this.attribute('GUI_coding');
            if (guiCoding) {
                if (this.valueSize() === 16) {
                    return util.toEnumFromValue(definitions.ByteOrder16Bits, guiCoding);
                }
                else if (this.valueSize() === 32) {
                    return util.toEnumFromValue(definitions.ByteOrder32Bits, guiCoding);
                }
            }
            return undefined;
        };
        /**
         * Convert unit size found in configuration file into a number of bits
         */
        IotizeVariableModel.unitSizeToBitSize = function (unitSize) {
            switch (unitSize) {
                case 0:
                    return 1;
                case 1:
                    return 8;
                case 2:
                    return 16;
                case 3:
                    return 32;
                default:
                    throw new Error("Invalid unit size: " + unitSize);
            }
        };
        return IotizeVariableModel;
    }());
    exports.IotizeVariableModel = IotizeVariableModel;

    });

    var iotizeVariableModel$1 = unwrapExports(iotizeVariableModel);
    var iotizeVariableModel_1 = iotizeVariableModel.IotizeVariableModel;

    var iotizeProfileModel = createCommonjsModule(function (module, exports) {
    "use strict";
    /**
     * @module model
     */
    Object.defineProperty(exports, "__esModule", { value: true });
    var IotizeProfileModel = /** @class */ (function () {
        function IotizeProfileModel(data) {
            this.data = data;
        }
        IotizeProfileModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeProfileModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeProfileModel.prototype.name = function () {
            return this.data.$.Name;
        };
        IotizeProfileModel.prototype.id = function () {
            return this.data.$.Id;
        };
        return IotizeProfileModel;
    }());
    exports.IotizeProfileModel = IotizeProfileModel;

    });

    var iotizeProfileModel$1 = unwrapExports(iotizeProfileModel);
    var iotizeProfileModel_1 = iotizeProfileModel.IotizeProfileModel;

    var baseError = createCommonjsModule(function (module, exports) {
    "use strict";
    var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
        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 (b.hasOwnProperty(p)) d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    var BaseError = /** @class */ (function (_super) {
        __extends(BaseError, _super);
        function BaseError(message, errCode, original) {
            var _this = _super.call(this, message) || this;
            _this.message = message;
            _this.name = _this.constructor.name;
            _this.code = errCode || BaseError.UNKNOWN_ERROR;
            _this.original = original;
            return _this;
            // this.stack = (new Error()).stack;
        }
        BaseError.UNKNOWN_ERROR = 'UnknownError';
        return BaseError;
    }(Error));
    exports.BaseError = BaseError;

    });

    var baseError$1 = unwrapExports(baseError);
    var baseError_1 = baseError.BaseError;

    var invalidConfigurationError = createCommonjsModule(function (module, exports) {
    "use strict";
    /**
     * @module model
     */
    var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
        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 (b.hasOwnProperty(p)) d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });

    var InvalidConfigurationError = /** @class */ (function (_super) {
        __extends(InvalidConfigurationError, _super);
        function InvalidConfigurationError(msg) {
            return _super.call(this, msg, 'InvalidConfigurationError') || this;
        }
        return InvalidConfigurationError;
    }(baseError.BaseError));
    exports.InvalidConfigurationError = InvalidConfigurationError;

    });

    var invalidConfigurationError$1 = unwrapExports(invalidConfigurationError);
    var invalidConfigurationError_1 = invalidConfigurationError.InvalidConfigurationError;

    var iotizeAcl = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */

    var IotizeACL = /** @class */ (function () {
        function IotizeACL(data, aclGroup) {
            this.aclGroup = aclGroup;
            this.data = data;
        }
        IotizeACL.create = function (profileName, aclGroup) {
            return new IotizeACL({
                $: {
                    ProfileName: profileName,
                    Rights: ''
                }
            }, aclGroup);
        };
        IotizeACL.prototype.toJson = function () {
            return this.data;
        };
        IotizeACL.prototype.listRights = function () {
            var rights = this._getProperty('Rights', '');
            if (rights.length === 0) {
                return [];
            }
            return rights.split(',').map(function (entry) {
                return entry.trim();
            });
        };
        IotizeACL.prototype.username = function () {
            return this._getProperty('ProfileName');
        };
        IotizeACL.prototype.hasRight = function (name) {
            if (this.username() === 'admin') {
                return true;
            }
            var rights = this.listRights();
            return rights.indexOf(name) !== -1;
        };
        IotizeACL.prototype._getProperty = function (name, defaultValue) {
            if (!(name in this.data.$)) {
                if (defaultValue === undefined) {
                    throw new invalidConfigurationError.InvalidConfigurationError('Missing key ' + name + ' in IoTize ACL');
                }
                return defaultValue;
            }
            return this.data.$[name];
        };
        return IotizeACL;
    }());
    exports.IotizeACL = IotizeACL;

    });

    var iotizeAcl$1 = unwrapExports(iotizeAcl);
    var iotizeAcl_1 = iotizeAcl.IotizeACL;

    var iotizeAclGroup = createCommonjsModule(function (module, exports) {
    "use strict";
    var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */

    var ANONYMOUS_PROFILE = 'anonymous';
    /**
     *
     */
    var IotizeACLGroup = /** @class */ (function () {
        function IotizeACLGroup(data, bundle) {
            this.bundle = bundle;
            this.data = data;
        }
        IotizeACLGroup.prototype.toJson = function () {
            return this.data;
        };
        /**
         * Get acl for a profile
         * @param profileName
         */
        IotizeACLGroup.prototype.getByProfileName = function (profileName) {
            var e_1, _a;
            var profiles = this.listProfiles();
            try {
                for (var profiles_1 = __values(profiles), profiles_1_1 = profiles_1.next(); !profiles_1_1.done; profiles_1_1 = profiles_1.next()) {
                    var profileAcl = profiles_1_1.value;
                    if (profileAcl.username() === profileName) {
                        return profileAcl;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (profiles_1_1 && !profiles_1_1.done && (_a = profiles_1.return)) _a.call(profiles_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return iotizeAcl.IotizeACL.create(profileName, this);
        };
        IotizeACLGroup.prototype.hasRight = function (profileName, right) {
            var anonymousProfile = this.getByProfileName(ANONYMOUS_PROFILE);
            if (anonymousProfile && anonymousProfile.hasRight(right)) {
                return true;
            }
            if (profileName !== ANONYMOUS_PROFILE) {
                var profile = this.getByProfileName(profileName);
                if (profile) {
                    return profile.hasRight(right);
                }
            }
            return false;
        };
        /**
         * List acl entries for each profile
         */
        IotizeACLGroup.prototype.listProfiles = function () {
            var e_2, _a;
            if (!this.data.IOTizeACL) {
                return [];
            }
            var entries = [];
            try {
                for (var _b = __values(this.data.IOTizeACL), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var data = _c.value;
                    entries.push(new iotizeAcl.IotizeACL(data, this));
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return entries;
        };
        return IotizeACLGroup;
    }());
    exports.IotizeACLGroup = IotizeACLGroup;

    });

    var iotizeAclGroup$1 = unwrapExports(iotizeAclGroup);
    var iotizeAclGroup_1 = iotizeAclGroup.IotizeACLGroup;

    var iotizeBundleModel = createCommonjsModule(function (module, exports) {
    "use strict";
    var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */





    var IotizeBundleModel = /** @class */ (function () {
        function IotizeBundleModel(data, iotizeModule) {
            this.data = data;
            this.iotizeModule = iotizeModule;
        }
        IotizeBundleModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeBundleModel.prototype.module = function () {
            return this.iotizeModule;
        };
        IotizeBundleModel.prototype.id = function () {
            if (!this.data.$.Id) {
                throw new invalidConfigurationError.InvalidConfigurationError('This bundle does not have an id');
            }
            return this.data.$.Id;
        };
        IotizeBundleModel.prototype.name = function () {
            return this.data.$.GUI_Name || '#' + this.id();
        };
        IotizeBundleModel.prototype.dataLogPeriod = function () {
            if (!this.data.$.DataLogPeriod) {
                return 0;
            }
            return Number(this.data.$.DataLogPeriod);
        };
        IotizeBundleModel.prototype.hasDataLog = function () {
            return this.dataLogPeriod() > 0;
        };
        IotizeBundleModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeBundleModel.prototype.variable = function (variableId) {
            var e_1, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() === variableId) {
                        return variable;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            throw new iotizeConfigModel.VariableDoesNotExistError(variableId, this.iotizeModule);
        };
        IotizeBundleModel.prototype.hasVariable = function (variableId) {
            var e_2, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() === variableId) {
                        return variable;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return false;
        };
        IotizeBundleModel.prototype.profiles = function () {
            var e_3, _a;
            if (!this.data.IOTizeAccessControl) {
                return [];
            }
            var profiles = [];
            try {
                for (var _b = __values(this.data.IOTizeAccessControl), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var profile = _c.value;
                    profiles.push(new iotizeProfileModel.IotizeProfileModel(profile));
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
            return profiles;
        };
        IotizeBundleModel.prototype.variables = function () {
            var e_4, _a;
            if (!this.data.IOTizeVariable) {
                return [];
            }
            var variables = [];
            try {
                for (var _b = __values(this.data.IOTizeVariable), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    variables.push(new iotizeVariableModel.IotizeVariableModel(variable, this.iotizeModule, this));
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return variables;
        };
        IotizeBundleModel.prototype.getACLGroup = function () {
            var data = {};
            if (!this.data.IOTizeAccessControl) {
                this.data.IOTizeAccessControl = [];
            }
            if (this.data.IOTizeAccessControl.length > 0) {
                data = this.data.IOTizeAccessControl[0];
            }
            return new iotizeAclGroup.IotizeACLGroup(data, this);
        };
        return IotizeBundleModel;
    }());
    exports.IotizeBundleModel = IotizeBundleModel;

    });

    var iotizeBundleModel$1 = unwrapExports(iotizeBundleModel);
    var iotizeBundleModel_1 = iotizeBundleModel.IotizeBundleModel;

    var iotizeConfigModel = createCommonjsModule(function (module, exports) {
    "use strict";
    var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
        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 (b.hasOwnProperty(p)) d[p] = b[p]; };
            return extendStatics(d, b);
        };
        return function (d, b) {
            extendStatics(d, b);
            function __() { this.constructor = d; }
            d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
        };
    })();
    var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m) return m.call(o);
        if (o && typeof o.length === "number") return {
            next: function () {
                if (o && i >= o.length) o = void 0;
                return { value: o && o[i++], done: !o };
            }
        };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */




    /**
     *
     */
    var BundleDoesNotExistError = /** @class */ (function (_super) {
        __extends(BundleDoesNotExistError, _super);
        function BundleDoesNotExistError(bundleId, config) {
            var _this = _super.call(this, 'Bundle "' + bundleId + '" does not exist.', BundleDoesNotExistError.CODE) || this;
            _this.bundleId = bundleId;
            _this.config = config;
            return _this;
        }
        BundleDoesNotExistError.CODE = 'BundleDoesNotExistError';
        return BundleDoesNotExistError;
    }(baseError.BaseError));
    exports.BundleDoesNotExistError = BundleDoesNotExistError;
    /**
     *
     */
    var VariableDoesNotExistError = /** @class */ (function (_super) {
        __extends(VariableDoesNotExistError, _super);
        function VariableDoesNotExistError(variableId, config) {
            var _this = _super.call(this, "Variable \"" + variableId + "\" does not exist.", VariableDoesNotExistError.CODE) || this;
            _this.variableId = variableId;
            _this.config = config;
            return _this;
        }
        VariableDoesNotExistError.CODE = 'VariableDoesNotExistError';
        return VariableDoesNotExistError;
    }(baseError.BaseError));
    exports.VariableDoesNotExistError = VariableDoesNotExistError;
    /**
     * Class representing an iotize studio configuration for a module
     */
    var IotizeConfigModel = /** @class */ (function () {
        function IotizeConfigModel(data) {
            if (!data.IOTizeConfiguration) {
                //console.error('Trying to create an IotizeConfigModel with invalid data: ', data);
                throw new invalidConfigurationError.InvalidConfigurationError('Key IOTizeConfiguration must exists');
            }
            if (!data.IOTizeConfiguration.IOTizeApp) {
                throw new invalidConfigurationError.InvalidConfigurationError('Key IOTizeConfiguration.IOTizeApp must exists');
            }
            if (data.IOTizeConfiguration.IOTizeApp.length === 0 ||
                !data.IOTizeConfiguration.IOTizeApp[0]['$']) {
                throw new invalidConfigurationError.InvalidConfigurationError('No IOTizeConfiguration.IOTizeApp defined in this configuration file');
            }
            this.data = data;
        }
        IotizeConfigModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeConfigModel.prototype.getAppConfig = function () {
            return this.data.IOTizeConfiguration.IOTizeApp[0];
        };
        /**
         * Get application name
         */
        IotizeConfigModel.prototype.appName = function () {
            if (!this.getAppConfig().$.Name) {
                throw new invalidConfigurationError.InvalidConfigurationError('Application Name is not set');
            }
            return this.getAppConfig().$.Name;
        };
        /**
         * Get config version
         */
        IotizeConfigModel.prototype.version = function () {
            if (!this.getAppConfig().$.Config) {
                throw new invalidConfigurationError.InvalidConfigurationError('App config version is not set');
            }
            return this.getAppConfig().$.Config;
        };
        /**
         * Get module serial number
         */
        IotizeConfigModel.prototype.id = function () {
            if (!this.getAppConfig().$.DevIoTizeSN) {
                throw new invalidConfigurationError.InvalidConfigurationError('Serial number is not set');
            }
            return this.getAppConfig().$.DevIoTizeSN;
        };
        /**
         * Set module serial number
         * @param id
         */
        IotizeConfigModel.prototype.setId = function (id) {
            this.getAppConfig().$.DevIoTizeSN = id;
            return this;
        };
        /**
         * Alias for this.id();
         */
        IotizeConfigModel.prototype.serialNumber = function () {
            return this.id();
        };
        /**
         * Get an array of all bundles
         */
        IotizeConfigModel.prototype.bundles = function () {
            var e_1, _a;
            if (!this.data.IOTizeConfiguration.IOTizeBundle) {
                return [];
            }
            var bundles = [];
            try {
                for (var _b = __values(this.data.IOTizeConfiguration.IOTizeBundle), _c = _b.next(); !_c.done; _c = _b.next()) { // TODO bug if only one bundle
                    var bundle = _c.value;
                    bundles.push(new iotizeBundleModel.IotizeBundleModel(bundle, this));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return bundles;
        };
        /**
         * Array of bundles available for a specific profile
         */
        IotizeConfigModel.prototype.bundleAvailableForProfileName = function (profileName) {
            return this.bundles().reduce(function (list, currentValue) {
                if (currentValue.getACLGroup().hasRight(profileName, 'read')) {
                    list.push(currentValue);
                }
                return list;
            }, []);
        };
        /**
         * Get an array of all variables
         */
        IotizeConfigModel.prototype.variables = function () {
            var e_2, _a, e_3, _b;
            if (!this.data.IOTizeConfiguration.IOTizeBundle) {
                return [];
            }
            var variables = {};
            try {
                for (var _c = __values(this.data.IOTizeConfiguration.IOTizeBundle), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var bundle = _d.value;
                    bundle = new iotizeBundleModel.IotizeBundleModel(bundle, this);
                    try {
                        //            console.log('VAR: ', bundle.variables());
                        for (var _e = (e_3 = void 0, __values(bundle.variables())), _f = _e.next(); !_f.done; _f = _e.next()) {
                            var variable = _f.value;
                            variables[variable.name()] = variable;
                        }
                    }
                    catch (e_3_1) { e_3 = { error: e_3_1 }; }
                    finally {
                        try {
                            if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
                        }
                        finally { if (e_3) throw e_3.error; }
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
                }
                finally { if (e_2) throw e_2.error; }
            }
            var res = [];
            for (var key in variables) {
                res.push(variables[key]);
            }
            return res;
        };
        /**
         * Get bundle by id, if it does not exist, throw BundleDoesNotExistError
         * @throws BundleDoesNotExistError
         * @param id
         */
        IotizeConfigModel.prototype.bundle = function (id) {
            var e_4, _a;
            try {
                for (var _b = __values(this.bundles()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    if (bundle.id() === id) {
                        return bundle;
                    }
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_4) throw e_4.error; }
            }
            throw new BundleDoesNotExistError(id, this);
        };
        IotizeConfigModel.prototype.hasBundle = function (id) {
            var e_5, _a;
            try {
                for (var _b = __values(this.bundles()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    if (bundle.id() === id) {
                        return bundle;
                    }
                }
            }
            catch (e_5_1) { e_5 = { error: e_5_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_5) throw e_5.error; }
            }
            return false;
        };
        /**
         * Get variable by id, if it does not exist, throw VariableDoesNotExistError
         * @throws VariableDoesNotExistError
         * @param id
         */
        IotizeConfigModel.prototype.variable = function (variableId) {
            var e_6, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() == variableId) {
                        return variable;
                    }
                }
            }
            catch (e_6_1) { e_6 = { error: e_6_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_6) throw e_6.error; }
            }
            throw new VariableDoesNotExistError(variableId, this);
        };
        /**
         * Get an array of all profiles
         */
        IotizeConfigModel.prototype.profiles = function () {
            var e_7, _a;
            if (!this.data.IOTizeConfiguration.IOTizeProfile) {
                return [];
            }
            var profiles = [];
            try {
                for (var _b = __values(this.data.IOTizeConfiguration.IOTizeProfile), _c = _b.next(); !_c.done; _c = _b.next()) { // TODO bug if there is only one profile...
                    var profile = _c.value;
                    profiles.push(new iotizeProfileModel.IotizeProfileModel(profile));
                }
            }
            catch (e_7_1) { e_7 = { error: e_7_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_7) throw e_7.error; }
            }
            return profiles;
        };
        IotizeConfigModel.prototype.description = function () {
            return this.getAppConfig().$.GUI_Description;
        };
        IotizeConfigModel.prototype.name = function () {
            return this.getAppConfig().$.GUI_Name;
        };
        return IotizeConfigModel;
    }());
    exports.IotizeConfigModel = IotizeConfigModel;

    });

    var iotizeConfigModel$1 = unwrapExports(iotizeConfigModel);
    var iotizeConfigModel_1 = iotizeConfigModel.BundleDoesNotExistError;
    var iotizeConfigModel_2 = iotizeConfigModel.VariableDoesNotExistError;
    var iotizeConfigModel_3 = iotizeConfigModel.IotizeConfigModel;

    var iotizeConfigFactory = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });

    /**
     * Utility class to create iotize config model from XML or JSON file
     */
    var IotizeConfigFactory = /** @class */ (function () {
        function IotizeConfigFactory() {
        }
        /**
         * Create IotizeConfigModel from a XML string
         * @param xml
         */
        IotizeConfigFactory.fromXML = function (xml) {
            throw new Error("Add import to @iotize/device-client.js/config/iotize-studio/parser/xml to create configuration model from XML file");
        };
        /**
         * Create IotizeConfigModel from a JSON string
         * @param json
         */
        IotizeConfigFactory.fromJson = function (json) {
            return new iotizeConfigModel.IotizeConfigModel(JSON.parse(json));
        };
        /**
         * Build and IotizeConfigModel
         * Input can either be
         * - A json string
         * - A XML string
         * - A JSON Object
         *
         * TODO create test
         * @param data
         */
        IotizeConfigFactory.create = function (data) {
            if (typeof data === 'string') {
                data.trim();
                if (data.length === 0) {
                    throw new Error('Cannot create configuration from empty data');
                }
                if (data[0] === '{') {
                    return IotizeConfigFactory.fromJson(data);
                }
                else {
                    return IotizeConfigFactory.fromXML(data);
                }
            }
            else {
                return new iotizeConfigModel.IotizeConfigModel(data);
            }
        };
        return IotizeConfigFactory;
    }());
    exports.IotizeConfigFactory = IotizeConfigFactory;

    });

    var iotizeConfigFactory$1 = unwrapExports(iotizeConfigFactory);
    var iotizeConfigFactory_1 = iotizeConfigFactory.IotizeConfigFactory;

    var model = createCommonjsModule(function (module, exports) {
    "use strict";
    function __export(m) {
        for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * @module model
     */
    __export(iotizeBundleModel);
    __export(iotizeConfigModel);
    __export(iotizeProfileModel);
    __export(iotizeVariableModel);
    __export(variableDataTypes);

    exports.InvalidConfigurationError = invalidConfigurationError.InvalidConfigurationError;

    });

    var index = unwrapExports(model);
    var model_1 = model.InvalidConfigurationError;

    var tapConfigConfigurator = createCommonjsModule(function (module, exports) {
    "use strict";
    var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m) return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
        }
        catch (error) { e = { error: error }; }
        finally {
            try {
                if (r && !r.done && (m = i["return"])) m.call(i);
            }
            finally { if (e) throw e.error; }
        }
        return ar;
    };
    var __spread = (commonjsGlobal && commonjsGlobal.__spread) || function () {
        for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
        return ar;
    };
    Object.defineProperty(exports, "__esModule", { value: true });



    function toVariableConfig(variables) {
        return variables.map(function (value) {
            return {
                converter: TapConfigConfigurator.getConverterFromVariableModel(value),
                id: parseInt(value.id()),
                length: value.valueQuantity(),
                name: value.name(),
                unit: value.unit()
            };
        });
    }
    exports.toVariableConfig = toVariableConfig;
    function toBundleConfig(bundles) {
        return bundles.map(function (bundle) {
            return {
                id: parseInt(bundle.id()),
                name: bundle.name(),
                variables: toVariableConfig(bundle.variables())
            };
        });
    }
    exports.toBundleConfig = toBundleConfig;
    /**
     * Configure your tap device instance from a configuration model
     * This will
     *  - populate variable manager and bundle manager according to the configuration
     */
    var TapConfigConfigurator = /** @class */ (function () {
        function TapConfigConfigurator(configModel) {
            this.configModel = configModel;
        }
        TapConfigConfigurator.prototype.configure = function (device) {
            var _this = this;
            return rxjs.Observable.create(function (observer) {
                try {
                    observer.next(_this.configureVariables(device));
                    observer.complete();
                }
                catch (error) {
                    observer.error(error);
                }
            });
        };
        TapConfigConfigurator.prototype.configureVariables = function (tap) {
            var bundleConfig = toBundleConfig(this.configModel.bundles());
            tap.bundles.addFromConfig(bundleConfig);
            var variableConfigs = this.configModel
                .bundles()
                .map(function (bundle) {
                return toVariableConfig(bundle.variables());
            })
                .reduce(function (prev, variableConfig) {
                prev.push.apply(prev, __spread(variableConfig));
                return prev;
            }, []);
            tap.variables.addFromConfig(variableConfigs);
        };
        TapConfigConfigurator.getConverterFromVariableModel = function (variable) {
            switch (variable.type()) {
                case model.VariableDataTypes.float:
                    return impl.FloatConverter.instance32();
                case model.VariableDataTypes.int:
                    return new impl.NumberConverter({
                        signed: true,
                        sizeOf: variable.valueSize(),
                        leastSignificantBitFirst: false
                    });
                case model.VariableDataTypes.unsigned_int:
                    return new impl.NumberConverter({
                        signed: false,
                        sizeOf: variable.valueSize(),
                        leastSignificantBitFirst: false
                    });
                default:
                    throw new Error("Unknown converter for: " + variable);
            }
        };
        return TapConfigConfigurator;
    }());
    exports.TapConfigConfigurator = TapConfigConfigurator;

    });

    var tapConfigConfigurator$1 = unwrapExports(tapConfigConfigurator);
    var tapConfigConfigurator_1 = tapConfigConfigurator.toVariableConfig;
    var tapConfigConfigurator_2 = tapConfigConfigurator.toBundleConfig;
    var tapConfigConfigurator_3 = tapConfigConfigurator.TapConfigConfigurator;

    var tapScriptConfiguratorLoader = createCommonjsModule(function (module, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });



    /**
     * Load configuration on your tap
     */
    var TapScriptConfiguratorLoader = /** @class */ (function () {
        function TapScriptConfiguratorLoader(
        /**
         * The script content string
         */
        script, 
        /**
         * Script runner instance (optional)
         */
        scriptRunner, 
        /**
         * Extra options
         */
        options) {
            if (options === void 0) { options = {
                waitDurationMs: 400
            }; }
            this.script = script;
            this.options = options;
            if (!scriptRunner) {
                scriptRunner = new testingGrammar.ScriptRunner();
            }
            this.scriptRunner = scriptRunner;
        }
        TapScriptConfiguratorLoader.prototype.configure = function (device) {
            var instructions = testingGrammar.GrammarHelper.toProgInstructions(this.script);
            var result = rxjs.from(device.service.device.factoryReset()).pipe(operators.concat(this.scriptRunner.run(instructions, device), TapScriptConfiguratorLoader.sleep(this.options.waitDurationMs), device.service.interface.reloadConfig(), TapScriptConfiguratorLoader.sleep(this.options.waitDurationMs)));
            return result;
        };
        TapScriptConfiguratorLoader.sleep = function (ms) {
            return new Promise(function (resolve, reject) {
                setTimeout(function () {
                    resolve();
                }, ms);
            });
        };
        return TapScriptConfiguratorLoader;
    }());
    exports.TapScriptConfiguratorLoader = TapScriptConfiguratorLoader;

    });

    var tapScriptConfiguratorLoader$1 = unwrapExports(tapScriptConfiguratorLoader);
    var tapScriptConfiguratorLoader_1 = tapScriptConfiguratorLoader.TapScriptConfiguratorLoader;

    var lib = createCommonjsModule(function (module, exports) {
    "use strict";
    function __export(m) {
        for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    __export(iotizeConfigFactory);
    __export(definitions);
    __export(tapConfigConfigurator);
    __export(tapScriptConfiguratorLoader);
    __export(model);

    });

    var index$1 = unwrapExports(lib);

    var public_api = createCommonjsModule(function (module, exports) {
    "use strict";
    function __export(m) {
        for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    __export(lib);

    });

    var public_api$1 = unwrapExports(public_api);

    var iotizeDeviceClient_jsConfigIotizeStudio = createCommonjsModule(function (module, exports) {
    "use strict";
    /**
     * Generated bundle index. Do not edit.
     */
    function __export(m) {
        for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
    }
    Object.defineProperty(exports, "__esModule", { value: true });
    __export(public_api);

    exports.ɵb = model.IotizeConfigModel;

    exports.ɵa = iotizeConfigModel.IotizeConfigModel;

    });

    var iotizeDeviceClient_jsConfigIotizeStudio$1 = unwrapExports(iotizeDeviceClient_jsConfigIotizeStudio);

    return iotizeDeviceClient_jsConfigIotizeStudio$1;

})));
//# sourceMappingURL=iotize-device-client.js-config-iotize-studio.umd.js.map
