(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@iotize/tap/client/impl'), require('@iotize/common/error'), require('@iotize/common/utility'), require('@iotize/tap/service/core'), require('@iotize/tap/client/api'), require('@iotize/tap/service/impl/target'), require('@iotize/tap/service/impl/variable'), require('@iotize/tap/service/impl/interface'), require('rxjs'), require('rxjs/operators')) :
    typeof define === 'function' && define.amd ? define('@iotize/tap/extra/dbiot', ['exports', '@iotize/tap/client/impl', '@iotize/common/error', '@iotize/common/utility', '@iotize/tap/service/core', '@iotize/tap/client/api', '@iotize/tap/service/impl/target', '@iotize/tap/service/impl/variable', '@iotize/tap/service/impl/interface', 'rxjs', 'rxjs/operators'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.iotize = global.iotize || {}, global.iotize.tap = global.iotize.tap || {}, global.iotize.tap.extra = global.iotize.tap.extra || {}, global.iotize.tap.extra.dbiot = {}), global.iotize.tap.client.impl, global.error, global.utility, global.iotize.tap.service.core, global.iotize.tap.client.api, global.iotize.tap.service.impl.target, global.iotize.tap.service.impl.variable, global.iotize.tap.service.impl["interface"], global.rxjs, global.rxjs.operators));
})(this, (function (exports, impl, error, utility, core, api, target, variable, _interface, rxjs, operators) { 'use strict';

    var ASCIIControl;
    (function (ASCIIControl) {
        ASCIIControl[ASCIIControl["DEVICE_CONTROL_1"] = 17] = "DEVICE_CONTROL_1";
    })(ASCIIControl || (ASCIIControl = {}));

    /*! *****************************************************************************
    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 __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 __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter$1(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 (_)
                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 };
        }
    }
    var __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(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.");
    }
    function __read(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;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    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));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n])
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    var TlvJsonCompressorError = /** @class */ (function (_super) {
        __extends(TlvJsonCompressorError, _super);
        function TlvJsonCompressorError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        TlvJsonCompressorError.maxDataLengthReach = function (length, maxLength) {
            return new TlvJsonCompressorError("Cannot write " + length + " bytes. Maximum field length is " + maxLength + " bytes.", TlvJsonCompressorError.Code.MaxDataLengthReach);
        };
        TlvJsonCompressorError.unknownFieldName = function (fieldName) {
            return new TlvJsonCompressorError("Cannot find definition for field name \"" + fieldName + "\"", TlvJsonCompressorError.Code.UnknownFieldName);
        };
        TlvJsonCompressorError.unknownFieldCode = function (code) {
            return new TlvJsonCompressorError("Cannot find definition for code \"" + code + "\"", TlvJsonCompressorError.Code.UnknownFieldCode);
        };
        TlvJsonCompressorError.unexpectedCharacter = function (msg) {
            return new TlvJsonCompressorError(msg, TlvJsonCompressorError.Code.UnexpectedCharacter);
        };
        TlvJsonCompressorError.invalidEnumKey = function (key, mapping) {
            return new TlvJsonCompressorError("Invalid enum key \"" + key + "\". Authorized keys are " + utility.listEnumValues(mapping)
                .map(function (key) { return key + ": " + mapping[key]; })
                .join(', '), TlvJsonCompressorError.Code.InvalidEnumKey);
        };
        return TlvJsonCompressorError;
    }(error.CodeError));
    (function (TlvJsonCompressorError) {
        var Code;
        (function (Code) {
            Code["UnknownFieldCode"] = "TlvJsonCompressorErrorUnknownFieldCode";
            Code["UnknownFieldName"] = "TlvJsonCompressorErrorUnknownFieldName";
            Code["UnexpectedCharacter"] = "TlvJsonCompressorErrorUnexpectedCharacter";
            Code["MaxDataLengthReach"] = "TlvJsonCompressorErrorMaxDataLengthReach";
            Code["InvalidEnumKey"] = "TlvJsonCompressorErrorInvalidEnumKey";
        })(Code = TlvJsonCompressorError.Code || (TlvJsonCompressorError.Code = {}));
    })(TlvJsonCompressorError || (TlvJsonCompressorError = {}));

    function getRequiredByteLengthToEncodeInteger(input, signed) {
        var bits = Math.ceil(Math.log2(Math.abs(input) + 1)) + (signed ? 1 : 0);
        return Math.ceil(bits / 8);
    }
    var TLVMappedJsonIntegerCompressor = /** @class */ (function () {
        function TLVMappedJsonIntegerCompressor(signed) {
            this.signed = signed;
        }
        TLVMappedJsonIntegerCompressor.prototype.encode = function (input, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            var bytesLength;
            if (input === 0) {
                bytesLength = 1;
            }
            else {
                bytesLength = getRequiredByteLengthToEncodeInteger(input, this.signed);
                if (bytesLength <= 0) {
                    throw new Error('Invalid byte length ' + bytesLength);
                }
            }
            if (bytesLength === 3) {
                bytesLength = 4;
            }
            writeFieldLength(stream, bytesLength);
            if (this.signed) {
                stream.writeS(input, bytesLength);
            }
            else {
                stream.writeU(input, bytesLength);
            }
            return stream.toBytes;
        };
        TLVMappedJsonIntegerCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            if (length === 0) {
                return 0;
            }
            if (this.signed) {
                return stream.readS(length);
            }
            else {
                return stream.readU(length);
            }
        };
        return TLVMappedJsonIntegerCompressor;
    }());

    var TLVMappedFloat64Compressor = /** @class */ (function () {
        function TLVMappedFloat64Compressor() {
        }
        TLVMappedFloat64Compressor.prototype.encode = function (input, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            if (input === 0) {
                writeFieldLength(stream, 0);
                return stream.toBytes;
            }
            if (Number.isInteger(input)) {
                var length = getRequiredByteLengthToEncodeInteger(input, true);
                if (length < 3) {
                    writeFieldLength(stream, length);
                    stream.writeS(input, length);
                    return stream.toBytes;
                }
            }
            var floatLength = Math.fround(input) === input ? 4 : 8;
            writeFieldLength(stream, floatLength);
            stream.writeF(input, floatLength);
            return stream.toBytes;
        };
        TLVMappedFloat64Compressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            if (length === 0) {
                return 0;
            }
            else if (length === 4 || length == 8) {
                return stream.readFloat(length);
            }
            else if (length < 3) {
                return stream.readS(length);
            }
            else {
                console.warn("failed to decode float64 number with length \"" + length + "\"");
                return 0;
            }
        };
        return TLVMappedFloat64Compressor;
    }());

    var TLVMappedBooleanValueCompressor = /** @class */ (function () {
        function TLVMappedBooleanValueCompressor() {
        }
        TLVMappedBooleanValueCompressor.prototype.encode = function (input, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            if (input) {
                writeFieldLength(stream, 0);
            }
            else {
                writeFieldLength(stream, 1);
                stream.writeU1(0);
            }
            return stream.toBytes;
        };
        TLVMappedBooleanValueCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            if (length === 0) {
                return true;
            }
            else {
                return stream.readU(length) !== 0;
            }
        };
        return TLVMappedBooleanValueCompressor;
    }());

    var TLVMappedJsonValueCompressor = /** @class */ (function () {
        function TLVMappedJsonValueCompressor(converter) {
            this.converter = converter;
        }
        TLVMappedJsonValueCompressor.prototype.encode = function (input, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            var encodedValue = this.converter.encode(input);
            writeFieldLength(stream, encodedValue.length);
            stream.writeBytes(encodedValue);
            return stream.toBytes;
        };
        TLVMappedJsonValueCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            return this.converter.decode(stream.readBytes(length));
        };
        return TLVMappedJsonValueCompressor;
    }());

    var DBIOT_UTF8_CONVERTER = new TLVMappedJsonValueCompressor(core.converters.utf8);
    var DBIOT_BOOLEAN_CONVERTER = new TLVMappedBooleanValueCompressor();
    var DBIOT_FLOAT32_CONVERTER = new TLVMappedJsonValueCompressor(core.converters.float);
    var DBIOT_UINT_CONVERTER = new TLVMappedJsonIntegerCompressor(false);
    var DBIOT_INT32_CONVERTER = new TLVMappedJsonIntegerCompressor(true);
    var DBIOT_FLOAT64_CONVERTER = new TLVMappedFloat64Compressor();

    function findCodeDefinition(code, mapping) {
        return Object.entries(mapping).find(function (_a) {
            var _b = __read(_a, 2), _ = _b[0], value = _b[1];
            return value.code === String.fromCharCode(code);
        });
    }

    function writeFieldLength(stream, length) {
        if (length > 127) {
            if (length > 0x7fff) {
                throw TlvJsonCompressorError.maxDataLengthReach(length, 0x7fff);
            }
            stream.writeBits(1, 1);
            stream.writeBits(length, 15);
        }
        else {
            stream.writeBits(0, 1);
            stream.writeBits(length, 7);
        }
    }
    function readFieldLength(stream) {
        var extendedFieldLength = stream.readBits(1);
        return stream.readBits(extendedFieldLength ? 15 : 7);
    }
    var TLVMappedJsonObjectCompressor = /** @class */ (function () {
        function TLVMappedJsonObjectCompressor(mapping) {
            this.mapping = mapping;
            this.strictMode = false;
        }
        TLVMappedJsonObjectCompressor.prototype.encode = function (input, stream) {
            var _this = this;
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            var entries = Object.entries(input);
            var fieldsStream = new impl.TapStreamWriter();
            entries.forEach(function (_a) {
                var _b = __read(_a, 2), fieldName = _b[0], value = _b[1];
                var definition = _this.mapping[fieldName];
                if (!definition) {
                    throw TlvJsonCompressorError.unknownFieldName(fieldName);
                }
                fieldsStream.writeU1(definition.code.charCodeAt(0));
                var encodedValue = definition.converter.encode(value);
                writeFieldLength(fieldsStream, encodedValue.length);
                fieldsStream.writeBytes(encodedValue);
            });
            var bytes = fieldsStream.toBytes;
            writeFieldLength(stream, bytes.length);
            stream.writeBytes(bytes);
            return stream.toBytes;
        };
        TLVMappedJsonObjectCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var result = {};
            var totalLength = readFieldLength(stream);
            var initialPosition = stream.pos;
            while (stream.pos - initialPosition < totalLength) {
                var tag = stream.readU1();
                var entry = findCodeDefinition(tag, this.mapping);
                var length = readFieldLength(stream);
                if (!entry) {
                    if (this.strictMode) {
                        throw TlvJsonCompressorError.unknownFieldCode(tag);
                    }
                    else {
                        stream.forward(length);
                    }
                }
                else {
                    var _a = __read(entry, 2), fieldName = _a[0], definition = _a[1];
                    result[fieldName] = definition.converter.decode(stream);
                }
            }
            return result;
        };
        return TLVMappedJsonObjectCompressor;
    }());
    var TLVMappedJsonArrayCompressor = /** @class */ (function () {
        function TLVMappedJsonArrayCompressor(options) {
            this.options = options;
        }
        TLVMappedJsonArrayCompressor.prototype.encode = function (input, stream) {
            var _this = this;
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            var itemsStream = new impl.TapStreamWriter();
            input.forEach(function (v) {
                _this.options.itemConverter.encode(v, itemsStream);
            });
            var encodedItems = itemsStream.toBytes;
            writeFieldLength(stream, encodedItems.length);
            stream.writeBytes(encodedItems);
            return stream.toBytes;
        };
        TLVMappedJsonArrayCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            var itemsStream = stream.subStream(length);
            var result = [];
            while (!itemsStream.isEof()) {
                var item = this.options.itemConverter.decode(itemsStream);
                result.push(item);
            }
            return result;
        };
        return TLVMappedJsonArrayCompressor;
    }());
    /**
     * Optimization for an array of object,
     * It will not duplicate object/field information for each items
     */
    var TLVMappedJsonArrayOfObjectCompressor = /** @class */ (function () {
        function TLVMappedJsonArrayOfObjectCompressor(options) {
            this.options = options;
        }
        TLVMappedJsonArrayOfObjectCompressor.prototype.encode = function (input, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            var itemsStream = new impl.TapStreamWriter();
            DBIOT_UINT_CONVERTER.encode(input.length, itemsStream);
            this.options.fields.forEach(function (_a) {
                var fieldName = _a.fieldName, converter = _a.converter;
                input.forEach(function (item, index) {
                    if (!(fieldName in item)) {
                        writeFieldLength(itemsStream, 0);
                        // throw new Error(`Field ${fieldName} is missing for item ${index}`);
                    }
                    else {
                        converter.encode(item[fieldName], itemsStream);
                    }
                });
            });
            var encodedItems = itemsStream.toBytes;
            writeFieldLength(stream, encodedItems.length);
            stream.writeBytes(encodedItems);
            return stream.toBytes;
        };
        TLVMappedJsonArrayOfObjectCompressor.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            var length = readFieldLength(stream);
            var itemCount = DBIOT_UINT_CONVERTER.decode(stream);
            var result = new Array(itemCount)
                .fill(undefined)
                .map(function () { return ({}); });
            this.options.fields.forEach(function (_a) {
                var fieldName = _a.fieldName, converter = _a.converter;
                result.forEach(function (value, index) {
                    var fieldValue = converter.decode(stream);
                    value[fieldName] = fieldValue;
                });
            });
            return result;
        };
        return TLVMappedJsonArrayOfObjectCompressor;
    }());

    var POS_BIT_SIZE = 4;
    var ɵ0 = function (input, stream) {
        var e_1, _a;
        if (stream === void 0) { stream = new impl.TapStreamWriter(); }
        var subStream = new impl.TapStreamWriter();
        var itemBitLength = POS_BIT_SIZE;
        var itemCount = input.length;
        // writeFieldLength(subStream, itemBitLength);
        writeFieldLength(subStream, itemCount);
        try {
            for (var input_1 = __values(input), input_1_1 = input_1.next(); !input_1_1.done; input_1_1 = input_1.next()) {
                var value = input_1_1.value;
                subStream.writeBitsInt(value, itemBitLength);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (input_1_1 && !input_1_1.done && (_a = input_1.return)) _a.call(input_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        var encoded = subStream.toBytes;
        writeFieldLength(stream, encoded.length);
        stream.writeBytes(encoded);
        return stream.toBytes;
    }, ɵ1 = function (stream) {
        stream = impl.TapStreamReader.create(stream);
        var _byteLength = readFieldLength(stream);
        var subStream = stream.subStream(_byteLength);
        var itemBitSize = POS_BIT_SIZE; //readFieldLength(subStream);
        var itemCount = readFieldLength(subStream);
        var result = [];
        for (var i = 0; i < itemCount; i++) {
            result.push(subStream.readBitsInt(itemBitSize));
        }
        return result;
    };
    var DBIOT_BYTE_ORDER_CONVERTER = {
        encode: ɵ0,
        decode: ɵ1,
    };

    var ButtonSizeEnum;
    (function (ButtonSizeEnum) {
        ButtonSizeEnum[ButtonSizeEnum["DEFAULT"] = 0] = "DEFAULT";
        ButtonSizeEnum[ButtonSizeEnum["SMALL"] = 1] = "SMALL";
        ButtonSizeEnum[ButtonSizeEnum["LARGE"] = 2] = "LARGE";
    })(ButtonSizeEnum || (ButtonSizeEnum = {}));
    var DBIOT_INNER_CONVERTER = new TLVMappedJsonObjectCompressor({
        encoding: {
            code: 'E',
            converter: new TLVMappedJsonObjectCompressor({
                scaling: {
                    code: 'x',
                    converter: DBIOT_FLOAT32_CONVERTER,
                },
                bitLength: {
                    code: 'b',
                    converter: DBIOT_UINT_CONVERTER,
                },
                offset: {
                    code: 'o',
                    converter: DBIOT_FLOAT32_CONVERTER,
                },
            }),
        },
        tap: {
            code: 'T',
            converter: new TLVMappedJsonObjectCompressor({
                address: {
                    code: 'a',
                    converter: DBIOT_UINT_CONVERTER,
                },
                valueAcquisitionPeriod: {
                    code: 's',
                    converter: DBIOT_UINT_CONVERTER,
                },
            }),
        },
        dashboard: {
            code: 'D',
            converter: new TLVMappedJsonObjectCompressor({
                offset: {
                    code: 'O',
                    converter: DBIOT_FLOAT64_CONVERTER,
                },
                scaling: {
                    code: 'X',
                    converter: DBIOT_FLOAT64_CONVERTER,
                },
                readable: {
                    code: 'R',
                    converter: DBIOT_BOOLEAN_CONVERTER,
                },
                writable: {
                    code: 'W',
                    converter: DBIOT_BOOLEAN_CONVERTER,
                },
                format: {
                    code: 'F',
                    converter: DBIOT_UTF8_CONVERTER,
                },
                name: {
                    code: 'N',
                    converter: DBIOT_UTF8_CONVERTER,
                },
                unit: {
                    code: 'U',
                    converter: DBIOT_UTF8_CONVERTER,
                },
                byteOrder: {
                    code: 'B',
                    converter: DBIOT_BYTE_ORDER_CONVERTER,
                },
                component: {
                    code: 'C',
                    converter: new TLVMappedJsonObjectCompressor({
                        'tap-variable-number': {
                            code: 't',
                            converter: new TLVMappedJsonObjectCompressor({}),
                        },
                        'tap-variable-range': {
                            code: 'r',
                            converter: new TLVMappedJsonObjectCompressor({
                                min: {
                                    code: 'm',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                max: {
                                    code: 'M',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                step: {
                                    code: 's',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                writeValueForEveryChange: {
                                    code: 'w',
                                    converter: DBIOT_BOOLEAN_CONVERTER,
                                },
                            }),
                        },
                        'tap-variable-linear-gauge': {
                            code: 'G',
                            converter: new TLVMappedJsonObjectCompressor({
                                min: {
                                    code: 'm',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                max: {
                                    code: 'M',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                            }),
                        },
                        'tap-variable-gauge': {
                            code: 'g',
                            converter: new TLVMappedJsonObjectCompressor({
                                min: {
                                    code: 'm',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                max: {
                                    code: 'M',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                            }),
                        },
                        'tap-variable-line-chart': {
                            code: 'l',
                            converter: new TLVMappedJsonObjectCompressor({}),
                        },
                        'tap-variable-bar-chart': {
                            code: 'B',
                            converter: new TLVMappedJsonObjectCompressor({}),
                        },
                        'tap-variable-table': {
                            code: 'T',
                            converter: new TLVMappedJsonObjectCompressor({}),
                        },
                        'tap-variable-bits-editor': {
                            code: 'b',
                            converter: new TLVMappedJsonObjectCompressor({
                                bitsTemplate: {
                                    code: 'T',
                                    converter: new TLVMappedJsonArrayOfObjectCompressor({
                                        fields: [
                                            {
                                                fieldName: 'index',
                                                converter: DBIOT_UINT_CONVERTER,
                                            },
                                            {
                                                fieldName: 'label',
                                                converter: DBIOT_UTF8_CONVERTER,
                                            },
                                        ],
                                    }),
                                },
                            }),
                        },
                        'tap-variable-buttons': {
                            code: 'U',
                            converter: new TLVMappedJsonObjectCompressor({
                                buttons: {
                                    code: 'b',
                                    converter: new TLVMappedJsonArrayOfObjectCompressor({
                                        fields: [
                                            {
                                                fieldName: 'value',
                                                converter: DBIOT_FLOAT64_CONVERTER,
                                            },
                                            {
                                                fieldName: 'label',
                                                converter: DBIOT_UTF8_CONVERTER,
                                            },
                                        ],
                                    }),
                                },
                            }),
                        },
                        'tap-variable-push-button': {
                            code: 'P',
                            converter: new TLVMappedJsonObjectCompressor({
                                mouseDownValue: {
                                    code: 'd',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                mouseUpValue: {
                                    code: 'U',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                value: {
                                    code: 'u',
                                    converter: DBIOT_FLOAT64_CONVERTER,
                                },
                                buttonText: {
                                    code: 'l',
                                    converter: DBIOT_UTF8_CONVERTER,
                                },
                                // size: {
                                //   code: 's',
                                //   converter: new TLVMappedEnumConverter(ButtonSizeEnum),
                                // },
                                icon: {
                                    code: 'i',
                                    converter: DBIOT_UTF8_CONVERTER,
                                },
                            }),
                        },
                        'tap-variable-select': {
                            code: 'S',
                            converter: new TLVMappedJsonObjectCompressor({
                                options: {
                                    code: 'o',
                                    converter: new TLVMappedJsonArrayOfObjectCompressor({
                                        fields: [
                                            {
                                                fieldName: 'value',
                                                converter: DBIOT_FLOAT64_CONVERTER,
                                            },
                                            {
                                                fieldName: 'text',
                                                converter: DBIOT_UTF8_CONVERTER,
                                            },
                                        ],
                                    }),
                                },
                            }),
                        },
                    }),
                },
            }),
        },
        cloud: {
            code: 'C',
            converter: new TLVMappedJsonObjectCompressor({
                name: {
                    code: 'N',
                    converter: DBIOT_UTF8_CONVERTER,
                },
                optional: {
                    code: 'p',
                    converter: DBIOT_UINT_CONVERTER,
                },
                uploadPeriod: {
                    code: 't',
                    converter: DBIOT_UINT_CONVERTER,
                },
                valueDelta: {
                    code: 'd',
                    converter: DBIOT_FLOAT32_CONVERTER,
                },
                alarmMinValue: {
                    code: 'l',
                    converter: DBIOT_FLOAT32_CONVERTER,
                },
                alarmMaxValue: {
                    code: 'h',
                    converter: DBIOT_FLOAT32_CONVERTER,
                },
            }),
        },
    });
    var DBIOTVarConfigConverter = /** @class */ (function () {
        function DBIOTVarConfigConverter() {
        }
        DBIOTVarConfigConverter.prototype.encode = function (mainConfig) {
            if (!mainConfig) {
                return new Uint8Array();
            }
            var writter = new impl.TapStreamWriter();
            writter.writeU1(ASCIIControl.DEVICE_CONTROL_1);
            DBIOT_INNER_CONVERTER.encode(mainConfig, writter);
            return writter.toBytes;
        };
        DBIOTVarConfigConverter.prototype.decode = function (streamOrBuffer) {
            var stream = impl.TapStreamReader.create(streamOrBuffer);
            if (stream.byteLeft === 0) {
                return undefined;
            }
            var char;
            if (!stream.isEof() && char !== ASCIIControl.DEVICE_CONTROL_1) {
                char = stream.readU1();
            }
            if (char === ASCIIControl.DEVICE_CONTROL_1) {
                try {
                    return DBIOT_INNER_CONVERTER.decode(stream);
                }
                catch (err) {
                    console.warn("Failed to restore variable configuration", err);
                }
            }
            return undefined;
        };
        return DBIOTVarConfigConverter;
    }());

    var DBIOT_VARIABLE_CONFIG_CONVERTER = new DBIOTVarConfigConverter();

    var TLVMappedEnumConverter = /** @class */ (function () {
        function TLVMappedEnumConverter(mapping) {
            this.mapping = mapping;
        }
        TLVMappedEnumConverter.prototype.encode = function (keyValue, stream) {
            if (stream === void 0) { stream = new impl.TapStreamWriter(); }
            if (!(keyValue in this.mapping)) {
                throw TlvJsonCompressorError.invalidEnumKey(keyValue, this.mapping);
            }
            return TLVMappedEnumConverter._valueConverter.encode(keyValue, stream);
        };
        TLVMappedEnumConverter.prototype.decode = function (streamOrBuffer) {
            var keyValue = TLVMappedEnumConverter._valueConverter.decode(streamOrBuffer);
            if (!(keyValue in this.mapping)) {
                throw TlvJsonCompressorError.invalidEnumKey(keyValue, this.mapping);
            }
            return keyValue;
        };
        return TLVMappedEnumConverter;
    }());
    TLVMappedEnumConverter._valueConverter = new TLVMappedJsonIntegerCompressor(false);

    var __awaiter = (this && this.__awaiter) || function (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());
        });
    };
    /**
     * Create shared observable that read DBIOT configuration from tap
     * @param tap
     * @param maxVar
     * @returns
     */
    function createReadDBIOTConfigurationFromTapObservable(tap, maxVar) {
        var _this = this;
        var obs = new rxjs.Observable(function (emitter) {
            var stopLoop = false;
            var progressEvent = {
                type: 'start',
                data: {
                    total: maxVar,
                },
            };
            emitter.next(progressEvent);
            (function () { return __awaiter(_this, void 0, void 0, function () {
                var targetProtocol, variables, progressEvent_1, variableId, variableConfig, progressEvent_2, result, err_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 6, , 7]);
                            return [4 /*yield*/, tap.service.target.getProtocol()];
                        case 1:
                            targetProtocol = (_a.sent()).body();
                            variables = [];
                            progressEvent_1 = {
                                type: 'progress',
                                data: {
                                    current: 0,
                                    total: maxVar,
                                },
                            };
                            emitter.next(progressEvent_1);
                            variableId = 0;
                            _a.label = 2;
                        case 2:
                            if (!(variableId < maxVar && !stopLoop)) return [3 /*break*/, 5];
                            return [4 /*yield*/, readTapVariableConfigWithDBIOTuration(tap, variableId)];
                        case 3:
                            variableConfig = _a.sent();
                            if (variableConfig) {
                                variables.push(variableConfig);
                            }
                            progressEvent_2 = {
                                type: 'progress',
                                data: {
                                    current: variableId + 1,
                                    total: maxVar,
                                    variable: variableConfig,
                                },
                            };
                            emitter.next(progressEvent_2);
                            _a.label = 4;
                        case 4:
                            variableId++;
                            return [3 /*break*/, 2];
                        case 5:
                            if (!stopLoop) {
                                result = {
                                    type: 'complete',
                                    data: {
                                        bundles: [],
                                        variables: variables,
                                        targetProtocol: targetProtocol,
                                    },
                                };
                                emitter.next(result);
                            }
                            emitter.complete();
                            return [3 /*break*/, 7];
                        case 6:
                            err_1 = _a.sent();
                            emitter.error(err_1);
                            return [3 /*break*/, 7];
                        case 7: return [2 /*return*/];
                    }
                });
            }); })();
            return function () {
                stopLoop = true;
            };
        });
        return obs.pipe(operators.share());
    }
    function readTapVariableConfigWithDBIOTuration(tap, id) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, lengthRes, typeRes, bundleIdRes, length, dbiot, rawMetaResponse, rawData;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, tap.service.interface.executeMultipleCalls([
                            tap.service.variable.getNumberOfElementsCall(id),
                            tap.service.variable.getTypeCall(id),
                            tap.service.variable.getBundleIdCall(id),
                        ])];
                    case 1:
                        _a = __read.apply(void 0, [_b.sent(), 3]), lengthRes = _a[0], typeRes = _a[1], bundleIdRes = _a[2];
                        if (!lengthRes.isSuccessful()) {
                            if (lengthRes.codeRet() === api.ResultCode.NOT_FOUND) {
                                return [2 /*return*/, undefined];
                            }
                        }
                        length = lengthRes.body();
                        dbiot = undefined;
                        if (!(length > 0)) return [3 /*break*/, 3];
                        return [4 /*yield*/, tap.service.variable.getRawMeta(id)];
                    case 2:
                        rawMetaResponse = _b.sent();
                        rawData = rawMetaResponse.body();
                        if (rawData.length > 0) {
                            try {
                                dbiot = DBIOT_VARIABLE_CONFIG_CONVERTER.decode(rawData);
                            }
                            catch (err) {
                                // Ignore if dbiot variable is not set property
                                console.warn("Cannot parse dbiot info for variable \"" + id + "\"", err);
                                return [2 /*return*/];
                            }
                        }
                        _b.label = 3;
                    case 3: return [2 /*return*/, {
                            id: id,
                            bundleId: bundleIdRes.body(),
                            length: length,
                            type: typeRes.body(),
                            dbiot: dbiot,
                        }];
                }
            });
        });
    }

    /**
     * Generated bundle index. Do not edit.
     */

    exports.DBIOTVarConfigConverter = DBIOTVarConfigConverter;
    exports.DBIOT_VARIABLE_CONFIG_CONVERTER = DBIOT_VARIABLE_CONFIG_CONVERTER;
    exports.TLVMappedEnumConverter = TLVMappedEnumConverter;
    exports.TLVMappedJsonArrayCompressor = TLVMappedJsonArrayCompressor;
    exports.createReadDBIOTConfigurationFromTapObservable = createReadDBIOTConfigurationFromTapObservable;
    exports["ɵa"] = TLVMappedJsonIntegerCompressor;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=iotize-tap-extra-dbiot.umd.js.map
