UNPKG

lakutata

Version:

An IoC-based universal application framework.

49,609 lines 1.72 MB
/* Build Date: Mon Jan 05 2026 23:52:23 GMT+0800 (China Standard Time) */
"use strict";

const tslib_es6 = require("./Package.internal.3.cjs");

const Provider = require("../src/lib/core/Provider.cjs");

const Configurable = require("../src/decorators/di/Configurable.cjs");

const ObjectSchemaValidation = require("./Package.internal.7.cjs");

const _commonjsHelpers = require("./Package.internal.2.cjs");

const require$$0$8 = require("events");

const require$$0$9 = require("querystring");

const require$$0 = require("https");

const require$$1$1 = require("http");

const require$$4$1 = require("url");

const require$$0$5 = require("fs");

const require$$0$4 = require("path");

const require$$0$6 = require("net");

const require$$0$7 = require("stream");

const require$$4$2 = require("child_process");

const require$$0$3 = require("crypto");

const require$$0$2 = require("assert");

const require$$0$1 = require("buffer");

const _commonjsDynamicModules = require("./Package.internal.6.cjs");

const require$$2$1 = require("tls");

const require$$2 = require("dns");

const require$$1$2 = require("util");

const require$$4$3 = require("zlib");

const index = require("./Package.internal.52.cjs");

const require$$1$3 = require("os");

const require$$1$4 = require("constants");

const Logger = require("./Package.internal.54.cjs");

const require$$1$5 = require("string_decoder");

const require$$1$6 = require("process");

const require$$0$a = require("http2");

const Lifetime = require("../src/decorators/di/Lifetime.cjs");

const ContainerTTYConsoleSizeOptions = require("../src/components/docker/options/container/ContainerTTYConsoleSizeOptions.cjs");

const Accept = require("../src/decorators/dto/Accept.cjs");

const As = require("../src/lib/helpers/As.cjs");

const Inject = require("../src/decorators/di/Inject.cjs");

const _interopDefault = e => e && e.__esModule ? e : {
    default: e
};

const require$$0__default$8 = _interopDefault(require$$0$8);

const require$$0__default$9 = _interopDefault(require$$0$9);

const require$$0__default = _interopDefault(require$$0);

const require$$1__default = _interopDefault(require$$1$1);

const require$$4__default = _interopDefault(require$$4$1);

const require$$0__default$5 = _interopDefault(require$$0$5);

const require$$0__default$4 = _interopDefault(require$$0$4);

const require$$0__default$6 = _interopDefault(require$$0$6);

const require$$0__default$7 = _interopDefault(require$$0$7);

const require$$4__default$1 = _interopDefault(require$$4$2);

const require$$0__default$3 = _interopDefault(require$$0$3);

const require$$0__default$2 = _interopDefault(require$$0$2);

const require$$0__default$1 = _interopDefault(require$$0$1);

const require$$2__default$1 = _interopDefault(require$$2$1);

const require$$2__default = _interopDefault(require$$2);

const require$$1__default$1 = _interopDefault(require$$1$2);

const require$$4__default$2 = _interopDefault(require$$4$3);

const require$$1__default$2 = _interopDefault(require$$1$3);

const require$$1__default$3 = _interopDefault(require$$1$4);

const require$$1__default$4 = _interopDefault(require$$1$5);

const require$$1__default$5 = _interopDefault(require$$1$6);

const require$$0__default$a = _interopDefault(require$$0$a);

var http$3 = {
    exports: {}
};

var utils$3 = {};

var arr = [];

var each = arr.forEach;

var slice = arr.slice;

utils$3.extend = function(e) {
    each.call(slice.call(arguments, 1), function(t) {
        if (t) {
            for (var r in t) {
                e[r] = t[r];
            }
        }
    });
    return e;
};

utils$3.parseJSON = function(e) {
    try {
        return JSON.parse(e);
    } catch (e) {
        return null;
    }
};

http$3.exports;

(function(e, t) {
    var r = require$$0__default.default, n = require$$1__default.default, s = require$$4__default.default, o = utils$3;
    e.exports.maxRedirects = 5;
    var a = {
        https: r,
        http: n
    };
    for (var l in a) {
        var c = function() {};
        c.prototype = a[l];
        c = new c;
        c.request = function(r) {
            return function(n, a, c) {
                c = c || {};
                var u = typeof n === "object" && "maxRedirects" in n ? n.maxRedirects : t.maxRedirects;
                var d = o.extend({
                    count: 0,
                    max: u,
                    clientRequest: null,
                    userCallback: a
                }, c);
                if (d.count > d.max) {
                    var h = new Error("Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.");
                    d.clientRequest.emit("error", h);
                    return d.clientRequest;
                }
                d.count++;
                var p;
                if (typeof n === "string") {
                    p = n;
                } else {
                    p = s.format(o.extend({
                        protocol: l
                    }, n));
                }
                var g = Object.getPrototypeOf(r).request(n, m(p, d));
                if (!d.clientRequest) d.clientRequest = g;
                function m(t, r) {
                    return function(n) {
                        if (n.statusCode < 300 || n.statusCode > 399) {
                            return r.userCallback(n);
                        }
                        if (!("location" in n.headers)) {
                            return r.userCallback(n);
                        }
                        var o = s.resolve(t, n.headers.location);
                        var a = s.parse(o).protocol;
                        a = a.substr(0, a.length - 1);
                        return e.exports[a].get(o, m(t, r), r);
                    };
                }
                return g;
            };
        }(c);
        c.get = function(e) {
            return function(t, r, n) {
                var s = e.request(t, r, n);
                s.end();
                return s;
            };
        }(c);
        e.exports[l] = c;
    }
})(http$3, http$3.exports);

var httpExports = http$3.exports;

var ber = {
    exports: {}
};

var errors$3 = {
    newInvalidAsn1Error: function(e) {
        var t = new Error;
        t.name = "InvalidAsn1Error";
        t.message = e || "";
        return t;
    }
};

var types$2 = {
    EOC: 0,
    Boolean: 1,
    Integer: 2,
    BitString: 3,
    OctetString: 4,
    Null: 5,
    OID: 6,
    ObjectDescriptor: 7,
    External: 8,
    Real: 9,
    Enumeration: 10,
    PDV: 11,
    Utf8String: 12,
    RelativeOID: 13,
    Sequence: 16,
    Set: 17,
    NumericString: 18,
    PrintableString: 19,
    T61String: 20,
    VideotexString: 21,
    IA5String: 22,
    UTCTime: 23,
    GeneralizedTime: 24,
    GraphicString: 25,
    VisibleString: 26,
    GeneralString: 28,
    UniversalString: 29,
    CharacterString: 30,
    BMPString: 31,
    Constructor: 32,
    Context: 128
};

var buffer = require$$0__default$1.default;

var Buffer$4 = buffer.Buffer;

var safer = {};

var key;

for (key in buffer) {
    if (!buffer.hasOwnProperty(key)) continue;
    if (key === "SlowBuffer" || key === "Buffer") continue;
    safer[key] = buffer[key];
}

var Safer = safer.Buffer = {};

for (key in Buffer$4) {
    if (!Buffer$4.hasOwnProperty(key)) continue;
    if (key === "allocUnsafe" || key === "allocUnsafeSlow") continue;
    Safer[key] = Buffer$4[key];
}

safer.Buffer.prototype = Buffer$4.prototype;

if (!Safer.from || Safer.from === Uint8Array.from) {
    Safer.from = function(e, t, r) {
        if (typeof e === "number") {
            throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof e);
        }
        if (e && typeof e.length === "undefined") {
            throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e);
        }
        return Buffer$4(e, t, r);
    };
}

if (!Safer.alloc) {
    Safer.alloc = function(e, t, r) {
        if (typeof e !== "number") {
            throw new TypeError('The "size" argument must be of type number. Received type ' + typeof e);
        }
        if (e < 0 || e >= 2 * (1 << 30)) {
            throw new RangeError('The value "' + e + '" is invalid for option "size"');
        }
        var n = Buffer$4(e);
        if (!t || t.length === 0) {
            n.fill(0);
        } else if (typeof r === "string") {
            n.fill(t, r);
        } else {
            n.fill(t);
        }
        return n;
    };
}

if (!safer.kStringMaxLength) {
    try {
        safer.kStringMaxLength = process.binding("buffer").kStringMaxLength;
    } catch (e) {}
}

if (!safer.constants) {
    safer.constants = {
        MAX_LENGTH: safer.kMaxLength
    };
    if (safer.kStringMaxLength) {
        safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength;
    }
}

var safer_1 = safer;

var assert$2 = require$$0__default$2.default;

var Buffer$3 = safer_1.Buffer;

var ASN1$1 = types$2;

var errors$2 = errors$3;

var newInvalidAsn1Error$1 = errors$2.newInvalidAsn1Error;

function Reader$2(e) {
    if (!e || !Buffer$3.isBuffer(e)) throw new TypeError("data must be a node Buffer");
    this._buf = e;
    this._size = e.length;
    this._len = 0;
    this._offset = 0;
}

Object.defineProperty(Reader$2.prototype, "length", {
    enumerable: true,
    get: function() {
        return this._len;
    }
});

Object.defineProperty(Reader$2.prototype, "offset", {
    enumerable: true,
    get: function() {
        return this._offset;
    }
});

Object.defineProperty(Reader$2.prototype, "remain", {
    get: function() {
        return this._size - this._offset;
    }
});

Object.defineProperty(Reader$2.prototype, "buffer", {
    get: function() {
        return this._buf.slice(this._offset);
    }
});

Reader$2.prototype.readByte = function(e) {
    if (this._size - this._offset < 1) return null;
    var t = this._buf[this._offset] & 255;
    if (!e) this._offset += 1;
    return t;
};

Reader$2.prototype.peek = function() {
    return this.readByte(true);
};

Reader$2.prototype.readLength = function(e) {
    if (e === undefined) e = this._offset;
    if (e >= this._size) return null;
    var t = this._buf[e++] & 255;
    if (t === null) return null;
    if ((t & 128) === 128) {
        t &= 127;
        if (t === 0) throw newInvalidAsn1Error$1("Indefinite length not supported");
        if (t > 4) throw newInvalidAsn1Error$1("encoding too long");
        if (this._size - e < t) return null;
        this._len = 0;
        for (var r = 0; r < t; r++) this._len = (this._len << 8) + (this._buf[e++] & 255);
    } else {
        this._len = t;
    }
    return e;
};

Reader$2.prototype.readSequence = function(e) {
    var t = this.peek();
    if (t === null) return null;
    if (e !== undefined && e !== t) throw newInvalidAsn1Error$1("Expected 0x" + e.toString(16) + ": got 0x" + t.toString(16));
    var r = this.readLength(this._offset + 1);
    if (r === null) return null;
    this._offset = r;
    return t;
};

Reader$2.prototype.readInt = function() {
    return this._readTag(ASN1$1.Integer);
};

Reader$2.prototype.readBoolean = function() {
    return this._readTag(ASN1$1.Boolean) === 0 ? false : true;
};

Reader$2.prototype.readEnumeration = function() {
    return this._readTag(ASN1$1.Enumeration);
};

Reader$2.prototype.readString = function(e, t) {
    if (!e) e = ASN1$1.OctetString;
    var r = this.peek();
    if (r === null) return null;
    if (r !== e) throw newInvalidAsn1Error$1("Expected 0x" + e.toString(16) + ": got 0x" + r.toString(16));
    var n = this.readLength(this._offset + 1);
    if (n === null) return null;
    if (this.length > this._size - n) return null;
    this._offset = n;
    if (this.length === 0) return t ? Buffer$3.alloc(0) : "";
    var s = this._buf.slice(this._offset, this._offset + this.length);
    this._offset += this.length;
    return t ? s : s.toString("utf8");
};

Reader$2.prototype.readOID = function(e) {
    if (!e) e = ASN1$1.OID;
    var t = this.readString(e, true);
    if (t === null) return null;
    var r = [];
    var n = 0;
    for (var s = 0; s < t.length; s++) {
        var o = t[s] & 255;
        n <<= 7;
        n += o & 127;
        if ((o & 128) === 0) {
            r.push(n);
            n = 0;
        }
    }
    n = r.shift();
    r.unshift(n % 40);
    r.unshift(n / 40 >> 0);
    return r.join(".");
};

Reader$2.prototype._readTag = function(e) {
    assert$2.ok(e !== undefined);
    var t = this.peek();
    if (t === null) return null;
    if (t !== e) throw newInvalidAsn1Error$1("Expected 0x" + e.toString(16) + ": got 0x" + t.toString(16));
    var r = this.readLength(this._offset + 1);
    if (r === null) return null;
    if (this.length > 4) throw newInvalidAsn1Error$1("Integer too long: " + this.length);
    if (this.length > this._size - r) return null;
    this._offset = r;
    var n = this._buf[this._offset];
    var s = 0;
    for (var o = 0; o < this.length; o++) {
        s <<= 8;
        s |= this._buf[this._offset++] & 255;
    }
    if ((n & 128) === 128 && o !== 4) s -= 1 << o * 8;
    return s >> 0;
};

var reader$1 = Reader$2;

var assert$1 = require$$0__default$2.default;

var Buffer$2 = safer_1.Buffer;

var ASN1 = types$2;

var errors$1 = errors$3;

var newInvalidAsn1Error = errors$1.newInvalidAsn1Error;

var DEFAULT_OPTS = {
    size: 1024,
    growthFactor: 8
};

function merge(e, t) {
    assert$1.ok(e);
    assert$1.equal(typeof e, "object");
    assert$1.ok(t);
    assert$1.equal(typeof t, "object");
    var r = Object.getOwnPropertyNames(e);
    r.forEach(function(r) {
        if (t[r]) return;
        var n = Object.getOwnPropertyDescriptor(e, r);
        Object.defineProperty(t, r, n);
    });
    return t;
}

function Writer$2(e) {
    e = merge(DEFAULT_OPTS, e || {});
    this._buf = Buffer$2.alloc(e.size || 1024);
    this._size = this._buf.length;
    this._offset = 0;
    this._options = e;
    this._seq = [];
}

Object.defineProperty(Writer$2.prototype, "buffer", {
    get: function() {
        if (this._seq.length) throw newInvalidAsn1Error(this._seq.length + " unended sequence(s)");
        return this._buf.slice(0, this._offset);
    }
});

Writer$2.prototype.writeByte = function(e) {
    if (typeof e !== "number") throw new TypeError("argument must be a Number");
    this._ensure(1);
    this._buf[this._offset++] = e;
};

Writer$2.prototype.writeInt = function(e, t) {
    if (typeof e !== "number") throw new TypeError("argument must be a Number");
    if (typeof t !== "number") t = ASN1.Integer;
    var r = 4;
    while (((e & 4286578688) === 0 || (e & 4286578688) === 4286578688 >> 0) && r > 1) {
        r--;
        e <<= 8;
    }
    if (r > 4) throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff");
    this._ensure(2 + r);
    this._buf[this._offset++] = t;
    this._buf[this._offset++] = r;
    while (r-- > 0) {
        this._buf[this._offset++] = (e & 4278190080) >>> 24;
        e <<= 8;
    }
};

Writer$2.prototype.writeNull = function() {
    this.writeByte(ASN1.Null);
    this.writeByte(0);
};

Writer$2.prototype.writeEnumeration = function(e, t) {
    if (typeof e !== "number") throw new TypeError("argument must be a Number");
    if (typeof t !== "number") t = ASN1.Enumeration;
    return this.writeInt(e, t);
};

Writer$2.prototype.writeBoolean = function(e, t) {
    if (typeof e !== "boolean") throw new TypeError("argument must be a Boolean");
    if (typeof t !== "number") t = ASN1.Boolean;
    this._ensure(3);
    this._buf[this._offset++] = t;
    this._buf[this._offset++] = 1;
    this._buf[this._offset++] = e ? 255 : 0;
};

Writer$2.prototype.writeString = function(e, t) {
    if (typeof e !== "string") throw new TypeError("argument must be a string (was: " + typeof e + ")");
    if (typeof t !== "number") t = ASN1.OctetString;
    var r = Buffer$2.byteLength(e);
    this.writeByte(t);
    this.writeLength(r);
    if (r) {
        this._ensure(r);
        this._buf.write(e, this._offset);
        this._offset += r;
    }
};

Writer$2.prototype.writeBuffer = function(e, t) {
    if (typeof t !== "number") throw new TypeError("tag must be a number");
    if (!Buffer$2.isBuffer(e)) throw new TypeError("argument must be a buffer");
    this.writeByte(t);
    this.writeLength(e.length);
    this._ensure(e.length);
    e.copy(this._buf, this._offset, 0, e.length);
    this._offset += e.length;
};

Writer$2.prototype.writeStringArray = function(e) {
    if (!e instanceof Array) throw new TypeError("argument must be an Array[String]");
    var t = this;
    e.forEach(function(e) {
        t.writeString(e);
    });
};

Writer$2.prototype.writeOID = function(e, t) {
    if (typeof e !== "string") throw new TypeError("argument must be a string");
    if (typeof t !== "number") t = ASN1.OID;
    if (!/^([0-9]+\.){3,}[0-9]+$/.test(e)) throw new Error("argument is not a valid OID string");
    function r(e, t) {
        if (t < 128) {
            e.push(t);
        } else if (t < 16384) {
            e.push(t >>> 7 | 128);
            e.push(t & 127);
        } else if (t < 2097152) {
            e.push(t >>> 14 | 128);
            e.push((t >>> 7 | 128) & 255);
            e.push(t & 127);
        } else if (t < 268435456) {
            e.push(t >>> 21 | 128);
            e.push((t >>> 14 | 128) & 255);
            e.push((t >>> 7 | 128) & 255);
            e.push(t & 127);
        } else {
            e.push((t >>> 28 | 128) & 255);
            e.push((t >>> 21 | 128) & 255);
            e.push((t >>> 14 | 128) & 255);
            e.push((t >>> 7 | 128) & 255);
            e.push(t & 127);
        }
    }
    var n = e.split(".");
    var s = [];
    s.push(parseInt(n[0], 10) * 40 + parseInt(n[1], 10));
    n.slice(2).forEach(function(e) {
        r(s, parseInt(e, 10));
    });
    var o = this;
    this._ensure(2 + s.length);
    this.writeByte(t);
    this.writeLength(s.length);
    s.forEach(function(e) {
        o.writeByte(e);
    });
};

Writer$2.prototype.writeLength = function(e) {
    if (typeof e !== "number") throw new TypeError("argument must be a Number");
    this._ensure(4);
    if (e <= 127) {
        this._buf[this._offset++] = e;
    } else if (e <= 255) {
        this._buf[this._offset++] = 129;
        this._buf[this._offset++] = e;
    } else if (e <= 65535) {
        this._buf[this._offset++] = 130;
        this._buf[this._offset++] = e >> 8;
        this._buf[this._offset++] = e;
    } else if (e <= 16777215) {
        this._buf[this._offset++] = 131;
        this._buf[this._offset++] = e >> 16;
        this._buf[this._offset++] = e >> 8;
        this._buf[this._offset++] = e;
    } else {
        throw newInvalidAsn1Error("Length too long (> 4 bytes)");
    }
};

Writer$2.prototype.startSequence = function(e) {
    if (typeof e !== "number") e = ASN1.Sequence | ASN1.Constructor;
    this.writeByte(e);
    this._seq.push(this._offset);
    this._ensure(3);
    this._offset += 3;
};

Writer$2.prototype.endSequence = function() {
    var e = this._seq.pop();
    var t = e + 3;
    var r = this._offset - t;
    if (r <= 127) {
        this._shift(t, r, -2);
        this._buf[e] = r;
    } else if (r <= 255) {
        this._shift(t, r, -1);
        this._buf[e] = 129;
        this._buf[e + 1] = r;
    } else if (r <= 65535) {
        this._buf[e] = 130;
        this._buf[e + 1] = r >> 8;
        this._buf[e + 2] = r;
    } else if (r <= 16777215) {
        this._shift(t, r, 1);
        this._buf[e] = 131;
        this._buf[e + 1] = r >> 16;
        this._buf[e + 2] = r >> 8;
        this._buf[e + 3] = r;
    } else {
        throw newInvalidAsn1Error("Sequence too long");
    }
};

Writer$2.prototype._shift = function(e, t, r) {
    assert$1.ok(e !== undefined);
    assert$1.ok(t !== undefined);
    assert$1.ok(r);
    this._buf.copy(this._buf, e + r, e, e + t);
    this._offset += r;
};

Writer$2.prototype._ensure = function(e) {
    assert$1.ok(e);
    if (this._size - this._offset < e) {
        var t = this._size * this._options.growthFactor;
        if (t - this._offset < e) t += e;
        var r = Buffer$2.alloc(t);
        this._buf.copy(r, 0, 0, this._offset);
        this._buf = r;
        this._size = t;
    }
};

var writer$1 = Writer$2;

ber.exports;

(function(e) {
    var t = errors$3;
    var r = types$2;
    var n = reader$1;
    var s = writer$1;
    e.exports = {
        Reader: n,
        Writer: s
    };
    for (var o in r) {
        if (r.hasOwnProperty(o)) e.exports[o] = r[o];
    }
    for (var a in t) {
        if (t.hasOwnProperty(a)) e.exports[a] = t[a];
    }
})(ber);

var berExports = ber.exports;

var Ber$2 = berExports;

var lib$1 = {
    Ber: Ber$2,
    BerReader: Ber$2.Reader,
    BerWriter: Ber$2.Writer
};

var naclFast = {
    exports: {}
};

naclFast.exports;

(function(e) {
    (function(e) {
        var t = function(e) {
            var t, r = new Float64Array(16);
            if (e) for (t = 0; t < e.length; t++) r[t] = e[t];
            return r;
        };
        var r = function() {
            throw new Error("no PRNG");
        };
        var n = new Uint8Array(16);
        var s = new Uint8Array(32);
        s[0] = 9;
        var o = t(), a = t([ 1 ]), l = t([ 56129, 1 ]), c = t([ 30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995 ]), u = t([ 61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222 ]), d = t([ 54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553 ]), h = t([ 26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214 ]), p = t([ 41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139 ]);
        function g(e, t, r, n) {
            e[t] = r >> 24 & 255;
            e[t + 1] = r >> 16 & 255;
            e[t + 2] = r >> 8 & 255;
            e[t + 3] = r & 255;
            e[t + 4] = n >> 24 & 255;
            e[t + 5] = n >> 16 & 255;
            e[t + 6] = n >> 8 & 255;
            e[t + 7] = n & 255;
        }
        function m(e, t, r, n, s) {
            var o, a = 0;
            for (o = 0; o < s; o++) a |= e[t + o] ^ r[n + o];
            return (1 & a - 1 >>> 8) - 1;
        }
        function _(e, t, r, n) {
            return m(e, t, r, n, 16);
        }
        function E(e, t, r, n) {
            return m(e, t, r, n, 32);
        }
        function v(e, t, r, n) {
            var s = n[0] & 255 | (n[1] & 255) << 8 | (n[2] & 255) << 16 | (n[3] & 255) << 24, o = r[0] & 255 | (r[1] & 255) << 8 | (r[2] & 255) << 16 | (r[3] & 255) << 24, a = r[4] & 255 | (r[5] & 255) << 8 | (r[6] & 255) << 16 | (r[7] & 255) << 24, l = r[8] & 255 | (r[9] & 255) << 8 | (r[10] & 255) << 16 | (r[11] & 255) << 24, c = r[12] & 255 | (r[13] & 255) << 8 | (r[14] & 255) << 16 | (r[15] & 255) << 24, u = n[4] & 255 | (n[5] & 255) << 8 | (n[6] & 255) << 16 | (n[7] & 255) << 24, d = t[0] & 255 | (t[1] & 255) << 8 | (t[2] & 255) << 16 | (t[3] & 255) << 24, h = t[4] & 255 | (t[5] & 255) << 8 | (t[6] & 255) << 16 | (t[7] & 255) << 24, p = t[8] & 255 | (t[9] & 255) << 8 | (t[10] & 255) << 16 | (t[11] & 255) << 24, g = t[12] & 255 | (t[13] & 255) << 8 | (t[14] & 255) << 16 | (t[15] & 255) << 24, m = n[8] & 255 | (n[9] & 255) << 8 | (n[10] & 255) << 16 | (n[11] & 255) << 24, _ = r[16] & 255 | (r[17] & 255) << 8 | (r[18] & 255) << 16 | (r[19] & 255) << 24, E = r[20] & 255 | (r[21] & 255) << 8 | (r[22] & 255) << 16 | (r[23] & 255) << 24, v = r[24] & 255 | (r[25] & 255) << 8 | (r[26] & 255) << 16 | (r[27] & 255) << 24, y = r[28] & 255 | (r[29] & 255) << 8 | (r[30] & 255) << 16 | (r[31] & 255) << 24, S = n[12] & 255 | (n[13] & 255) << 8 | (n[14] & 255) << 16 | (n[15] & 255) << 24;
            var A = s, b = o, C = a, w = l, I = c, T = u, R = d, k = h, P = p, $ = g, O = m, B = _, N = E, D = v, L = y, U = S, M;
            for (var x = 0; x < 20; x += 2) {
                M = A + N | 0;
                I ^= M << 7 | M >>> 32 - 7;
                M = I + A | 0;
                P ^= M << 9 | M >>> 32 - 9;
                M = P + I | 0;
                N ^= M << 13 | M >>> 32 - 13;
                M = N + P | 0;
                A ^= M << 18 | M >>> 32 - 18;
                M = T + b | 0;
                $ ^= M << 7 | M >>> 32 - 7;
                M = $ + T | 0;
                D ^= M << 9 | M >>> 32 - 9;
                M = D + $ | 0;
                b ^= M << 13 | M >>> 32 - 13;
                M = b + D | 0;
                T ^= M << 18 | M >>> 32 - 18;
                M = O + R | 0;
                L ^= M << 7 | M >>> 32 - 7;
                M = L + O | 0;
                C ^= M << 9 | M >>> 32 - 9;
                M = C + L | 0;
                R ^= M << 13 | M >>> 32 - 13;
                M = R + C | 0;
                O ^= M << 18 | M >>> 32 - 18;
                M = U + B | 0;
                w ^= M << 7 | M >>> 32 - 7;
                M = w + U | 0;
                k ^= M << 9 | M >>> 32 - 9;
                M = k + w | 0;
                B ^= M << 13 | M >>> 32 - 13;
                M = B + k | 0;
                U ^= M << 18 | M >>> 32 - 18;
                M = A + w | 0;
                b ^= M << 7 | M >>> 32 - 7;
                M = b + A | 0;
                C ^= M << 9 | M >>> 32 - 9;
                M = C + b | 0;
                w ^= M << 13 | M >>> 32 - 13;
                M = w + C | 0;
                A ^= M << 18 | M >>> 32 - 18;
                M = T + I | 0;
                R ^= M << 7 | M >>> 32 - 7;
                M = R + T | 0;
                k ^= M << 9 | M >>> 32 - 9;
                M = k + R | 0;
                I ^= M << 13 | M >>> 32 - 13;
                M = I + k | 0;
                T ^= M << 18 | M >>> 32 - 18;
                M = O + $ | 0;
                B ^= M << 7 | M >>> 32 - 7;
                M = B + O | 0;
                P ^= M << 9 | M >>> 32 - 9;
                M = P + B | 0;
                $ ^= M << 13 | M >>> 32 - 13;
                M = $ + P | 0;
                O ^= M << 18 | M >>> 32 - 18;
                M = U + L | 0;
                N ^= M << 7 | M >>> 32 - 7;
                M = N + U | 0;
                D ^= M << 9 | M >>> 32 - 9;
                M = D + N | 0;
                L ^= M << 13 | M >>> 32 - 13;
                M = L + D | 0;
                U ^= M << 18 | M >>> 32 - 18;
            }
            A = A + s | 0;
            b = b + o | 0;
            C = C + a | 0;
            w = w + l | 0;
            I = I + c | 0;
            T = T + u | 0;
            R = R + d | 0;
            k = k + h | 0;
            P = P + p | 0;
            $ = $ + g | 0;
            O = O + m | 0;
            B = B + _ | 0;
            N = N + E | 0;
            D = D + v | 0;
            L = L + y | 0;
            U = U + S | 0;
            e[0] = A >>> 0 & 255;
            e[1] = A >>> 8 & 255;
            e[2] = A >>> 16 & 255;
            e[3] = A >>> 24 & 255;
            e[4] = b >>> 0 & 255;
            e[5] = b >>> 8 & 255;
            e[6] = b >>> 16 & 255;
            e[7] = b >>> 24 & 255;
            e[8] = C >>> 0 & 255;
            e[9] = C >>> 8 & 255;
            e[10] = C >>> 16 & 255;
            e[11] = C >>> 24 & 255;
            e[12] = w >>> 0 & 255;
            e[13] = w >>> 8 & 255;
            e[14] = w >>> 16 & 255;
            e[15] = w >>> 24 & 255;
            e[16] = I >>> 0 & 255;
            e[17] = I >>> 8 & 255;
            e[18] = I >>> 16 & 255;
            e[19] = I >>> 24 & 255;
            e[20] = T >>> 0 & 255;
            e[21] = T >>> 8 & 255;
            e[22] = T >>> 16 & 255;
            e[23] = T >>> 24 & 255;
            e[24] = R >>> 0 & 255;
            e[25] = R >>> 8 & 255;
            e[26] = R >>> 16 & 255;
            e[27] = R >>> 24 & 255;
            e[28] = k >>> 0 & 255;
            e[29] = k >>> 8 & 255;
            e[30] = k >>> 16 & 255;
            e[31] = k >>> 24 & 255;
            e[32] = P >>> 0 & 255;
            e[33] = P >>> 8 & 255;
            e[34] = P >>> 16 & 255;
            e[35] = P >>> 24 & 255;
            e[36] = $ >>> 0 & 255;
            e[37] = $ >>> 8 & 255;
            e[38] = $ >>> 16 & 255;
            e[39] = $ >>> 24 & 255;
            e[40] = O >>> 0 & 255;
            e[41] = O >>> 8 & 255;
            e[42] = O >>> 16 & 255;
            e[43] = O >>> 24 & 255;
            e[44] = B >>> 0 & 255;
            e[45] = B >>> 8 & 255;
            e[46] = B >>> 16 & 255;
            e[47] = B >>> 24 & 255;
            e[48] = N >>> 0 & 255;
            e[49] = N >>> 8 & 255;
            e[50] = N >>> 16 & 255;
            e[51] = N >>> 24 & 255;
            e[52] = D >>> 0 & 255;
            e[53] = D >>> 8 & 255;
            e[54] = D >>> 16 & 255;
            e[55] = D >>> 24 & 255;
            e[56] = L >>> 0 & 255;
            e[57] = L >>> 8 & 255;
            e[58] = L >>> 16 & 255;
            e[59] = L >>> 24 & 255;
            e[60] = U >>> 0 & 255;
            e[61] = U >>> 8 & 255;
            e[62] = U >>> 16 & 255;
            e[63] = U >>> 24 & 255;
        }
        function y(e, t, r, n) {
            var s = n[0] & 255 | (n[1] & 255) << 8 | (n[2] & 255) << 16 | (n[3] & 255) << 24, o = r[0] & 255 | (r[1] & 255) << 8 | (r[2] & 255) << 16 | (r[3] & 255) << 24, a = r[4] & 255 | (r[5] & 255) << 8 | (r[6] & 255) << 16 | (r[7] & 255) << 24, l = r[8] & 255 | (r[9] & 255) << 8 | (r[10] & 255) << 16 | (r[11] & 255) << 24, c = r[12] & 255 | (r[13] & 255) << 8 | (r[14] & 255) << 16 | (r[15] & 255) << 24, u = n[4] & 255 | (n[5] & 255) << 8 | (n[6] & 255) << 16 | (n[7] & 255) << 24, d = t[0] & 255 | (t[1] & 255) << 8 | (t[2] & 255) << 16 | (t[3] & 255) << 24, h = t[4] & 255 | (t[5] & 255) << 8 | (t[6] & 255) << 16 | (t[7] & 255) << 24, p = t[8] & 255 | (t[9] & 255) << 8 | (t[10] & 255) << 16 | (t[11] & 255) << 24, g = t[12] & 255 | (t[13] & 255) << 8 | (t[14] & 255) << 16 | (t[15] & 255) << 24, m = n[8] & 255 | (n[9] & 255) << 8 | (n[10] & 255) << 16 | (n[11] & 255) << 24, _ = r[16] & 255 | (r[17] & 255) << 8 | (r[18] & 255) << 16 | (r[19] & 255) << 24, E = r[20] & 255 | (r[21] & 255) << 8 | (r[22] & 255) << 16 | (r[23] & 255) << 24, v = r[24] & 255 | (r[25] & 255) << 8 | (r[26] & 255) << 16 | (r[27] & 255) << 24, y = r[28] & 255 | (r[29] & 255) << 8 | (r[30] & 255) << 16 | (r[31] & 255) << 24, S = n[12] & 255 | (n[13] & 255) << 8 | (n[14] & 255) << 16 | (n[15] & 255) << 24;
            var A = s, b = o, C = a, w = l, I = c, T = u, R = d, k = h, P = p, $ = g, O = m, B = _, N = E, D = v, L = y, U = S, M;
            for (var x = 0; x < 20; x += 2) {
                M = A + N | 0;
                I ^= M << 7 | M >>> 32 - 7;
                M = I + A | 0;
                P ^= M << 9 | M >>> 32 - 9;
                M = P + I | 0;
                N ^= M << 13 | M >>> 32 - 13;
                M = N + P | 0;
                A ^= M << 18 | M >>> 32 - 18;
                M = T + b | 0;
                $ ^= M << 7 | M >>> 32 - 7;
                M = $ + T | 0;
                D ^= M << 9 | M >>> 32 - 9;
                M = D + $ | 0;
                b ^= M << 13 | M >>> 32 - 13;
                M = b + D | 0;
                T ^= M << 18 | M >>> 32 - 18;
                M = O + R | 0;
                L ^= M << 7 | M >>> 32 - 7;
                M = L + O | 0;
                C ^= M << 9 | M >>> 32 - 9;
                M = C + L | 0;
                R ^= M << 13 | M >>> 32 - 13;
                M = R + C | 0;
                O ^= M << 18 | M >>> 32 - 18;
                M = U + B | 0;
                w ^= M << 7 | M >>> 32 - 7;
                M = w + U | 0;
                k ^= M << 9 | M >>> 32 - 9;
                M = k + w | 0;
                B ^= M << 13 | M >>> 32 - 13;
                M = B + k | 0;
                U ^= M << 18 | M >>> 32 - 18;
                M = A + w | 0;
                b ^= M << 7 | M >>> 32 - 7;
                M = b + A | 0;
                C ^= M << 9 | M >>> 32 - 9;
                M = C + b | 0;
                w ^= M << 13 | M >>> 32 - 13;
                M = w + C | 0;
                A ^= M << 18 | M >>> 32 - 18;
                M = T + I | 0;
                R ^= M << 7 | M >>> 32 - 7;
                M = R + T | 0;
                k ^= M << 9 | M >>> 32 - 9;
                M = k + R | 0;
                I ^= M << 13 | M >>> 32 - 13;
                M = I + k | 0;
                T ^= M << 18 | M >>> 32 - 18;
                M = O + $ | 0;
                B ^= M << 7 | M >>> 32 - 7;
                M = B + O | 0;
                P ^= M << 9 | M >>> 32 - 9;
                M = P + B | 0;
                $ ^= M << 13 | M >>> 32 - 13;
                M = $ + P | 0;
                O ^= M << 18 | M >>> 32 - 18;
                M = U + L | 0;
                N ^= M << 7 | M >>> 32 - 7;
                M = N + U | 0;
                D ^= M << 9 | M >>> 32 - 9;
                M = D + N | 0;
                L ^= M << 13 | M >>> 32 - 13;
                M = L + D | 0;
                U ^= M << 18 | M >>> 32 - 18;
            }
            e[0] = A >>> 0 & 255;
            e[1] = A >>> 8 & 255;
            e[2] = A >>> 16 & 255;
            e[3] = A >>> 24 & 255;
            e[4] = T >>> 0 & 255;
            e[5] = T >>> 8 & 255;
            e[6] = T >>> 16 & 255;
            e[7] = T >>> 24 & 255;
            e[8] = O >>> 0 & 255;
            e[9] = O >>> 8 & 255;
            e[10] = O >>> 16 & 255;
            e[11] = O >>> 24 & 255;
            e[12] = U >>> 0 & 255;
            e[13] = U >>> 8 & 255;
            e[14] = U >>> 16 & 255;
            e[15] = U >>> 24 & 255;
            e[16] = R >>> 0 & 255;
            e[17] = R >>> 8 & 255;
            e[18] = R >>> 16 & 255;
            e[19] = R >>> 24 & 255;
            e[20] = k >>> 0 & 255;
            e[21] = k >>> 8 & 255;
            e[22] = k >>> 16 & 255;
            e[23] = k >>> 24 & 255;
            e[24] = P >>> 0 & 255;
            e[25] = P >>> 8 & 255;
            e[26] = P >>> 16 & 255;
            e[27] = P >>> 24 & 255;
            e[28] = $ >>> 0 & 255;
            e[29] = $ >>> 8 & 255;
            e[30] = $ >>> 16 & 255;
            e[31] = $ >>> 24 & 255;
        }
        function S(e, t, r, n) {
            v(e, t, r, n);
        }
        function A(e, t, r, n) {
            y(e, t, r, n);
        }
        var b = new Uint8Array([ 101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107 ]);
        function C(e, t, r, n, s, o, a) {
            var l = new Uint8Array(16), c = new Uint8Array(64);
            var u, d;
            for (d = 0; d < 16; d++) l[d] = 0;
            for (d = 0; d < 8; d++) l[d] = o[d];
            while (s >= 64) {
                S(c, l, a, b);
                for (d = 0; d < 64; d++) e[t + d] = r[n + d] ^ c[d];
                u = 1;
                for (d = 8; d < 16; d++) {
                    u = u + (l[d] & 255) | 0;
                    l[d] = u & 255;
                    u >>>= 8;
                }
                s -= 64;
                t += 64;
                n += 64;
            }
            if (s > 0) {
                S(c, l, a, b);
                for (d = 0; d < s; d++) e[t + d] = r[n + d] ^ c[d];
            }
            return 0;
        }
        function w(e, t, r, n, s) {
            var o = new Uint8Array(16), a = new Uint8Array(64);
            var l, c;
            for (c = 0; c < 16; c++) o[c] = 0;
            for (c = 0; c < 8; c++) o[c] = n[c];
            while (r >= 64) {
                S(a, o, s, b);
                for (c = 0; c < 64; c++) e[t + c] = a[c];
                l = 1;
                for (c = 8; c < 16; c++) {
                    l = l + (o[c] & 255) | 0;
                    o[c] = l & 255;
                    l >>>= 8;
                }
                r -= 64;
                t += 64;
            }
            if (r > 0) {
                S(a, o, s, b);
                for (c = 0; c < r; c++) e[t + c] = a[c];
            }
            return 0;
        }
        function I(e, t, r, n, s) {
            var o = new Uint8Array(32);
            A(o, n, s, b);
            var a = new Uint8Array(8);
            for (var l = 0; l < 8; l++) a[l] = n[l + 16];
            return w(e, t, r, a, o);
        }
        function T(e, t, r, n, s, o, a) {
            var l = new Uint8Array(32);
            A(l, o, a, b);
            var c = new Uint8Array(8);
            for (var u = 0; u < 8; u++) c[u] = o[u + 16];
            return C(e, t, r, n, s, c, l);
        }
        var R = function(e) {
            this.buffer = new Uint8Array(16);
            this.r = new Uint16Array(10);
            this.h = new Uint16Array(10);
            this.pad = new Uint16Array(8);
            this.leftover = 0;
            this.fin = 0;
            var t, r, n, s, o, a, l, c;
            t = e[0] & 255 | (e[1] & 255) << 8;
            this.r[0] = t & 8191;
            r = e[2] & 255 | (e[3] & 255) << 8;
            this.r[1] = (t >>> 13 | r << 3) & 8191;
            n = e[4] & 255 | (e[5] & 255) << 8;
            this.r[2] = (r >>> 10 | n << 6) & 7939;
            s = e[6] & 255 | (e[7] & 255) << 8;
            this.r[3] = (n >>> 7 | s << 9) & 8191;
            o = e[8] & 255 | (e[9] & 255) << 8;
            this.r[4] = (s >>> 4 | o << 12) & 255;
            this.r[5] = o >>> 1 & 8190;
            a = e[10] & 255 | (e[11] & 255) << 8;
            this.r[6] = (o >>> 14 | a << 2) & 8191;
            l = e[12] & 255 | (e[13] & 255) << 8;
            this.r[7] = (a >>> 11 | l << 5) & 8065;
            c = e[14] & 255 | (e[15] & 255) << 8;
            this.r[8] = (l >>> 8 | c << 8) & 8191;
            this.r[9] = c >>> 5 & 127;
            this.pad[0] = e[16] & 255 | (e[17] & 255) << 8;
            this.pad[1] = e[18] & 255 | (e[19] & 255) << 8;
            this.pad[2] = e[20] & 255 | (e[21] & 255) << 8;
            this.pad[3] = e[22] & 255 | (e[23] & 255) << 8;
            this.pad[4] = e[24] & 255 | (e[25] & 255) << 8;
            this.pad[5] = e[26] & 255 | (e[27] & 255) << 8;
            this.pad[6] = e[28] & 255 | (e[29] & 255) << 8;
            this.pad[7] = e[30] & 255 | (e[31] & 255) << 8;
        };
        R.prototype.blocks = function(e, t, r) {
            var n = this.fin ? 0 : 1 << 11;
            var s, o, a, l, c, u, d, h, p;
            var g, m, _, E, v, y, S, A, b, C;
            var w = this.h[0], I = this.h[1], T = this.h[2], R = this.h[3], k = this.h[4], P = this.h[5], $ = this.h[6], O = this.h[7], B = this.h[8], N = this.h[9];
            var D = this.r[0], L = this.r[1], U = this.r[2], M = this.r[3], x = this.r[4], q = this.r[5], H = this.r[6], W = this.r[7], j = this.r[8], Q = this.r[9];
            while (r >= 16) {
                s = e[t + 0] & 255 | (e[t + 1] & 255) << 8;
                w += s & 8191;
                o = e[t + 2] & 255 | (e[t + 3] & 255) << 8;
                I += (s >>> 13 | o << 3) & 8191;
                a = e[t + 4] & 255 | (e[t + 5] & 255) << 8;
                T += (o >>> 10 | a << 6) & 8191;
                l = e[t + 6] & 255 | (e[t + 7] & 255) << 8;
                R += (a >>> 7 | l << 9) & 8191;
                c = e[t + 8] & 255 | (e[t + 9] & 255) << 8;
                k += (l >>> 4 | c << 12) & 8191;
                P += c >>> 1 & 8191;
                u = e[t + 10] & 255 | (e[t + 11] & 255) << 8;
                $ += (c >>> 14 | u << 2) & 8191;
                d = e[t + 12] & 255 | (e[t + 13] & 255) << 8;
                O += (u >>> 11 | d << 5) & 8191;
                h = e[t + 14] & 255 | (e[t + 15] & 255) << 8;
                B += (d >>> 8 | h << 8) & 8191;
                N += h >>> 5 | n;
                p = 0;
                g = p;
                g += w * D;
                g += I * (5 * Q);
                g += T * (5 * j);
                g += R * (5 * W);
                g += k * (5 * H);
                p = g >>> 13;
                g &= 8191;
                g += P * (5 * q);
                g += $ * (5 * x);
                g += O * (5 * M);
                g += B * (5 * U);
                g += N * (5 * L);
                p += g >>> 13;
                g &= 8191;
                m = p;
                m += w * L;
                m += I * D;
                m += T * (5 * Q);
                m += R * (5 * j);
                m += k * (5 * W);
                p = m >>> 13;
                m &= 8191;
                m += P * (5 * H);
                m += $ * (5 * q);
                m += O * (5 * x);
                m += B * (5 * M);
                m += N * (5 * U);
                p += m >>> 13;
                m &= 8191;
                _ = p;
                _ += w * U;
                _ += I * L;
                _ += T * D;
                _ += R * (5 * Q);
                _ += k * (5 * j);
                p = _ >>> 13;
                _ &= 8191;
                _ += P * (5 * W);
                _ += $ * (5 * H);
                _ += O * (5 * q);
                _ += B * (5 * x);
                _ += N * (5 * M);
                p += _ >>> 13;
                _ &= 8191;
                E = p;
                E += w * M;
                E += I * U;
                E += T * L;
                E += R * D;
                E += k * (5 * Q);
                p = E >>> 13;
                E &= 8191;
                E += P * (5 * j);
                E += $ * (5 * W);
                E += O * (5 * H);
                E += B * (5 * q);
                E += N * (5 * x);
                p += E >>> 13;
                E &= 8191;
                v = p;
                v += w * x;
                v += I * M;
                v += T * U;
                v += R * L;
                v += k * D;
                p = v >>> 13;
                v &= 8191;
                v += P * (5 * Q);
                v += $ * (5 * j);
                v += O * (5 * W);
                v += B * (5 * H);
                v += N * (5 * q);
                p += v >>> 13;
                v &= 8191;
                y = p;
                y += w * q;
                y += I * x;
                y += T * M;
                y += R * U;
                y += k * L;
                p = y >>> 13;
                y &= 8191;
                y += P * D;
                y += $ * (5 * Q);
                y += O * (5 * j);
                y += B * (5 * W);
                y += N * (5 * H);
                p += y >>> 13;
                y &= 8191;
                S = p;
                S += w * H;
                S += I * q;
                S += T * x;
                S += R * M;
                S += k * U;
                p = S >>> 13;
                S &= 8191;
                S += P * L;
                S += $ * D;
                S += O * (5 * Q);
                S += B * (5 * j);
                S += N * (5 * W);
                p += S >>> 13;
                S &= 8191;
                A = p;
                A += w * W;
                A += I * H;
                A += T * q;
                A += R * x;
                A += k * M;
                p = A >>> 13;
                A &= 8191;
                A += P * U;
                A += $ * L;
                A += O * D;
                A += B * (5 * Q);
                A += N * (5 * j);
                p += A >>> 13;
                A &= 8191;
                b = p;
                b += w * j;
                b += I * W;
                b += T * H;
                b += R * q;
                b += k * x;
                p = b >>> 13;
                b &= 8191;
                b += P * M;
                b += $ * U;
                b += O * L;
                b += B * D;
                b += N * (5 * Q);
                p += b >>> 13;
                b &= 8191;
                C = p;
                C += w * Q;
                C += I * j;
                C += T * W;
                C += R * H;
                C += k * q;
                p = C >>> 13;
                C &= 8191;
                C += P * x;
                C += $ * M;
                C += O * U;
                C += B * L;
                C += N * D;
                p += C >>> 13;
                C &= 8191;
                p = (p << 2) + p | 0;
                p = p + g | 0;
                g = p & 8191;
                p = p >>> 13;
                m += p;
                w = g;
                I = m;
                T = _;
                R = E;
                k = v;
                P = y;
                $ = S;
                O = A;
                B = b;
                N = C;
                t += 16;
                r -= 16;
            }
            this.h[0] = w;
            this.h[1] = I;
            this.h[2] = T;
            this.h[3] = R;
            this.h[4] = k;
            this.h[5] = P;
            this.h[6] = $;
            this.h[7] = O;
            this.h[8] = B;
            this.h[9] = N;
        };
        R.prototype.finish = function(e, t) {
            var r = new Uint16Array(10);
            var n, s, o, a;
            if (this.leftover) {
                a = this.leftover;
                this.buffer[a++] = 1;
                for (;a < 16; a++) this.buffer[a] = 0;
                this.fin = 1;
                this.blocks(this.buffer, 0, 16);
            }
            n = this.h[1] >>> 13;
            this.h[1] &= 8191;
            for (a = 2; a < 10; a++) {
                this.h[a] += n;
                n = this.h[a] >>> 13;
                this.h[a] &= 8191;
            }
            this.h[0] += n * 5;
            n = this.h[0] >>> 13;
            this.h[0] &= 8191;
            this.h[1] += n;
            n = this.h[1] >>> 13;
            this.h[1] &= 8191;
            this.h[2] += n;
            r[0] = this.h[0] + 5;
            n = r[0] >>> 13;
            r[0] &= 8191;
            for (a = 1; a < 10; a++) {
                r[a] = this.h[a] + n;
                n = r[a] >>> 13;
                r[a] &= 8191;
            }
            r[9] -= 1 << 13;
            s = (n ^ 1) - 1;
            for (a = 0; a < 10; a++) r[a] &= s;
            s = ~s;
            for (a = 0; a < 10; a++) this.h[a] = this.h[a] & s | r[a];
            this.h[0] = (this.h[0] | this.h[1] << 13) & 65535;
            this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535;
            this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535;
            this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535;
            this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535;
            this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535;
            this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535;
            this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535;
            o = this.h[0] + this.pad[0];
            this.h[0] = o & 65535;
            for (a = 1; a < 8; a++) {
                o = (this.h[a] + this.pad[a] | 0) + (o >>> 16) | 0;
                this.h[a] = o & 65535;
            }
            e[t + 0] = this.h[0] >>> 0 & 255;
            e[t + 1] = this.h[0] >>> 8 & 255;
            e[t + 2] = this.h[1] >>> 0 & 255;
            e[t + 3] = this.h[1] >>> 8 & 255;
            e[t + 4] = this.h[2] >>> 0 & 255;
            e[t + 5] = this.h[2] >>> 8 & 255;
            e[t + 6] = this.h[3] >>> 0 & 255;
            e[t + 7] = this.h[3] >>> 8 & 255;
            e[t + 8] = this.h[4] >>> 0 & 255;
            e[t + 9] = this.h[4] >>> 8 & 255;
            e[t + 10] = this.h[5] >>> 0 & 255;
            e[t + 11] = this.h[5] >>> 8 & 255;
            e[t + 12] = this.h[6] >>> 0 & 255;
            e[t + 13] = this.h[6] >>> 8 & 255;
            e[t + 14] = this.h[7] >>> 0 & 255;
            e[t + 15] = this.h[7] >>> 8 & 255;
        };
        R.prototype.update = function(e, t, r) {
            var n, s;
            if (this.leftover) {
                s = 16 - this.leftover;
                if (s > r) s = r;
                for (n = 0; n < s; n++) this.buffer[this.leftover + n] = e[t + n];
                r -= s;
                t += s;
                this.leftover += s;
                if (this.leftover < 16) return;
                this.blocks(this.buffer, 0, 16);
                this.leftover = 0;
            }
            if (r >= 16) {
                s = r - r % 16;
                this.blocks(e, t, s);
                t += s;
                r -= s;
            }
            if (r) {
                for (n = 0; n < r; n++) this.buffer[this.leftover + n] = e[t + n];
                this.leftover += r;
            }
        };
        function k(e, t, r, n, s, o) {
            var a = new R(o);
            a.update(r, n, s);
            a.finish(e, t);
            return 0;
        }
        function P(e, t, r, n, s, o) {
            var a = new Uint8Array(16);
            k(a, 0, r, n, s, o);
            return _(e, t, a, 0);
        }
        function $(e, t, r, n, s) {
            var o;
            if (r < 32) return -1;
            T(e, 0, t, 0, r, n, s);
            k(e, 16, e, 32, r - 32, e);
            for (o = 0; o < 16; o++) e[o] = 0;
            return 0;
        }
        function O(e, t, r, n, s) {
            var o;
            var a = new Uint8Array(32);
            if (r < 32) return -1;
            I(a, 0, 32, n, s);
            if (P(t, 16, t, 32, r - 32, a) !== 0) return -1;
            T(e, 0, t, 0, r, n, s);
            for (o = 0; o < 32; o++) e[o] = 0;
            return 0;
        }
        function B(e, t) {
            var r;
            for (r = 0; r < 16; r++) e[r] = t[r] | 0;
        }
        function N(e) {
            var t, r, n = 1;
            for (t = 0; t < 16; t++) {
                r = e[t] + n + 65535;
                n = Math.floor(r / 65536);
                e[t] = r - n * 65536;
            }
            e[0] += n - 1 + 37 * (n - 1);
        }
        function D(e, t, r) {
            var n, s = ~(r - 1);
            for (var o = 0; o < 16; o++) {
                n = s & (e[o] ^ t[o]);
                e[o] ^= n;
                t[o] ^= n;
            }
        }
        function L(e, r) {
            var n, s, o;
            var a = t(), l = t();
            for (n = 0; n < 16; n++) l[n] = r[n];
            N(l);
            N(l);
            N(l);
            for (s = 0; s < 2; s++) {
                a[0] = l[0] - 65517;
                for (n = 1; n < 15; n++) {
                    a[n] = l[n] - 65535 - (a[n - 1] >> 16 & 1);
                    a[n - 1] &= 65535;
                }
                a[15] = l[15] - 32767 - (a[14] >> 16 & 1);
                o = a[15] >> 16 & 1;
                a[14] &= 65535;
                D(l, a, 1 - o);
            }
            for (n = 0; n < 16; n++) {
                e[2 * n] = l[n] & 255;
                e[2 * n + 1] = l[n] >> 8;
            }
        }
        function U(e, t) {
            var r = new Uint8Array(32), n = new Uint8Array(32);
            L(r, e);
            L(n, t);
            return E(r, 0, n, 0);
        }
        function M(e) {
            var t = new Uint8Array(32);
            L(t, e);
            return t[0] & 1;
        }
        function x(e, t) {
            var r;
            for (r = 0; r < 16; r++) e[r] = t[2 * r] + (t[2 * r + 1] << 8);
            e[15] &= 32767;
        }
        function q(e, t, r) {
            for (var n = 0; n < 16; n++) e[n] = t[n] + r[n];
        }
        function H(e, t, r) {
            for (var n = 0; n < 16; n++) e[n] = t[n] - r[n];
        }
        function W(e, t, r) {
            var n, s, o = 0, a = 0, l = 0, c = 0, u = 0, d = 0, h = 0, p = 0, g = 0, m = 0, _ = 0, E = 0, v = 0, y = 0, S = 0, A = 0, b = 0, C = 0, w = 0, I = 0, T = 0, R = 0, k = 0, P = 0, $ = 0, O = 0, B = 0, N = 0, D = 0, L = 0, U = 0, M = r[0], x = r[1], q = r[2], H = r[3], W = r[4], j = r[5], Q = r[6], G = r[7], K = r[8], z = r[9], Y = r[10], V = r[11], X = r[12], J = r[13], Z = r[14], ee = r[15];
            n = t[0];
            o += n * M;
            a += n * x;
            l += n * q;
            c += n * H;
            u += n * W;
            d += n * j;
            h += n * Q;
            p += n * G;
            g += n * K;
            m += n * z;
            _ += n * Y;
            E += n * V;
            v += n * X;
            y += n * J;
            S += n * Z;
            A += n * ee;
            n = t[1];
            a += n * M;
            l += n * x;
            c += n * q;
            u += n * H;
            d += n * W;
            h += n * j;
            p += n * Q;
            g += n * G;
            m += n * K;
            _ += n * z;
            E += n * Y;
            v += n * V;
            y += n * X;
            S += n * J;
            A += n * Z;
            b += n * ee;
            n = t[2];
            l += n * M;
            c += n * x;
            u += n * q;
            d += n * H;
            h += n * W;
            p += n * j;
            g += n * Q;
            m += n * G;
            _ += n * K;
            E += n * z;
            v += n * Y;
            y += n * V;
            S += n * X;
            A += n * J;
            b += n * Z;
            C += n * ee;
            n = t[3];
            c += n * M;
            u += n * x;
            d += n * q;
            h += n * H;
            p += n * W;
            g += n * j;
            m += n * Q;
            _ += n * G;
            E += n * K;
            v += n * z;
            y += n * Y;
            S += n * V;
            A += n * X;
            b += n * J;
            C += n * Z;
            w += n * ee;
            n = t[4];
            u += n * M;
            d += n * x;
            h += n * q;
            p += n * H;
            g += n * W;
            m += n * j;
            _ += n * Q;
            E += n * G;
            v += n * K;
            y += n * z;
            S += n * Y;
            A += n * V;
            b += n * X;
            C += n * J;
            w += n * Z;
            I += n * ee;
            n = t[5];
            d += n * M;
            h += n * x;
            p += n * q;
            g += n * H;
            m += n * W;
            _ += n * j;
            E += n * Q;
            v += n * G;
            y += n * K;
            S += n * z;
            A += n * Y;
            b += n * V;
            C += n * X;
            w += n * J;
            I += n * Z;
            T += n * ee;
            n = t[6];
            h += n * M;
            p += n * x;
            g += n * q;
            m += n * H;
            _ += n * W;
            E += n * j;
            v += n * Q;
            y += n * G;
            S += n * K;
            A += n * z;
            b += n * Y;
            C += n * V;
            w += n * X;
            I += n * J;
            T += n * Z;
            R += n * ee;
            n = t[7];
            p += n * M;
            g += n * x;
            m += n * q;
            _ += n * H;
            E += n * W;
            v += n * j;
            y += n * Q;
            S += n * G;
            A += n * K;
            b += n * z;
            C += n * Y;
            w += n * V;
            I += n * X;
            T += n * J;
            R += n * Z;
            k += n * ee;
            n = t[8];
            g += n * M;
            m += n * x;
            _ += n * q;
            E += n * H;
            v += n * W;
            y += n * j;
            S += n * Q;
            A += n * G;
            b += n * K;
            C += n * z;
            w += n * Y;
            I += n * V;
            T += n * X;
            R += n * J;
            k += n * Z;
            P += n * ee;
            n = t[9];
            m += n * M;
            _ += n * x;
            E += n * q;
            v += n * H;
            y += n * W;
            S += n * j;
            A += n * Q;
            b += n * G;
            C += n * K;
            w += n * z;
            I += n * Y;
            T += n * V;
            R += n * X;
            k += n * J;
            P += n * Z;
            $ += n * ee;
            n = t[10];
            _ += n * M;
            E += n * x;
            v += n * q;
            y += n * H;
            S += n * W;
            A += n * j;
            b += n * Q;
            C += n * G;
            w += n * K;
            I += n * z;
            T += n * Y;
            R += n * V;
            k += n * X;
            P += n * J;
            $ += n * Z;
            O += n * ee;
            n = t[11];
            E += n * M;
            v += n * x;
            y += n * q;
            S += n * H;
            A += n * W;
            b += n * j;
            C += n * Q;
            w += n * G;
            I += n * K;
            T += n * z;
            R += n * Y;
            k += n * V;
            P += n * X;
            $ += n * J;
            O += n * Z;
            B += n * ee;
            n = t[12];
            v += n * M;
            y += n * x;
            S += n * q;
            A += n * H;
            b += n * W;
            C += n * j;
            w += n * Q;
            I += n * G;
            T += n * K;
            R += n * z;
            k += n * Y;
            P += n * V;
            $ += n * X;
            O += n * J;
            B += n * Z;
            N += n * ee;
            n = t[13];
            y += n * M;
            S += n * x;
            A += n * q;
            b += n * H;
            C += n * W;
            w += n * j;
            I += n * Q;
            T += n * G;
            R += n * K;
            k += n * z;
            P += n * Y;
            $ += n * V;
            O += n * X;
            B += n * J;
            N += n * Z;
            D += n * ee;
            n = t[14];
            S += n * M;
            A += n * x;
            b += n * q;
            C += n * H;
            w += n * W;
            I += n * j;
            T += n * Q;
            R += n * G;
            k += n * K;
            P += n * z;
            $ += n * Y;
            O += n * V;
            B += n * X;
            N += n * J;
            D += n * Z;
            L += n * ee;
            n = t[15];
            A += n * M;
            b += n * x;
            C += n * q;
            w += n * H;
            I += n * W;
            T += n * j;
            R += n * Q;
            k += n * G;
            P += n * K;
            $ += n * z;
            O += n * Y;
            B += n * V;
            N += n * X;
            D += n * J;
            L += n * Z;
            U += n * ee;
            o += 38 * b;
            a += 38 * C;
            l += 38 * w;
            c += 38 * I;
            u += 38 * T;
            d += 38 * R;
            h += 38 * k;
            p += 38 * P;
            g += 38 * $;
            m += 38 * O;
            _ += 38 * B;
            E += 38 * N;
            v += 38 * D;
            y += 38 * L;
            S += 38 * U;
            s = 1;
            n = o + s + 65535;
            s = Math.floor(n / 65536);
            o = n - s * 65536;
            n = a + s + 65535;
            s = Math.floor(n / 65536);
            a = n - s * 65536;
            n = l + s + 65535;
            s = Math.floor(n / 65536);
            l = n - s * 65536;
            n = c + s + 65535;
            s = Math.floor(n / 65536);
            c = n - s * 65536;
            n = u + s + 65535;
            s = Math.floor(n / 65536);
            u = n - s * 65536;
            n = d + s + 65535;
            s = Math.floor(n / 65536);
            d = n - s * 65536;
            n = h + s + 65535;
            s = Math.floor(n / 65536);
            h = n - s * 65536;
            n = p + s + 65535;
            s = Math.floor(n / 65536);
            p = n - s * 65536;
            n = g + s + 65535;
            s = Math.floor(n / 65536);
            g = n - s * 65536;
            n = m + s + 65535;
            s = Math.floor(n / 65536);
            m = n - s * 65536;
            n = _ + s + 65535;
            s = Math.floor(n / 65536);
            _ = n - s * 65536;
            n = E + s + 65535;
            s = Math.floor(n / 65536);
            E = n - s * 65536;
            n = v + s + 65535;
            s = Math.floor(n / 65536);
            v = n - s * 65536;
            n = y + s + 65535;
            s = Math.floor(n / 65536);
            y = n - s * 65536;
            n = S + s + 65535;
            s = Math.floor(n / 65536);
            S = n - s * 65536;
            n = A + s + 65535;
            s = Math.floor(n / 65536);
            A = n - s * 65536;
            o += s - 1 + 37 * (s - 1);
            s = 1;
            n = o + s + 65535;
            s = Math.floor(n / 65536);
            o = n - s * 65536;
            n = a + s + 65535;
            s = Math.floor(n / 65536);
            a = n - s * 65536;
            n = l + s + 65535;
            s = Math.floor(n / 65536);
            l = n - s * 65536;
            n = c + s + 65535;
            s = Math.floor(n / 65536);
            c = n - s * 65536;
            n = u + s + 65535;
            s = Math.floor(n / 65536);
            u = n - s * 65536;
            n = d + s + 65535;
            s = Math.floor(n / 65536);
            d = n - s * 65536;
            n = h + s + 65535;
            s = Math.floor(n / 65536);
            h = n - s * 65536;
            n = p + s + 65535;
            s = Math.floor(n / 65536);
            p = n - s * 65536;
            n = g + s + 65535;
            s = Math.floor(n / 65536);
            g = n - s * 65536;
            n = m + s + 65535;
            s = Math.floor(n / 65536);
            m = n - s * 65536;
            n = _ + s + 65535;
            s = Math.floor(n / 65536);
            _ = n - s * 65536;
            n = E + s + 65535;
            s = Math.floor(n / 65536);
            E = n - s * 65536;
            n = v + s + 65535;
            s = Math.floor(n / 65536);
            v = n - s * 65536;
            n = y + s + 65535;
            s = Math.floor(n / 65536);
            y = n - s * 65536;
            n = S + s + 65535;
            s = Math.floor(n / 65536);
            S = n - s * 65536;
            n = A + s + 65535;
            s = Math.floor(n / 65536);
            A = n - s * 65536;
            o += s - 1 + 37 * (s - 1);
            e[0] = o;
            e[1] = a;
            e[2] = l;
            e[3] = c;
            e[4] = u;
            e[5] = d;
            e[6] = h;
            e[7] = p;
            e[8] = g;
            e[9] = m;
            e[10] = _;
            e[11] = E;
            e[12] = v;
            e[13] = y;
            e[14] = S;
            e[15] = A;
        }
        function j(e, t) {
            W(e, t, t);
        }
        function Q(e, r) {
            var n = t();
            var s;
            for (s = 0; s < 16; s++) n[s] = r[s];
            for (s = 253; s >= 0; s--) {
                j(n, n);
                if (s !== 2 && s !== 4) W(n, n, r);
            }
            for (s = 0; s < 16; s++) e[s] = n[s];
        }
        function G(e, r) {
            var n = t();
            var s;
            for (s = 0; s < 16; s++) n[s] = r[s];
            for (s = 250; s >= 0; s--) {
                j(n, n);
                if (s !== 1) W(n, n, r);
            }
            for (s = 0; s < 16; s++) e[s] = n[s];
        }
        function K(e, r, n) {
            var s = new Uint8Array(32);
            var o = new Float64Array(80), a, c;
            var u = t(), d = t(), h = t(), p = t(), g = t(), m = t();
            for (c = 0; c < 31; c++) s[c] = r[c];
            s[31] = r[31] & 127 | 64;
            s[0] &= 248;
            x(o, n);
            for (c = 0; c < 16; c++) {
                d[c] = o[c];
                p[c] = u[c] = h[c] = 0;
            }
            u[0] = p[0] = 1;
            for (c = 254; c >= 0; --c) {
                a = s[c >>> 3] >>> (c & 7) & 1;
                D(u, d, a);
                D(h, p, a);
                q(g, u, h);
                H(u, u, h);
                q(h, d, p);
                H(d, d, p);
                j(p, g);
                j(m, u);
                W(u, h, u);
                W(h, d, g);
                q(g, u, h);
                H(u, u, h);
                j(d, u);
                H(h, p, m);
                W(u, h, l);
                q(u, u, p);
                W(h, h, u);
                W(u, p, m);
                W(p, d, o);
                j(d, g);
                D(u, d, a);
                D(h, p, a);
            }
            for (c = 0; c < 16; c++) {
                o[c + 16] = u[c];
                o[c + 32] = h[c];
                o[c + 48] = d[c];
                o[c + 64] = p[c];
            }
            var _ = o.subarray(32);
            var E = o.subarray(16);
            Q(_, _);
            W(E, E, _);
            L(e, E);
            return 0;
        }
        function z(e, t) {
            return K(e, t, s);
        }
        function Y(e, t) {
            r(t, 32);
            return z(e, t);
        }
        function V(e, t, r) {
            var s = new Uint8Array(32);
            K(s, r, t);
            return A(e, n, s, b);
        }
        var X = $;
        var J = O;
        function Z(e, t, r, n, s, o) {
            var a = new Uint8Array(32);
            V(a, s, o);
            return X(e, t, r, n, a);
        }
        function ee(e, t, r, n, s, o) {
            var a = new Uint8Array(32);
            V(a, s, o);
            return J(e, t, r, n, a);
        }
        var te = [ 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591 ];
        function re(e, t, r, n) {
            var s = new Int32Array(16), o = new Int32Array(16), a, l, c, u, d, h, p, g, m, _, E, v, y, S, A, b, C, w, I, T, R, k, P, $, O, B;
            var N = e[0], D = e[1], L = e[2], U = e[3], M = e[4], x = e[5], q = e[6], H = e[7], W = t[0], j = t[1], Q = t[2], G = t[3], K = t[4], z = t[5], Y = t[6], V = t[7];
            var X = 0;
            while (n >= 128) {
                for (I = 0; I < 16; I++) {
                    T = 8 * I + X;
                    s[I] = r[T + 0] << 24 | r[T + 1] << 16 | r[T + 2] << 8 | r[T + 3];
                    o[I] = r[T + 4] << 24 | r[T + 5] << 16 | r[T + 6] << 8 | r[T + 7];
                }
                for (I = 0; I < 80; I++) {
                    a = N;
                    l = D;
                    c = L;
                    u = U;
                    d = M;
                    h = x;
                    p = q;
                    g = H;
                    m = W;
                    _ = j;
                    E = Q;
                    v = G;
                    y = K;
                    S = z;
                    A = Y;
                    b = V;
                    R = H;
                    k = V;
                    P = k & 65535;
                    $ = k >>> 16;
                    O = R & 65535;
                    B = R >>> 16;
                    R = (M >>> 14 | K << 32 - 14) ^ (M >>> 18 | K << 32 - 18) ^ (K >>> 41 - 32 | M << 32 - (41 - 32));
                    k = (K >>> 14 | M << 32 - 14) ^ (K >>> 18 | M << 32 - 18) ^ (M >>> 41 - 32 | K << 32 - (41 - 32));
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    R = M & x ^ ~M & q;
                    k = K & z ^ ~K & Y;
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    R = te[I * 2];
                    k = te[I * 2 + 1];
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    R = s[I % 16];
                    k = o[I % 16];
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    $ += P >>> 16;
                    O += $ >>> 16;
                    B += O >>> 16;
                    C = O & 65535 | B << 16;
                    w = P & 65535 | $ << 16;
                    R = C;
                    k = w;
                    P = k & 65535;
                    $ = k >>> 16;
                    O = R & 65535;
                    B = R >>> 16;
                    R = (N >>> 28 | W << 32 - 28) ^ (W >>> 34 - 32 | N << 32 - (34 - 32)) ^ (W >>> 39 - 32 | N << 32 - (39 - 32));
                    k = (W >>> 28 | N << 32 - 28) ^ (N >>> 34 - 32 | W << 32 - (34 - 32)) ^ (N >>> 39 - 32 | W << 32 - (39 - 32));
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    R = N & D ^ N & L ^ D & L;
                    k = W & j ^ W & Q ^ j & Q;
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    $ += P >>> 16;
                    O += $ >>> 16;
                    B += O >>> 16;
                    g = O & 65535 | B << 16;
                    b = P & 65535 | $ << 16;
                    R = u;
                    k = v;
                    P = k & 65535;
                    $ = k >>> 16;
                    O = R & 65535;
                    B = R >>> 16;
                    R = C;
                    k = w;
                    P += k & 65535;
                    $ += k >>> 16;
                    O += R & 65535;
                    B += R >>> 16;
                    $ += P >>> 16;
                    O += $ >>> 16;
                    B += O >>> 16;
                    u = O & 65535 | B << 16;
                    v = P & 65535 | $ << 16;
                    D = a;
                    L = l;
                    U = c;
                    M = u;
                    x = d;
                    q = h;
                    H = p;
                    N = g;
                    j = m;
                    Q = _;
                    G = E;
                    K = v;
                    z = y;
                    Y = S;
                    V = A;
                    W = b;
                    if (I % 16 === 15) {
                        for (T = 0; T < 16; T++) {
                            R = s[T];
                            k = o[T];
                            P = k & 65535;
                            $ = k >>> 16;
                            O = R & 65535;
                            B = R >>> 16;
                            R = s[(T + 9) % 16];
                            k = o[(T + 9) % 16];
                            P += k & 65535;
                            $ += k >>> 16;
                            O += R & 65535;
                            B += R >>> 16;
                            C = s[(T + 1) % 16];
                            w = o[(T + 1) % 16];
                            R = (C >>> 1 | w << 32 - 1) ^ (C >>> 8 | w << 32 - 8) ^ C >>> 7;
                            k = (w >>> 1 | C << 32 - 1) ^ (w >>> 8 | C << 32 - 8) ^ (w >>> 7 | C << 32 - 7);
                            P += k & 65535;
                            $ += k >>> 16;
                            O += R & 65535;
                            B += R >>> 16;
                            C = s[(T + 14) % 16];
                            w = o[(T + 14) % 16];
                            R = (C >>> 19 | w << 32 - 19) ^ (w >>> 61 - 32 | C << 32 - (61 - 32)) ^ C >>> 6;
                            k = (w >>> 19 | C << 32 - 19) ^ (C >>> 61 - 32 | w << 32 - (61 - 32)) ^ (w >>> 6 | C << 32 - 6);
                            P += k & 65535;
                            $ += k >>> 16;
                            O += R & 65535;
                            B += R >>> 16;
                            $ += P >>> 16;
                            O += $ >>> 16;
                            B += O >>> 16;
                            s[T] = O & 65535 | B << 16;
                            o[T] = P & 65535 | $ << 16;
                        }
                    }
                }
                R = N;
                k = W;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[0];
                k = t[0];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[0] = N = O & 65535 | B << 16;
                t[0] = W = P & 65535 | $ << 16;
                R = D;
                k = j;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[1];
                k = t[1];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[1] = D = O & 65535 | B << 16;
                t[1] = j = P & 65535 | $ << 16;
                R = L;
                k = Q;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[2];
                k = t[2];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[2] = L = O & 65535 | B << 16;
                t[2] = Q = P & 65535 | $ << 16;
                R = U;
                k = G;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[3];
                k = t[3];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[3] = U = O & 65535 | B << 16;
                t[3] = G = P & 65535 | $ << 16;
                R = M;
                k = K;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[4];
                k = t[4];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[4] = M = O & 65535 | B << 16;
                t[4] = K = P & 65535 | $ << 16;
                R = x;
                k = z;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[5];
                k = t[5];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[5] = x = O & 65535 | B << 16;
                t[5] = z = P & 65535 | $ << 16;
                R = q;
                k = Y;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[6];
                k = t[6];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[6] = q = O & 65535 | B << 16;
                t[6] = Y = P & 65535 | $ << 16;
                R = H;
                k = V;
                P = k & 65535;
                $ = k >>> 16;
                O = R & 65535;
                B = R >>> 16;
                R = e[7];
                k = t[7];
                P += k & 65535;
                $ += k >>> 16;
                O += R & 65535;
                B += R >>> 16;
                $ += P >>> 16;
                O += $ >>> 16;
                B += O >>> 16;
                e[7] = H = O & 65535 | B << 16;
                t[7] = V = P & 65535 | $ << 16;
                X += 128;
                n -= 128;
            }
            return n;
        }
        function ne(e, t, r) {
            var n = new Int32Array(8), s = new Int32Array(8), o = new Uint8Array(256), a, l = r;
            n[0] = 1779033703;
            n[1] = 3144134277;
            n[2] = 1013904242;
            n[3] = 2773480762;
            n[4] = 1359893119;
            n[5] = 2600822924;
            n[6] = 528734635;
            n[7] = 1541459225;
            s[0] = 4089235720;
            s[1] = 2227873595;
            s[2] = 4271175723;
            s[3] = 1595750129;
            s[4] = 2917565137;
            s[5] = 725511199;
            s[6] = 4215389547;
            s[7] = 327033209;
            re(n, s, t, r);
            r %= 128;
            for (a = 0; a < r; a++) o[a] = t[l - r + a];
            o[r] = 128;
            r = 256 - 128 * (r < 112 ? 1 : 0);
            o[r - 9] = 0;
            g(o, r - 8, l / 536870912 | 0, l << 3);
            re(n, s, o, r);
            for (a = 0; a < 8; a++) g(e, 8 * a, n[a], s[a]);
            return 0;
        }
        function ie(e, r) {
            var n = t(), s = t(), o = t(), a = t(), l = t(), c = t(), d = t(), h = t(), p = t();
            H(n, e[1], e[0]);
            H(p, r[1], r[0]);
            W(n, n, p);
            q(s, e[0], e[1]);
            q(p, r[0], r[1]);
            W(s, s, p);
            W(o, e[3], r[3]);
            W(o, o, u);
            W(a, e[2], r[2]);
            q(a, a, a);
            H(l, s, n);
            H(c, a, o);
            q(d, a, o);
            q(h, s, n);
            W(e[0], l, c);
            W(e[1], h, d);
            W(e[2], d, c);
            W(e[3], l, h);
        }
        function se(e, t, r) {
            var n;
            for (n = 0; n < 4; n++) {
                D(e[n], t[n], r);
            }
        }
        function oe(e, r) {
            var n = t(), s = t(), o = t();
            Q(o, r[2]);
            W(n, r[0], o);
            W(s, r[1], o);
            L(e, s);
            e[31] ^= M(n) << 7;
        }
        function ae(e, t, r) {
            var n, s;
            B(e[0], o);
            B(e[1], a);
            B(e[2], a);
            B(e[3], o);
            for (s = 255; s >= 0; --s) {
                n = r[s / 8 | 0] >> (s & 7) & 1;
                se(e, t, n);
                ie(t, e);
                ie(e, e);
                se(e, t, n);
            }
        }
        function le(e, r) {
            var n = [ t(), t(), t(), t() ];
            B(n[0], d);
            B(n[1], h);
            B(n[2], a);
            W(n[3], d, h);
            ae(e, n, r);
        }
        function ce(e, n, s) {
            var o = new Uint8Array(64);
            var a = [ t(), t(), t(), t() ];
            var l;
            if (!s) r(n, 32);
            ne(o, n, 32);
            o[0] &= 248;
            o[31] &= 127;
            o[31] |= 64;
            le(a, o);
            oe(e, a);
            for (l = 0; l < 32; l++) n[l + 32] = e[l];
            return 0;
        }
        var ue = new Float64Array([ 237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 ]);
        function fe(e, t) {
            var r, n, s, o;
            for (n = 63; n >= 32; --n) {
                r = 0;
                for (s = n - 32, o = n - 12; s < o; ++s) {
                    t[s] += r - 16 * t[n] * ue[s - (n - 32)];
                    r = t[s] + 128 >> 8;
                    t[s] -= r * 256;
                }
                t[s] += r;
                t[n] = 0;
            }
            r = 0;
            for (s = 0; s < 32; s++) {
                t[s] += r - (t[31] >> 4) * ue[s];
                r = t[s] >> 8;
                t[s] &= 255;
            }
            for (s = 0; s < 32; s++) t[s] -= r * ue[s];
            for (n = 0; n < 32; n++) {
                t[n + 1] += t[n] >> 8;
                e[n] = t[n] & 255;
            }
        }
        function de(e) {
            var t = new Float64Array(64), r;
            for (r = 0; r < 64; r++) t[r] = e[r];
            for (r = 0; r < 64; r++) e[r] = 0;
            fe(e, t);
        }
        function he(e, r, n, s) {
            var o = new Uint8Array(64), a = new Uint8Array(64), l = new Uint8Array(64);
            var c, u, d = new Float64Array(64);
            var h = [ t(), t(), t(), t() ];
            ne(o, s, 32);
            o[0] &= 248;
            o[31] &= 127;
            o[31] |= 64;
            var p = n + 64;
            for (c = 0; c < n; c++) e[64 + c] = r[c];
            for (c = 0; c < 32; c++) e[32 + c] = o[32 + c];
            ne(l, e.subarray(32), n + 32);
            de(l);
            le(h, l);
            oe(e, h);
            for (c = 32; c < 64; c++) e[c] = s[c];
            ne(a, e, n + 64);
            de(a);
            for (c = 0; c < 64; c++) d[c] = 0;
            for (c = 0; c < 32; c++) d[c] = l[c];
            for (c = 0; c < 32; c++) {
                for (u = 0; u < 32; u++) {
                    d[c + u] += a[c] * o[u];
                }
            }
            fe(e.subarray(32), d);
            return p;
        }
        function pe(e, r) {
            var n = t(), s = t(), l = t(), u = t(), d = t(), h = t(), g = t();
            B(e[2], a);
            x(e[1], r);
            j(l, e[1]);
            W(u, l, c);
            H(l, l, e[2]);
            q(u, e[2], u);
            j(d, u);
            j(h, d);
            W(g, h, d);
            W(n, g, l);
            W(n, n, u);
            G(n, n);
            W(n, n, l);
            W(n, n, u);
            W(n, n, u);
            W(e[0], n, u);
            j(s, e[0]);
            W(s, s, u);
            if (U(s, l)) W(e[0], e[0], p);
            j(s, e[0]);
            W(s, s, u);
            if (U(s, l)) return -1;
            if (M(e[0]) === r[31] >> 7) H(e[0], o, e[0]);
            W(e[3], e[0], e[1]);
            return 0;
        }
        function ge(e, r, n, s) {
            var o, a;
            var l = new Uint8Array(32), c = new Uint8Array(64);
            var u = [ t(), t(), t(), t() ], d = [ t(), t(), t(), t() ];
            a = -1;
            if (n < 64) return -1;
            if (pe(d, s)) return -1;
            for (o = 0; o < n; o++) e[o] = r[o];
            for (o = 0; o < 32; o++) e[o + 32] = s[o];
            ne(c, e, n);
            de(c);
            ae(u, d, c);
            le(d, r.subarray(32));
            ie(u, d);
            oe(l, u);
            n -= 64;
            if (E(r, 0, l, 0)) {
                for (o = 0; o < n; o++) e[o] = 0;
                return -1;
            }
            for (o = 0; o < n; o++) e[o] = r[o + 64];
            a = n;
            return a;
        }
        var me = 32, _e = 24, Ee = 32, ve = 16, ye = 32, Se = 32, Ae = 32, be = 32, Ce = 32, we = _e, Ie = Ee, Te = ve, Re = 64, ke = 32, Pe = 64, $e = 32, Oe = 64;
        e.lowlevel = {
            crypto_core_hsalsa20: A,
            crypto_stream_xor: T,
            crypto_stream: I,
            crypto_stream_salsa20_xor: C,
            crypto_stream_salsa20: w,
            crypto_onetimeauth: k,
            crypto_onetimeauth_verify: P,
            crypto_verify_16: _,
            crypto_verify_32: E,
            crypto_secretbox: $,
            crypto_secretbox_open: O,
            crypto_scalarmult: K,
            crypto_scalarmult_base: z,
            crypto_box_beforenm: V,
            crypto_box_afternm: X,
            crypto_box: Z,
            crypto_box_open: ee,
            crypto_box_keypair: Y,
            crypto_hash: ne,
            crypto_sign: he,
            crypto_sign_keypair: ce,
            crypto_sign_open: ge,
            crypto_secretbox_KEYBYTES: me,
            crypto_secretbox_NONCEBYTES: _e,
            crypto_secretbox_ZEROBYTES: Ee,
            crypto_secretbox_BOXZEROBYTES: ve,
            crypto_scalarmult_BYTES: ye,
            crypto_scalarmult_SCALARBYTES: Se,
            crypto_box_PUBLICKEYBYTES: Ae,
            crypto_box_SECRETKEYBYTES: be,
            crypto_box_BEFORENMBYTES: Ce,
            crypto_box_NONCEBYTES: we,
            crypto_box_ZEROBYTES: Ie,
            crypto_box_BOXZEROBYTES: Te,
            crypto_sign_BYTES: Re,
            crypto_sign_PUBLICKEYBYTES: ke,
            crypto_sign_SECRETKEYBYTES: Pe,
            crypto_sign_SEEDBYTES: $e,
            crypto_hash_BYTES: Oe
        };
        function Be(e, t) {
            if (e.length !== me) throw new Error("bad key size");
            if (t.length !== _e) throw new Error("bad nonce size");
        }
        function Ne(e, t) {
            if (e.length !== Ae) throw new Error("bad public key size");
            if (t.length !== be) throw new Error("bad secret key size");
        }
        function De() {
            var e, t;
            for (t = 0; t < arguments.length; t++) {
                if ((e = Object.prototype.toString.call(arguments[t])) !== "[object Uint8Array]") throw new TypeError("unexpected type " + e + ", use Uint8Array");
            }
        }
        function Le(e) {
            for (var t = 0; t < e.length; t++) e[t] = 0;
        }
        if (!e.util) {
            e.util = {};
            e.util.decodeUTF8 = e.util.encodeUTF8 = e.util.encodeBase64 = e.util.decodeBase64 = function() {
                throw new Error("nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js");
            };
        }
        e.randomBytes = function(e) {
            var t = new Uint8Array(e);
            r(t, e);
            return t;
        };
        e.secretbox = function(e, t, r) {
            De(e, t, r);
            Be(r, t);
            var n = new Uint8Array(Ee + e.length);
            var s = new Uint8Array(n.length);
            for (var o = 0; o < e.length; o++) n[o + Ee] = e[o];
            $(s, n, n.length, t, r);
            return s.subarray(ve);
        };
        e.secretbox.open = function(e, t, r) {
            De(e, t, r);
            Be(r, t);
            var n = new Uint8Array(ve + e.length);
            var s = new Uint8Array(n.length);
            for (var o = 0; o < e.length; o++) n[o + ve] = e[o];
            if (n.length < 32) return false;
            if (O(s, n, n.length, t, r) !== 0) return false;
            return s.subarray(Ee);
        };
        e.secretbox.keyLength = me;
        e.secretbox.nonceLength = _e;
        e.secretbox.overheadLength = ve;
        e.scalarMult = function(e, t) {
            De(e, t);
            if (e.length !== Se) throw new Error("bad n size");
            if (t.length !== ye) throw new Error("bad p size");
            var r = new Uint8Array(ye);
            K(r, e, t);
            return r;
        };
        e.scalarMult.base = function(e) {
            De(e);
            if (e.length !== Se) throw new Error("bad n size");
            var t = new Uint8Array(ye);
            z(t, e);
            return t;
        };
        e.scalarMult.scalarLength = Se;
        e.scalarMult.groupElementLength = ye;
        e.box = function(t, r, n, s) {
            var o = e.box.before(n, s);
            return e.secretbox(t, r, o);
        };
        e.box.before = function(e, t) {
            De(e, t);
            Ne(e, t);
            var r = new Uint8Array(Ce);
            V(r, e, t);
            return r;
        };
        e.box.after = e.secretbox;
        e.box.open = function(t, r, n, s) {
            var o = e.box.before(n, s);
            return e.secretbox.open(t, r, o);
        };
        e.box.open.after = e.secretbox.open;
        e.box.keyPair = function() {
            var e = new Uint8Array(Ae);
            var t = new Uint8Array(be);
            Y(e, t);
            return {
                publicKey: e,
                secretKey: t
            };
        };
        e.box.keyPair.fromSecretKey = function(e) {
            De(e);
            if (e.length !== be) throw new Error("bad secret key size");
            var t = new Uint8Array(Ae);
            z(t, e);
            return {
                publicKey: t,
                secretKey: new Uint8Array(e)
            };
        };
        e.box.publicKeyLength = Ae;
        e.box.secretKeyLength = be;
        e.box.sharedKeyLength = Ce;
        e.box.nonceLength = we;
        e.box.overheadLength = e.secretbox.overheadLength;
        e.sign = function(e, t) {
            De(e, t);
            if (t.length !== Pe) throw new Error("bad secret key size");
            var r = new Uint8Array(Re + e.length);
            he(r, e, e.length, t);
            return r;
        };
        e.sign.open = function(e, t) {
            if (arguments.length !== 2) throw new Error("nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?");
            De(e, t);
            if (t.length !== ke) throw new Error("bad public key size");
            var r = new Uint8Array(e.length);
            var n = ge(r, e, e.length, t);
            if (n < 0) return null;
            var s = new Uint8Array(n);
            for (var o = 0; o < s.length; o++) s[o] = r[o];
            return s;
        };
        e.sign.detached = function(t, r) {
            var n = e.sign(t, r);
            var s = new Uint8Array(Re);
            for (var o = 0; o < s.length; o++) s[o] = n[o];
            return s;
        };
        e.sign.detached.verify = function(e, t, r) {
            De(e, t, r);
            if (t.length !== Re) throw new Error("bad signature size");
            if (r.length !== ke) throw new Error("bad public key size");
            var n = new Uint8Array(Re + e.length);
            var s = new Uint8Array(Re + e.length);
            var o;
            for (o = 0; o < Re; o++) n[o] = t[o];
            for (o = 0; o < e.length; o++) n[o + Re] = e[o];
            return ge(s, n, n.length, r) >= 0;
        };
        e.sign.keyPair = function() {
            var e = new Uint8Array(ke);
            var t = new Uint8Array(Pe);
            ce(e, t);
            return {
                publicKey: e,
                secretKey: t
            };
        };
        e.sign.keyPair.fromSecretKey = function(e) {
            De(e);
            if (e.length !== Pe) throw new Error("bad secret key size");
            var t = new Uint8Array(ke);
            for (var r = 0; r < t.length; r++) t[r] = e[32 + r];
            return {
                publicKey: t,
                secretKey: new Uint8Array(e)
            };
        };
        e.sign.keyPair.fromSeed = function(e) {
            De(e);
            if (e.length !== $e) throw new Error("bad seed size");
            var t = new Uint8Array(ke);
            var r = new Uint8Array(Pe);
            for (var n = 0; n < 32; n++) r[n] = e[n];
            ce(t, r, true);
            return {
                publicKey: t,
                secretKey: r
            };
        };
        e.sign.publicKeyLength = ke;
        e.sign.secretKeyLength = Pe;
        e.sign.seedLength = $e;
        e.sign.signatureLength = Re;
        e.hash = function(e) {
            De(e);
            var t = new Uint8Array(Oe);
            ne(t, e, e.length);
            return t;
        };
        e.hash.hashLength = Oe;
        e.verify = function(e, t) {
            De(e, t);
            if (e.length === 0 || t.length === 0) return false;
            if (e.length !== t.length) return false;
            return m(e, 0, t, 0, e.length) === 0 ? true : false;
        };
        e.setPRNG = function(e) {
            r = e;
        };
        (function() {
            var t = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
            if (t && t.getRandomValues) {
                var r = 65536;
                e.setPRNG(function(e, n) {
                    var s, o = new Uint8Array(n);
                    for (s = 0; s < n; s += r) {
                        t.getRandomValues(o.subarray(s, s + Math.min(n - s, r)));
                    }
                    for (s = 0; s < n; s++) e[s] = o[s];
                    Le(o);
                });
            } else if (typeof _commonjsDynamicModules.commonjsRequire !== "undefined") {
                t = require$$0__default$3.default;
                if (t && t.randomBytes) {
                    e.setPRNG(function(e, r) {
                        var n, s = t.randomBytes(r);
                        for (n = 0; n < r; n++) e[n] = s[n];
                        Le(s);
                    });
                }
            }
        })();
    })(e.exports ? e.exports : self.nacl = self.nacl || {});
})(naclFast);

var naclFastExports = naclFast.exports;

var crypto_hash_sha512 = naclFastExports.lowlevel.crypto_hash;

var BLF_J = 0;

var Blowfish = function() {
    this.S = [ new Uint32Array([ 3509652390, 2564797868, 805139163, 3491422135, 3101798381, 1780907670, 3128725573, 4046225305, 614570311, 3012652279, 134345442, 2240740374, 1667834072, 1901547113, 2757295779, 4103290238, 227898511, 1921955416, 1904987480, 2182433518, 2069144605, 3260701109, 2620446009, 720527379, 3318853667, 677414384, 3393288472, 3101374703, 2390351024, 1614419982, 1822297739, 2954791486, 3608508353, 3174124327, 2024746970, 1432378464, 3864339955, 2857741204, 1464375394, 1676153920, 1439316330, 715854006, 3033291828, 289532110, 2706671279, 2087905683, 3018724369, 1668267050, 732546397, 1947742710, 3462151702, 2609353502, 2950085171, 1814351708, 2050118529, 680887927, 999245976, 1800124847, 3300911131, 1713906067, 1641548236, 4213287313, 1216130144, 1575780402, 4018429277, 3917837745, 3693486850, 3949271944, 596196993, 3549867205, 258830323, 2213823033, 772490370, 2760122372, 1774776394, 2652871518, 566650946, 4142492826, 1728879713, 2882767088, 1783734482, 3629395816, 2517608232, 2874225571, 1861159788, 326777828, 3124490320, 2130389656, 2716951837, 967770486, 1724537150, 2185432712, 2364442137, 1164943284, 2105845187, 998989502, 3765401048, 2244026483, 1075463327, 1455516326, 1322494562, 910128902, 469688178, 1117454909, 936433444, 3490320968, 3675253459, 1240580251, 122909385, 2157517691, 634681816, 4142456567, 3825094682, 3061402683, 2540495037, 79693498, 3249098678, 1084186820, 1583128258, 426386531, 1761308591, 1047286709, 322548459, 995290223, 1845252383, 2603652396, 3431023940, 2942221577, 3202600964, 3727903485, 1712269319, 422464435, 3234572375, 1170764815, 3523960633, 3117677531, 1434042557, 442511882, 3600875718, 1076654713, 1738483198, 4213154764, 2393238008, 3677496056, 1014306527, 4251020053, 793779912, 2902807211, 842905082, 4246964064, 1395751752, 1040244610, 2656851899, 3396308128, 445077038, 3742853595, 3577915638, 679411651, 2892444358, 2354009459, 1767581616, 3150600392, 3791627101, 3102740896, 284835224, 4246832056, 1258075500, 768725851, 2589189241, 3069724005, 3532540348, 1274779536, 3789419226, 2764799539, 1660621633, 3471099624, 4011903706, 913787905, 3497959166, 737222580, 2514213453, 2928710040, 3937242737, 1804850592, 3499020752, 2949064160, 2386320175, 2390070455, 2415321851, 4061277028, 2290661394, 2416832540, 1336762016, 1754252060, 3520065937, 3014181293, 791618072, 3188594551, 3933548030, 2332172193, 3852520463, 3043980520, 413987798, 3465142937, 3030929376, 4245938359, 2093235073, 3534596313, 375366246, 2157278981, 2479649556, 555357303, 3870105701, 2008414854, 3344188149, 4221384143, 3956125452, 2067696032, 3594591187, 2921233993, 2428461, 544322398, 577241275, 1471733935, 610547355, 4027169054, 1432588573, 1507829418, 2025931657, 3646575487, 545086370, 48609733, 2200306550, 1653985193, 298326376, 1316178497, 3007786442, 2064951626, 458293330, 2589141269, 3591329599, 3164325604, 727753846, 2179363840, 146436021, 1461446943, 4069977195, 705550613, 3059967265, 3887724982, 4281599278, 3313849956, 1404054877, 2845806497, 146425753, 1854211946 ]), new Uint32Array([ 1266315497, 3048417604, 3681880366, 3289982499, 290971e4, 1235738493, 2632868024, 2414719590, 3970600049, 1771706367, 1449415276, 3266420449, 422970021, 1963543593, 2690192192, 3826793022, 1062508698, 1531092325, 1804592342, 2583117782, 2714934279, 4024971509, 1294809318, 4028980673, 1289560198, 2221992742, 1669523910, 35572830, 157838143, 1052438473, 1016535060, 1802137761, 1753167236, 1386275462, 3080475397, 2857371447, 1040679964, 2145300060, 2390574316, 1461121720, 2956646967, 4031777805, 4028374788, 33600511, 2920084762, 1018524850, 629373528, 3691585981, 3515945977, 2091462646, 2486323059, 586499841, 988145025, 935516892, 3367335476, 2599673255, 2839830854, 265290510, 3972581182, 2759138881, 3795373465, 1005194799, 847297441, 406762289, 1314163512, 1332590856, 1866599683, 4127851711, 750260880, 613907577, 1450815602, 3165620655, 3734664991, 3650291728, 3012275730, 3704569646, 1427272223, 778793252, 1343938022, 2676280711, 2052605720, 1946737175, 3164576444, 3914038668, 3967478842, 3682934266, 1661551462, 3294938066, 4011595847, 840292616, 3712170807, 616741398, 312560963, 711312465, 1351876610, 322626781, 1910503582, 271666773, 2175563734, 1594956187, 70604529, 3617834859, 1007753275, 1495573769, 4069517037, 2549218298, 2663038764, 504708206, 2263041392, 3941167025, 2249088522, 1514023603, 1998579484, 1312622330, 694541497, 2582060303, 2151582166, 1382467621, 776784248, 2618340202, 3323268794, 2497899128, 2784771155, 503983604, 4076293799, 907881277, 423175695, 432175456, 1378068232, 4145222326, 3954048622, 3938656102, 3820766613, 2793130115, 2977904593, 26017576, 3274890735, 3194772133, 1700274565, 1756076034, 4006520079, 3677328699, 720338349, 1533947780, 354530856, 688349552, 3973924725, 1637815568, 332179504, 3949051286, 53804574, 2852348879, 3044236432, 1282449977, 3583942155, 3416972820, 4006381244, 1617046695, 2628476075, 3002303598, 1686838959, 431878346, 2686675385, 1700445008, 1080580658, 1009431731, 832498133, 3223435511, 2605976345, 2271191193, 2516031870, 1648197032, 4164389018, 2548247927, 300782431, 375919233, 238389289, 3353747414, 2531188641, 2019080857, 1475708069, 455242339, 2609103871, 448939670, 3451063019, 1395535956, 2413381860, 1841049896, 1491858159, 885456874, 4264095073, 4001119347, 1565136089, 3898914787, 1108368660, 540939232, 1173283510, 2745871338, 3681308437, 4207628240, 3343053890, 4016749493, 1699691293, 1103962373, 3625875870, 2256883143, 3830138730, 1031889488, 3479347698, 1535977030, 4236805024, 3251091107, 2132092099, 1774941330, 1199868427, 1452454533, 157007616, 2904115357, 342012276, 595725824, 1480756522, 206960106, 497939518, 591360097, 863170706, 2375253569, 3596610801, 1814182875, 2094937945, 3421402208, 1082520231, 3463918190, 2785509508, 435703966, 3908032597, 1641649973, 2842273706, 3305899714, 1510255612, 2148256476, 2655287854, 3276092548, 4258621189, 236887753, 3681803219, 274041037, 1734335097, 3815195456, 3317970021, 1899903192, 1026095262, 4050517792, 356393447, 2410691914, 3873677099, 3682840055 ]), new Uint32Array([ 3913112168, 2491498743, 4132185628, 2489919796, 1091903735, 1979897079, 3170134830, 3567386728, 3557303409, 857797738, 1136121015, 1342202287, 507115054, 2535736646, 337727348, 3213592640, 1301675037, 2528481711, 1895095763, 1721773893, 3216771564, 62756741, 2142006736, 835421444, 2531993523, 1442658625, 3659876326, 2882144922, 676362277, 1392781812, 170690266, 3921047035, 1759253602, 3611846912, 1745797284, 664899054, 1329594018, 3901205900, 3045908486, 2062866102, 2865634940, 3543621612, 3464012697, 1080764994, 553557557, 3656615353, 3996768171, 991055499, 499776247, 1265440854, 648242737, 3940784050, 980351604, 3713745714, 1749149687, 3396870395, 4211799374, 3640570775, 1161844396, 3125318951, 1431517754, 545492359, 4268468663, 3499529547, 1437099964, 2702547544, 3433638243, 2581715763, 2787789398, 1060185593, 1593081372, 2418618748, 4260947970, 69676912, 2159744348, 86519011, 2512459080, 3838209314, 1220612927, 3339683548, 133810670, 1090789135, 1078426020, 1569222167, 845107691, 3583754449, 4072456591, 1091646820, 628848692, 1613405280, 3757631651, 526609435, 236106946, 48312990, 2942717905, 3402727701, 1797494240, 859738849, 992217954, 4005476642, 2243076622, 3870952857, 3732016268, 765654824, 3490871365, 2511836413, 1685915746, 3888969200, 1414112111, 2273134842, 3281911079, 4080962846, 172450625, 2569994100, 980381355, 4109958455, 2819808352, 2716589560, 2568741196, 3681446669, 3329971472, 1835478071, 660984891, 3704678404, 4045999559, 3422617507, 3040415634, 1762651403, 1719377915, 3470491036, 2693910283, 3642056355, 3138596744, 1364962596, 2073328063, 1983633131, 926494387, 3423689081, 2150032023, 4096667949, 1749200295, 3328846651, 309677260, 2016342300, 1779581495, 3079819751, 111262694, 1274766160, 443224088, 298511866, 1025883608, 3806446537, 1145181785, 168956806, 3641502830, 3584813610, 1689216846, 3666258015, 3200248200, 1692713982, 2646376535, 4042768518, 1618508792, 1610833997, 3523052358, 4130873264, 2001055236, 3610705100, 2202168115, 4028541809, 2961195399, 1006657119, 2006996926, 3186142756, 1430667929, 3210227297, 1314452623, 4074634658, 4101304120, 2273951170, 1399257539, 3367210612, 3027628629, 1190975929, 2062231137, 2333990788, 2221543033, 2438960610, 1181637006, 548689776, 2362791313, 3372408396, 3104550113, 3145860560, 296247880, 1970579870, 3078560182, 3769228297, 1714227617, 3291629107, 3898220290, 166772364, 1251581989, 493813264, 448347421, 195405023, 2709975567, 677966185, 3703036547, 1463355134, 2715995803, 1338867538, 1343315457, 2802222074, 2684532164, 233230375, 2599980071, 2000651841, 3277868038, 1638401717, 4028070440, 3237316320, 6314154, 819756386, 300326615, 590932579, 1405279636, 3267499572, 3150704214, 2428286686, 3959192993, 3461946742, 1862657033, 1266418056, 963775037, 2089974820, 2263052895, 1917689273, 448879540, 3550394620, 3981727096, 150775221, 3627908307, 1303187396, 508620638, 2975983352, 2726630617, 1817252668, 1876281319, 1457606340, 908771278, 3720792119, 3617206836, 2455994898, 1729034894, 1080033504 ]), new Uint32Array([ 976866871, 3556439503, 2881648439, 1522871579, 1555064734, 1336096578, 3548522304, 2579274686, 3574697629, 3205460757, 3593280638, 3338716283, 3079412587, 564236357, 2993598910, 1781952180, 1464380207, 3163844217, 3332601554, 1699332808, 1393555694, 1183702653, 3581086237, 1288719814, 691649499, 2847557200, 2895455976, 3193889540, 2717570544, 1781354906, 1676643554, 2592534050, 3230253752, 1126444790, 2770207658, 2633158820, 2210423226, 2615765581, 2414155088, 3127139286, 673620729, 2805611233, 1269405062, 4015350505, 3341807571, 4149409754, 1057255273, 2012875353, 2162469141, 2276492801, 2601117357, 993977747, 3918593370, 2654263191, 753973209, 36408145, 2530585658, 25011837, 3520020182, 2088578344, 530523599, 2918365339, 1524020338, 1518925132, 3760827505, 3759777254, 1202760957, 3985898139, 3906192525, 674977740, 4174734889, 2031300136, 2019492241, 3983892565, 4153806404, 3822280332, 352677332, 2297720250, 60907813, 90501309, 3286998549, 1016092578, 2535922412, 2839152426, 457141659, 509813237, 4120667899, 652014361, 1966332200, 2975202805, 55981186, 2327461051, 676427537, 3255491064, 2882294119, 3433927263, 1307055953, 942726286, 933058658, 2468411793, 3933900994, 4215176142, 1361170020, 2001714738, 2830558078, 3274259782, 1222529897, 1679025792, 2729314320, 3714953764, 1770335741, 151462246, 3013232138, 1682292957, 1483529935, 471910574, 1539241949, 458788160, 3436315007, 1807016891, 3718408830, 978976581, 1043663428, 3165965781, 1927990952, 4200891579, 2372276910, 3208408903, 3533431907, 1412390302, 2931980059, 4132332400, 1947078029, 3881505623, 4168226417, 2941484381, 1077988104, 1320477388, 886195818, 18198404, 3786409e3, 2509781533, 112762804, 3463356488, 1866414978, 891333506, 18488651, 661792760, 1628790961, 3885187036, 3141171499, 876946877, 2693282273, 1372485963, 791857591, 2686433993, 3759982718, 3167212022, 3472953795, 2716379847, 445679433, 3561995674, 3504004811, 3574258232, 54117162, 3331405415, 2381918588, 3769707343, 4154350007, 1140177722, 4074052095, 668550556, 3214352940, 367459370, 261225585, 2610173221, 4209349473, 3468074219, 3265815641, 314222801, 3066103646, 3808782860, 282218597, 3406013506, 3773591054, 379116347, 1285071038, 846784868, 2669647154, 3771962079, 3550491691, 2305946142, 453669953, 1268987020, 3317592352, 3279303384, 3744833421, 2610507566, 3859509063, 266596637, 3847019092, 517658769, 3462560207, 3443424879, 370717030, 4247526661, 2224018117, 4143653529, 4112773975, 2788324899, 2477274417, 1456262402, 2901442914, 1517677493, 1846949527, 2295493580, 3734397586, 2176403920, 1280348187, 1908823572, 3871786941, 846861322, 1172426758, 3287448474, 3383383037, 1655181056, 3139813346, 901632758, 1897031941, 2986607138, 3066810236, 3447102507, 1393639104, 373351379, 950779232, 625454576, 3124240540, 4148612726, 2007998917, 544563296, 2244738638, 2330496472, 2058025392, 1291430526, 424198748, 50039436, 29584100, 3605783033, 2429876329, 2791104160, 1057563949, 3255363231, 3075367218, 3463963227, 1469046755, 985887462 ]) ];
    this.P = new Uint32Array([ 608135816, 2242054355, 320440878, 57701188, 2752067618, 698298832, 137296536, 3964562569, 1160258022, 953160567, 3193202383, 887688300, 3232508343, 3380367581, 1065670069, 3041331479, 2450970073, 2306472731 ]);
};

function F(e, t, r) {
    return (e[0][t[r + 3]] + e[1][t[r + 2]] ^ e[2][t[r + 1]]) + e[3][t[r]];
}

Blowfish.prototype.encipher = function(e, t) {
    if (t === undefined) {
        t = new Uint8Array(e.buffer);
        if (e.byteOffset !== 0) t = t.subarray(e.byteOffset);
    }
    e[0] ^= this.P[0];
    for (var r = 1; r < 16; r += 2) {
        e[1] ^= F(this.S, t, 0) ^ this.P[r];
        e[0] ^= F(this.S, t, 4) ^ this.P[r + 1];
    }
    var n = e[0];
    e[0] = e[1] ^ this.P[17];
    e[1] = n;
};

Blowfish.prototype.decipher = function(e) {
    var t = new Uint8Array(e.buffer);
    if (e.byteOffset !== 0) t = t.subarray(e.byteOffset);
    e[0] ^= this.P[17];
    for (var r = 16; r > 0; r -= 2) {
        e[1] ^= F(this.S, t, 0) ^ this.P[r];
        e[0] ^= F(this.S, t, 4) ^ this.P[r - 1];
    }
    var n = e[0];
    e[0] = e[1] ^ this.P[0];
    e[1] = n;
};

function stream2word(e, t) {
    var r, n = 0;
    for (r = 0; r < 4; r++, BLF_J++) {
        if (BLF_J >= t) BLF_J = 0;
        n = n << 8 | e[BLF_J];
    }
    return n;
}

Blowfish.prototype.expand0state = function(e, t) {
    var r = new Uint32Array(2), n, s;
    var o = new Uint8Array(r.buffer);
    for (n = 0, BLF_J = 0; n < 18; n++) {
        this.P[n] ^= stream2word(e, t);
    }
    BLF_J = 0;
    for (n = 0; n < 18; n += 2) {
        this.encipher(r, o);
        this.P[n] = r[0];
        this.P[n + 1] = r[1];
    }
    for (n = 0; n < 4; n++) {
        for (s = 0; s < 256; s += 2) {
            this.encipher(r, o);
            this.S[n][s] = r[0];
            this.S[n][s + 1] = r[1];
        }
    }
};

Blowfish.prototype.expandstate = function(e, t, r, n) {
    var s = new Uint32Array(2), o, a;
    for (o = 0, BLF_J = 0; o < 18; o++) {
        this.P[o] ^= stream2word(r, n);
    }
    for (o = 0, BLF_J = 0; o < 18; o += 2) {
        s[0] ^= stream2word(e, t);
        s[1] ^= stream2word(e, t);
        this.encipher(s);
        this.P[o] = s[0];
        this.P[o + 1] = s[1];
    }
    for (o = 0; o < 4; o++) {
        for (a = 0; a < 256; a += 2) {
            s[0] ^= stream2word(e, t);
            s[1] ^= stream2word(e, t);
            this.encipher(s);
            this.S[o][a] = s[0];
            this.S[o][a + 1] = s[1];
        }
    }
    BLF_J = 0;
};

Blowfish.prototype.enc = function(e, t) {
    for (var r = 0; r < t; r++) {
        this.encipher(e.subarray(r * 2));
    }
};

Blowfish.prototype.dec = function(e, t) {
    for (var r = 0; r < t; r++) {
        this.decipher(e.subarray(r * 2));
    }
};

var BCRYPT_BLOCKS = 8, BCRYPT_HASHSIZE = 32;

function bcrypt_hash(e, t, r) {
    var n = new Blowfish, s = new Uint32Array(BCRYPT_BLOCKS), o, a = new Uint8Array([ 79, 120, 121, 99, 104, 114, 111, 109, 97, 116, 105, 99, 66, 108, 111, 119, 102, 105, 115, 104, 83, 119, 97, 116, 68, 121, 110, 97, 109, 105, 116, 101 ]);
    n.expandstate(t, 64, e, 64);
    for (o = 0; o < 64; o++) {
        n.expand0state(t, 64);
        n.expand0state(e, 64);
    }
    for (o = 0; o < BCRYPT_BLOCKS; o++) s[o] = stream2word(a, a.byteLength);
    for (o = 0; o < 64; o++) n.enc(s, s.byteLength / 8);
    for (o = 0; o < BCRYPT_BLOCKS; o++) {
        r[4 * o + 3] = s[o] >>> 24;
        r[4 * o + 2] = s[o] >>> 16;
        r[4 * o + 1] = s[o] >>> 8;
        r[4 * o + 0] = s[o];
    }
}

function bcrypt_pbkdf$2(e, t, r, n, s, o, a) {
    var l = new Uint8Array(64), c = new Uint8Array(64), u = new Uint8Array(BCRYPT_HASHSIZE), d = new Uint8Array(BCRYPT_HASHSIZE), h = new Uint8Array(n + 4), p, g, m, _, E, v, y = o;
    if (a < 1) return -1;
    if (t === 0 || n === 0 || o === 0 || o > u.byteLength * u.byteLength || n > 1 << 20) return -1;
    _ = Math.floor((o + u.byteLength - 1) / u.byteLength);
    m = Math.floor((o + _ - 1) / _);
    for (p = 0; p < n; p++) h[p] = r[p];
    crypto_hash_sha512(l, e, t);
    for (v = 1; o > 0; v++) {
        h[n + 0] = v >>> 24;
        h[n + 1] = v >>> 16;
        h[n + 2] = v >>> 8;
        h[n + 3] = v;
        crypto_hash_sha512(c, h, n + 4);
        bcrypt_hash(l, c, d);
        for (p = u.byteLength; p--; ) u[p] = d[p];
        for (p = 1; p < a; p++) {
            crypto_hash_sha512(c, d, d.byteLength);
            bcrypt_hash(l, c, d);
            for (g = 0; g < u.byteLength; g++) u[g] ^= d[g];
        }
        m = Math.min(m, o);
        for (p = 0; p < m; p++) {
            E = p * _ + (v - 1);
            if (E >= y) break;
            s[E] = u[p];
        }
        o -= p;
    }
    return 0;
}

var bcryptPbkdf = {
    BLOCKS: BCRYPT_BLOCKS,
    HASHSIZE: BCRYPT_HASHSIZE,
    hash: bcrypt_hash,
    pbkdf: bcrypt_pbkdf$2
};

var constants$3 = {
    exports: {}
};

constants$3.exports;

var hasRequiredConstants;

function requireConstants() {
    if (hasRequiredConstants) return constants$3.exports;
    hasRequiredConstants = 1;
    (function(e) {
        const t = require$$0__default$3.default;
        let r;
        try {
            r = require("cpu-features")();
        } catch {}
        const {bindingAvailable: n, CIPHER_INFO: s, MAC_INFO: o} = requireCrypto();
        const a = (() => {
            if (typeof t.sign === "function" && typeof t.verify === "function") {
                const e = "-----BEGIN PRIVATE KEY-----\r\nMC4CAQAwBQYDK2VwBCIEIHKj+sVa9WcD" + "/q2DJUJaf43Kptc8xYuUQA4bOFj9vC8T\r\n-----END PRIVATE KEY-----";
                const r = Buffer.from("a");
                let n;
                let s;
                try {
                    n = t.sign(null, r, e);
                    s = t.verify(null, r, e, n);
                } catch {}
                return Buffer.isBuffer(n) && n.length === 64 && s === true;
            }
            return false;
        })();
        const l = typeof t.diffieHellman === "function" && typeof t.generateKeyPairSync === "function" && typeof t.createPublicKey === "function";
        const c = [ "ecdh-sha2-nistp256", "ecdh-sha2-nistp384", "ecdh-sha2-nistp521", "diffie-hellman-group-exchange-sha256", "diffie-hellman-group14-sha256", "diffie-hellman-group15-sha512", "diffie-hellman-group16-sha512", "diffie-hellman-group17-sha512", "diffie-hellman-group18-sha512" ];
        if (l) {
            c.unshift("curve25519-sha256");
            c.unshift("curve25519-sha256@libssh.org");
        }
        const u = c.concat([ "diffie-hellman-group-exchange-sha1", "diffie-hellman-group14-sha1", "diffie-hellman-group1-sha1" ]);
        const d = [ "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "rsa-sha2-512", "rsa-sha2-256", "ssh-rsa" ];
        if (a) d.unshift("ssh-ed25519");
        const h = d.concat([ "ssh-dss" ]);
        const p = (() => {
            const e = t.getCiphers();
            return t => e.includes(s[t].sslName);
        })();
        let g = [ "aes128-gcm@openssh.com", "aes256-gcm@openssh.com", "aes128-ctr", "aes192-ctr", "aes256-ctr" ];
        if (r && r.flags && !r.flags.aes) {
            if (n) g.unshift("chacha20-poly1305@openssh.com"); else g.push("chacha20-poly1305@openssh.com");
        } else if (n && r && r.arch === "x86") {
            g.splice(4, 0, "chacha20-poly1305@openssh.com");
        } else {
            g.push("chacha20-poly1305@openssh.com");
        }
        g = g.filter(p);
        const m = g.concat([ "aes256-cbc", "aes192-cbc", "aes128-cbc", "blowfish-cbc", "3des-cbc", "aes128-gcm", "aes256-gcm", "arcfour256", "arcfour128", "cast128-cbc", "arcfour" ].filter(p));
        const _ = (() => {
            const e = t.getHashes();
            return t => e.includes(o[t].sslName);
        })();
        const E = [ "hmac-sha2-256-etm@openssh.com", "hmac-sha2-512-etm@openssh.com", "hmac-sha1-etm@openssh.com", "hmac-sha2-256", "hmac-sha2-512", "hmac-sha1" ].filter(_);
        const v = E.concat([ "hmac-md5", "hmac-sha2-256-96", "hmac-sha2-512-96", "hmac-ripemd160", "hmac-sha1-96", "hmac-md5-96" ].filter(_));
        const y = [ "none", "zlib@openssh.com", "zlib" ];
        const S = y.concat([]);
        const A = {
            BAD_DHGEX: 1 << 0,
            OLD_EXIT: 1 << 1,
            DYN_RPORT_BUG: 1 << 2,
            BUG_DHGEX_LARGE: 1 << 3,
            IMPLY_RSA_SHA2_SIGALGS: 1 << 4
        };
        e.exports = {
            MESSAGE: {
                DISCONNECT: 1,
                IGNORE: 2,
                UNIMPLEMENTED: 3,
                DEBUG: 4,
                SERVICE_REQUEST: 5,
                SERVICE_ACCEPT: 6,
                EXT_INFO: 7,
                KEXINIT: 20,
                NEWKEYS: 21,
                KEXDH_INIT: 30,
                KEXDH_REPLY: 31,
                KEXDH_GEX_GROUP: 31,
                KEXDH_GEX_INIT: 32,
                KEXDH_GEX_REPLY: 33,
                KEXDH_GEX_REQUEST: 34,
                KEXECDH_INIT: 30,
                KEXECDH_REPLY: 31,
                USERAUTH_REQUEST: 50,
                USERAUTH_FAILURE: 51,
                USERAUTH_SUCCESS: 52,
                USERAUTH_BANNER: 53,
                USERAUTH_PASSWD_CHANGEREQ: 60,
                USERAUTH_PK_OK: 60,
                USERAUTH_INFO_REQUEST: 60,
                USERAUTH_INFO_RESPONSE: 61,
                GLOBAL_REQUEST: 80,
                REQUEST_SUCCESS: 81,
                REQUEST_FAILURE: 82,
                CHANNEL_OPEN: 90,
                CHANNEL_OPEN_CONFIRMATION: 91,
                CHANNEL_OPEN_FAILURE: 92,
                CHANNEL_WINDOW_ADJUST: 93,
                CHANNEL_DATA: 94,
                CHANNEL_EXTENDED_DATA: 95,
                CHANNEL_EOF: 96,
                CHANNEL_CLOSE: 97,
                CHANNEL_REQUEST: 98,
                CHANNEL_SUCCESS: 99,
                CHANNEL_FAILURE: 100
            },
            DISCONNECT_REASON: {
                HOST_NOT_ALLOWED_TO_CONNECT: 1,
                PROTOCOL_ERROR: 2,
                KEY_EXCHANGE_FAILED: 3,
                RESERVED: 4,
                MAC_ERROR: 5,
                COMPRESSION_ERROR: 6,
                SERVICE_NOT_AVAILABLE: 7,
                PROTOCOL_VERSION_NOT_SUPPORTED: 8,
                HOST_KEY_NOT_VERIFIABLE: 9,
                CONNECTION_LOST: 10,
                BY_APPLICATION: 11,
                TOO_MANY_CONNECTIONS: 12,
                AUTH_CANCELED_BY_USER: 13,
                NO_MORE_AUTH_METHODS_AVAILABLE: 14,
                ILLEGAL_USER_NAME: 15
            },
            DISCONNECT_REASON_STR: undefined,
            CHANNEL_OPEN_FAILURE: {
                ADMINISTRATIVELY_PROHIBITED: 1,
                CONNECT_FAILED: 2,
                UNKNOWN_CHANNEL_TYPE: 3,
                RESOURCE_SHORTAGE: 4
            },
            TERMINAL_MODE: {
                TTY_OP_END: 0,
                VINTR: 1,
                VQUIT: 2,
                VERASE: 3,
                VKILL: 4,
                VEOF: 5,
                VEOL: 6,
                VEOL2: 7,
                VSTART: 8,
                VSTOP: 9,
                VSUSP: 10,
                VDSUSP: 11,
                VREPRINT: 12,
                VWERASE: 13,
                VLNEXT: 14,
                VFLUSH: 15,
                VSWTCH: 16,
                VSTATUS: 17,
                VDISCARD: 18,
                IGNPAR: 30,
                PARMRK: 31,
                INPCK: 32,
                ISTRIP: 33,
                INLCR: 34,
                IGNCR: 35,
                ICRNL: 36,
                IUCLC: 37,
                IXON: 38,
                IXANY: 39,
                IXOFF: 40,
                IMAXBEL: 41,
                ISIG: 50,
                ICANON: 51,
                XCASE: 52,
                ECHO: 53,
                ECHOE: 54,
                ECHOK: 55,
                ECHONL: 56,
                NOFLSH: 57,
                TOSTOP: 58,
                IEXTEN: 59,
                ECHOCTL: 60,
                ECHOKE: 61,
                PENDIN: 62,
                OPOST: 70,
                OLCUC: 71,
                ONLCR: 72,
                OCRNL: 73,
                ONOCR: 74,
                ONLRET: 75,
                CS7: 90,
                CS8: 91,
                PARENB: 92,
                PARODD: 93,
                TTY_OP_ISPEED: 128,
                TTY_OP_OSPEED: 129
            },
            CHANNEL_EXTENDED_DATATYPE: {
                STDERR: 1
            },
            SIGNALS: [ "ABRT", "ALRM", "FPE", "HUP", "ILL", "INT", "QUIT", "SEGV", "TERM", "USR1", "USR2", "KILL", "PIPE" ].reduce((e, t) => ({
                ...e,
                [t]: 1
            }), {}),
            COMPAT: A,
            COMPAT_CHECKS: [ [ "Cisco-1.25", A.BAD_DHGEX ], [ /^Cisco-1[.]/, A.BUG_DHGEX_LARGE ], [ /^[0-9.]+$/, A.OLD_EXIT ], [ /^OpenSSH_5[.][0-9]+/, A.DYN_RPORT_BUG ], [ /^OpenSSH_7[.]4/, A.IMPLY_RSA_SHA2_SIGALGS ] ],
            DEFAULT_KEX: c,
            SUPPORTED_KEX: u,
            DEFAULT_SERVER_HOST_KEY: d,
            SUPPORTED_SERVER_HOST_KEY: h,
            DEFAULT_CIPHER: g,
            SUPPORTED_CIPHER: m,
            DEFAULT_MAC: E,
            SUPPORTED_MAC: v,
            DEFAULT_COMPRESSION: y,
            SUPPORTED_COMPRESSION: S,
            curve25519Supported: l,
            eddsaSupported: a
        };
        e.exports.DISCONNECT_REASON_BY_VALUE = Array.from(Object.entries(e.exports.DISCONNECT_REASON)).reduce((e, [t, r]) => ({
            ...e,
            [r]: t
        }), {});
    })(constants$3);
    return constants$3.exports;
}

var utils$2;

var hasRequiredUtils;

function requireUtils() {
    if (hasRequiredUtils) return utils$2;
    hasRequiredUtils = 1;
    const e = lib$1.Ber;
    let t;
    const r = Buffer[Symbol.species];
    const n = Object.getPrototypeOf(Uint8Array.prototype).fill;
    function s(e, t) {
        return e[t++] * 16777216 + e[t++] * 65536 + e[t++] * 256 + e[t];
    }
    function o(e, t, r, n, s) {
        if (!s) s = 0;
        if (n > e.length) n = e.length;
        let o = n - r;
        const a = t.length - s;
        if (o > a) o = a;
        t.set(new Uint8Array(e.buffer, e.byteOffset + r, o), s);
        return o;
    }
    function a(e, t, n) {
        if (n === undefined) n = e.length;
        return new r(e.buffer, e.byteOffset + t, n - t);
    }
    function l() {
        let e = 0;
        let t;
        const r = {
            init: (r, n) => {
                t = r;
                e = typeof n === "number" ? n : 0;
            },
            pos: () => e,
            length: () => t ? t.length : 0,
            avail: () => t && e < t.length ? t.length - e : 0,
            clear: () => {
                t = undefined;
            },
            readUInt32BE: () => {
                if (!t || e + 3 >= t.length) return;
                return t[e++] * 16777216 + t[e++] * 65536 + t[e++] * 256 + t[e++];
            },
            readUInt64BE: r => {
                if (!t || e + 7 >= t.length) return;
                switch (r) {
                  case "always":
                    return BigInt(`0x${t.hexSlice(e, e += 8)}`);

                  case "maybe":
                    if (t[e] > 31) return BigInt(`0x${t.hexSlice(e, e += 8)}`);

                  default:
                    return t[e++] * 72057594037927940 + t[e++] * 281474976710656 + t[e++] * 1099511627776 + t[e++] * 4294967296 + t[e++] * 16777216 + t[e++] * 65536 + t[e++] * 256 + t[e++];
                }
            },
            skip: r => {
                if (t && r > 0) e += r;
            },
            skipString: () => {
                const n = r.readUInt32BE();
                if (n === undefined) return;
                e += n;
                return e <= t.length ? n : undefined;
            },
            readByte: () => {
                if (t && e < t.length) return t[e++];
            },
            readBool: () => {
                if (t && e < t.length) return !!t[e++];
            },
            readList: () => {
                const e = r.readString(true);
                if (e === undefined) return;
                return e ? e.split(",") : [];
            },
            readString: (n, s) => {
                if (typeof n === "number") {
                    s = n;
                    n = undefined;
                }
                const l = r.readUInt32BE();
                if (l === undefined) return;
                if (t.length - e < l || typeof s === "number" && l > s) {
                    return;
                }
                if (n) {
                    if (Buffer.isBuffer(n)) return o(t, n, e, e += l);
                    return t.utf8Slice(e, e += l);
                }
                return a(t, e, e += l);
            },
            readRaw: r => {
                if (!t) return;
                if (typeof r !== "number") return a(t, e, e += t.length - e);
                if (t.length - e >= r) return a(t, e, e += r);
            }
        };
        return r;
    }
    function c(e, t, r) {
        const n = new Error(e);
        if (typeof t === "boolean") {
            r = t;
            n.level = "protocol";
        } else {
            n.level = t || "protocol";
        }
        n.fatal = !!r;
        return n;
    }
    function u(e, t, r) {
        e[r++] = t >>> 24;
        e[r++] = t >>> 16;
        e[r++] = t >>> 8;
        e[r++] = t;
        return r;
    }
    const d = l();
    utils$2 = {
        bufferCopy: o,
        bufferSlice: a,
        FastBuffer: r,
        bufferFill: (e, t, r, s) => n.call(e, t, r, s),
        makeError: c,
        doFatalError: (e, r, n, s) => {
            let o;
            if (t === undefined) ({DISCONNECT_REASON: t} = requireConstants());
            if (r instanceof Error) {
                o = r;
                if (typeof n !== "number") s = t.PROTOCOL_ERROR; else s = n;
            } else {
                o = c(r, n, true);
            }
            if (typeof s !== "number") s = t.PROTOCOL_ERROR;
            e.disconnect(s);
            e._destruct();
            e._onError(o);
            return Infinity;
        },
        readUInt32BE: s,
        writeUInt32BE: u,
        writeUInt32LE: (e, t, r) => {
            e[r++] = t;
            e[r++] = t >>> 8;
            e[r++] = t >>> 16;
            e[r++] = t >>> 24;
            return r;
        },
        makeBufferParser: l,
        bufferParser: l(),
        readString: (e, t, r, n) => {
            if (typeof r === "number") {
                n = r;
                r = undefined;
            }
            if (t === undefined) t = 0;
            const l = e.length - t;
            if (t < 0 || t >= e.length || l < 4) return;
            const c = s(e, t);
            if (l < 4 + c || typeof n === "number" && c > n) return;
            t += 4;
            const u = t + c;
            e._pos = u;
            if (r) {
                if (Buffer.isBuffer(r)) return o(e, r, t, u);
                return e.utf8Slice(t, u);
            }
            return a(e, t, u);
        },
        sigSSHToASN1: (t, r) => {
            switch (r) {
              case "ssh-dss":
                {
                    if (t.length > 40) return t;
                    const r = new e.Writer;
                    r.startSequence();
                    let n = t.slice(0, 20);
                    let s = t.slice(20);
                    if (n[0] & 128) {
                        const e = Buffer.allocUnsafe(21);
                        e[0] = 0;
                        n.copy(e, 1);
                        n = e;
                    } else if (n[0] === 0 && !(n[1] & 128)) {
                        n = n.slice(1);
                    }
                    if (s[0] & 128) {
                        const e = Buffer.allocUnsafe(21);
                        e[0] = 0;
                        s.copy(e, 1);
                        s = e;
                    } else if (s[0] === 0 && !(s[1] & 128)) {
                        s = s.slice(1);
                    }
                    r.writeBuffer(n, e.Integer);
                    r.writeBuffer(s, e.Integer);
                    r.endSequence();
                    return r.buffer;
                }

              case "ecdsa-sha2-nistp256":
              case "ecdsa-sha2-nistp384":
              case "ecdsa-sha2-nistp521":
                {
                    d.init(t, 0);
                    const r = d.readString();
                    const n = d.readString();
                    d.clear();
                    if (r === undefined || n === undefined) return;
                    const s = new e.Writer;
                    s.startSequence();
                    s.writeBuffer(r, e.Integer);
                    s.writeBuffer(n, e.Integer);
                    s.endSequence();
                    return s.buffer;
                }

              default:
                return t;
            }
        },
        convertSignature: (t, r) => {
            switch (r) {
              case "ssh-dss":
                {
                    if (t.length <= 40) return t;
                    const r = new e.Reader(t);
                    r.readSequence();
                    let n = r.readString(e.Integer, true);
                    let s = r.readString(e.Integer, true);
                    let a = 0;
                    let l = 0;
                    if (n.length < 20) {
                        const e = Buffer.allocUnsafe(20);
                        e.set(n, 1);
                        n = e;
                        n[0] = 0;
                    }
                    if (s.length < 20) {
                        const e = Buffer.allocUnsafe(20);
                        e.set(s, 1);
                        s = e;
                        s[0] = 0;
                    }
                    if (n.length > 20 && n[0] === 0) a = 1;
                    if (s.length > 20 && s[0] === 0) l = 1;
                    const c = Buffer.allocUnsafe(n.length - a + (s.length - l));
                    o(n, c, a, n.length, 0);
                    o(s, c, l, s.length, n.length - a);
                    return c;
                }

              case "ecdsa-sha2-nistp256":
              case "ecdsa-sha2-nistp384":
              case "ecdsa-sha2-nistp521":
                {
                    if (t[0] === 0) return t;
                    const r = new e.Reader(t);
                    r.readSequence();
                    const n = r.readString(e.Integer, true);
                    const s = r.readString(e.Integer, true);
                    if (n === null || s === null) return;
                    const o = Buffer.allocUnsafe(4 + n.length + 4 + s.length);
                    u(o, n.length, 0);
                    o.set(n, 4);
                    u(o, s.length, 4 + n.length);
                    o.set(s, 4 + 4 + n.length);
                    return o;
                }
            }
            return t;
        },
        sendPacket: (e, t, r) => {
            if (!r && e._kexinit !== undefined) {
                if (e._queue === undefined) e._queue = [];
                e._queue.push(t);
                e._debug && e._debug("Outbound: ... packet queued");
                return false;
            }
            e._cipher.encrypt(t);
            return true;
        }
    };
    return utils$2;
}

var poly1305 = {
    exports: {}
};

poly1305.exports;

var hasRequiredPoly1305;

function requirePoly1305() {
    if (hasRequiredPoly1305) return poly1305.exports;
    hasRequiredPoly1305 = 1;
    (function(e, t) {
        var r = function() {
            var e = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : undefined;
            if (typeof __filename !== "undefined") e = e || __filename;
            return function(t) {
                t = t || {};
                var r;
                r || (r = typeof t !== "undefined" ? t : {});
                var n, s;
                r.ready = new Promise(function(e, t) {
                    n = e;
                    s = t;
                });
                var o = {}, a;
                for (a in r) r.hasOwnProperty(a) && (o[a] = r[a]);
                var l = "object" === typeof window, c = "function" === typeof importScripts, u = "object" === typeof process && "object" === typeof process.versions && "string" === typeof process.versions.node, d = "", h, p, g, m, _;
                if (u) d = c ? require$$0__default$4.default.dirname(d) + "/" : __dirname + "/", 
                h = function(e, t) {
                    var r = z(e);
                    if (r) return t ? r : r.toString();
                    m || (m = require$$0__default$5.default);
                    _ || (_ = require$$0__default$4.default);
                    e = _.normalize(e);
                    return m.readFileSync(e, t ? null : "utf8");
                }, g = function(e) {
                    e = h(e, true);
                    e.buffer || (e = new Uint8Array(e));
                    A(e.buffer);
                    return e;
                }, p = function(e, t, r) {
                    var n = z(e);
                    n && t(n);
                    m || (m = require$$0__default$5.default);
                    _ || (_ = require$$0__default$4.default);
                    e = _.normalize(e);
                    m.readFile(e, function(e, n) {
                        e ? r(e) : t(n.buffer);
                    });
                }, 1 < process.argv.length && process.argv[1].replace(/\\/g, "/"), process.argv.slice(2), 
                r.inspect = function() {
                    return "[Emscripten Module object]";
                }; else if (l || c) c ? d = self.location.href : "undefined" !== typeof document && document.currentScript && (d = document.currentScript.src), 
                e && (d = e), 0 !== d.indexOf("blob:") ? d = d.substr(0, d.lastIndexOf("/") + 1) : d = "", 
                h = function(e) {
                    try {
                        var t = new XMLHttpRequest;
                        t.open("GET", e, !1);
                        t.send(null);
                        return t.responseText;
                    } catch (s) {
                        if (e = z(e)) {
                            t = [];
                            for (var r = 0; r < e.length; r++) {
                                var n = e[r];
                                255 < n && (G && A(false, "Character code " + n + " (" + String.fromCharCode(n) + ")  at offset " + r + " not in 0x00-0xFF."), 
                                n &= 255);
                                t.push(String.fromCharCode(n));
                            }
                            return t.join("");
                        }
                        throw s;
                    }
                }, c && (g = function(e) {
                    try {
                        var t = new XMLHttpRequest;
                        t.open("GET", e, !1);
                        t.responseType = "arraybuffer";
                        t.send(null);
                        return new Uint8Array(t.response);
                    } catch (t) {
                        if (e = z(e)) return e;
                        throw t;
                    }
                }), p = function(e, t, r) {
                    var n = new XMLHttpRequest;
                    n.open("GET", e, true);
                    n.responseType = "arraybuffer";
                    n.onload = function() {
                        if (200 == n.status || 0 == n.status && n.response) t(n.response); else {
                            var s = z(e);
                            s ? t(s.buffer) : r();
                        }
                    };
                    n.onerror = r;
                    n.send(null);
                };
                r.print || console.log.bind(console);
                var E = r.printErr || console.warn.bind(console);
                for (a in o) o.hasOwnProperty(a) && (r[a] = o[a]);
                o = null;
                var v;
                r.wasmBinary && (v = r.wasmBinary);
                r.noExitRuntime || true;
                "object" !== typeof WebAssembly && M("no native wasm support detected");
                var y, S = false;
                function A(e, t) {
                    e || M("Assertion failed: " + t);
                }
                function b(e) {
                    var t = r["_" + e];
                    A(t, "Cannot call unknown function " + e + ", make sure it is exported");
                    return t;
                }
                function C(e, t, r, n) {
                    var s = {
                        string: function(e) {
                            var t = 0;
                            if (null !== e && void 0 !== e && 0 !== e) {
                                var r = (e.length << 2) + 1;
                                t = J(r);
                                var n = t, s = R;
                                if (0 < r) {
                                    r = n + r - 1;
                                    for (var o = 0; o < e.length; ++o) {
                                        var a = e.charCodeAt(o);
                                        if (55296 <= a && 57343 >= a) {
                                            var l = e.charCodeAt(++o);
                                            a = 65536 + ((a & 1023) << 10) | l & 1023;
                                        }
                                        if (127 >= a) {
                                            if (n >= r) break;
                                            s[n++] = a;
                                        } else {
                                            if (2047 >= a) {
                                                if (n + 1 >= r) break;
                                                s[n++] = 192 | a >> 6;
                                            } else {
                                                if (65535 >= a) {
                                                    if (n + 2 >= r) break;
                                                    s[n++] = 224 | a >> 12;
                                                } else {
                                                    if (n + 3 >= r) break;
                                                    s[n++] = 240 | a >> 18;
                                                    s[n++] = 128 | a >> 12 & 63;
                                                }
                                                s[n++] = 128 | a >> 6 & 63;
                                            }
                                            s[n++] = 128 | a & 63;
                                        }
                                    }
                                    s[n] = 0;
                                }
                            }
                            return t;
                        },
                        array: function(e) {
                            var t = J(e.length);
                            T.set(e, t);
                            return t;
                        }
                    }, o = b(e), a = [];
                    e = 0;
                    if (n) for (var l = 0; l < n.length; l++) {
                        var c = s[r[l]];
                        c ? (0 === e && (e = V()), a[l] = c(n[l])) : a[l] = n[l];
                    }
                    r = o.apply(null, a);
                    r = function(e) {
                        if ("string" === t) if (e) {
                            for (var r = R, n = e + NaN, s = e; r[s] && !(s >= n); ) ++s;
                            if (16 < s - e && r.subarray && w) e = w.decode(r.subarray(e, s)); else {
                                for (n = ""; e < s; ) {
                                    var o = r[e++];
                                    if (o & 128) {
                                        var a = r[e++] & 63;
                                        if (192 == (o & 224)) n += String.fromCharCode((o & 31) << 6 | a); else {
                                            var l = r[e++] & 63;
                                            o = 224 == (o & 240) ? (o & 15) << 12 | a << 6 | l : (o & 7) << 18 | a << 12 | l << 6 | r[e++] & 63;
                                            65536 > o ? n += String.fromCharCode(o) : (o -= 65536, n += String.fromCharCode(55296 | o >> 10, 56320 | o & 1023));
                                        }
                                    } else n += String.fromCharCode(o);
                                }
                                e = n;
                            }
                        } else e = ""; else e = "boolean" === t ? !!e : e;
                        return e;
                    }(r);
                    0 !== e && X(e);
                    return r;
                }
                var w = "undefined" !== typeof TextDecoder ? new TextDecoder("utf8") : void 0, I, T, R;
                function k() {
                    var e = y.buffer;
                    I = e;
                    r.HEAP8 = T = new Int8Array(e);
                    r.HEAP16 = new Int16Array(e);
                    r.HEAP32 = new Int32Array(e);
                    r.HEAPU8 = R = new Uint8Array(e);
                    r.HEAPU16 = new Uint16Array(e);
                    r.HEAPU32 = new Uint32Array(e);
                    r.HEAPF32 = new Float32Array(e);
                    r.HEAPF64 = new Float64Array(e);
                }
                var P, $ = [], O = [], B = [];
                function N() {
                    var e = r.preRun.shift();
                    $.unshift(e);
                }
                var D = 0, L = null, U = null;
                r.preloadedImages = {};
                r.preloadedAudios = {};
                function M(e) {
                    if (r.onAbort) r.onAbort(e);
                    E(e);
                    S = true;
                    e = new WebAssembly.RuntimeError("abort(" + e + "). Build with -s ASSERTIONS=1 for more info.");
                    s(e);
                    throw e;
                }
                var x = "data:application/octet-stream;base64,", q;
                q = "data:application/octet-stream;base64,AGFzbQEAAAABIAZgAX8Bf2ADf39/AGABfwBgAABgAAF/YAZ/f39/f38AAgcBAWEBYQAAAwsKAAEDAQAAAgQFAgQFAXABAQEFBwEBgAKAgAIGCQF/AUGAjMACCwclCQFiAgABYwADAWQACQFlAAgBZgAHAWcABgFoAAUBaQAKAWoBAAqGTQpPAQJ/QYAIKAIAIgEgAEEDakF8cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQAEUNAQtBgAggADYCACABDwtBhAhBMDYCAEF/C4wFAg5+Cn8gACgCJCEUIAAoAiAhFSAAKAIcIREgACgCGCESIAAoAhQhEyACQRBPBEAgAC0ATEVBGHQhFyAAKAIEIhZBBWytIQ8gACgCCCIYQQVsrSENIAAoAgwiGUEFbK0hCyAAKAIQIhpBBWytIQkgADUCACEIIBqtIRAgGa0hDiAYrSEMIBatIQoDQCASIAEtAAMiEiABLQAEQQh0ciABLQAFQRB0ciABLQAGIhZBGHRyQQJ2Qf///x9xaq0iAyAOfiABLwAAIAEtAAJBEHRyIBNqIBJBGHRBgICAGHFqrSIEIBB+fCARIAEtAAdBCHQgFnIgAS0ACEEQdHIgAS0ACSIRQRh0ckEEdkH///8fcWqtIgUgDH58IAEtAApBCHQgEXIgAS0AC0EQdHIgAS0ADEEYdHJBBnYgFWqtIgYgCn58IBQgF2ogAS8ADSABLQAPQRB0cmqtIgcgCH58IAMgDH4gBCAOfnwgBSAKfnwgBiAIfnwgByAJfnwgAyAKfiAEIAx+fCAFIAh+fCAGIAl+fCAHIAt+fCADIAh+IAQgCn58IAUgCX58IAYgC358IAcgDX58IAMgCX4gBCAIfnwgBSALfnwgBiANfnwgByAPfnwiA0IaiEL/////D4N8IgRCGohC/////w+DfCIFQhqIQv////8Pg3wiBkIaiEL/////D4N8IgdCGoinQQVsIAOnQf///x9xaiITQRp2IASnQf///x9xaiESIAWnQf///x9xIREgBqdB////H3EhFSAHp0H///8fcSEUIBNB////H3EhEyABQRBqIQEgAkEQayICQQ9LDQALCyAAIBQ2AiQgACAVNgIgIAAgETYCHCAAIBI2AhggACATNgIUCwMAAQu2BAEGfwJAIAAoAjgiBARAIABBPGohBQJAIAJBECAEayIDIAIgA0kbIgZFDQAgBkEDcSEHAkAgBkEBa0EDSQRAQQAhAwwBCyAGQXxxIQhBACEDA0AgBSADIARqaiABIANqLQAAOgAAIAUgA0EBciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0ECciIEIAAoAjhqaiABIARqLQAAOgAAIAUgA0EDciIEIAAoAjhqaiABIARqLQAAOgAAIANBBGohAyAAKAI4IQQgCEEEayIIDQALCyAHRQ0AA0AgBSADIARqaiABIANqLQAAOgAAIANBAWohAyAAKAI4IQQgB0EBayIHDQALCyAAIAQgBmoiAzYCOCADQRBJDQEgACAFQRAQAiAAQQA2AjggAiAGayECIAEgBmohAQsgAkEQTwRAIAAgASACQXBxIgMQAiACQQ9xIQIgASADaiEBCyACRQ0AIAJBA3EhBCAAQTxqIQVBACEDIAJBAWtBA08EQCACQXxxIQcDQCAFIAAoAjggA2pqIAEgA2otAAA6AAAgBSADQQFyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQJyIgYgACgCOGpqIAEgBmotAAA6AAAgBSADQQNyIgYgACgCOGpqIAEgBmotAAA6AAAgA0EEaiEDIAdBBGsiBw0ACwsgBARAA0AgBSAAKAI4IANqaiABIANqLQAAOgAAIANBAWohAyAEQQFrIgQNAAsLIAAgACgCOCACajYCOAsLoS0BDH8jAEEQayIMJAACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEGICCgCACIFQRAgAEELakF4cSAAQQtJGyIIQQN2IgJ2IgFBA3EEQCABQX9zQQFxIAJqIgNBA3QiAUG4CGooAgAiBEEIaiEAAkAgBCgCCCICIAFBsAhqIgFGBEBBiAggBUF+IAN3cTYCAAwBCyACIAE2AgwgASACNgIICyAEIANBA3QiAUEDcjYCBCABIARqIgEgASgCBEEBcjYCBAwNCyAIQZAIKAIAIgpNDQEgAQRAAkBBAiACdCIAQQAgAGtyIAEgAnRxIgBBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2aiIDQQN0IgBBuAhqKAIAIgQoAggiASAAQbAIaiIARgRAQYgIIAVBfiADd3EiBTYCAAwBCyABIAA2AgwgACABNgIICyAEQQhqIQAgBCAIQQNyNgIEIAQgCGoiAiADQQN0IgEgCGsiA0EBcjYCBCABIARqIAM2AgAgCgRAIApBA3YiAUEDdEGwCGohB0GcCCgCACEEAn8gBUEBIAF0IgFxRQRAQYgIIAEgBXI2AgAgBwwBCyAHKAIICyEBIAcgBDYCCCABIAQ2AgwgBCAHNgIMIAQgATYCCAtBnAggAjYCAEGQCCADNgIADA0LQYwIKAIAIgZFDQEgBkEAIAZrcUEBayIAIABBDHZBEHEiAnYiAUEFdkEIcSIAIAJyIAEgAHYiAUECdkEEcSIAciABIAB2IgFBAXZBAnEiAHIgASAAdiIBQQF2QQFxIgByIAEgAHZqQQJ0QbgKaigCACIBKAIEQXhxIAhrIQMgASECA0ACQCACKAIQIgBFBEAgAigCFCIARQ0BCyAAKAIEQXhxIAhrIgIgAyACIANJIgIbIQMgACABIAIbIQEgACECDAELCyABIAhqIgkgAU0NAiABKAIYIQsgASABKAIMIgRHBEAgASgCCCIAQZgIKAIASRogACAENgIMIAQgADYCCAwMCyABQRRqIgIoAgAiAEUEQCABKAIQIgBFDQQgAUEQaiECCwNAIAIhByAAIgRBFGoiAigCACIADQAgBEEQaiECIAQoAhAiAA0ACyAHQQA2AgAMCwtBfyEIIABBv39LDQAgAEELaiIAQXhxIQhBjAgoAgAiCUUNAEEAIAhrIQMCQAJAAkACf0EAIAhBgAJJDQAaQR8gCEH///8HSw0AGiAAQQh2IgAgAEGA/j9qQRB2QQhxIgJ0IgAgAEGA4B9qQRB2QQRxIgF0IgAgAEGAgA9qQRB2QQJxIgB0QQ92IAEgAnIgAHJrIgBBAXQgCCAAQRVqdkEBcXJBHGoLIgVBAnRBuApqKAIAIgJFBEBBACEADAELQQAhACAIQQBBGSAFQQF2ayAFQR9GG3QhAQNAAkAgAigCBEF4cSAIayIHIANPDQAgAiEEIAciAw0AQQAhAyACIQAMAwsgACACKAIUIgcgByACIAFBHXZBBHFqKAIQIgJGGyAAIAcbIQAgAUEBdCEBIAINAAsLIAAgBHJFBEBBACEEQQIgBXQiAEEAIABrciAJcSIARQ0DIABBACAAa3FBAWsiACAAQQx2QRBxIgJ2IgFBBXZBCHEiACACciABIAB2IgFBAnZBBHEiAHIgASAAdiIBQQF2QQJxIgByIAEgAHYiAUEBdkEBcSIAciABIAB2akECdEG4CmooAgAhAAsgAEUNAQsDQCAAKAIEQXhxIAhrIgEgA0khAiABIAMgAhshAyAAIAQgAhshBCAAKAIQIgEEfyABBSAAKAIUCyIADQALCyAERQ0AIANBkAgoAgAgCGtPDQAgBCAIaiIGIARNDQEgBCgCGCEFIAQgBCgCDCIBRwRAIAQoAggiAEGYCCgCAEkaIAAgATYCDCABIAA2AggMCgsgBEEUaiICKAIAIgBFBEAgBCgCECIARQ0EIARBEGohAgsDQCACIQcgACIBQRRqIgIoAgAiAA0AIAFBEGohAiABKAIQIgANAAsgB0EANgIADAkLIAhBkAgoAgAiAk0EQEGcCCgCACEDAkAgAiAIayIBQRBPBEBBkAggATYCAEGcCCADIAhqIgA2AgAgACABQQFyNgIEIAIgA2ogATYCACADIAhBA3I2AgQMAQtBnAhBADYCAEGQCEEANgIAIAMgAkEDcjYCBCACIANqIgAgACgCBEEBcjYCBAsgA0EIaiEADAsLIAhBlAgoAgAiBkkEQEGUCCAGIAhrIgE2AgBBoAhBoAgoAgAiAiAIaiIANgIAIAAgAUEBcjYCBCACIAhBA3I2AgQgAkEIaiEADAsLQQAhACAIQS9qIgkCf0HgCygCAARAQegLKAIADAELQewLQn83AgBB5AtCgKCAgICABDcCAEHgCyAMQQxqQXBxQdiq1aoFczYCAEH0C0EANgIAQcQLQQA2AgBBgCALIgFqIgVBACABayIHcSICIAhNDQpBwAsoAgAiBARAQbgLKAIAIgMgAmoiASADTQ0LIAEgBEsNCwtBxAstAABBBHENBQJAAkBBoAgoAgAiAwRAQcgLIQADQCADIAAoAgAiAU8EQCABIAAoAgRqIANLDQMLIAAoAggiAA0ACwtBABABIgFBf0YNBiACIQVB5AsoAgAiA0EBayIAIAFxBEAgAiABayAAIAFqQQAgA2txaiEFCyAFIAhNDQYgBUH+////B0sNBkHACygCACIEBEBBuAsoAgAiAyAFaiIAIANNDQcgACAESw0HCyAFEAEiACABRw0BDAgLIAUgBmsgB3EiBUH+////B0sNBSAFEAEiASAAKAIAIAAoAgRqRg0EIAEhAAsCQCAAQX9GDQAgCEEwaiAFTQ0AQegLKAIAIgEgCSAFa2pBACABa3EiAUH+////B0sEQCAAIQEMCAsgARABQX9HBEAgASAFaiEFIAAhAQwIC0EAIAVrEAEaDAULIAAiAUF/Rw0GDAQLAAtBACEEDAcLQQAhAQwFCyABQX9HDQILQcQLQcQLKAIAQQRyNgIACyACQf7///8HSw0BIAIQASEBQQAQASEAIAFBf0YNASAAQX9GDQEgACABTQ0BIAAgAWsiBSAIQShqTQ0BC0G4C0G4CygCACAFaiIANgIAQbwLKAIAIABJBEBBvAsgADYCAAsCQAJAAkBBoAgoAgAiBwRAQcgLIQADQCABIAAoAgAiAyAAKAIEIgJqRg0CIAAoAggiAA0ACwwCC0GYCCgCACIAQQAgACABTRtFBEBBmAggATYCAAtBACEAQcwLIAU2AgBByAsgATYCAEGoCEF/NgIAQawIQeALKAIANgIAQdQLQQA2AgADQCAAQQN0IgNBuAhqIANBsAhqIgI2AgAgA0G8CGogAjYCACAAQQFqIgBBIEcNAAtBlAggBUEoayIDQXggAWtBB3FBACABQQhqQQdxGyIAayICNgIAQaAIIAAgAWoiADYCACAAIAJBAXI2AgQgASADakEoNgIEQaQIQfALKAIANgIADAILIAAtAAxBCHENACADIAdLDQAgASAHTQ0AIAAgAiAFajYCBEGgCCAHQXggB2tBB3FBACAHQQhqQQdxGyIAaiICNgIAQZQIQZQIKAIAIAVqIgEgAGsiADYCACACIABBAXI2AgQgASAHakEoNgIEQaQIQfALKAIANgIADAELQZgIKAIAIAFLBEBBmAggATYCAAsgASAFaiECQcgLIQACQAJAAkACQAJAAkADQCACIAAoAgBHBEAgACgCCCIADQEMAgsLIAAtAAxBCHFFDQELQcgLIQADQCAHIAAoAgAiAk8EQCACIAAoAgRqIgQgB0sNAwsgACgCCCEADAALAAsgACABNgIAIAAgACgCBCAFajYCBCABQXggAWtBB3FBACABQQhqQQdxG2oiCSAIQQNyNgIEIAJBeCACa0EHcUEAIAJBCGpBB3EbaiIFIAggCWoiBmshAiAFIAdGBEBBoAggBjYCAEGUCEGUCCgCACACaiIANgIAIAYgAEEBcjYCBAwDCyAFQZwIKAIARgRAQZwIIAY2AgBBkAhBkAgoAgAgAmoiADYCACAGIABBAXI2AgQgACAGaiAANgIADAMLIAUoAgQiAEEDcUEBRgRAIABBeHEhBwJAIABB/wFNBEAgBSgCCCIDIABBA3YiAEEDdEGwCGpGGiADIAUoAgwiAUYEQEGICEGICCgCAEF+IAB3cTYCAAwCCyADIAE2AgwgASADNgIIDAELIAUoAhghCAJAIAUgBSgCDCIBRwRAIAUoAggiACABNgIMIAEgADYCCAwBCwJAIAVBFGoiACgCACIDDQAgBUEQaiIAKAIAIgMNAEEAIQEMAQsDQCAAIQQgAyIBQRRqIgAoAgAiAw0AIAFBEGohACABKAIQIgMNAAsgBEEANgIACyAIRQ0AAkAgBSAFKAIcIgNBAnRBuApqIgAoAgBGBEAgACABNgIAIAENAUGMCEGMCCgCAEF+IAN3cTYCAAwCCyAIQRBBFCAIKAIQIAVGG2ogATYCACABRQ0BCyABIAg2AhggBSgCECIABEAgASAANgIQIAAgATYCGAsgBSgCFCIARQ0AIAEgADYCFCAAIAE2AhgLIAUgB2ohBSACIAdqIQILIAUgBSgCBEF+cTYCBCAGIAJBAXI2AgQgAiAGaiACNgIAIAJB/wFNBEAgAkEDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwDC0EfIQAgAkH///8HTQRAIAJBCHYiACAAQYD+P2pBEHZBCHEiA3QiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASADciAAcmsiAEEBdCACIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQQCQEGMCCgCACIDQQEgAHQiAXFFBEBBjAggASADcjYCACAEIAY2AgAgBiAENgIYDAELIAJBAEEZIABBAXZrIABBH0YbdCEAIAQoAgAhAQNAIAEiAygCBEF4cSACRg0DIABBHXYhASAAQQF0IQAgAyABQQRxaiIEKAIQIgENAAsgBCAGNgIQIAYgAzYCGAsgBiAGNgIMIAYgBjYCCAwCC0GUCCAFQShrIgNBeCABa0EHcUEAIAFBCGpBB3EbIgBrIgI2AgBBoAggACABaiIANgIAIAAgAkEBcjYCBCABIANqQSg2AgRBpAhB8AsoAgA2AgAgByAEQScgBGtBB3FBACAEQSdrQQdxG2pBL2siACAAIAdBEGpJGyICQRs2AgQgAkHQCykCADcCECACQcgLKQIANwIIQdALIAJBCGo2AgBBzAsgBTYCAEHICyABNgIAQdQLQQA2AgAgAkEYaiEAA0AgAEEHNgIEIABBCGohASAAQQRqIQAgASAESQ0ACyACIAdGDQMgAiACKAIEQX5xNgIEIAcgAiAHayIEQQFyNgIEIAIgBDYCACAEQf8BTQRAIARBA3YiAEEDdEGwCGohAgJ/QYgIKAIAIgFBASAAdCIAcUUEQEGICCAAIAFyNgIAIAIMAQsgAigCCAshACACIAc2AgggACAHNgIMIAcgAjYCDCAHIAA2AggMBAtBHyEAIAdCADcCECAEQf///wdNBEAgBEEIdiIAIABBgP4/akEQdkEIcSICdCIAIABBgOAfakEQdkEEcSIBdCIAIABBgIAPakEQdkECcSIAdEEPdiABIAJyIAByayIAQQF0IAQgAEEVanZBAXFyQRxqIQALIAcgADYCHCAAQQJ0QbgKaiEDAkBBjAgoAgAiAkEBIAB0IgFxRQRAQYwIIAEgAnI2AgAgAyAHNgIAIAcgAzYCGAwBCyAEQQBBGSAAQQF2ayAAQR9GG3QhACADKAIAIQEDQCABIgIoAgRBeHEgBEYNBCAAQR12IQEgAEEBdCEAIAIgAUEEcWoiAygCECIBDQALIAMgBzYCECAHIAI2AhgLIAcgBzYCDCAHIAc2AggMAwsgAygCCCIAIAY2AgwgAyAGNgIIIAZBADYCGCAGIAM2AgwgBiAANgIICyAJQQhqIQAMBQsgAigCCCIAIAc2AgwgAiAHNgIIIAdBADYCGCAHIAI2AgwgByAANgIIC0GUCCgCACIAIAhNDQBBlAggACAIayIBNgIAQaAIQaAIKAIAIgIgCGoiADYCACAAIAFBAXI2AgQgAiAIQQNyNgIEIAJBCGohAAwDC0GECEEwNgIAQQAhAAwCCwJAIAVFDQACQCAEKAIcIgJBAnRBuApqIgAoAgAgBEYEQCAAIAE2AgAgAQ0BQYwIIAlBfiACd3EiCTYCAAwCCyAFQRBBFCAFKAIQIARGG2ogATYCACABRQ0BCyABIAU2AhggBCgCECIABEAgASAANgIQIAAgATYCGAsgBCgCFCIARQ0AIAEgADYCFCAAIAE2AhgLAkAgA0EPTQRAIAQgAyAIaiIAQQNyNgIEIAAgBGoiACAAKAIEQQFyNgIEDAELIAQgCEEDcjYCBCAGIANBAXI2AgQgAyAGaiADNgIAIANB/wFNBEAgA0EDdiIAQQN0QbAIaiECAn9BiAgoAgAiAUEBIAB0IgBxRQRAQYgIIAAgAXI2AgAgAgwBCyACKAIICyEAIAIgBjYCCCAAIAY2AgwgBiACNgIMIAYgADYCCAwBC0EfIQAgA0H///8HTQRAIANBCHYiACAAQYD+P2pBEHZBCHEiAnQiACAAQYDgH2pBEHZBBHEiAXQiACAAQYCAD2pBEHZBAnEiAHRBD3YgASACciAAcmsiAEEBdCADIABBFWp2QQFxckEcaiEACyAGIAA2AhwgBkIANwIQIABBAnRBuApqIQICQAJAIAlBASAAdCIBcUUEQEGMCCABIAlyNgIAIAIgBjYCACAGIAI2AhgMAQsgA0EAQRkgAEEBdmsgAEEfRht0IQAgAigCACEIA0AgCCIBKAIEQXhxIANGDQIgAEEddiECIABBAXQhACABIAJBBHFqIgIoAhAiCA0ACyACIAY2AhAgBiABNgIYCyAGIAY2AgwgBiAGNgIIDAELIAEoAggiACAGNgIMIAEgBjYCCCAGQQA2AhggBiABNgIMIAYgADYCCAsgBEEIaiEADAELAkAgC0UNAAJAIAEoAhwiAkECdEG4CmoiACgCACABRgRAIAAgBDYCACAEDQFBjAggBkF+IAJ3cTYCAAwCCyALQRBBFCALKAIQIAFGG2ogBDYCACAERQ0BCyAEIAs2AhggASgCECIABEAgBCAANgIQIAAgBDYCGAsgASgCFCIARQ0AIAQgADYCFCAAIAQ2AhgLAkAgA0EPTQRAIAEgAyAIaiIAQQNyNgIEIAAgAWoiACAAKAIEQQFyNgIEDAELIAEgCEEDcjYCBCAJIANBAXI2AgQgAyAJaiADNgIAIAoEQCAKQQN2IgBBA3RBsAhqIQRBnAgoAgAhAgJ/QQEgAHQiACAFcUUEQEGICCAAIAVyNgIAIAQMAQsgBCgCCAshACAEIAI2AgggACACNgIMIAIgBDYCDCACIAA2AggLQZwIIAk2AgBBkAggAzYCAAsgAUEIaiEACyAMQRBqJAAgAAsQACMAIABrQXBxIgAkACAACwYAIAAkAAsEACMAC4AJAgh/BH4jAEGQAWsiBiQAIAYgBS0AA0EYdEGAgIAYcSAFLwAAIAUtAAJBEHRycjYCACAGIAUoAANBAnZBg/7/H3E2AgQgBiAFKAAGQQR2Qf+B/x9xNgIIIAYgBSgACUEGdkH//8AfcTYCDCAFLwANIQggBS0ADyEJIAZCADcCFCAGQgA3AhwgBkEANgIkIAYgCCAJQRB0QYCAPHFyNgIQIAYgBSgAEDYCKCAGIAUoABQ2AiwgBiAFKAAYNgIwIAUoABwhBSAGQQA6AEwgBkEANgI4IAYgBTYCNCAGIAEgAhAEIAQEQCAGIAMgBBAECyAGKAI4IgEEQCAGQTxqIgIgAWpBAToAACABQQFqQQ9NBEAgASAGakE9aiEEAkBBDyABayIDRQ0AIAMgBGoiAUEBa0EAOgAAIARBADoAACADQQNJDQAgAUECa0EAOgAAIARBADoAASABQQNrQQA6AAAgBEEAOgACIANBB0kNACABQQRrQQA6AAAgBEEAOgADIANBCUkNACAEQQAgBGtBA3EiAWoiBEEANgIAIAQgAyABa0F8cSIBaiIDQQRrQQA2AgAgAUEJSQ0AIARBADYCCCAEQQA2AgQgA0EIa0EANgIAIANBDGtBADYCACABQRlJDQAgBEEANgIYIARBADYCFCAEQQA2AhAgBEEANgIMIANBEGtBADYCACADQRRrQQA2AgAgA0EYa0EANgIAIANBHGtBADYCACABIARBBHFBGHIiAWsiA0EgSQ0AIAEgBGohAQNAIAFCADcDGCABQgA3AxAgAUIANwMIIAFCADcDACABQSBqIQEgA0EgayIDQR9LDQALCwsgBkEBOgBMIAYgAkEQEAILIAY1AjQhECAGNQIwIREgBjUCLCEOIAAgBjUCKCAGKAIkIAYoAiAgBigCHCAGKAIYIgNBGnZqIgJBGnZqIgFBGnZqIgtBgICAYHIgAUH///8fcSINIAJB////H3EiCCAGKAIUIAtBGnZBBWxqIgFB////H3EiCUEFaiIFQRp2IANB////H3EgAUEadmoiA2oiAUEadmoiAkEadmoiBEEadmoiDEEfdSIHIANxIAEgDEEfdkEBayIDQf///x9xIgpxciIBQRp0IAUgCnEgByAJcXJyrXwiDzwAACAAIA9CGIg8AAMgACAPQhCIPAACIAAgD0IIiDwAASAAIA4gByAIcSACIApxciICQRR0IAFBBnZyrXwgD0IgiHwiDjwABCAAIA5CGIg8AAcgACAOQhCIPAAGIAAgDkIIiDwABSAAIBEgByANcSAEIApxciIBQQ50IAJBDHZyrXwgDkIgiHwiDjwACCAAIA5CGIg8AAsgACAOQhCIPAAKIAAgDkIIiDwACSAAIBAgAyAMcSAHIAtxckEIdCABQRJ2cq18IA5CIIh8Ig48AAwgACAOQhiIPAAPIAAgDkIQiDwADiAAIA5CCIg8AA0gBkIANwIwIAZCADcCKCAGQgA3AiAgBkIANwIYIAZCADcCECAGQgA3AgggBkIANwIAIAZBkAFqJAALpwwBB38CQCAARQ0AIABBCGsiAyAAQQRrKAIAIgFBeHEiAGohBQJAIAFBAXENACABQQNxRQ0BIAMgAygCACIBayIDQZgIKAIASQ0BIAAgAWohACADQZwIKAIARwRAIAFB/wFNBEAgAygCCCICIAFBA3YiBEEDdEGwCGpGGiACIAMoAgwiAUYEQEGICEGICCgCAEF+IAR3cTYCAAwDCyACIAE2AgwgASACNgIIDAILIAMoAhghBgJAIAMgAygCDCIBRwRAIAMoAggiAiABNgIMIAEgAjYCCAwBCwJAIANBFGoiAigCACIEDQAgA0EQaiICKAIAIgQNAEEAIQEMAQsDQCACIQcgBCIBQRRqIgIoAgAiBA0AIAFBEGohAiABKAIQIgQNAAsgB0EANgIACyAGRQ0BAkAgAyADKAIcIgJBAnRBuApqIgQoAgBGBEAgBCABNgIAIAENAUGMCEGMCCgCAEF+IAJ3cTYCAAwDCyAGQRBBFCAGKAIQIANGG2ogATYCACABRQ0CCyABIAY2AhggAygCECICBEAgASACNgIQIAIgATYCGAsgAygCFCICRQ0BIAEgAjYCFCACIAE2AhgMAQsgBSgCBCIBQQNxQQNHDQBBkAggADYCACAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAA8LIAMgBU8NACAFKAIEIgFBAXFFDQACQCABQQJxRQRAIAVBoAgoAgBGBEBBoAggAzYCAEGUCEGUCCgCACAAaiIANgIAIAMgAEEBcjYCBCADQZwIKAIARw0DQZAIQQA2AgBBnAhBADYCAA8LIAVBnAgoAgBGBEBBnAggAzYCAEGQCEGQCCgCACAAaiIANgIAIAMgAEEBcjYCBCAAIANqIAA2AgAPCyABQXhxIABqIQACQCABQf8BTQRAIAUoAggiAiABQQN2IgRBA3RBsAhqRhogAiAFKAIMIgFGBEBBiAhBiAgoAgBBfiAEd3E2AgAMAgsgAiABNgIMIAEgAjYCCAwBCyAFKAIYIQYCQCAFIAUoAgwiAUcEQCAFKAIIIgJBmAgoAgBJGiACIAE2AgwgASACNgIIDAELAkAgBUEUaiICKAIAIgQNACAFQRBqIgIoAgAiBA0AQQAhAQwBCwNAIAIhByAEIgFBFGoiAigCACIEDQAgAUEQaiECIAEoAhAiBA0ACyAHQQA2AgALIAZFDQACQCAFIAUoAhwiAkECdEG4CmoiBCgCAEYEQCAEIAE2AgAgAQ0BQYwIQYwIKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgIEQCABIAI2AhAgAiABNgIYCyAFKAIUIgJFDQAgASACNgIUIAIgATYCGAsgAyAAQQFyNgIEIAAgA2ogADYCACADQZwIKAIARw0BQZAIIAA2AgAPCyAFIAFBfnE2AgQgAyAAQQFyNgIEIAAgA2ogADYCAAsgAEH/AU0EQCAAQQN2IgFBA3RBsAhqIQACf0GICCgCACICQQEgAXQiAXFFBEBBiAggASACcjYCACAADAELIAAoAggLIQIgACADNgIIIAIgAzYCDCADIAA2AgwgAyACNgIIDwtBHyECIANCADcCECAAQf///wdNBEAgAEEIdiIBIAFBgP4/akEQdkEIcSIBdCICIAJBgOAfakEQdkEEcSICdCIEIARBgIAPakEQdkECcSIEdEEPdiABIAJyIARyayIBQQF0IAAgAUEVanZBAXFyQRxqIQILIAMgAjYCHCACQQJ0QbgKaiEBAkACQAJAQYwIKAIAIgRBASACdCIHcUUEQEGMCCAEIAdyNgIAIAEgAzYCACADIAE2AhgMAQsgAEEAQRkgAkEBdmsgAkEfRht0IQIgASgCACEBA0AgASIEKAIEQXhxIABGDQIgAkEddiEBIAJBAXQhAiAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAM2AhAgAyAENgIYCyADIAM2AgwgAyADNgIIDAELIAQoAggiACADNgIMIAQgAzYCCCADQQA2AhggAyAENgIMIAMgADYCCAtBqAhBqAgoAgBBAWsiAEF/IAAbNgIACwsLCQEAQYEICwIGUA==";
                if (!q.startsWith(x)) {
                    var H = q;
                    q = r.locateFile ? r.locateFile(H, d) : d + H;
                }
                function W() {
                    var e = q;
                    try {
                        if (e == q && v) return new Uint8Array(v);
                        var t = z(e);
                        if (t) return t;
                        if (g) return g(e);
                        throw "both async and sync fetching of the wasm failed";
                    } catch (e) {
                        M(e);
                    }
                }
                function j() {
                    if (!v && (l || c)) {
                        if ("function" === typeof fetch && !q.startsWith("file://")) return fetch(q, {
                            credentials: "same-origin"
                        }).then(function(e) {
                            if (!e.ok) throw "failed to load wasm binary file at '" + q + "'";
                            return e.arrayBuffer();
                        }).catch(function() {
                            return W();
                        });
                        if (p) return new Promise(function(e, t) {
                            p(q, function(t) {
                                e(new Uint8Array(t));
                            }, t);
                        });
                    }
                    return Promise.resolve().then(function() {
                        return W();
                    });
                }
                function Q(e) {
                    for (;0 < e.length; ) {
                        var t = e.shift();
                        if ("function" == typeof t) t(r); else {
                            var n = t.m;
                            "number" === typeof n ? void 0 === t.l ? P.get(n)() : P.get(n)(t.l) : n(void 0 === t.l ? null : t.l);
                        }
                    }
                }
                var G = false, K = "function" === typeof atob ? atob : function(e) {
                    var t = "", r = 0;
                    e = e.replace(/[^A-Za-z0-9\+\/=]/g, "");
                    do {
                        var n = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++));
                        var s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++));
                        var o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++));
                        var a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e.charAt(r++));
                        n = n << 2 | s >> 4;
                        s = (s & 15) << 4 | o >> 2;
                        var l = (o & 3) << 6 | a;
                        t += String.fromCharCode(n);
                        64 !== o && (t += String.fromCharCode(s));
                        64 !== a && (t += String.fromCharCode(l));
                    } while (r < e.length);
                    return t;
                };
                function z(e) {
                    if (e.startsWith(x)) {
                        e = e.slice(x.length);
                        if ("boolean" === typeof u && u) {
                            var t = Buffer.from(e, "base64");
                            t = new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
                        } else try {
                            var r = K(e), n = new Uint8Array(r.length);
                            for (e = 0; e < r.length; ++e) n[e] = r.charCodeAt(e);
                            t = n;
                        } catch (e) {
                            throw Error("Converting base64 string to bytes failed.");
                        }
                        return t;
                    }
                }
                var Y = {
                    a: function(e) {
                        var t = R.length;
                        e >>>= 0;
                        if (2147483648 < e) return false;
                        for (var r = 1; 4 >= r; r *= 2) {
                            var n = t * (1 + .2 / r);
                            n = Math.min(n, e + 100663296);
                            n = Math.max(e, n);
                            0 < n % 65536 && (n += 65536 - n % 65536);
                            e: {
                                try {
                                    y.grow(Math.min(2147483648, n) - I.byteLength + 65535 >>> 16);
                                    k();
                                    var s = 1;
                                    break e;
                                } catch (e) {}
                                s = void 0;
                            }
                            if (s) return true;
                        }
                        return false;
                    }
                };
                (function() {
                    function e(e) {
                        r.asm = e.exports;
                        y = r.asm.b;
                        k();
                        P = r.asm.j;
                        O.unshift(r.asm.c);
                        D--;
                        r.monitorRunDependencies && r.monitorRunDependencies(D);
                        0 == D && (null !== L && (clearInterval(L), L = null), U && (e = U, U = null, e()));
                    }
                    function t(t) {
                        e(t.instance);
                    }
                    function n(e) {
                        return j().then(function(e) {
                            return WebAssembly.instantiate(e, o);
                        }).then(e, function(e) {
                            E("failed to asynchronously prepare wasm: " + e);
                            M(e);
                        });
                    }
                    var o = {
                        a: Y
                    };
                    D++;
                    r.monitorRunDependencies && r.monitorRunDependencies(D);
                    if (r.instantiateWasm) try {
                        return r.instantiateWasm(o, e);
                    } catch (e) {
                        return E("Module.instantiateWasm callback failed with error: " + e), false;
                    }
                    (function() {
                        return v || "function" !== typeof WebAssembly.instantiateStreaming || q.startsWith(x) || q.startsWith("file://") || "function" !== typeof fetch ? n(t) : fetch(q, {
                            credentials: "same-origin"
                        }).then(function(e) {
                            return WebAssembly.instantiateStreaming(e, o).then(t, function(e) {
                                E("wasm streaming compile failed: " + e);
                                E("falling back to ArrayBuffer instantiation");
                                return n(t);
                            });
                        });
                    })().catch(s);
                    return {};
                })();
                r.___wasm_call_ctors = function() {
                    return (r.___wasm_call_ctors = r.asm.c).apply(null, arguments);
                };
                r._poly1305_auth = function() {
                    return (r._poly1305_auth = r.asm.d).apply(null, arguments);
                };
                var V = r.stackSave = function() {
                    return (V = r.stackSave = r.asm.e).apply(null, arguments);
                }, X = r.stackRestore = function() {
                    return (X = r.stackRestore = r.asm.f).apply(null, arguments);
                }, J = r.stackAlloc = function() {
                    return (J = r.stackAlloc = r.asm.g).apply(null, arguments);
                };
                r._malloc = function() {
                    return (r._malloc = r.asm.h).apply(null, arguments);
                };
                r._free = function() {
                    return (r._free = r.asm.i).apply(null, arguments);
                };
                r.cwrap = function(e, t, r, n) {
                    r = r || [];
                    var s = r.every(function(e) {
                        return "number" === e;
                    });
                    return "string" !== t && s && !n ? b(e) : function() {
                        return C(e, t, r, arguments);
                    };
                };
                var Z;
                U = function e() {
                    Z || ee();
                    Z || (U = e);
                };
                function ee() {
                    function e() {
                        if (!Z && (Z = true, r.calledRun = true, !S)) {
                            Q(O);
                            n(r);
                            if (r.onRuntimeInitialized) r.onRuntimeInitialized();
                            if (r.postRun) for ("function" == typeof r.postRun && (r.postRun = [ r.postRun ]); r.postRun.length; ) {
                                var e = r.postRun.shift();
                                B.unshift(e);
                            }
                            Q(B);
                        }
                    }
                    if (!(0 < D)) {
                        if (r.preRun) for ("function" == typeof r.preRun && (r.preRun = [ r.preRun ]); r.preRun.length; ) N();
                        Q($);
                        0 < D || (r.setStatus ? (r.setStatus("Running..."), setTimeout(function() {
                            setTimeout(function() {
                                r.setStatus("");
                            }, 1);
                            e();
                        }, 1)) : e());
                    }
                }
                r.run = ee;
                if (r.preInit) for ("function" == typeof r.preInit && (r.preInit = [ r.preInit ]); 0 < r.preInit.length; ) r.preInit.pop()();
                ee();
                return t.ready;
            };
        }();
        e.exports = r;
    })(poly1305, poly1305.exports);
    return poly1305.exports;
}

var crypto$1;

var hasRequiredCrypto;

function requireCrypto() {
    if (hasRequiredCrypto) return crypto$1;
    hasRequiredCrypto = 1;
    const {createCipheriv: e, createDecipheriv: t, createHmac: r, randomFillSync: n, timingSafeEqual: s} = require$$0__default$3.default;
    const {readUInt32BE: o, writeUInt32BE: a} = requireUtils();
    const l = Buffer[Symbol.species];
    const c = 2 ** 32 - 1;
    const u = Buffer.alloc(0);
    const d = Buffer.alloc(4);
    const h = new Map;
    const p = 35e3;
    let g;
    let m;
    let _;
    let E;
    let v;
    let y;
    let S;
    try {
        g = require("./crypto/build/Release/sshcrypto.node");
        ({AESGCMCipher: m, ChaChaPolyCipher: _, GenericCipher: E, AESGCMDecipher: v, ChaChaPolyDecipher: y, GenericDecipher: S} = g);
    } catch {}
    const A = 1 << 0;
    const b = (() => {
        function e(e, t, r, n, s, o, a) {
            return {
                sslName: e,
                blockLen: t,
                keyLen: r,
                ivLen: n !== 0 || a & A ? n : t,
                authLen: s,
                discardLen: o,
                stream: !!(a & A)
            };
        }
        return {
            "chacha20-poly1305@openssh.com": e("chacha20", 8, 64, 0, 16, 0, A),
            "aes128-gcm": e("aes-128-gcm", 16, 16, 12, 16, 0, A),
            "aes256-gcm": e("aes-256-gcm", 16, 32, 12, 16, 0, A),
            "aes128-gcm@openssh.com": e("aes-128-gcm", 16, 16, 12, 16, 0, A),
            "aes256-gcm@openssh.com": e("aes-256-gcm", 16, 32, 12, 16, 0, A),
            "aes128-cbc": e("aes-128-cbc", 16, 16, 0, 0, 0, 0),
            "aes192-cbc": e("aes-192-cbc", 16, 24, 0, 0, 0, 0),
            "aes256-cbc": e("aes-256-cbc", 16, 32, 0, 0, 0, 0),
            "rijndael-cbc@lysator.liu.se": e("aes-256-cbc", 16, 32, 0, 0, 0, 0),
            "3des-cbc": e("des-ede3-cbc", 8, 24, 0, 0, 0, 0),
            "blowfish-cbc": e("bf-cbc", 8, 16, 0, 0, 0, 0),
            "idea-cbc": e("idea-cbc", 8, 16, 0, 0, 0, 0),
            "cast128-cbc": e("cast-cbc", 8, 16, 0, 0, 0, 0),
            "aes128-ctr": e("aes-128-ctr", 16, 16, 16, 0, 0, A),
            "aes192-ctr": e("aes-192-ctr", 16, 24, 16, 0, 0, A),
            "aes256-ctr": e("aes-256-ctr", 16, 32, 16, 0, 0, A),
            "3des-ctr": e("des-ede3", 8, 24, 8, 0, 0, A),
            "blowfish-ctr": e("bf-ecb", 8, 16, 8, 0, 0, A),
            "cast128-ctr": e("cast5-ecb", 8, 16, 8, 0, 0, A),
            arcfour: e("rc4", 8, 16, 0, 0, 1536, A),
            arcfour128: e("rc4", 8, 16, 0, 0, 1536, A),
            arcfour256: e("rc4", 8, 32, 0, 0, 1536, A),
            arcfour512: e("rc4", 8, 64, 0, 0, 1536, A)
        };
    })();
    const C = (() => {
        function e(e, t, r, n) {
            return {
                sslName: e,
                len: t,
                actualLen: r,
                isETM: n
            };
        }
        return {
            "hmac-md5": e("md5", 16, 16, false),
            "hmac-md5-96": e("md5", 16, 12, false),
            "hmac-ripemd160": e("ripemd160", 20, 20, false),
            "hmac-sha1": e("sha1", 20, 20, false),
            "hmac-sha1-etm@openssh.com": e("sha1", 20, 20, true),
            "hmac-sha1-96": e("sha1", 20, 12, false),
            "hmac-sha2-256": e("sha256", 32, 32, false),
            "hmac-sha2-256-etm@openssh.com": e("sha256", 32, 32, true),
            "hmac-sha2-256-96": e("sha256", 32, 12, false),
            "hmac-sha2-512": e("sha512", 64, 64, false),
            "hmac-sha2-512-etm@openssh.com": e("sha512", 64, 64, true),
            "hmac-sha2-512-96": e("sha512", 64, 12, false)
        };
    })();
    class NullCipher {
        constructor(e, t) {
            this.outSeqno = e;
            this._onWrite = t;
            this._dead = false;
        }
        free() {
            this._dead = true;
        }
        allocPacket(e) {
            let t = 4 + 1 + e;
            let r = 8 - (t & 8 - 1);
            if (r < 4) r += 8;
            t += r;
            const s = Buffer.allocUnsafe(t);
            a(s, t - 4, 0);
            s[4] = r;
            n(s, 5 + e, r);
            return s;
        }
        encrypt(e) {
            if (this._dead) return;
            this._onWrite(e);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    const w = Buffer.alloc(32);
    const I = Buffer.alloc(16);
    let T;
    let R;
    let k;
    class ChaChaPolyCipherNative {
        constructor(e) {
            const t = e.outbound;
            this.outSeqno = t.seqno;
            this._onWrite = t.onWrite;
            this._encKeyMain = t.cipherKey.slice(0, 32);
            this._encKeyPktLen = t.cipherKey.slice(32);
            this._dead = false;
        }
        free() {
            this._dead = true;
        }
        allocPacket(e) {
            let t = 4 + 1 + e;
            let r = 8 - (t - 4 & 8 - 1);
            if (r < 4) r += 8;
            t += r;
            const s = Buffer.allocUnsafe(t);
            a(s, t - 4, 0);
            s[4] = r;
            n(s, 5 + e, r);
            return s;
        }
        encrypt(t) {
            if (this._dead) return;
            I[0] = 0;
            a(I, this.outSeqno, 12);
            const r = e("chacha20", this._encKeyMain, I).update(w);
            const n = e("chacha20", this._encKeyPktLen, I).update(t.slice(0, 4));
            this._onWrite(n);
            I[0] = 1;
            const s = e("chacha20", this._encKeyMain, I).update(t.slice(4));
            this._onWrite(s);
            k(R, n, n.length, s, s.length, r);
            const o = Buffer.allocUnsafe(16);
            o.set(new Uint8Array(T.HEAPU8.buffer, R, 16), 0);
            this._onWrite(o);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class ChaChaPolyCipherBinding {
        constructor(e) {
            const t = e.outbound;
            this.outSeqno = t.seqno;
            this._onWrite = t.onWrite;
            this._instance = new _(t.cipherKey);
            this._dead = false;
        }
        free() {
            this._dead = true;
            this._instance.free();
        }
        allocPacket(e) {
            let t = 4 + 1 + e;
            let r = 8 - (t - 4 & 8 - 1);
            if (r < 4) r += 8;
            t += r;
            const s = Buffer.allocUnsafe(t + 16);
            a(s, t - 4, 0);
            s[4] = r;
            n(s, 5 + e, r);
            return s;
        }
        encrypt(e) {
            if (this._dead) return;
            this._instance.encrypt(e, this.outSeqno);
            this._onWrite(e);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class AESGCMCipherNative {
        constructor(e) {
            const t = e.outbound;
            this.outSeqno = t.seqno;
            this._onWrite = t.onWrite;
            this._encSSLName = t.cipherInfo.sslName;
            this._encKey = t.cipherKey;
            this._encIV = t.cipherIV;
            this._dead = false;
        }
        free() {
            this._dead = true;
        }
        allocPacket(e) {
            let t = 4 + 1 + e;
            let r = 16 - (t - 4 & 16 - 1);
            if (r < 4) r += 16;
            t += r;
            const s = Buffer.allocUnsafe(t);
            a(s, t - 4, 0);
            s[4] = r;
            n(s, 5 + e, r);
            return s;
        }
        encrypt(t) {
            if (this._dead) return;
            const r = e(this._encSSLName, this._encKey, this._encIV);
            r.setAutoPadding(false);
            const n = t.slice(0, 4);
            r.setAAD(n);
            this._onWrite(n);
            const s = r.update(t.slice(4));
            this._onWrite(s);
            const o = r.final();
            if (o.length) this._onWrite(o);
            const a = r.getAuthTag();
            this._onWrite(a);
            P(this._encIV);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class AESGCMCipherBinding {
        constructor(e) {
            const t = e.outbound;
            this.outSeqno = t.seqno;
            this._onWrite = t.onWrite;
            this._instance = new m(t.cipherInfo.sslName, t.cipherKey, t.cipherIV);
            this._dead = false;
        }
        free() {
            this._dead = true;
            this._instance.free();
        }
        allocPacket(e) {
            let t = 4 + 1 + e;
            let r = 16 - (t - 4 & 16 - 1);
            if (r < 4) r += 16;
            t += r;
            const s = Buffer.allocUnsafe(t + 16);
            a(s, t - 4, 0);
            s[4] = r;
            n(s, 5 + e, r);
            return s;
        }
        encrypt(e) {
            if (this._dead) return;
            this._instance.encrypt(e);
            this._onWrite(e);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class GenericCipherNative {
        constructor(t) {
            const r = t.outbound;
            this.outSeqno = r.seqno;
            this._onWrite = r.onWrite;
            this._encBlockLen = r.cipherInfo.blockLen;
            this._cipherInstance = e(r.cipherInfo.sslName, r.cipherKey, r.cipherIV);
            this._macSSLName = r.macInfo.sslName;
            this._macKey = r.macKey;
            this._macActualLen = r.macInfo.actualLen;
            this._macETM = r.macInfo.isETM;
            this._aadLen = this._macETM ? 4 : 0;
            this._dead = false;
            const n = r.cipherInfo.discardLen;
            if (n) {
                let e = h.get(n);
                if (e === undefined) {
                    e = Buffer.alloc(n);
                    h.set(n, e);
                }
                this._cipherInstance.update(e);
            }
        }
        free() {
            this._dead = true;
        }
        allocPacket(e) {
            const t = this._encBlockLen;
            let r = 4 + 1 + e;
            let s = t - (r - this._aadLen & t - 1);
            if (s < 4) s += t;
            r += s;
            const o = Buffer.allocUnsafe(r);
            a(o, r - 4, 0);
            o[4] = s;
            n(o, 5 + e, s);
            return o;
        }
        encrypt(e) {
            if (this._dead) return;
            let t;
            if (this._macETM) {
                const n = new Uint8Array(e.buffer, e.byteOffset, 4);
                const s = this._cipherInstance.update(new Uint8Array(e.buffer, e.byteOffset + 4, e.length - 4));
                this._onWrite(n);
                this._onWrite(s);
                t = r(this._macSSLName, this._macKey);
                a(d, this.outSeqno, 0);
                t.update(d);
                t.update(n);
                t.update(s);
            } else {
                const n = this._cipherInstance.update(e);
                this._onWrite(n);
                t = r(this._macSSLName, this._macKey);
                a(d, this.outSeqno, 0);
                t.update(d);
                t.update(e);
            }
            let n = t.digest();
            if (n.length > this._macActualLen) n = n.slice(0, this._macActualLen);
            this._onWrite(n);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class GenericCipherBinding {
        constructor(e) {
            const t = e.outbound;
            this.outSeqno = t.seqno;
            this._onWrite = t.onWrite;
            this._encBlockLen = t.cipherInfo.blockLen;
            this._macLen = t.macInfo.len;
            this._macActualLen = t.macInfo.actualLen;
            this._aadLen = t.macInfo.isETM ? 4 : 0;
            this._instance = new E(t.cipherInfo.sslName, t.cipherKey, t.cipherIV, t.macInfo.sslName, t.macKey, t.macInfo.isETM);
            this._dead = false;
        }
        free() {
            this._dead = true;
            this._instance.free();
        }
        allocPacket(e) {
            const t = this._encBlockLen;
            let r = 4 + 1 + e;
            let s = t - (r - this._aadLen & t - 1);
            if (s < 4) s += t;
            r += s;
            const o = Buffer.allocUnsafe(r + this._macLen);
            a(o, r - 4, 0);
            o[4] = s;
            n(o, 5 + e, s);
            return o;
        }
        encrypt(e) {
            if (this._dead) return;
            this._instance.encrypt(e, this.outSeqno);
            if (this._macActualLen < this._macLen) {
                e = new l(e.buffer, e.byteOffset, e.length - (this._macLen - this._macActualLen));
            }
            this._onWrite(e);
            this.outSeqno = this.outSeqno + 1 >>> 0;
        }
    }
    class NullDecipher {
        constructor(e, t) {
            this.inSeqno = e;
            this._onPayload = t;
            this._len = 0;
            this._lenBytes = 0;
            this._packet = null;
            this._packetPos = 0;
        }
        free() {}
        decrypt(e, t, r) {
            while (t < r) {
                if (this._lenBytes < 4) {
                    let n = Math.min(4 - this._lenBytes, r - t);
                    this._lenBytes += n;
                    while (n--) this._len = (this._len << 8) + e[t++];
                    if (this._lenBytes < 4) return;
                    if (this._len > p || this._len < 8 || (4 + this._len & 7) !== 0) {
                        throw new Error("Bad packet length");
                    }
                    if (t >= r) return;
                }
                if (this._packetPos < this._len) {
                    const n = Math.min(this._len - this._packetPos, r - t);
                    let s;
                    if (t !== 0 || n !== r) s = new Uint8Array(e.buffer, e.byteOffset + t, n); else s = e;
                    if (n === this._len) {
                        this._packet = s;
                    } else {
                        if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(s, this._packetPos);
                    }
                    t += n;
                    this._packetPos += n;
                    if (this._packetPos < this._len) return;
                }
                const n = !this._packet ? u : new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._len = 0;
                this._lenBytes = 0;
                this._packet = null;
                this._packetPos = 0;
                {
                    const e = this._onPayload(n);
                    if (e !== undefined) return e === false ? t : e;
                }
            }
        }
    }
    class ChaChaPolyDecipherNative {
        constructor(e) {
            const t = e.inbound;
            this.inSeqno = t.seqno;
            this._onPayload = t.onPayload;
            this._decKeyMain = t.decipherKey.slice(0, 32);
            this._decKeyPktLen = t.decipherKey.slice(32);
            this._len = 0;
            this._lenBuf = Buffer.alloc(4);
            this._lenPos = 0;
            this._packet = null;
            this._pktLen = 0;
            this._mac = Buffer.allocUnsafe(16);
            this._calcMac = Buffer.allocUnsafe(16);
            this._macPos = 0;
        }
        free() {}
        decrypt(r, n, c) {
            while (n < c) {
                if (this._lenPos < 4) {
                    let e = Math.min(4 - this._lenPos, c - n);
                    while (e--) this._lenBuf[this._lenPos++] = r[n++];
                    if (this._lenPos < 4) return;
                    I[0] = 0;
                    a(I, this.inSeqno, 12);
                    const s = t("chacha20", this._decKeyPktLen, I).update(this._lenBuf);
                    this._len = o(s, 0);
                    if (this._len > p || this._len < 8 || (this._len & 7) !== 0) {
                        throw new Error("Bad packet length");
                    }
                }
                if (this._pktLen < this._len) {
                    if (n >= c) return;
                    const e = Math.min(this._len - this._pktLen, c - n);
                    let t;
                    if (n !== 0 || e !== c) t = new Uint8Array(r.buffer, r.byteOffset + n, e); else t = r;
                    if (e === this._len) {
                        this._packet = t;
                    } else {
                        if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(t, this._pktLen);
                    }
                    n += e;
                    this._pktLen += e;
                    if (this._pktLen < this._len || n >= c) return;
                }
                {
                    const e = Math.min(16 - this._macPos, c - n);
                    if (n !== 0 || e !== c) {
                        this._mac.set(new Uint8Array(r.buffer, r.byteOffset + n, e), this._macPos);
                    } else {
                        this._mac.set(r, this._macPos);
                    }
                    n += e;
                    this._macPos += e;
                    if (this._macPos < 16) return;
                }
                I[0] = 0;
                a(I, this.inSeqno, 12);
                const u = e("chacha20", this._decKeyMain, I).update(w);
                k(R, this._lenBuf, 4, this._packet, this._packet.length, u);
                this._calcMac.set(new Uint8Array(T.HEAPU8.buffer, R, 16), 0);
                if (!s(this._calcMac, this._mac)) throw new Error("Invalid MAC");
                I[0] = 1;
                const d = t("chacha20", this._decKeyMain, I).update(this._packet);
                const h = new l(d.buffer, d.byteOffset + 1, d.length - d[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._len = 0;
                this._lenPos = 0;
                this._packet = null;
                this._pktLen = 0;
                this._macPos = 0;
                {
                    const e = this._onPayload(h);
                    if (e !== undefined) return e === false ? n : e;
                }
            }
        }
    }
    class ChaChaPolyDecipherBinding {
        constructor(e) {
            const t = e.inbound;
            this.inSeqno = t.seqno;
            this._onPayload = t.onPayload;
            this._instance = new y(t.decipherKey);
            this._len = 0;
            this._lenBuf = Buffer.alloc(4);
            this._lenPos = 0;
            this._packet = null;
            this._pktLen = 0;
            this._mac = Buffer.allocUnsafe(16);
            this._macPos = 0;
        }
        free() {
            this._instance.free();
        }
        decrypt(e, t, r) {
            while (t < r) {
                if (this._lenPos < 4) {
                    let n = Math.min(4 - this._lenPos, r - t);
                    while (n--) this._lenBuf[this._lenPos++] = e[t++];
                    if (this._lenPos < 4) return;
                    this._len = this._instance.decryptLen(this._lenBuf, this.inSeqno);
                    if (this._len > p || this._len < 8 || (this._len & 7) !== 0) {
                        throw new Error("Bad packet length");
                    }
                    if (t >= r) return;
                }
                if (this._pktLen < this._len) {
                    const n = Math.min(this._len - this._pktLen, r - t);
                    let s;
                    if (t !== 0 || n !== r) s = new Uint8Array(e.buffer, e.byteOffset + t, n); else s = e;
                    if (n === this._len) {
                        this._packet = s;
                    } else {
                        if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(s, this._pktLen);
                    }
                    t += n;
                    this._pktLen += n;
                    if (this._pktLen < this._len || t >= r) return;
                }
                {
                    const n = Math.min(16 - this._macPos, r - t);
                    if (t !== 0 || n !== r) {
                        this._mac.set(new Uint8Array(e.buffer, e.byteOffset + t, n), this._macPos);
                    } else {
                        this._mac.set(e, this._macPos);
                    }
                    t += n;
                    this._macPos += n;
                    if (this._macPos < 16) return;
                }
                this._instance.decrypt(this._packet, this._mac, this.inSeqno);
                const n = new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._len = 0;
                this._lenPos = 0;
                this._packet = null;
                this._pktLen = 0;
                this._macPos = 0;
                {
                    const e = this._onPayload(n);
                    if (e !== undefined) return e === false ? t : e;
                }
            }
        }
    }
    class AESGCMDecipherNative {
        constructor(e) {
            const t = e.inbound;
            this.inSeqno = t.seqno;
            this._onPayload = t.onPayload;
            this._decipherInstance = null;
            this._decipherSSLName = t.decipherInfo.sslName;
            this._decipherKey = t.decipherKey;
            this._decipherIV = t.decipherIV;
            this._len = 0;
            this._lenBytes = 0;
            this._packet = null;
            this._packetPos = 0;
            this._pktLen = 0;
            this._tag = Buffer.allocUnsafe(16);
            this._tagPos = 0;
        }
        free() {}
        decrypt(e, r, n) {
            while (r < n) {
                if (this._lenBytes < 4) {
                    let s = Math.min(4 - this._lenBytes, n - r);
                    this._lenBytes += s;
                    while (s--) this._len = (this._len << 8) + e[r++];
                    if (this._lenBytes < 4) return;
                    if (this._len + 20 > p || this._len < 16 || (this._len & 15) !== 0) {
                        throw new Error("Bad packet length");
                    }
                    this._decipherInstance = t(this._decipherSSLName, this._decipherKey, this._decipherIV);
                    this._decipherInstance.setAutoPadding(false);
                    this._decipherInstance.setAAD($(this._len));
                }
                if (this._pktLen < this._len) {
                    if (r >= n) return;
                    const t = Math.min(this._len - this._pktLen, n - r);
                    let s;
                    if (r !== 0 || t !== n) {
                        s = this._decipherInstance.update(new Uint8Array(e.buffer, e.byteOffset + r, t));
                    } else {
                        s = this._decipherInstance.update(e);
                    }
                    if (s.length) {
                        if (t === this._len) {
                            this._packet = s;
                        } else {
                            if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                            this._packet.set(s, this._packetPos);
                        }
                        this._packetPos += s.length;
                    }
                    r += t;
                    this._pktLen += t;
                    if (this._pktLen < this._len || r >= n) return;
                }
                {
                    const t = Math.min(16 - this._tagPos, n - r);
                    if (r !== 0 || t !== n) {
                        this._tag.set(new Uint8Array(e.buffer, e.byteOffset + r, t), this._tagPos);
                    } else {
                        this._tag.set(e, this._tagPos);
                    }
                    r += t;
                    this._tagPos += t;
                    if (this._tagPos < 16) return;
                }
                {
                    this._decipherInstance.setAuthTag(this._tag);
                    const e = this._decipherInstance.final();
                    if (e.length) {
                        if (this._packet) this._packet.set(e, this._packetPos); else this._packet = e;
                    }
                }
                const s = !this._packet ? u : new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                P(this._decipherIV);
                this._len = 0;
                this._lenBytes = 0;
                this._packet = null;
                this._packetPos = 0;
                this._pktLen = 0;
                this._tagPos = 0;
                {
                    const e = this._onPayload(s);
                    if (e !== undefined) return e === false ? r : e;
                }
            }
        }
    }
    class AESGCMDecipherBinding {
        constructor(e) {
            const t = e.inbound;
            this.inSeqno = t.seqno;
            this._onPayload = t.onPayload;
            this._instance = new v(t.decipherInfo.sslName, t.decipherKey, t.decipherIV);
            this._len = 0;
            this._lenBytes = 0;
            this._packet = null;
            this._pktLen = 0;
            this._tag = Buffer.allocUnsafe(16);
            this._tagPos = 0;
        }
        free() {}
        decrypt(e, t, r) {
            while (t < r) {
                if (this._lenBytes < 4) {
                    let n = Math.min(4 - this._lenBytes, r - t);
                    this._lenBytes += n;
                    while (n--) this._len = (this._len << 8) + e[t++];
                    if (this._lenBytes < 4) return;
                    if (this._len + 20 > p || this._len < 16 || (this._len & 15) !== 0) {
                        throw new Error(`Bad packet length: ${this._len}`);
                    }
                }
                if (this._pktLen < this._len) {
                    if (t >= r) return;
                    const n = Math.min(this._len - this._pktLen, r - t);
                    let s;
                    if (t !== 0 || n !== r) s = new Uint8Array(e.buffer, e.byteOffset + t, n); else s = e;
                    if (n === this._len) {
                        this._packet = s;
                    } else {
                        if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(s, this._pktLen);
                    }
                    t += n;
                    this._pktLen += n;
                    if (this._pktLen < this._len || t >= r) return;
                }
                {
                    const n = Math.min(16 - this._tagPos, r - t);
                    if (t !== 0 || n !== r) {
                        this._tag.set(new Uint8Array(e.buffer, e.byteOffset + t, n), this._tagPos);
                    } else {
                        this._tag.set(e, this._tagPos);
                    }
                    t += n;
                    this._tagPos += n;
                    if (this._tagPos < 16) return;
                }
                this._instance.decrypt(this._packet, this._len, this._tag);
                const n = new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._len = 0;
                this._lenBytes = 0;
                this._packet = null;
                this._pktLen = 0;
                this._tagPos = 0;
                {
                    const e = this._onPayload(n);
                    if (e !== undefined) return e === false ? t : e;
                }
            }
        }
    }
    class GenericDecipherNative {
        constructor(e) {
            const r = e.inbound;
            this.inSeqno = r.seqno;
            this._onPayload = r.onPayload;
            this._decipherInstance = t(r.decipherInfo.sslName, r.decipherKey, r.decipherIV);
            this._decipherInstance.setAutoPadding(false);
            this._block = Buffer.allocUnsafe(r.macInfo.isETM ? 4 : r.decipherInfo.blockLen);
            this._blockSize = r.decipherInfo.blockLen;
            this._blockPos = 0;
            this._len = 0;
            this._packet = null;
            this._packetPos = 0;
            this._pktLen = 0;
            this._mac = Buffer.allocUnsafe(r.macInfo.actualLen);
            this._macPos = 0;
            this._macSSLName = r.macInfo.sslName;
            this._macKey = r.macKey;
            this._macActualLen = r.macInfo.actualLen;
            this._macETM = r.macInfo.isETM;
            this._macInstance = null;
            const n = r.decipherInfo.discardLen;
            if (n) {
                let e = h.get(n);
                if (e === undefined) {
                    e = Buffer.alloc(n);
                    h.set(n, e);
                }
                this._decipherInstance.update(e);
            }
        }
        free() {}
        decrypt(e, t, n) {
            while (t < n) {
                if (this._blockPos < this._block.length) {
                    const s = Math.min(this._block.length - this._blockPos, n - t);
                    if (t !== 0 || s !== n || s < e.length) {
                        this._block.set(new Uint8Array(e.buffer, e.byteOffset + t, s), this._blockPos);
                    } else {
                        this._block.set(e, this._blockPos);
                    }
                    t += s;
                    this._blockPos += s;
                    if (this._blockPos < this._block.length) return;
                    let l;
                    let c;
                    if (this._macETM) {
                        this._len = c = o(this._block, 0);
                    } else {
                        l = this._decipherInstance.update(this._block);
                        this._len = o(l, 0);
                        c = 4 + this._len - this._blockSize;
                    }
                    if (this._len > p || this._len < 5 || (c & this._blockSize - 1) !== 0) {
                        throw new Error("Bad packet length");
                    }
                    this._macInstance = r(this._macSSLName, this._macKey);
                    a(d, this.inSeqno, 0);
                    this._macInstance.update(d);
                    if (this._macETM) {
                        this._macInstance.update(this._block);
                    } else {
                        this._macInstance.update(new Uint8Array(l.buffer, l.byteOffset, 4));
                        this._pktLen = l.length - 4;
                        this._packetPos = this._pktLen;
                        this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(new Uint8Array(l.buffer, l.byteOffset + 4, this._packetPos), 0);
                    }
                    if (t >= n) return;
                }
                if (this._pktLen < this._len) {
                    const r = Math.min(this._len - this._pktLen, n - t);
                    let s;
                    if (t !== 0 || r !== n) s = new Uint8Array(e.buffer, e.byteOffset + t, r); else s = e;
                    if (this._macETM) this._macInstance.update(s);
                    const o = this._decipherInstance.update(s);
                    if (o.length) {
                        if (r === this._len) {
                            this._packet = o;
                        } else {
                            if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                            this._packet.set(o, this._packetPos);
                        }
                        this._packetPos += o.length;
                    }
                    t += r;
                    this._pktLen += r;
                    if (this._pktLen < this._len || t >= n) return;
                }
                {
                    const r = Math.min(this._macActualLen - this._macPos, n - t);
                    if (t !== 0 || r !== n) {
                        this._mac.set(new Uint8Array(e.buffer, e.byteOffset + t, r), this._macPos);
                    } else {
                        this._mac.set(e, this._macPos);
                    }
                    t += r;
                    this._macPos += r;
                    if (this._macPos < this._macActualLen) return;
                }
                if (!this._macETM) this._macInstance.update(this._packet);
                let s = this._macInstance.digest();
                if (this._macActualLen < s.length) {
                    s = new Uint8Array(s.buffer, s.byteOffset, this._macActualLen);
                }
                if (!O(s, this._mac)) throw new Error("Invalid MAC");
                const c = new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._blockPos = 0;
                this._len = 0;
                this._packet = null;
                this._packetPos = 0;
                this._pktLen = 0;
                this._macPos = 0;
                this._macInstance = null;
                {
                    const e = this._onPayload(c);
                    if (e !== undefined) return e === false ? t : e;
                }
            }
        }
    }
    class GenericDecipherBinding {
        constructor(e) {
            const t = e.inbound;
            this.inSeqno = t.seqno;
            this._onPayload = t.onPayload;
            this._instance = new S(t.decipherInfo.sslName, t.decipherKey, t.decipherIV, t.macInfo.sslName, t.macKey, t.macInfo.isETM, t.macInfo.actualLen);
            this._block = Buffer.allocUnsafe(t.macInfo.isETM || t.decipherInfo.stream ? 4 : t.decipherInfo.blockLen);
            this._blockPos = 0;
            this._len = 0;
            this._packet = null;
            this._pktLen = 0;
            this._mac = Buffer.allocUnsafe(t.macInfo.actualLen);
            this._macPos = 0;
            this._macActualLen = t.macInfo.actualLen;
            this._macETM = t.macInfo.isETM;
        }
        free() {
            this._instance.free();
        }
        decrypt(e, t, r) {
            while (t < r) {
                if (this._blockPos < this._block.length) {
                    const n = Math.min(this._block.length - this._blockPos, r - t);
                    if (t !== 0 || n !== r || n < e.length) {
                        this._block.set(new Uint8Array(e.buffer, e.byteOffset + t, n), this._blockPos);
                    } else {
                        this._block.set(e, this._blockPos);
                    }
                    t += n;
                    this._blockPos += n;
                    if (this._blockPos < this._block.length) return;
                    let s;
                    if (this._macETM) {
                        this._len = s = o(this._block, 0);
                    } else {
                        this._instance.decryptBlock(this._block);
                        this._len = o(this._block, 0);
                        s = 4 + this._len - this._block.length;
                    }
                    if (this._len > p || this._len < 5 || (s & this._block.length - 1) !== 0) {
                        throw new Error("Bad packet length");
                    }
                    if (!this._macETM) {
                        this._pktLen = this._block.length - 4;
                        if (this._pktLen) {
                            this._packet = Buffer.allocUnsafe(this._len);
                            this._packet.set(new Uint8Array(this._block.buffer, this._block.byteOffset + 4, this._pktLen), 0);
                        }
                    }
                    if (t >= r) return;
                }
                if (this._pktLen < this._len) {
                    const n = Math.min(this._len - this._pktLen, r - t);
                    let s;
                    if (t !== 0 || n !== r) s = new Uint8Array(e.buffer, e.byteOffset + t, n); else s = e;
                    if (n === this._len) {
                        this._packet = s;
                    } else {
                        if (!this._packet) this._packet = Buffer.allocUnsafe(this._len);
                        this._packet.set(s, this._pktLen);
                    }
                    t += n;
                    this._pktLen += n;
                    if (this._pktLen < this._len || t >= r) return;
                }
                {
                    const n = Math.min(this._macActualLen - this._macPos, r - t);
                    if (t !== 0 || n !== r) {
                        this._mac.set(new Uint8Array(e.buffer, e.byteOffset + t, n), this._macPos);
                    } else {
                        this._mac.set(e, this._macPos);
                    }
                    t += n;
                    this._macPos += n;
                    if (this._macPos < this._macActualLen) return;
                }
                this._instance.decrypt(this._packet, this.inSeqno, this._block, this._mac);
                const n = new l(this._packet.buffer, this._packet.byteOffset + 1, this._packet.length - this._packet[0] - 1);
                this.inSeqno = this.inSeqno + 1 >>> 0;
                this._blockPos = 0;
                this._len = 0;
                this._packet = null;
                this._pktLen = 0;
                this._macPos = 0;
                this._macInstance = null;
                {
                    const e = this._onPayload(n);
                    if (e !== undefined) return e === false ? t : e;
                }
            }
        }
    }
    function P(e) {
        ++e[11] >>> 8 && ++e[10] >>> 8 && ++e[9] >>> 8 && ++e[8] >>> 8 && ++e[7] >>> 8 && ++e[6] >>> 8 && ++e[5] >>> 8 && ++e[4] >>> 8;
    }
    const $ = (() => {
        const e = Buffer.alloc(4);
        return t => {
            e[0] = t >>> 24;
            e[1] = t >>> 16;
            e[2] = t >>> 8;
            e[3] = t;
            return e;
        };
    })();
    function O(e, t) {
        if (e.length !== t.length) {
            s(e, e);
            return false;
        }
        return s(e, t);
    }
    function B(e) {
        if (typeof e !== "object" || e === null) throw new Error("Invalid config");
        if (typeof e.outbound !== "object" || e.outbound === null) throw new Error("Invalid outbound");
        const t = e.outbound;
        if (typeof t.onWrite !== "function") throw new Error("Invalid outbound.onWrite");
        if (typeof t.cipherInfo !== "object" || t.cipherInfo === null) throw new Error("Invalid outbound.cipherInfo");
        if (!Buffer.isBuffer(t.cipherKey) || t.cipherKey.length !== t.cipherInfo.keyLen) {
            throw new Error("Invalid outbound.cipherKey");
        }
        if (t.cipherInfo.ivLen && (!Buffer.isBuffer(t.cipherIV) || t.cipherIV.length !== t.cipherInfo.ivLen)) {
            throw new Error("Invalid outbound.cipherIV");
        }
        if (typeof t.seqno !== "number" || t.seqno < 0 || t.seqno > c) {
            throw new Error("Invalid outbound.seqno");
        }
        const r = !!t.forceNative;
        switch (t.cipherInfo.sslName) {
          case "aes-128-gcm":
          case "aes-256-gcm":
            return m && !r ? new AESGCMCipherBinding(e) : new AESGCMCipherNative(e);

          case "chacha20":
            return _ && !r ? new ChaChaPolyCipherBinding(e) : new ChaChaPolyCipherNative(e);

          default:
            {
                if (typeof t.macInfo !== "object" || t.macInfo === null) throw new Error("Invalid outbound.macInfo");
                if (!Buffer.isBuffer(t.macKey) || t.macKey.length !== t.macInfo.len) {
                    throw new Error("Invalid outbound.macKey");
                }
                return E && !r ? new GenericCipherBinding(e) : new GenericCipherNative(e);
            }
        }
    }
    function N(e) {
        if (typeof e !== "object" || e === null) throw new Error("Invalid config");
        if (typeof e.inbound !== "object" || e.inbound === null) throw new Error("Invalid inbound");
        const t = e.inbound;
        if (typeof t.onPayload !== "function") throw new Error("Invalid inbound.onPayload");
        if (typeof t.decipherInfo !== "object" || t.decipherInfo === null) {
            throw new Error("Invalid inbound.decipherInfo");
        }
        if (!Buffer.isBuffer(t.decipherKey) || t.decipherKey.length !== t.decipherInfo.keyLen) {
            throw new Error("Invalid inbound.decipherKey");
        }
        if (t.decipherInfo.ivLen && (!Buffer.isBuffer(t.decipherIV) || t.decipherIV.length !== t.decipherInfo.ivLen)) {
            throw new Error("Invalid inbound.decipherIV");
        }
        if (typeof t.seqno !== "number" || t.seqno < 0 || t.seqno > c) {
            throw new Error("Invalid inbound.seqno");
        }
        const r = !!t.forceNative;
        switch (t.decipherInfo.sslName) {
          case "aes-128-gcm":
          case "aes-256-gcm":
            return v && !r ? new AESGCMDecipherBinding(e) : new AESGCMDecipherNative(e);

          case "chacha20":
            return y && !r ? new ChaChaPolyDecipherBinding(e) : new ChaChaPolyDecipherNative(e);

          default:
            {
                if (typeof t.macInfo !== "object" || t.macInfo === null) throw new Error("Invalid inbound.macInfo");
                if (!Buffer.isBuffer(t.macKey) || t.macKey.length !== t.macInfo.len) {
                    throw new Error("Invalid inbound.macKey");
                }
                return S && !r ? new GenericDecipherBinding(e) : new GenericDecipherNative(e);
            }
        }
    }
    crypto$1 = {
        CIPHER_INFO: b,
        MAC_INFO: C,
        bindingAvailable: !!g,
        init: (() => new Promise(async (e, t) => {
            try {
                T = await requirePoly1305()();
                R = T._malloc(16);
                k = T.cwrap("poly1305_auth", null, [ "number", "array", "number", "array", "number", "array" ]);
            } catch (e) {
                return t(e);
            }
            e();
        }))(),
        NullCipher: NullCipher,
        createCipher: B,
        NullDecipher: NullDecipher,
        createDecipher: N
    };
    return crypto$1;
}

const {createDecipheriv: createDecipheriv, createECDH: createECDH, createHash: createHash$1, createHmac: createHmac, createSign: createSign, createVerify: createVerify, getCiphers: getCiphers, sign: sign_, verify: verify_} = require$$0__default$3.default;

const supportedOpenSSLCiphers = getCiphers();

const {Ber: Ber$1} = lib$1;

const bcrypt_pbkdf$1 = bcryptPbkdf.pbkdf;

const {CIPHER_INFO: CIPHER_INFO$1} = requireCrypto();

const {eddsaSupported: eddsaSupported$1, SUPPORTED_CIPHER: SUPPORTED_CIPHER$2} = requireConstants();

const {bufferSlice: bufferSlice$4, makeBufferParser: makeBufferParser$3, readString: readString, readUInt32BE: readUInt32BE$2, writeUInt32BE: writeUInt32BE$6} = requireUtils();

const SYM_HASH_ALGO = Symbol("Hash Algorithm");

const SYM_PRIV_PEM = Symbol("Private key PEM");

const SYM_PUB_PEM = Symbol("Public key PEM");

const SYM_PUB_SSH = Symbol("Public key SSH");

const SYM_DECRYPTED = Symbol("Decrypted Key");

const CIPHER_INFO_OPENSSL = Object.create(null);

{
    const t = Object.keys(CIPHER_INFO$1);
    for (let r = 0; r < t.length; ++r) {
        const n = CIPHER_INFO$1[t[r]].sslName;
        if (!n || CIPHER_INFO_OPENSSL[n]) continue;
        CIPHER_INFO_OPENSSL[n] = CIPHER_INFO$1[t[r]];
    }
}

const binaryKeyParser = makeBufferParser$3();

function makePEM(e, t) {
    t = t.base64Slice(0, t.length);
    let r = t.replace(/.{64}/g, "$&\n");
    if (t.length & 63) r += "\n";
    return `-----BEGIN ${e} KEY-----\n${r}-----END ${e} KEY-----`;
}

function combineBuffers(e, t) {
    const r = Buffer.allocUnsafe(e.length + t.length);
    r.set(e, 0);
    r.set(t, e.length);
    return r;
}

function skipFields(e, t) {
    const r = e.length;
    let n = e._pos || 0;
    for (let s = 0; s < t; ++s) {
        const t = r - n;
        if (n >= r || t < 4) return false;
        const s = readUInt32BE$2(e, n);
        if (t < 4 + s) return false;
        n += 4 + s;
    }
    e._pos = n;
    return true;
}

function genOpenSSLRSAPub(e, t) {
    const r = new Ber$1.Writer;
    r.startSequence();
    r.startSequence();
    r.writeOID("1.2.840.113549.1.1.1");
    r.writeNull();
    r.endSequence();
    r.startSequence(Ber$1.BitString);
    r.writeByte(0);
    r.startSequence();
    r.writeBuffer(e, Ber$1.Integer);
    r.writeBuffer(t, Ber$1.Integer);
    r.endSequence();
    r.endSequence();
    r.endSequence();
    return makePEM("PUBLIC", r.buffer);
}

function genOpenSSHRSAPub(e, t) {
    const r = Buffer.allocUnsafe(4 + 7 + 4 + t.length + 4 + e.length);
    writeUInt32BE$6(r, 7, 0);
    r.utf8Write("ssh-rsa", 4, 7);
    let n = 4 + 7;
    writeUInt32BE$6(r, t.length, n);
    r.set(t, n += 4);
    writeUInt32BE$6(r, e.length, n += t.length);
    r.set(e, n + 4);
    return r;
}

const genOpenSSLRSAPriv = (() => {
    function e(e, t, r, n, s, o, a, l) {
        const c = new Ber$1.Writer;
        c.startSequence();
        c.writeInt(0, Ber$1.Integer);
        c.writeBuffer(e, Ber$1.Integer);
        c.writeBuffer(t, Ber$1.Integer);
        c.writeBuffer(r, Ber$1.Integer);
        c.writeBuffer(n, Ber$1.Integer);
        c.writeBuffer(s, Ber$1.Integer);
        c.writeBuffer(o, Ber$1.Integer);
        c.writeBuffer(a, Ber$1.Integer);
        c.writeBuffer(l, Ber$1.Integer);
        c.endSequence();
        return c.buffer;
    }
    function t(e) {
        return BigInt(`0x${e.hexSlice(0, e.length)}`);
    }
    function r(e) {
        let t = e.toString(16);
        if ((t.length & 1) !== 0) {
            t = `0${t}`;
        } else {
            const e = t.charCodeAt(0);
            if (e === 56 || e === 57 || e >= 97 && e <= 102) {
                t = `00${t}`;
            }
        }
        return Buffer.from(t, "hex");
    }
    return function n(s, o, a, l, c, u) {
        const d = t(a);
        const h = r(d % (t(c) - 1n));
        const p = r(d % (t(u) - 1n));
        return makePEM("RSA PRIVATE", e(s, o, a, c, u, h, p, l));
    };
})();

function genOpenSSLDSAPub(e, t, r, n) {
    const s = new Ber$1.Writer;
    s.startSequence();
    s.startSequence();
    s.writeOID("1.2.840.10040.4.1");
    s.startSequence();
    s.writeBuffer(e, Ber$1.Integer);
    s.writeBuffer(t, Ber$1.Integer);
    s.writeBuffer(r, Ber$1.Integer);
    s.endSequence();
    s.endSequence();
    s.startSequence(Ber$1.BitString);
    s.writeByte(0);
    s.writeBuffer(n, Ber$1.Integer);
    s.endSequence();
    s.endSequence();
    return makePEM("PUBLIC", s.buffer);
}

function genOpenSSHDSAPub(e, t, r, n) {
    const s = Buffer.allocUnsafe(4 + 7 + 4 + e.length + 4 + t.length + 4 + r.length + 4 + n.length);
    writeUInt32BE$6(s, 7, 0);
    s.utf8Write("ssh-dss", 4, 7);
    let o = 4 + 7;
    writeUInt32BE$6(s, e.length, o);
    s.set(e, o += 4);
    writeUInt32BE$6(s, t.length, o += e.length);
    s.set(t, o += 4);
    writeUInt32BE$6(s, r.length, o += t.length);
    s.set(r, o += 4);
    writeUInt32BE$6(s, n.length, o += r.length);
    s.set(n, o + 4);
    return s;
}

function genOpenSSLDSAPriv(e, t, r, n, s) {
    const o = new Ber$1.Writer;
    o.startSequence();
    o.writeInt(0, Ber$1.Integer);
    o.writeBuffer(e, Ber$1.Integer);
    o.writeBuffer(t, Ber$1.Integer);
    o.writeBuffer(r, Ber$1.Integer);
    o.writeBuffer(n, Ber$1.Integer);
    o.writeBuffer(s, Ber$1.Integer);
    o.endSequence();
    return makePEM("DSA PRIVATE", o.buffer);
}

function genOpenSSLEdPub(e) {
    const t = new Ber$1.Writer;
    t.startSequence();
    t.startSequence();
    t.writeOID("1.3.101.112");
    t.endSequence();
    t.startSequence(Ber$1.BitString);
    t.writeByte(0);
    t._ensure(e.length);
    t._buf.set(e, t._offset);
    t._offset += e.length;
    t.endSequence();
    t.endSequence();
    return makePEM("PUBLIC", t.buffer);
}

function genOpenSSHEdPub(e) {
    const t = Buffer.allocUnsafe(4 + 11 + 4 + e.length);
    writeUInt32BE$6(t, 11, 0);
    t.utf8Write("ssh-ed25519", 4, 11);
    writeUInt32BE$6(t, e.length, 15);
    t.set(e, 19);
    return t;
}

function genOpenSSLEdPriv(e) {
    const t = new Ber$1.Writer;
    t.startSequence();
    t.writeInt(0, Ber$1.Integer);
    t.startSequence();
    t.writeOID("1.3.101.112");
    t.endSequence();
    t.startSequence(Ber$1.OctetString);
    t.writeBuffer(e, Ber$1.OctetString);
    t.endSequence();
    t.endSequence();
    return makePEM("PRIVATE", t.buffer);
}

function genOpenSSLECDSAPub(e, t) {
    const r = new Ber$1.Writer;
    r.startSequence();
    r.startSequence();
    r.writeOID("1.2.840.10045.2.1");
    r.writeOID(e);
    r.endSequence();
    r.startSequence(Ber$1.BitString);
    r.writeByte(0);
    r._ensure(t.length);
    r._buf.set(t, r._offset);
    r._offset += t.length;
    r.endSequence();
    r.endSequence();
    return makePEM("PUBLIC", r.buffer);
}

function genOpenSSHECDSAPub(e, t) {
    let r;
    switch (e) {
      case "1.2.840.10045.3.1.7":
        r = "nistp256";
        break;

      case "1.3.132.0.34":
        r = "nistp384";
        break;

      case "1.3.132.0.35":
        r = "nistp521";
        break;

      default:
        return;
    }
    const n = Buffer.allocUnsafe(4 + 19 + 4 + 8 + 4 + t.length);
    writeUInt32BE$6(n, 19, 0);
    n.utf8Write(`ecdsa-sha2-${r}`, 4, 19);
    writeUInt32BE$6(n, 8, 23);
    n.utf8Write(r, 27, 8);
    writeUInt32BE$6(n, t.length, 35);
    n.set(t, 39);
    return n;
}

function genOpenSSLECDSAPriv(e, t, r) {
    const n = new Ber$1.Writer;
    n.startSequence();
    n.writeInt(1, Ber$1.Integer);
    n.writeBuffer(r, Ber$1.OctetString);
    n.startSequence(160);
    n.writeOID(e);
    n.endSequence();
    n.startSequence(161);
    n.startSequence(Ber$1.BitString);
    n.writeByte(0);
    n._ensure(t.length);
    n._buf.set(t, n._offset);
    n._offset += t.length;
    n.endSequence();
    n.endSequence();
    n.endSequence();
    return makePEM("EC PRIVATE", n.buffer);
}

function genOpenSSLECDSAPubFromPriv(e, t) {
    const r = createECDH(e);
    r.setPrivateKey(t);
    return r.getPublicKey();
}

const BaseKey = {
    sign: (() => {
        if (typeof sign_ === "function") {
            return function e(t, r) {
                const n = this[SYM_PRIV_PEM];
                if (n === null) return new Error("No private key available");
                if (!r || typeof r !== "string") r = this[SYM_HASH_ALGO];
                try {
                    return sign_(r, t, n);
                } catch (e) {
                    return e;
                }
            };
        }
        return function e(t, r) {
            const n = this[SYM_PRIV_PEM];
            if (n === null) return new Error("No private key available");
            if (!r || typeof r !== "string") r = this[SYM_HASH_ALGO];
            const s = createSign(r);
            s.update(t);
            try {
                return s.sign(n);
            } catch (e) {
                return e;
            }
        };
    })(),
    verify: (() => {
        if (typeof verify_ === "function") {
            return function e(t, r, n) {
                const s = this[SYM_PUB_PEM];
                if (s === null) return new Error("No public key available");
                if (!n || typeof n !== "string") n = this[SYM_HASH_ALGO];
                try {
                    return verify_(n, t, s, r);
                } catch (e) {
                    return e;
                }
            };
        }
        return function e(t, r, n) {
            const s = this[SYM_PUB_PEM];
            if (s === null) return new Error("No public key available");
            if (!n || typeof n !== "string") n = this[SYM_HASH_ALGO];
            const o = createVerify(n);
            o.update(t);
            try {
                return o.verify(s, r);
            } catch (e) {
                return e;
            }
        };
    })(),
    isPrivateKey: function e() {
        return this[SYM_PRIV_PEM] !== null;
    },
    getPrivatePEM: function e() {
        return this[SYM_PRIV_PEM];
    },
    getPublicPEM: function e() {
        return this[SYM_PUB_PEM];
    },
    getPublicSSH: function e() {
        return this[SYM_PUB_SSH];
    },
    equals: function e(t) {
        const r = parseKey$6(t);
        if (r instanceof Error) return false;
        return this.type === r.type && this[SYM_PRIV_PEM] === r[SYM_PRIV_PEM] && this[SYM_PUB_PEM] === r[SYM_PUB_PEM] && this[SYM_PUB_SSH].equals(r[SYM_PUB_SSH]);
    }
};

function OpenSSH_Private(e, t, r, n, s, o, a) {
    this.type = e;
    this.comment = t;
    this[SYM_PRIV_PEM] = r;
    this[SYM_PUB_PEM] = n;
    this[SYM_PUB_SSH] = s;
    this[SYM_HASH_ALGO] = o;
    this[SYM_DECRYPTED] = a;
}

OpenSSH_Private.prototype = BaseKey;

{
    const s = /^-----BEGIN OPENSSH PRIVATE KEY-----(?:\r\n|\n)([\s\S]+)(?:\r\n|\n)-----END OPENSSH PRIVATE KEY-----$/;
    OpenSSH_Private.parse = (e, t) => {
        const r = s.exec(e);
        if (r === null) return null;
        let n;
        const a = Buffer.from(r[1], "base64");
        if (a.length < 31) return new Error("Malformed OpenSSH private key");
        const l = a.utf8Slice(0, 15);
        if (l !== "openssh-key-v1\0") return new Error(`Unsupported OpenSSH key magic: ${l}`);
        const c = readString(a, 15, true);
        if (c === undefined) return new Error("Malformed OpenSSH private key");
        if (c !== "none" && SUPPORTED_CIPHER$2.indexOf(c) === -1) return new Error(`Unsupported cipher for OpenSSH key: ${c}`);
        const u = readString(a, a._pos, true);
        if (u === undefined) return new Error("Malformed OpenSSH private key");
        if (u !== "none") {
            if (c === "none") return new Error("Malformed OpenSSH private key");
            if (u !== "bcrypt") return new Error(`Unsupported kdf name for OpenSSH key: ${u}`);
            if (!t) {
                return new Error("Encrypted private OpenSSH key detected, but no passphrase given");
            }
        } else if (c !== "none") {
            return new Error("Malformed OpenSSH private key");
        }
        let d;
        let h;
        let p;
        if (c !== "none") d = CIPHER_INFO$1[c];
        const g = readString(a, a._pos);
        if (g === undefined) return new Error("Malformed OpenSSH private key");
        if (g.length) {
            switch (u) {
              case "none":
                return new Error("Malformed OpenSSH private key");

              case "bcrypt":
                {
                    const e = readString(g, 0);
                    if (e === undefined || g._pos + 4 > g.length) return new Error("Malformed OpenSSH private key");
                    const r = readUInt32BE$2(g, g._pos);
                    const n = Buffer.allocUnsafe(d.keyLen + d.ivLen);
                    const s = bcrypt_pbkdf$1(t, t.length, e, e.length, n, n.length, r);
                    if (s !== 0) return new Error("Failed to generate information to decrypt key");
                    h = bufferSlice$4(n, 0, d.keyLen);
                    p = bufferSlice$4(n, d.keyLen, n.length);
                    break;
                }
            }
        } else if (u !== "none") {
            return new Error("Malformed OpenSSH private key");
        }
        if (a._pos + 3 >= a.length) return new Error("Malformed OpenSSH private key");
        const m = readUInt32BE$2(a, a._pos);
        a._pos += 4;
        if (m > 0) {
            for (let e = 0; e < m; ++e) {
                const e = readString(a, a._pos);
                if (e === undefined) return new Error("Malformed OpenSSH private key");
                const t = readString(e, 0, true);
                if (t === undefined) return new Error("Malformed OpenSSH private key");
            }
            let e = readString(a, a._pos);
            if (e === undefined) return new Error("Malformed OpenSSH private key");
            if (h !== undefined) {
                if (e.length < d.blockLen || e.length % d.blockLen !== 0) {
                    return new Error("Malformed OpenSSH private key");
                }
                try {
                    const t = {
                        authTagLength: d.authLen
                    };
                    const r = createDecipheriv(d.sslName, h, p, t);
                    r.setAutoPadding(false);
                    if (d.authLen > 0) {
                        if (a.length - a._pos < d.authLen) return new Error("Malformed OpenSSH private key");
                        r.setAuthTag(bufferSlice$4(a, a._pos, a._pos += d.authLen));
                    }
                    e = combineBuffers(r.update(e), r.final());
                } catch (e) {
                    return e;
                }
            }
            if (a._pos !== a.length) return new Error("Malformed OpenSSH private key");
            n = o(e, m, h !== undefined);
        } else {
            n = [];
        }
        if (n instanceof Error) return n;
        return n[0];
    };
    function o(e, t, r) {
        const n = [];
        if (e.length < 8) return new Error("Malformed OpenSSH private key");
        const s = readUInt32BE$2(e, 0);
        const o = readUInt32BE$2(e, 4);
        if (s !== o) {
            if (r) {
                return new Error("OpenSSH key integrity check failed -- bad passphrase?");
            }
            return new Error("OpenSSH key integrity check failed");
        }
        e._pos = 8;
        let a;
        let l;
        for (a = 0; a < t; ++a) {
            let t;
            let s;
            let o;
            let a;
            const c = readString(e, e._pos, true);
            if (c === undefined) return new Error("Malformed OpenSSH private key");
            switch (c) {
              case "ssh-rsa":
                {
                    const r = readString(e, e._pos);
                    if (r === undefined) return new Error("Malformed OpenSSH private key");
                    const n = readString(e, e._pos);
                    if (n === undefined) return new Error("Malformed OpenSSH private key");
                    const l = readString(e, e._pos);
                    if (l === undefined) return new Error("Malformed OpenSSH private key");
                    const c = readString(e, e._pos);
                    if (c === undefined) return new Error("Malformed OpenSSH private key");
                    const u = readString(e, e._pos);
                    if (u === undefined) return new Error("Malformed OpenSSH private key");
                    const d = readString(e, e._pos);
                    if (d === undefined) return new Error("Malformed OpenSSH private key");
                    o = genOpenSSLRSAPub(r, n);
                    a = genOpenSSHRSAPub(r, n);
                    s = genOpenSSLRSAPriv(r, n, l, c, u, d);
                    t = "sha1";
                    break;
                }

              case "ssh-dss":
                {
                    const r = readString(e, e._pos);
                    if (r === undefined) return new Error("Malformed OpenSSH private key");
                    const n = readString(e, e._pos);
                    if (n === undefined) return new Error("Malformed OpenSSH private key");
                    const l = readString(e, e._pos);
                    if (l === undefined) return new Error("Malformed OpenSSH private key");
                    const c = readString(e, e._pos);
                    if (c === undefined) return new Error("Malformed OpenSSH private key");
                    const u = readString(e, e._pos);
                    if (u === undefined) return new Error("Malformed OpenSSH private key");
                    o = genOpenSSLDSAPub(r, n, l, c);
                    a = genOpenSSHDSAPub(r, n, l, c);
                    s = genOpenSSLDSAPriv(r, n, l, c, u);
                    t = "sha1";
                    break;
                }

              case "ssh-ed25519":
                {
                    if (!eddsaSupported$1) return new Error(`Unsupported OpenSSH private key type: ${c}`);
                    const r = readString(e, e._pos);
                    if (r === undefined || r.length !== 32) return new Error("Malformed OpenSSH private key");
                    const n = readString(e, e._pos);
                    if (n === undefined || n.length !== 64) return new Error("Malformed OpenSSH private key");
                    o = genOpenSSLEdPub(r);
                    a = genOpenSSHEdPub(r);
                    s = genOpenSSLEdPriv(bufferSlice$4(n, 0, 32));
                    t = null;
                    break;
                }

              case "ecdsa-sha2-nistp256":
                t = "sha256";
                l = "1.2.840.10045.3.1.7";

              case "ecdsa-sha2-nistp384":
                if (t === undefined) {
                    t = "sha384";
                    l = "1.3.132.0.34";
                }

              case "ecdsa-sha2-nistp521":
                {
                    if (t === undefined) {
                        t = "sha512";
                        l = "1.3.132.0.35";
                    }
                    if (!skipFields(e, 1)) return new Error("Malformed OpenSSH private key");
                    const r = readString(e, e._pos);
                    if (r === undefined) return new Error("Malformed OpenSSH private key");
                    const n = readString(e, e._pos);
                    if (n === undefined) return new Error("Malformed OpenSSH private key");
                    o = genOpenSSLECDSAPub(l, r);
                    a = genOpenSSHECDSAPub(l, r);
                    s = genOpenSSLECDSAPriv(l, r, n);
                    break;
                }

              default:
                return new Error(`Unsupported OpenSSH private key type: ${c}`);
            }
            const u = readString(e, e._pos, true);
            if (u === undefined) return new Error("Malformed OpenSSH private key");
            n.push(new OpenSSH_Private(c, u, s, o, a, t, r));
        }
        let c = 0;
        for (a = e._pos; a < e.length; ++a) {
            if (e[a] !== ++c % 255) return new Error("Malformed OpenSSH private key");
        }
        return n;
    }
}

function OpenSSH_Old_Private(e, t, r, n, s, o, a) {
    this.type = e;
    this.comment = t;
    this[SYM_PRIV_PEM] = r;
    this[SYM_PUB_PEM] = n;
    this[SYM_PUB_SSH] = s;
    this[SYM_HASH_ALGO] = o;
    this[SYM_DECRYPTED] = a;
}

OpenSSH_Old_Private.prototype = BaseKey;

{
    const a = /^-----BEGIN (RSA|DSA|EC) PRIVATE KEY-----(?:\r\n|\n)((?:[^:]+:\s*[\S].*(?:\r\n|\n))*)([\s\S]+)(?:\r\n|\n)-----END (RSA|DSA|EC) PRIVATE KEY-----$/;
    OpenSSH_Old_Private.parse = (e, t) => {
        const r = a.exec(e);
        if (r === null) return null;
        let n = Buffer.from(r[3], "base64");
        let s = r[2];
        let o = false;
        if (s !== undefined) {
            s = s.split(/\r\n|\n/g);
            for (let e = 0; e < s.length; ++e) {
                const r = s[e];
                let a = r.indexOf(":");
                if (r.slice(0, a) === "DEK-Info") {
                    const e = r.slice(a + 2);
                    a = e.indexOf(",");
                    if (a === -1) continue;
                    const s = e.slice(0, a).toLowerCase();
                    if (supportedOpenSSLCiphers.indexOf(s) === -1) {
                        return new Error(`Cipher (${s}) not supported ` + "for encrypted OpenSSH private key");
                    }
                    const l = CIPHER_INFO_OPENSSL[s];
                    if (!l) {
                        return new Error(`Cipher (${s}) not supported ` + "for encrypted OpenSSH private key");
                    }
                    const c = Buffer.from(e.slice(a + 1), "hex");
                    if (c.length !== l.ivLen) return new Error("Malformed encrypted OpenSSH private key");
                    if (!t) {
                        return new Error("Encrypted OpenSSH private key detected, but no passphrase given");
                    }
                    const u = bufferSlice$4(c, 0, 8);
                    let d = createHash$1("md5").update(t).update(u).digest();
                    while (d.length < l.keyLen) {
                        d = combineBuffers(d, createHash$1("md5").update(d).update(t).update(u).digest());
                    }
                    if (d.length > l.keyLen) d = bufferSlice$4(d, 0, l.keyLen);
                    try {
                        const e = createDecipheriv(s, d, c);
                        e.setAutoPadding(false);
                        n = combineBuffers(e.update(n), e.final());
                        o = true;
                    } catch (e) {
                        return e;
                    }
                }
            }
        }
        let l;
        let c;
        let u;
        let d;
        let h;
        let p;
        let g = "Malformed OpenSSH private key";
        if (o) g += ". Bad passphrase?";
        switch (r[1]) {
          case "RSA":
            l = "ssh-rsa";
            c = makePEM("RSA PRIVATE", n);
            try {
                p = new Ber$1.Reader(n);
                p.readSequence();
                p.readInt();
                const e = p.readString(Ber$1.Integer, true);
                if (e === null) return new Error(g);
                const t = p.readString(Ber$1.Integer, true);
                if (t === null) return new Error(g);
                u = genOpenSSLRSAPub(e, t);
                d = genOpenSSHRSAPub(e, t);
            } catch {
                return new Error(g);
            }
            h = "sha1";
            break;

          case "DSA":
            l = "ssh-dss";
            c = makePEM("DSA PRIVATE", n);
            try {
                p = new Ber$1.Reader(n);
                p.readSequence();
                p.readInt();
                const e = p.readString(Ber$1.Integer, true);
                if (e === null) return new Error(g);
                const t = p.readString(Ber$1.Integer, true);
                if (t === null) return new Error(g);
                const r = p.readString(Ber$1.Integer, true);
                if (r === null) return new Error(g);
                const s = p.readString(Ber$1.Integer, true);
                if (s === null) return new Error(g);
                u = genOpenSSLDSAPub(e, t, r, s);
                d = genOpenSSHDSAPub(e, t, r, s);
            } catch {
                return new Error(g);
            }
            h = "sha1";
            break;

          case "EC":
            {
                let e;
                let t;
                let r;
                try {
                    p = new Ber$1.Reader(n);
                    p.readSequence();
                    p.readInt();
                    t = p.readString(Ber$1.OctetString, true);
                    p.readByte();
                    const s = p.readLength();
                    if (s !== null) {
                        p._offset = s;
                        r = p.readOID();
                        if (r === null) return new Error(g);
                        switch (r) {
                          case "1.2.840.10045.3.1.7":
                            e = "prime256v1";
                            l = "ecdsa-sha2-nistp256";
                            h = "sha256";
                            break;

                          case "1.3.132.0.34":
                            e = "secp384r1";
                            l = "ecdsa-sha2-nistp384";
                            h = "sha384";
                            break;

                          case "1.3.132.0.35":
                            e = "secp521r1";
                            l = "ecdsa-sha2-nistp521";
                            h = "sha512";
                            break;

                          default:
                            return new Error(`Unsupported private key EC OID: ${r}`);
                        }
                    } else {
                        return new Error(g);
                    }
                } catch {
                    return new Error(g);
                }
                c = makePEM("EC PRIVATE", n);
                const s = genOpenSSLECDSAPubFromPriv(e, t);
                u = genOpenSSLECDSAPub(r, s);
                d = genOpenSSHECDSAPub(r, s);
                break;
            }
        }
        return new OpenSSH_Old_Private(l, "", c, u, d, h, o);
    };
}

function PPK_Private(e, t, r, n, s, o, a) {
    this.type = e;
    this.comment = t;
    this[SYM_PRIV_PEM] = r;
    this[SYM_PUB_PEM] = n;
    this[SYM_PUB_SSH] = s;
    this[SYM_HASH_ALGO] = o;
    this[SYM_DECRYPTED] = a;
}

PPK_Private.prototype = BaseKey;

{
    const l = Buffer.alloc(0);
    const c = Buffer.from([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]);
    const u = Buffer.from([ 0, 0, 0, 0 ]);
    const d = Buffer.from([ 0, 0, 0, 1 ]);
    const h = /^PuTTY-User-Key-File-2: (ssh-(?:rsa|dss))\r?\nEncryption: (aes256-cbc|none)\r?\nComment: ([^\r\n]*)\r?\nPublic-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-Lines: \d+\r?\n([\s\S]+?)\r?\nPrivate-MAC: ([^\r\n]+)/;
    PPK_Private.parse = (e, t) => {
        const r = h.exec(e);
        if (r === null) return null;
        const n = r[2];
        const s = n !== "none";
        if (s && !t) {
            return new Error("Encrypted PPK private key detected, but no passphrase given");
        }
        let o = Buffer.from(r[5], "base64");
        if (s) {
            const e = CIPHER_INFO$1[n];
            let r = combineBuffers(createHash$1("sha1").update(u).update(t).digest(), createHash$1("sha1").update(d).update(t).digest());
            if (r.length > e.keyLen) r = bufferSlice$4(r, 0, e.keyLen);
            try {
                const t = createDecipheriv(e.sslName, r, c);
                t.setAutoPadding(false);
                o = combineBuffers(t.update(o), t.final());
            } catch (e) {
                return e;
            }
        }
        const a = r[1];
        const p = r[3];
        const g = Buffer.from(r[4], "base64");
        const m = r[6];
        const _ = a.length;
        const E = n.length;
        const v = Buffer.byteLength(p);
        const y = g.length;
        const S = o.length;
        const A = Buffer.allocUnsafe(4 + _ + 4 + E + 4 + v + 4 + y + 4 + S);
        let b = 0;
        writeUInt32BE$6(A, _, b);
        A.utf8Write(a, b += 4, _);
        writeUInt32BE$6(A, E, b += _);
        A.utf8Write(n, b += 4, E);
        writeUInt32BE$6(A, v, b += E);
        A.utf8Write(p, b += 4, v);
        writeUInt32BE$6(A, y, b += v);
        A.set(g, b += 4);
        writeUInt32BE$6(A, S, b += y);
        A.set(o, b + 4);
        if (!t) t = l;
        const C = createHmac("sha1", createHash$1("sha1").update("putty-private-key-file-mac-key").update(t).digest()).update(A).digest("hex");
        if (C !== m) {
            if (s) {
                return new Error("PPK private key integrity check failed -- bad passphrase?");
            }
            return new Error("PPK private key integrity check failed");
        }
        let w;
        let I;
        let T;
        g._pos = 0;
        skipFields(g, 1);
        switch (a) {
          case "ssh-rsa":
            {
                const e = readString(g, g._pos);
                if (e === undefined) return new Error("Malformed PPK public key");
                const t = readString(g, g._pos);
                if (t === undefined) return new Error("Malformed PPK public key");
                const r = readString(o, 0);
                if (r === undefined) return new Error("Malformed PPK private key");
                const n = readString(o, o._pos);
                if (n === undefined) return new Error("Malformed PPK private key");
                const s = readString(o, o._pos);
                if (s === undefined) return new Error("Malformed PPK private key");
                const a = readString(o, o._pos);
                if (a === undefined) return new Error("Malformed PPK private key");
                w = genOpenSSLRSAPub(t, e);
                I = genOpenSSHRSAPub(t, e);
                T = genOpenSSLRSAPriv(t, e, r, a, n, s);
                break;
            }

          case "ssh-dss":
            {
                const e = readString(g, g._pos);
                if (e === undefined) return new Error("Malformed PPK public key");
                const t = readString(g, g._pos);
                if (t === undefined) return new Error("Malformed PPK public key");
                const r = readString(g, g._pos);
                if (r === undefined) return new Error("Malformed PPK public key");
                const n = readString(g, g._pos);
                if (n === undefined) return new Error("Malformed PPK public key");
                const s = readString(o, 0);
                if (s === undefined) return new Error("Malformed PPK private key");
                w = genOpenSSLDSAPub(e, t, r, n);
                I = genOpenSSHDSAPub(e, t, r, n);
                T = genOpenSSLDSAPriv(e, t, r, n, s);
                break;
            }
        }
        return new PPK_Private(a, p, T, w, I, "sha1", s);
    };
}

function OpenSSH_Public(e, t, r, n, s) {
    this.type = e;
    this.comment = t;
    this[SYM_PRIV_PEM] = null;
    this[SYM_PUB_PEM] = r;
    this[SYM_PUB_SSH] = n;
    this[SYM_HASH_ALGO] = s;
    this[SYM_DECRYPTED] = false;
}

OpenSSH_Public.prototype = BaseKey;

{
    let p;
    if (eddsaSupported$1) p = /^(((?:ssh-(?:rsa|dss|ed25519))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/; else p = /^(((?:ssh-(?:rsa|dss))|ecdsa-sha2-nistp(?:256|384|521))(?:-cert-v0[01]@openssh.com)?) ([A-Z0-9a-z/+=]+)(?:$|\s+([\S].*)?)$/;
    OpenSSH_Public.parse = e => {
        const t = p.exec(e);
        if (t === null) return null;
        const r = t[1];
        const n = t[2];
        const s = Buffer.from(t[3], "base64");
        const o = t[4] || "";
        const a = readString(s, s._pos, true);
        if (a === undefined || a.indexOf(n) !== 0) return new Error("Malformed OpenSSH public key");
        return parseDER(s, n, o, r);
    };
}

function RFC4716_Public(e, t, r, n, s) {
    this.type = e;
    this.comment = t;
    this[SYM_PRIV_PEM] = null;
    this[SYM_PUB_PEM] = r;
    this[SYM_PUB_SSH] = n;
    this[SYM_HASH_ALGO] = s;
    this[SYM_DECRYPTED] = false;
}

RFC4716_Public.prototype = BaseKey;

{
    const g = /^---- BEGIN SSH2 PUBLIC KEY ----(?:\r?\n)((?:.{0,72}\r?\n)+)---- END SSH2 PUBLIC KEY ----$/;
    const m = /^[A-Z0-9a-z/+=\r\n]+$/;
    const _ = /^([\x21-\x39\x3B-\x7E]{1,64}): ((?:[^\\]*\\\r?\n)*[^\r\n]+)\r?\n/gm;
    const E = /\\\r?\n/g;
    RFC4716_Public.parse = e => {
        let t = g.exec(e);
        if (t === null) return null;
        const r = t[1];
        let n = 0;
        let s = "";
        while (t = _.exec(r)) {
            const e = t[1];
            const r = t[2].replace(E, "");
            if (r.length > 1024) {
                _.lastIndex = 0;
                return new Error("Malformed RFC4716 public key");
            }
            n = _.lastIndex;
            if (e.toLowerCase() === "comment") {
                s = r;
                if (s.length > 1 && s.charCodeAt(0) === 34 && s.charCodeAt(s.length - 1) === 34) {
                    s = s.slice(1, -1);
                }
            }
        }
        let o = r.slice(n);
        if (!m.test(o)) return new Error("Malformed RFC4716 public key");
        o = Buffer.from(o, "base64");
        const a = readString(o, 0, true);
        if (a === undefined) return new Error("Malformed RFC4716 public key");
        let l = null;
        let c = null;
        switch (a) {
          case "ssh-rsa":
            {
                const e = readString(o, o._pos);
                if (e === undefined) return new Error("Malformed RFC4716 public key");
                const t = readString(o, o._pos);
                if (t === undefined) return new Error("Malformed RFC4716 public key");
                l = genOpenSSLRSAPub(t, e);
                c = genOpenSSHRSAPub(t, e);
                break;
            }

          case "ssh-dss":
            {
                const e = readString(o, o._pos);
                if (e === undefined) return new Error("Malformed RFC4716 public key");
                const t = readString(o, o._pos);
                if (t === undefined) return new Error("Malformed RFC4716 public key");
                const r = readString(o, o._pos);
                if (r === undefined) return new Error("Malformed RFC4716 public key");
                const n = readString(o, o._pos);
                if (n === undefined) return new Error("Malformed RFC4716 public key");
                l = genOpenSSLDSAPub(e, t, r, n);
                c = genOpenSSHDSAPub(e, t, r, n);
                break;
            }

          default:
            return new Error("Malformed RFC4716 public key");
        }
        return new RFC4716_Public(a, s, l, c, "sha1");
    };
}

function parseDER(e, t, r, n) {
    if (!isSupportedKeyType(t)) return new Error(`Unsupported OpenSSH public key type: ${t}`);
    let s;
    let o;
    let a = null;
    let l = null;
    switch (t) {
      case "ssh-rsa":
        {
            const t = readString(e, e._pos || 0);
            if (t === undefined) return new Error("Malformed OpenSSH public key");
            const r = readString(e, e._pos);
            if (r === undefined) return new Error("Malformed OpenSSH public key");
            a = genOpenSSLRSAPub(r, t);
            l = genOpenSSHRSAPub(r, t);
            s = "sha1";
            break;
        }

      case "ssh-dss":
        {
            const t = readString(e, e._pos || 0);
            if (t === undefined) return new Error("Malformed OpenSSH public key");
            const r = readString(e, e._pos);
            if (r === undefined) return new Error("Malformed OpenSSH public key");
            const n = readString(e, e._pos);
            if (n === undefined) return new Error("Malformed OpenSSH public key");
            const o = readString(e, e._pos);
            if (o === undefined) return new Error("Malformed OpenSSH public key");
            a = genOpenSSLDSAPub(t, r, n, o);
            l = genOpenSSHDSAPub(t, r, n, o);
            s = "sha1";
            break;
        }

      case "ssh-ed25519":
        {
            const t = readString(e, e._pos || 0);
            if (t === undefined || t.length !== 32) return new Error("Malformed OpenSSH public key");
            a = genOpenSSLEdPub(t);
            l = genOpenSSHEdPub(t);
            s = null;
            break;
        }

      case "ecdsa-sha2-nistp256":
        s = "sha256";
        o = "1.2.840.10045.3.1.7";

      case "ecdsa-sha2-nistp384":
        if (s === undefined) {
            s = "sha384";
            o = "1.3.132.0.34";
        }

      case "ecdsa-sha2-nistp521":
        {
            if (s === undefined) {
                s = "sha512";
                o = "1.3.132.0.35";
            }
            if (!skipFields(e, 1)) return new Error("Malformed OpenSSH public key");
            const t = readString(e, e._pos || 0);
            if (t === undefined) return new Error("Malformed OpenSSH public key");
            a = genOpenSSLECDSAPub(o, t);
            l = genOpenSSHECDSAPub(o, t);
            break;
        }

      default:
        return new Error(`Unsupported OpenSSH public key type: ${t}`);
    }
    return new OpenSSH_Public(n, r, a, l, s);
}

function isSupportedKeyType(e) {
    switch (e) {
      case "ssh-rsa":
      case "ssh-dss":
      case "ecdsa-sha2-nistp256":
      case "ecdsa-sha2-nistp384":
      case "ecdsa-sha2-nistp521":
        return true;

      case "ssh-ed25519":
        if (eddsaSupported$1) return true;

      default:
        return false;
    }
}

function isParsedKey$1(e) {
    if (!e) return false;
    return typeof e[SYM_DECRYPTED] === "boolean";
}

function parseKey$6(e, t) {
    if (isParsedKey$1(e)) return e;
    let r;
    if (Buffer.isBuffer(e)) {
        r = e;
        e = e.utf8Slice(0, e.length).trim();
    } else if (typeof e === "string") {
        e = e.trim();
    } else {
        return new Error("Key data must be a Buffer or string");
    }
    if (t != undefined) {
        if (typeof t === "string") t = Buffer.from(t); else if (!Buffer.isBuffer(t)) return new Error("Passphrase must be a string or Buffer when supplied");
    }
    let n;
    if ((n = OpenSSH_Private.parse(e, t)) !== null) return n;
    if ((n = OpenSSH_Old_Private.parse(e, t)) !== null) return n;
    if ((n = PPK_Private.parse(e, t)) !== null) return n;
    if ((n = OpenSSH_Public.parse(e)) !== null) return n;
    if ((n = RFC4716_Public.parse(e)) !== null) return n;
    if (r) {
        binaryKeyParser.init(r, 0);
        const t = binaryKeyParser.readString(true);
        if (t !== undefined) {
            e = binaryKeyParser.readRaw();
            if (e !== undefined) {
                n = parseDER(e, t, "", t);
                if (n instanceof Error) n = null;
            }
        }
        binaryKeyParser.clear();
    }
    if (n) return n;
    return new Error("Unsupported key format");
}

var keyParser = {
    isParsedKey: isParsedKey$1,
    isSupportedKeyType: isSupportedKeyType,
    parseDERKey: (e, t) => parseDER(e, t, "", t),
    parseKey: parseKey$6
};

const {Socket: Socket$1} = require$$0__default$6.default;

const {Duplex: Duplex} = require$$0__default$7.default;

const {resolve: resolve} = require$$0__default$4.default;

const {readFile: readFile} = require$$0__default$5.default;

const {execFile: execFile, spawn: spawn} = require$$4__default$1.default;

const {isParsedKey: isParsedKey, parseKey: parseKey$5} = keyParser;

const {makeBufferParser: makeBufferParser$2, readUInt32BE: readUInt32BE$1, writeUInt32BE: writeUInt32BE$5, writeUInt32LE: writeUInt32LE} = requireUtils();

function once(e) {
    let t = false;
    return (...r) => {
        if (t) return;
        t = true;
        e(...r);
    };
}

function concat(e, t) {
    const r = Buffer.allocUnsafe(e.length + t.length);
    e.copy(r, 0);
    t.copy(r, e.length);
    return r;
}

function noop$9() {}

const EMPTY_BUF = Buffer.alloc(0);

const binaryParser = makeBufferParser$2();

let BaseAgent$1 = class BaseAgent {
    getIdentities(e) {
        e(new Error("Missing getIdentities() implementation"));
    }
    sign(e, t, r, n) {
        if (typeof r === "function") n = r;
        n(new Error("Missing sign() implementation"));
    }
};

let OpenSSHAgent$1 = class OpenSSHAgent extends BaseAgent$1 {
    constructor(e) {
        super();
        this.socketPath = e;
    }
    getStream(e) {
        e = once(e);
        const t = new Socket$1;
        t.on("connect", () => {
            e(null, t);
        });
        t.on("close", r).on("end", r).on("error", r);
        t.connect(this.socketPath);
        function r() {
            try {
                t.destroy();
            } catch {}
            e(new Error("Failed to connect to agent"));
        }
    }
    getIdentities(e) {
        e = once(e);
        this.getStream((t, r) => {
            function n(t) {
                if (r) {
                    try {
                        r.destroy();
                    } catch {}
                }
                if (!t) t = new Error("Failed to retrieve identities from agent");
                e(t);
            }
            if (t) return n(t);
            const s = new AgentProtocol$1(true);
            s.on("error", n);
            s.pipe(r).pipe(s);
            r.on("close", n).on("end", n).on("error", n);
            s.getIdentities((t, s) => {
                if (t) return n(t);
                try {
                    r.destroy();
                } catch {}
                e(null, s);
            });
        });
    }
    sign(e, t, r, n) {
        if (typeof r === "function") {
            n = r;
            r = undefined;
        } else if (typeof r !== "object" || r === null) {
            r = undefined;
        }
        n = once(n);
        this.getStream((s, o) => {
            function a(e) {
                if (o) {
                    try {
                        o.destroy();
                    } catch {}
                }
                if (!e) e = new Error("Failed to sign data with agent");
                n(e);
            }
            if (s) return a(s);
            const l = new AgentProtocol$1(true);
            l.on("error", a);
            l.pipe(o).pipe(l);
            o.on("close", a).on("end", a).on("error", a);
            l.sign(e, t, r, (e, t) => {
                if (e) return a(e);
                try {
                    o.destroy();
                } catch {}
                n(null, t);
            });
        });
    }
};

const PageantAgent$1 = (() => {
    const e = 10;
    const t = 11;
    const r = 12;
    const n = 13;
    const s = 14;
    const o = 15;
    const a = resolve(__dirname, "..", "util/pagent.exe");
    const l = {
        [e]: new Error("Invalid pagent.exe arguments"),
        [t]: new Error("Pageant is not running"),
        [r]: new Error("pagent.exe could not create an mmap"),
        [n]: new Error("pagent.exe could not set mode for stdin"),
        [s]: new Error("pagent.exe could not set mode for stdout"),
        [o]: new Error("pagent.exe did not get expected input payload")
    };
    function c(e) {
        e.buffer = null;
        if (e.proc) {
            e.proc.kill();
            e.proc = undefined;
        }
    }
    class PageantSocket extends Duplex {
        constructor() {
            super();
            this.proc = undefined;
            this.buffer = null;
        }
        _read(e) {}
        _write(e, t, r) {
            if (this.buffer === null) {
                this.buffer = e;
            } else {
                const t = Buffer.allocUnsafe(this.buffer.length + e.length);
                this.buffer.copy(t, 0);
                e.copy(t, this.buffer.length);
                this.buffer = t;
            }
            if (this.buffer.length < 4) return r();
            const n = readUInt32BE$1(this.buffer, 0);
            if (this.buffer.length - 4 < n) return r();
            e = this.buffer.slice(0, 4 + n);
            if (this.buffer.length > 4 + n) return r(new Error("Unexpected multiple agent requests"));
            this.buffer = null;
            let s;
            const o = this.proc = spawn(a, [ e.length ]);
            o.stdout.on("data", e => {
                this.push(e);
            });
            o.on("error", e => {
                s = e;
                r(s);
            });
            o.on("close", e => {
                this.proc = undefined;
                if (!s) {
                    if (s = l[e]) return r(s);
                    r();
                }
            });
            o.stdin.end(e);
        }
        _final(e) {
            c(this);
            e();
        }
        _destroy(e, t) {
            c(this);
            t();
        }
    }
    return class PageantAgent extends OpenSSHAgent$1 {
        getStream(e) {
            e(null, new PageantSocket);
        }
    };
})();

const CygwinAgent$1 = (() => {
    const e = /^!<socket >(\d+) s ([A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8}-[A-Z0-9]{8})/;
    return class CygwinAgent extends OpenSSHAgent$1 {
        getStream(t) {
            t = once(t);
            let r = this.socketPath;
            let n = false;
            readFile(r, function s(o, a) {
                if (o) {
                    if (n) return t(new Error("Invalid cygwin unix socket path"));
                    execFile("cygpath", [ "-w", r ], (e, o, a) => {
                        if (e || o.length === 0) return t(new Error("Invalid cygwin unix socket path"));
                        n = true;
                        r = o.toString().replace(/[\r\n]/g, "");
                        readFile(r, s);
                    });
                    return;
                }
                const l = e.exec(a.toString("ascii"));
                if (!l) return t(new Error("Malformed cygwin unix socket file"));
                let c;
                let u = 0;
                let d = false;
                const h = [];
                let p;
                let g = Buffer.alloc(12);
                const m = parseInt(l[1], 10);
                const _ = l[2].replace(/-/g, "");
                const E = Buffer.allocUnsafe(16);
                for (let e = 0, t = 0; t < 32; ++e, t += 2) E[e] = parseInt(_.substring(t, t + 2), 16);
                for (let e = 0; e < 16; e += 4) writeUInt32LE(E, readUInt32BE$1(E, e), e);
                A();
                function v() {
                    u = 0;
                    c = "secret";
                    p.write(E);
                }
                function y(e) {
                    u += e.length;
                    if (c === "secret") {
                        if (u === 16) {
                            u = 0;
                            c = "creds";
                            p.write(g);
                        }
                        return;
                    }
                    if (c === "creds") {
                        if (!d) h.push(e);
                        if (u === 12) {
                            p.removeListener("connect", v);
                            p.removeListener("data", y);
                            p.removeListener("error", S);
                            p.removeListener("end", S);
                            p.removeListener("close", S);
                            if (d) return t(null, p);
                            d = true;
                            g = Buffer.concat(h);
                            writeUInt32LE(g, process.pid, 0);
                            p.on("error", () => {});
                            p.destroy();
                            A();
                        }
                    }
                }
                function S() {
                    t(new Error("Problem negotiating cygwin unix socket security"));
                }
                function A() {
                    p = new Socket$1;
                    p.on("connect", v);
                    p.on("data", y);
                    p.on("error", S);
                    p.on("end", S);
                    p.on("close", S);
                    p.connect(m);
                }
            });
        }
    };
})();

const WINDOWS_PIPE_REGEX = /^[/\\][/\\]\.[/\\]pipe[/\\].+/;

function createAgent$2(e) {
    if (process.platform === "win32" && !WINDOWS_PIPE_REGEX.test(e)) {
        return e === "pageant" ? new PageantAgent$1 : new CygwinAgent$1(e);
    }
    return new OpenSSHAgent$1(e);
}

const AgentProtocol$1 = (() => {
    const e = 11;
    const t = 13;
    const r = 5;
    const n = 12;
    const s = 14;
    const o = 1 << 1;
    const a = 1 << 2;
    const l = 0;
    const c = 1;
    function u(e) {
        let t;
        while (e[v].length) {
            const r = e[v][0][h];
            if (r === undefined) break;
            e[v].shift();
            t = e.push(r);
        }
        return t;
    }
    const d = Symbol("Inbound Request Type");
    const h = Symbol("Inbound Request Response");
    const p = Symbol("Inbound Request Context");
    class AgentInboundRequest {
        constructor(e, t) {
            this[d] = e;
            this[h] = undefined;
            this[p] = t;
        }
        hasResponded() {
            return this[h] !== undefined;
        }
        getType() {
            return this[d];
        }
        getContext() {
            return this[p];
        }
    }
    function g(e, t, r) {
        t[h] = r;
        return u(e);
    }
    function m(e) {
        e[S] = null;
        if (e[y] === l) {
            const t = e[v];
            if (t && t.length) {
                e[v] = [];
                for (const e of t) e.cb(new Error("No reply from server"));
            }
        }
        try {
            e.end();
        } catch {}
        setImmediate(() => {
            if (!e[C]) e.emit("end");
            if (!e[b]) e.emit("close");
        });
    }
    function _() {
        this[b] = true;
    }
    function E() {
        this[C] = true;
    }
    const v = Symbol("Requests");
    const y = Symbol("Agent Protocol Role");
    const S = Symbol("Agent Protocol Buffer");
    const A = Symbol("Agent Protocol Current Message Length");
    const b = Symbol("Agent Protocol Closed");
    const C = Symbol("Agent Protocol Ended");
    return class AgentProtocol extends Duplex {
        constructor(e) {
            super({
                autoDestroy: true,
                emitClose: false
            });
            this[y] = e ? l : c;
            this[v] = [];
            this[S] = null;
            this[A] = -1;
            this.once("end", E);
            this.once("close", _);
        }
        _read(e) {}
        _write(c, u, d) {
            if (this[S] === null) this[S] = c; else this[S] = concat(this[S], c);
            let h = this[S];
            let p = h.length;
            let g = 0;
            while (g < p) {
                if (p < 5) break;
                if (this[A] === -1) this[A] = readUInt32BE$1(h, g);
                if (p < 4 + this[A]) break;
                const c = h[g += 4];
                ++g;
                if (this[y] === l) {
                    if (this[v].length === 0) return d(new Error("Received unexpected message from server"));
                    const o = this[v].shift();
                    switch (c) {
                      case r:
                        o.cb(new Error("Agent responded with failure"));
                        break;

                      case n:
                        {
                            if (o.type !== e) return d(new Error("Agent responded with wrong message type"));
                            binaryParser.init(h, g);
                            const t = binaryParser.readUInt32BE();
                            if (t === undefined) {
                                binaryParser.clear();
                                return d(new Error("Malformed agent response"));
                            }
                            const r = [];
                            for (let e = 0; e < t; ++e) {
                                let e = binaryParser.readString();
                                if (e === undefined) {
                                    binaryParser.clear();
                                    return d(new Error("Malformed agent response"));
                                }
                                const t = binaryParser.readString(true);
                                if (t === undefined) {
                                    binaryParser.clear();
                                    return d(new Error("Malformed agent response"));
                                }
                                e = parseKey$5(e);
                                if (e instanceof Error) continue;
                                e.comment = e.comment || t;
                                r.push(e);
                            }
                            g = binaryParser.pos();
                            binaryParser.clear();
                            o.cb(null, r);
                            break;
                        }

                      case s:
                        {
                            if (o.type !== t) return d(new Error("Agent responded with wrong message type"));
                            binaryParser.init(h, g);
                            let e = binaryParser.readString();
                            g = binaryParser.pos();
                            binaryParser.clear();
                            if (e === undefined) return d(new Error("Malformed agent response"));
                            binaryParser.init(e, 0);
                            binaryParser.readString(true);
                            e = binaryParser.readString();
                            binaryParser.clear();
                            if (e === undefined) return d(new Error("Malformed OpenSSH signature format"));
                            o.cb(null, e);
                            break;
                        }

                      default:
                        return d(new Error("Agent responded with unsupported message type"));
                    }
                } else {
                    switch (c) {
                      case e:
                        {
                            const e = new AgentInboundRequest(c);
                            this[v].push(e);
                            this.emit("identities", e);
                            break;
                        }

                      case t:
                        {
                            binaryParser.init(h, g);
                            let e = binaryParser.readString();
                            const t = binaryParser.readString();
                            const r = binaryParser.readUInt32BE();
                            g = binaryParser.pos();
                            binaryParser.clear();
                            if (r === undefined) {
                                const e = new AgentInboundRequest(c);
                                this[v].push(e);
                                return this.failureReply(e);
                            }
                            e = parseKey$5(e);
                            if (e instanceof Error) {
                                const e = new AgentInboundRequest(c);
                                this[v].push(e);
                                return this.failureReply(e);
                            }
                            const n = {
                                hash: undefined
                            };
                            let s;
                            if (e.type === "ssh-rsa") {
                                if (r & o) {
                                    s = "rsa-sha2-256";
                                    n.hash = "sha256";
                                } else if (r & a) {
                                    s = "rsa-sha2-512";
                                    n.hash = "sha512";
                                }
                            }
                            if (s === undefined) s = e.type;
                            const l = new AgentInboundRequest(c, s);
                            this[v].push(l);
                            this.emit("sign", l, e, t, n);
                            break;
                        }

                      default:
                        {
                            const e = new AgentInboundRequest(c);
                            this[v].push(e);
                            this.failureReply(e);
                        }
                    }
                }
                this[A] = -1;
                if (g === p) {
                    this[S] = null;
                    break;
                } else {
                    this[S] = h = h.slice(g);
                    p = h.length;
                    g = 0;
                }
            }
            d();
        }
        _destroy(e, t) {
            m(this);
            t();
        }
        _final(e) {
            m(this);
            e();
        }
        sign(e, r, n, s) {
            if (this[y] !== l) throw new Error("Client-only method called with server role");
            if (typeof n === "function") {
                s = n;
                n = undefined;
            } else if (typeof n !== "object" || n === null) {
                n = undefined;
            }
            let c = 0;
            e = parseKey$5(e);
            if (e instanceof Error) throw new Error("Invalid public key argument");
            if (e.type === "ssh-rsa" && n) {
                switch (n.hash) {
                  case "sha256":
                    c = o;
                    break;

                  case "sha512":
                    c = a;
                    break;
                }
            }
            e = e.getPublicSSH();
            const u = t;
            const d = e.length;
            const h = r.length;
            let p = 0;
            const g = Buffer.allocUnsafe(4 + 1 + 4 + d + 4 + h + 4);
            writeUInt32BE$5(g, g.length - 4, p);
            g[p += 4] = u;
            writeUInt32BE$5(g, d, ++p);
            e.copy(g, p += 4);
            writeUInt32BE$5(g, h, p += d);
            r.copy(g, p += 4);
            writeUInt32BE$5(g, c, p += h);
            if (typeof s !== "function") s = noop$9;
            this[v].push({
                type: u,
                cb: s
            });
            return this.push(g);
        }
        getIdentities(t) {
            if (this[y] !== l) throw new Error("Client-only method called with server role");
            const r = e;
            let n = 0;
            const s = Buffer.allocUnsafe(4 + 1);
            writeUInt32BE$5(s, s.length - 4, n);
            s[n += 4] = r;
            if (typeof t !== "function") t = noop$9;
            this[v].push({
                type: r,
                cb: t
            });
            return this.push(s);
        }
        failureReply(e) {
            if (this[y] !== c) throw new Error("Server-only method called with client role");
            if (!(e instanceof AgentInboundRequest)) throw new Error("Wrong request argument");
            if (e.hasResponded()) return true;
            let t = 0;
            const n = Buffer.allocUnsafe(4 + 1);
            writeUInt32BE$5(n, n.length - 4, t);
            n[t += 4] = r;
            return g(this, e, n);
        }
        getIdentitiesReply(t, r) {
            if (this[y] !== c) throw new Error("Server-only method called with client role");
            if (!(t instanceof AgentInboundRequest)) throw new Error("Wrong request argument");
            if (t.hasResponded()) return true;
            if (t.getType() !== e) throw new Error("Invalid response to request");
            if (!Array.isArray(r)) throw new Error("Keys argument must be an array");
            let s = 4;
            const o = [];
            for (let e = 0; e < r.length; ++e) {
                const t = r[e];
                if (typeof t !== "object" || t === null) throw new Error(`Invalid key entry: ${t}`);
                let n;
                let a;
                if (isParsedKey(t)) {
                    n = t;
                } else if (isParsedKey(t.pubKey)) {
                    n = t.pubKey;
                } else {
                    if (typeof t.pubKey !== "object" || t.pubKey === null) continue;
                    ({pubKey: n, comment: a} = t.pubKey);
                    n = parseKey$5(n);
                    if (n instanceof Error) continue;
                }
                a = n.comment || a;
                n = n.getPublicSSH();
                s += 4 + n.length;
                if (a && typeof a === "string") a = Buffer.from(a); else if (!Buffer.isBuffer(a)) a = EMPTY_BUF;
                s += 4 + a.length;
                o.push({
                    pubKey: n,
                    comment: a
                });
            }
            let a = 0;
            const l = Buffer.allocUnsafe(4 + 1 + s);
            writeUInt32BE$5(l, l.length - 4, a);
            l[a += 4] = n;
            writeUInt32BE$5(l, o.length, ++a);
            a += 4;
            for (let e = 0; e < o.length; ++e) {
                const {pubKey: t, comment: r} = o[e];
                writeUInt32BE$5(l, t.length, a);
                t.copy(l, a += 4);
                writeUInt32BE$5(l, r.length, a += t.length);
                a += 4;
                if (r.length) {
                    r.copy(l, a);
                    a += r.length;
                }
            }
            return g(this, t, l);
        }
        signReply(e, r) {
            if (this[y] !== c) throw new Error("Server-only method called with client role");
            if (!(e instanceof AgentInboundRequest)) throw new Error("Wrong request argument");
            if (e.hasResponded()) return true;
            if (e.getType() !== t) throw new Error("Invalid response to request");
            if (!Buffer.isBuffer(r)) throw new Error("Signature argument must be a Buffer");
            if (r.length === 0) throw new Error("Signature argument must be non-empty");
            let n = 0;
            const o = e.getContext();
            const a = Buffer.byteLength(o);
            const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + a + 4 + r.length);
            writeUInt32BE$5(l, l.length - 4, n);
            l[n += 4] = s;
            writeUInt32BE$5(l, 4 + a + 4 + r.length, ++n);
            writeUInt32BE$5(l, a, n += 4);
            l.utf8Write(o, n += 4, a);
            writeUInt32BE$5(l, r.length, n += a);
            r.copy(l, n += 4);
            return g(this, e, l);
        }
    };
})();

const SYM_AGENT = Symbol("Agent");

const SYM_AGENT_KEYS = Symbol("Agent Keys");

const SYM_AGENT_KEYS_IDX = Symbol("Agent Keys Index");

const SYM_AGENT_CBS = Symbol("Agent Init Callbacks");

let AgentContext$1 = class AgentContext {
    constructor(e) {
        if (typeof e === "string") e = createAgent$2(e); else if (!isAgent$1(e)) throw new Error("Invalid agent argument");
        this[SYM_AGENT] = e;
        this[SYM_AGENT_KEYS] = null;
        this[SYM_AGENT_KEYS_IDX] = -1;
        this[SYM_AGENT_CBS] = null;
    }
    init(e) {
        if (typeof e !== "function") e = noop$9;
        if (this[SYM_AGENT_KEYS] === null) {
            if (this[SYM_AGENT_CBS] === null) {
                this[SYM_AGENT_CBS] = [ e ];
                const t = (...e) => {
                    process.nextTick(() => {
                        const t = this[SYM_AGENT_CBS];
                        this[SYM_AGENT_CBS] = null;
                        for (const r of t) r(...e);
                    });
                };
                this[SYM_AGENT].getIdentities(once((e, r) => {
                    if (e) return t(e);
                    if (!Array.isArray(r)) {
                        return t(new Error("Agent implementation failed to provide keys"));
                    }
                    const n = [];
                    for (let e of r) {
                        e = parseKey$5(e);
                        if (e instanceof Error) {
                            continue;
                        }
                        n.push(e);
                    }
                    this[SYM_AGENT_KEYS] = n;
                    this[SYM_AGENT_KEYS_IDX] = -1;
                    t();
                }));
            } else {
                this[SYM_AGENT_CBS].push(e);
            }
        } else {
            process.nextTick(e);
        }
    }
    nextKey() {
        if (this[SYM_AGENT_KEYS] === null || ++this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) {
            return false;
        }
        return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]];
    }
    currentKey() {
        if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) {
            return null;
        }
        return this[SYM_AGENT_KEYS][this[SYM_AGENT_KEYS_IDX]];
    }
    pos() {
        if (this[SYM_AGENT_KEYS] === null || this[SYM_AGENT_KEYS_IDX] >= this[SYM_AGENT_KEYS].length) {
            return -1;
        }
        return this[SYM_AGENT_KEYS_IDX];
    }
    reset() {
        this[SYM_AGENT_KEYS_IDX] = -1;
    }
    sign(...e) {
        this[SYM_AGENT].sign(...e);
    }
};

function isAgent$1(e) {
    return e instanceof BaseAgent$1;
}

var agent = {
    AgentContext: AgentContext$1,
    AgentProtocol: AgentProtocol$1,
    BaseAgent: BaseAgent$1,
    createAgent: createAgent$2,
    CygwinAgent: CygwinAgent$1,
    isAgent: isAgent$1,
    OpenSSHAgent: OpenSSHAgent$1,
    PageantAgent: PageantAgent$1
};

var httpAgents = {};

const {kMaxLength: kMaxLength} = require$$0__default$1.default;

const {createInflate: createInflate, constants: {DEFLATE: DEFLATE, INFLATE: INFLATE, Z_DEFAULT_CHUNK: Z_DEFAULT_CHUNK, Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION, Z_DEFAULT_MEMLEVEL: Z_DEFAULT_MEMLEVEL, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY, Z_DEFAULT_WINDOWBITS: Z_DEFAULT_WINDOWBITS, Z_PARTIAL_FLUSH: Z_PARTIAL_FLUSH}} = require$$4__default$2.default;

const ZlibHandle = createInflate()._handle.constructor;

function processCallback() {
    throw new Error("Should not get here");
}

function zlibOnError(e, t, r) {
    const n = this._owner;
    const s = new Error(e);
    s.errno = t;
    s.code = r;
    n._err = s;
}

function _close(e) {
    if (!e._handle) return;
    e._handle.close();
    e._handle = null;
}

class Zlib {
    constructor(e) {
        const t = Z_DEFAULT_WINDOWBITS;
        const r = Z_DEFAULT_COMPRESSION;
        const n = Z_DEFAULT_MEMLEVEL;
        const s = Z_DEFAULT_STRATEGY;
        const o = undefined;
        this._err = undefined;
        this._writeState = new Uint32Array(2);
        this._chunkSize = Z_DEFAULT_CHUNK;
        this._maxOutputLength = kMaxLength;
        this._outBuffer = Buffer.allocUnsafe(this._chunkSize);
        this._outOffset = 0;
        this._handle = new ZlibHandle(e);
        this._handle._owner = this;
        this._handle.onerror = zlibOnError;
        this._handle.init(t, r, n, s, this._writeState, processCallback, o);
    }
    writeSync(e, t) {
        const r = this._handle;
        if (!r) throw new Error("Invalid Zlib instance");
        let n = e.length;
        let s = this._chunkSize - this._outOffset;
        let o = 0;
        let a;
        let l;
        let c;
        let u = 0;
        const d = this._writeState;
        let h = this._outBuffer;
        let p = this._outOffset;
        const g = this._chunkSize;
        while (true) {
            r.writeSync(Z_PARTIAL_FLUSH, e, o, n, h, p, s);
            if (this._err) throw this._err;
            a = d[0];
            l = d[1];
            const t = n - l;
            const m = s - a;
            if (m > 0) {
                const e = p === 0 && m === h.length ? h : h.slice(p, p + m);
                p += m;
                if (!c) c = e; else if (c.push === undefined) c = [ c, e ]; else c.push(e);
                u += e.byteLength;
                if (u > this._maxOutputLength) {
                    _close(this);
                    throw new Error(`Output length exceeded maximum of ${this._maxOutputLength}`);
                }
            } else if (m !== 0) {
                throw new Error("have should not go down");
            }
            if (a === 0 || p >= g) {
                s = g;
                p = 0;
                h = Buffer.allocUnsafe(g);
            }
            if (a === 0) {
                o += t;
                n = l;
            } else {
                break;
            }
        }
        this._outBuffer = h;
        this._outOffset = p;
        if (u === 0) c = Buffer.alloc(0);
        if (t) {
            c.totalLen = u;
            return c;
        }
        if (c.push === undefined) return c;
        const m = Buffer.allocUnsafe(u);
        for (let e = 0, t = 0; e < c.length; ++e) {
            const r = c[e];
            m.set(r, t);
            t += r.length;
        }
        return m;
    }
}

let ZlibPacketWriter$1 = class ZlibPacketWriter {
    constructor(e) {
        this.allocStart = 0;
        this.allocStartKEX = 0;
        this._protocol = e;
        this._zlib = new Zlib(DEFLATE);
    }
    cleanup() {
        if (this._zlib) _close(this._zlib);
    }
    alloc(e, t) {
        return Buffer.allocUnsafe(e);
    }
    finalize(e, t) {
        if (this._protocol._kexinit === undefined || t) {
            const t = this._zlib.writeSync(e, true);
            const r = this._protocol._cipher.allocPacket(t.totalLen);
            if (t.push === undefined) {
                r.set(t, 5);
            } else {
                for (let e = 0, n = 5; e < t.length; ++e) {
                    const s = t[e];
                    r.set(s, n);
                    n += s.length;
                }
            }
            return r;
        }
        return e;
    }
};

let PacketWriter$1 = class PacketWriter {
    constructor(e) {
        this.allocStart = 5;
        this.allocStartKEX = 5;
        this._protocol = e;
    }
    cleanup() {}
    alloc(e, t) {
        if (this._protocol._kexinit === undefined || t) return this._protocol._cipher.allocPacket(e);
        return Buffer.allocUnsafe(e);
    }
    finalize(e, t) {
        return e;
    }
};

let ZlibPacketReader$1 = class ZlibPacketReader {
    constructor() {
        this._zlib = new Zlib(INFLATE);
    }
    cleanup() {
        if (this._zlib) _close(this._zlib);
    }
    read(e) {
        return this._zlib.writeSync(e, false);
    }
};

let PacketReader$1 = class PacketReader {
    cleanup() {}
    read(e) {
        return e;
    }
};

var zlib$1 = {
    PacketReader: PacketReader$1,
    PacketWriter: PacketWriter$1,
    ZlibPacketReader: ZlibPacketReader$1,
    ZlibPacketWriter: ZlibPacketWriter$1
};

const {bufferSlice: bufferSlice$3, bufferParser: bufferParser$2, doFatalError: doFatalError, sigSSHToASN1: sigSSHToASN1$1, writeUInt32BE: writeUInt32BE$4} = requireUtils();

const {CHANNEL_OPEN_FAILURE: CHANNEL_OPEN_FAILURE$2, COMPAT: COMPAT$1, MESSAGE: MESSAGE$1, TERMINAL_MODE: TERMINAL_MODE$1} = requireConstants();

const {parseKey: parseKey$4} = keyParser;

const TERMINAL_MODE_BY_VALUE = Array.from(Object.entries(TERMINAL_MODE$1)).reduce((e, [t, r]) => ({
    ...e,
    [t]: r
}), {});

var handlers_misc = {
    [MESSAGE$1.DISCONNECT]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readString(true);
        const s = bufferParser$2.readString();
        bufferParser$2.clear();
        if (s === undefined) {
            return doFatalError(e, "Inbound: Malformed DISCONNECT packet");
        }
        e._debug && e._debug(`Inbound: Received DISCONNECT (${r}, "${n}")`);
        const o = e._handlers.DISCONNECT;
        o && o(e, r, n);
    },
    [MESSAGE$1.IGNORE]: (e, t) => {
        e._debug && e._debug("Inbound: Received IGNORE");
    },
    [MESSAGE$1.UNIMPLEMENTED]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed UNIMPLEMENTED packet");
        }
        e._debug && e._debug(`Inbound: Received UNIMPLEMENTED (seqno ${r})`);
    },
    [MESSAGE$1.DEBUG]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readBool();
        const n = bufferParser$2.readString(true);
        const s = bufferParser$2.readString();
        bufferParser$2.clear();
        if (s === undefined) {
            return doFatalError(e, "Inbound: Malformed DEBUG packet");
        }
        e._debug && e._debug("Inbound: Received DEBUG");
        const o = e._handlers.DEBUG;
        o && o(e, r, n);
    },
    [MESSAGE$1.SERVICE_REQUEST]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed SERVICE_REQUEST packet");
        }
        e._debug && e._debug(`Inbound: Received SERVICE_REQUEST (${r})`);
        const n = e._handlers.SERVICE_REQUEST;
        n && n(e, r);
    },
    [MESSAGE$1.SERVICE_ACCEPT]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed SERVICE_ACCEPT packet");
        }
        e._debug && e._debug(`Inbound: Received SERVICE_ACCEPT (${r})`);
        const n = e._handlers.SERVICE_ACCEPT;
        n && n(e, r);
    },
    [MESSAGE$1.EXT_INFO]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        let n;
        if (r !== undefined) {
            n = [];
            for (let e = 0; e < r; ++e) {
                const e = bufferParser$2.readString(true);
                const t = bufferParser$2.readString();
                if (t !== undefined) {
                    switch (e) {
                      case "server-sig-algs":
                        {
                            const r = t.latin1Slice(0, t.length).split(",");
                            n.push({
                                name: e,
                                algs: r
                            });
                            continue;
                        }

                      default:
                        continue;
                    }
                }
                n = undefined;
                break;
            }
        }
        bufferParser$2.clear();
        if (n === undefined) return doFatalError(e, "Inbound: Malformed EXT_INFO packet");
        e._debug && e._debug("Inbound: Received EXT_INFO");
        const s = e._handlers.EXT_INFO;
        s && s(e, n);
    },
    [MESSAGE$1.USERAUTH_REQUEST]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        const n = bufferParser$2.readString(true);
        const s = bufferParser$2.readString(true);
        let o;
        let a;
        switch (s) {
          case "none":
            o = null;
            break;

          case "password":
            {
                const e = bufferParser$2.readBool();
                if (e !== undefined) {
                    o = bufferParser$2.readString(true);
                    if (o !== undefined && e) {
                        const e = bufferParser$2.readString(true);
                        if (e !== undefined) o = {
                            oldPassword: o,
                            newPassword: e
                        }; else o = undefined;
                    }
                }
                break;
            }

          case "publickey":
            {
                const r = bufferParser$2.readBool();
                if (r !== undefined) {
                    const n = bufferParser$2.readString(true);
                    let s = n;
                    const l = bufferParser$2.readString();
                    let c;
                    switch (n) {
                      case "rsa-sha2-256":
                        s = "ssh-rsa";
                        c = "sha256";
                        break;

                      case "rsa-sha2-512":
                        s = "ssh-rsa";
                        c = "sha512";
                        break;
                    }
                    if (r) {
                        const r = bufferParser$2.pos();
                        let a = bufferParser$2.readString();
                        if (a !== undefined) {
                            if (a.length > 4 + n.length + 4 && a.utf8Slice(4, 4 + n.length) === n) {
                                a = bufferSlice$3(a, 4 + n.length + 4);
                            }
                            a = sigSSHToASN1$1(a, s);
                            if (a) {
                                const n = e._kex.sessionID;
                                const u = Buffer.allocUnsafe(4 + n.length + r);
                                writeUInt32BE$4(u, n.length, 0);
                                u.set(n, 4);
                                u.set(new Uint8Array(t.buffer, t.byteOffset, r), 4 + n.length);
                                o = {
                                    keyAlgo: s,
                                    key: l,
                                    signature: a,
                                    blob: u,
                                    hashAlgo: c
                                };
                            }
                        }
                    } else {
                        o = {
                            keyAlgo: s,
                            key: l,
                            hashAlgo: c
                        };
                        a = "publickey -- check";
                    }
                }
                break;
            }

          case "hostbased":
            {
                const r = bufferParser$2.readString(true);
                let n = r;
                const s = bufferParser$2.readString();
                const a = bufferParser$2.readString(true);
                const l = bufferParser$2.readString(true);
                let c;
                switch (r) {
                  case "rsa-sha2-256":
                    n = "ssh-rsa";
                    c = "sha256";
                    break;

                  case "rsa-sha2-512":
                    n = "ssh-rsa";
                    c = "sha512";
                    break;
                }
                const u = bufferParser$2.pos();
                let d = bufferParser$2.readString();
                if (d !== undefined) {
                    if (d.length > 4 + r.length + 4 && d.utf8Slice(4, 4 + r.length) === r) {
                        d = bufferSlice$3(d, 4 + r.length + 4);
                    }
                    d = sigSSHToASN1$1(d, n);
                    if (d !== undefined) {
                        const r = e._kex.sessionID;
                        const h = Buffer.allocUnsafe(4 + r.length + u);
                        writeUInt32BE$4(h, r.length, 0);
                        h.set(r, 4);
                        h.set(new Uint8Array(t.buffer, t.byteOffset, u), 4 + r.length);
                        o = {
                            keyAlgo: n,
                            key: s,
                            signature: d,
                            blob: h,
                            localHostname: a,
                            localUsername: l,
                            hashAlgo: c
                        };
                    }
                }
                break;
            }

          case "keyboard-interactive":
            bufferParser$2.skipString();
            o = bufferParser$2.readList();
            break;

          default:
            if (s !== undefined) o = bufferParser$2.readRaw();
        }
        bufferParser$2.clear();
        if (o === undefined) {
            return doFatalError(e, "Inbound: Malformed USERAUTH_REQUEST packet");
        }
        if (a === undefined) a = s;
        e._authsQueue.push(s);
        e._debug && e._debug(`Inbound: Received USERAUTH_REQUEST (${a})`);
        const l = e._handlers.USERAUTH_REQUEST;
        l && l(e, r, n, s, o);
    },
    [MESSAGE$1.USERAUTH_FAILURE]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readList();
        const n = bufferParser$2.readBool();
        bufferParser$2.clear();
        if (n === undefined) {
            return doFatalError(e, "Inbound: Malformed USERAUTH_FAILURE packet");
        }
        e._debug && e._debug(`Inbound: Received USERAUTH_FAILURE (${r})`);
        e._authsQueue.shift();
        const s = e._handlers.USERAUTH_FAILURE;
        s && s(e, r, n);
    },
    [MESSAGE$1.USERAUTH_SUCCESS]: (e, t) => {
        e._debug && e._debug("Inbound: Received USERAUTH_SUCCESS");
        e._authsQueue.shift();
        const r = e._handlers.USERAUTH_SUCCESS;
        r && r(e);
    },
    [MESSAGE$1.USERAUTH_BANNER]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        const n = bufferParser$2.readString();
        bufferParser$2.clear();
        if (n === undefined) {
            return doFatalError(e, "Inbound: Malformed USERAUTH_BANNER packet");
        }
        e._debug && e._debug("Inbound: Received USERAUTH_BANNER");
        const s = e._handlers.USERAUTH_BANNER;
        s && s(e, r);
    },
    60: (e, t) => {
        if (!e._authsQueue.length) {
            e._debug && e._debug("Inbound: Received payload type 60 without auth");
            return;
        }
        switch (e._authsQueue[0]) {
          case "password":
            {
                bufferParser$2.init(t, 1);
                const r = bufferParser$2.readString(true);
                const n = bufferParser$2.readString();
                bufferParser$2.clear();
                if (n === undefined) {
                    return doFatalError(e, "Inbound: Malformed USERAUTH_PASSWD_CHANGEREQ packet");
                }
                e._debug && e._debug("Inbound: Received USERAUTH_PASSWD_CHANGEREQ");
                const s = e._handlers.USERAUTH_PASSWD_CHANGEREQ;
                s && s(e, r);
                break;
            }

          case "publickey":
            {
                bufferParser$2.init(t, 1);
                const r = bufferParser$2.readString(true);
                const n = bufferParser$2.readString();
                bufferParser$2.clear();
                if (n === undefined) {
                    return doFatalError(e, "Inbound: Malformed USERAUTH_PK_OK packet");
                }
                e._debug && e._debug("Inbound: Received USERAUTH_PK_OK");
                e._authsQueue.shift();
                const s = e._handlers.USERAUTH_PK_OK;
                s && s(e, r, n);
                break;
            }

          case "keyboard-interactive":
            {
                bufferParser$2.init(t, 1);
                const r = bufferParser$2.readString(true);
                const n = bufferParser$2.readString(true);
                bufferParser$2.readString();
                const s = bufferParser$2.readUInt32BE();
                let o;
                if (s !== undefined) {
                    o = new Array(s);
                    let e;
                    for (e = 0; e < s; ++e) {
                        const t = bufferParser$2.readString(true);
                        const r = bufferParser$2.readBool();
                        if (r === undefined) break;
                        o[e] = {
                            prompt: t,
                            echo: r
                        };
                    }
                    if (e !== s) o = undefined;
                }
                bufferParser$2.clear();
                if (o === undefined) {
                    return doFatalError(e, "Inbound: Malformed USERAUTH_INFO_REQUEST packet");
                }
                e._debug && e._debug("Inbound: Received USERAUTH_INFO_REQUEST");
                const a = e._handlers.USERAUTH_INFO_REQUEST;
                a && a(e, r, n, o);
                break;
            }

          default:
            e._debug && e._debug("Inbound: Received unexpected payload type 60");
        }
    },
    61: (e, t) => {
        if (!e._authsQueue.length) {
            e._debug && e._debug("Inbound: Received payload type 61 without auth");
            return;
        }
        if (e._authsQueue[0] !== "keyboard-interactive") {
            return doFatalError(e, "Inbound: Received unexpected payload type 61");
        }
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        let n;
        if (r !== undefined) {
            n = new Array(r);
            let e;
            for (e = 0; e < r; ++e) {
                const t = bufferParser$2.readString(true);
                if (t === undefined) break;
                n[e] = t;
            }
            if (e !== r) n = undefined;
        }
        bufferParser$2.clear();
        if (n === undefined) {
            return doFatalError(e, "Inbound: Malformed USERAUTH_INFO_RESPONSE packet");
        }
        e._debug && e._debug("Inbound: Received USERAUTH_INFO_RESPONSE");
        const s = e._handlers.USERAUTH_INFO_RESPONSE;
        s && s(e, n);
    },
    [MESSAGE$1.GLOBAL_REQUEST]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        const n = bufferParser$2.readBool();
        let s;
        if (n !== undefined) {
            switch (r) {
              case "tcpip-forward":
              case "cancel-tcpip-forward":
                {
                    const e = bufferParser$2.readString(true);
                    const t = bufferParser$2.readUInt32BE();
                    if (t !== undefined) s = {
                        bindAddr: e,
                        bindPort: t
                    };
                    break;
                }

              case "streamlocal-forward@openssh.com":
              case "cancel-streamlocal-forward@openssh.com":
                {
                    const e = bufferParser$2.readString(true);
                    if (e !== undefined) s = {
                        socketPath: e
                    };
                    break;
                }

              case "no-more-sessions@openssh.com":
                s = null;
                break;

              case "hostkeys-00@openssh.com":
                {
                    s = [];
                    while (bufferParser$2.avail() > 0) {
                        const e = bufferParser$2.readString();
                        if (e === undefined) {
                            s = undefined;
                            break;
                        }
                        const t = parseKey$4(e);
                        if (!(t instanceof Error)) s.push(t);
                    }
                    break;
                }

              default:
                s = bufferParser$2.readRaw();
            }
        }
        bufferParser$2.clear();
        if (s === undefined) {
            return doFatalError(e, "Inbound: Malformed GLOBAL_REQUEST packet");
        }
        e._debug && e._debug(`Inbound: GLOBAL_REQUEST (${r})`);
        const o = e._handlers.GLOBAL_REQUEST;
        if (o) o(e, r, n, s); else e.requestFailure();
    },
    [MESSAGE$1.REQUEST_SUCCESS]: (e, t) => {
        const r = t.length > 1 ? bufferSlice$3(t, 1) : null;
        e._debug && e._debug("Inbound: REQUEST_SUCCESS");
        const n = e._handlers.REQUEST_SUCCESS;
        n && n(e, r);
    },
    [MESSAGE$1.REQUEST_FAILURE]: (e, t) => {
        e._debug && e._debug("Inbound: Received REQUEST_FAILURE");
        const r = e._handlers.REQUEST_FAILURE;
        r && r(e);
    },
    [MESSAGE$1.CHANNEL_OPEN]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readString(true);
        const n = bufferParser$2.readUInt32BE();
        const s = bufferParser$2.readUInt32BE();
        const o = bufferParser$2.readUInt32BE();
        let a;
        switch (r) {
          case "forwarded-tcpip":
          case "direct-tcpip":
            {
                const e = bufferParser$2.readString(true);
                const t = bufferParser$2.readUInt32BE();
                const l = bufferParser$2.readString(true);
                const c = bufferParser$2.readUInt32BE();
                if (c !== undefined) {
                    a = {
                        type: r,
                        sender: n,
                        window: s,
                        packetSize: o,
                        data: {
                            destIP: e,
                            destPort: t,
                            srcIP: l,
                            srcPort: c
                        }
                    };
                }
                break;
            }

          case "forwarded-streamlocal@openssh.com":
          case "direct-streamlocal@openssh.com":
            {
                const e = bufferParser$2.readString(true);
                if (e !== undefined) {
                    a = {
                        type: r,
                        sender: n,
                        window: s,
                        packetSize: o,
                        data: {
                            socketPath: e
                        }
                    };
                }
                break;
            }

          case "x11":
            {
                const e = bufferParser$2.readString(true);
                const t = bufferParser$2.readUInt32BE();
                if (t !== undefined) {
                    a = {
                        type: r,
                        sender: n,
                        window: s,
                        packetSize: o,
                        data: {
                            srcIP: e,
                            srcPort: t
                        }
                    };
                }
                break;
            }

          default:
            a = {
                type: r,
                sender: n,
                window: s,
                packetSize: o,
                data: {}
            };
        }
        bufferParser$2.clear();
        if (a === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_OPEN packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_OPEN (s:${n}, ${r})`);
        const l = e._handlers.CHANNEL_OPEN;
        if (l) {
            l(e, a);
        } else {
            e.channelOpenFail(a.sender, CHANNEL_OPEN_FAILURE$2.ADMINISTRATIVELY_PROHIBITED, "", "");
        }
    },
    [MESSAGE$1.CHANNEL_OPEN_CONFIRMATION]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readUInt32BE();
        const s = bufferParser$2.readUInt32BE();
        const o = bufferParser$2.readUInt32BE();
        const a = bufferParser$2.avail() ? bufferParser$2.readRaw() : undefined;
        bufferParser$2.clear();
        if (o === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_OPEN_CONFIRMATION packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_OPEN_CONFIRMATION (r:${r}, s:${n})`);
        const l = e._handlers.CHANNEL_OPEN_CONFIRMATION;
        if (l) l(e, {
            recipient: r,
            sender: n,
            window: s,
            packetSize: o,
            data: a
        });
    },
    [MESSAGE$1.CHANNEL_OPEN_FAILURE]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readUInt32BE();
        const s = bufferParser$2.readString(true);
        const o = bufferParser$2.readString();
        bufferParser$2.clear();
        if (o === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_OPEN_FAILURE packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_OPEN_FAILURE (r:${r})`);
        const a = e._handlers.CHANNEL_OPEN_FAILURE;
        a && a(e, r, n, s);
    },
    [MESSAGE$1.CHANNEL_WINDOW_ADJUST]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (n === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_WINDOW_ADJUST packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_WINDOW_ADJUST (r:${r}, ${n})`);
        const s = e._handlers.CHANNEL_WINDOW_ADJUST;
        s && s(e, r, n);
    },
    [MESSAGE$1.CHANNEL_DATA]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readString();
        bufferParser$2.clear();
        if (n === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_DATA packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_DATA (r:${r}, ${n.length})`);
        const s = e._handlers.CHANNEL_DATA;
        s && s(e, r, n);
    },
    [MESSAGE$1.CHANNEL_EXTENDED_DATA]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readUInt32BE();
        const s = bufferParser$2.readString();
        bufferParser$2.clear();
        if (s === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_EXTENDED_DATA packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_EXTENDED_DATA (r:${r}, ${s.length})`);
        const o = e._handlers.CHANNEL_EXTENDED_DATA;
        o && o(e, r, s, n);
    },
    [MESSAGE$1.CHANNEL_EOF]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_EOF packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_EOF (r:${r})`);
        const n = e._handlers.CHANNEL_EOF;
        n && n(e, r);
    },
    [MESSAGE$1.CHANNEL_CLOSE]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_CLOSE packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_CLOSE (r:${r})`);
        const n = e._handlers.CHANNEL_CLOSE;
        n && n(e, r);
    },
    [MESSAGE$1.CHANNEL_REQUEST]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        const n = bufferParser$2.readString(true);
        const s = bufferParser$2.readBool();
        let o;
        if (s !== undefined) {
            switch (n) {
              case "exit-status":
                o = bufferParser$2.readUInt32BE();
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${o})`);
                break;

              case "exit-signal":
                {
                    let t;
                    let s;
                    if (e._compatFlags & COMPAT$1.OLD_EXIT) {
                        const e = bufferParser$2.readUInt32BE();
                        switch (e) {
                          case 1:
                            t = "HUP";
                            break;

                          case 2:
                            t = "INT";
                            break;

                          case 3:
                            t = "QUIT";
                            break;

                          case 6:
                            t = "ABRT";
                            break;

                          case 9:
                            t = "KILL";
                            break;

                          case 14:
                            t = "ALRM";
                            break;

                          case 15:
                            t = "TERM";
                            break;

                          default:
                            if (e !== undefined) {
                                t = `UNKNOWN (${e})`;
                            }
                        }
                        s = false;
                    } else {
                        t = bufferParser$2.readString(true);
                        s = bufferParser$2.readBool();
                        if (s === undefined) t = undefined;
                    }
                    const a = bufferParser$2.readString(true);
                    if (bufferParser$2.skipString() !== undefined) o = {
                        signal: t,
                        coreDumped: s,
                        errorMessage: a
                    };
                    e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${t})`);
                    break;
                }

              case "pty-req":
                {
                    const t = bufferParser$2.readString(true);
                    const s = bufferParser$2.readUInt32BE();
                    const a = bufferParser$2.readUInt32BE();
                    const l = bufferParser$2.readUInt32BE();
                    const c = bufferParser$2.readUInt32BE();
                    const u = bufferParser$2.readString();
                    if (u !== undefined) {
                        bufferParser$2.init(u, 1);
                        let e = {};
                        while (bufferParser$2.avail()) {
                            const t = bufferParser$2.readByte();
                            if (t === TERMINAL_MODE$1.TTY_OP_END) break;
                            const r = TERMINAL_MODE_BY_VALUE[t];
                            const n = bufferParser$2.readUInt32BE();
                            if (t === undefined || r === undefined || n === undefined) {
                                e = undefined;
                                break;
                            }
                            e[r] = n;
                        }
                        if (e !== undefined) o = {
                            term: t,
                            cols: s,
                            rows: a,
                            width: l,
                            height: c,
                            modes: e
                        };
                    }
                    e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
                    break;
                }

              case "window-change":
                {
                    const t = bufferParser$2.readUInt32BE();
                    const s = bufferParser$2.readUInt32BE();
                    const a = bufferParser$2.readUInt32BE();
                    const l = bufferParser$2.readUInt32BE();
                    if (l !== undefined) o = {
                        cols: t,
                        rows: s,
                        width: a,
                        height: l
                    };
                    e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
                    break;
                }

              case "x11-req":
                {
                    const t = bufferParser$2.readBool();
                    const s = bufferParser$2.readString(true);
                    const a = bufferParser$2.readString();
                    const l = bufferParser$2.readUInt32BE();
                    if (l !== undefined) o = {
                        single: t,
                        protocol: s,
                        cookie: a,
                        screen: l
                    };
                    e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
                    break;
                }

              case "env":
                {
                    const t = bufferParser$2.readString(true);
                    const s = bufferParser$2.readString(true);
                    if (s !== undefined) o = {
                        name: t,
                        value: s
                    };
                    if (e._debug) {
                        e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ` + `${t}=${s})`);
                    }
                    break;
                }

              case "shell":
                o = null;
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
                break;

              case "exec":
                o = bufferParser$2.readString(true);
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${o})`);
                break;

              case "subsystem":
                o = bufferParser$2.readString(true);
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${o})`);
                break;

              case "signal":
                o = bufferParser$2.readString(true);
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${o})`);
                break;

              case "xon-xoff":
                o = bufferParser$2.readBool();
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n}: ${o})`);
                break;

              case "auth-agent-req@openssh.com":
                o = null;
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
                break;

              default:
                o = bufferParser$2.avail() ? bufferParser$2.readRaw() : null;
                e._debug && e._debug(`Inbound: CHANNEL_REQUEST (r:${r}, ${n})`);
            }
        }
        bufferParser$2.clear();
        if (o === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_REQUEST packet");
        }
        const a = e._handlers.CHANNEL_REQUEST;
        a && a(e, r, n, s, o);
    },
    [MESSAGE$1.CHANNEL_SUCCESS]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_SUCCESS packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_SUCCESS (r:${r})`);
        const n = e._handlers.CHANNEL_SUCCESS;
        n && n(e, r);
    },
    [MESSAGE$1.CHANNEL_FAILURE]: (e, t) => {
        bufferParser$2.init(t, 1);
        const r = bufferParser$2.readUInt32BE();
        bufferParser$2.clear();
        if (r === undefined) {
            return doFatalError(e, "Inbound: Malformed CHANNEL_FAILURE packet");
        }
        e._debug && e._debug(`Inbound: CHANNEL_FAILURE (r:${r})`);
        const n = e._handlers.CHANNEL_FAILURE;
        n && n(e, r);
    }
};

var handlers;

var hasRequiredHandlers;

function requireHandlers() {
    if (hasRequiredHandlers) return handlers;
    hasRequiredHandlers = 1;
    const e = new Array(256);
    [ requireKex().HANDLERS, handlers_misc ].forEach(t => {
        for (let [r, n] of Object.entries(t)) {
            r = +r;
            if (isFinite(r) && r >= 0 && r < e.length) e[r] = n;
        }
    });
    handlers = e;
    return handlers;
}

var kex;

var hasRequiredKex;

function requireKex() {
    if (hasRequiredKex) return kex;
    hasRequiredKex = 1;
    const {createDiffieHellman: e, createDiffieHellmanGroup: t, createECDH: r, createHash: n, createPublicKey: s, diffieHellman: o, generateKeyPairSync: a, randomFillSync: l} = require$$0__default$3.default;
    const {Ber: c} = lib$1;
    const {COMPAT: u, curve25519Supported: d, DEFAULT_KEX: h, DEFAULT_SERVER_HOST_KEY: p, DEFAULT_CIPHER: g, DEFAULT_MAC: m, DEFAULT_COMPRESSION: _, DISCONNECT_REASON: E, MESSAGE: v} = requireConstants();
    const {CIPHER_INFO: y, createCipher: S, createDecipher: A, MAC_INFO: b} = requireCrypto();
    const {parseDERKey: C} = keyParser;
    const {bufferFill: w, bufferParser: I, convertSignature: T, doFatalError: R, FastBuffer: k, sigSSHToASN1: P, writeUInt32BE: $} = requireUtils();
    const {PacketReader: O, PacketWriter: B, ZlibPacketReader: N, ZlibPacketWriter: D} = zlib$1;
    let L;
    const U = 2048;
    const M = 8192;
    const x = Buffer.alloc(0);
    function q(e) {
        let t;
        if (e._compatFlags & u.BAD_DHGEX) {
            const r = e._offer.lists.kex;
            let n = r.array;
            let s = false;
            for (let e = 0; e < n.length; ++e) {
                if (n[e].includes("group-exchange")) {
                    if (!s) {
                        s = true;
                        n = n.slice();
                    }
                    n.splice(e--, 1);
                }
            }
            if (s) {
                let s = 1 + 16 + e._offer.totalSize + 1 + 4;
                const o = Buffer.from(n.join(","));
                s -= r.buffer.length - o.length;
                const a = e._offer.lists.all;
                const l = new Uint8Array(a.buffer, a.byteOffset + 4 + r.buffer.length, a.length - (4 + r.buffer.length));
                t = Buffer.allocUnsafe(s);
                $(t, o.length, 17);
                t.set(o, 17 + 4);
                t.set(l, 17 + 4 + o.length);
            }
        }
        if (t === undefined) {
            t = Buffer.allocUnsafe(1 + 16 + e._offer.totalSize + 1 + 4);
            e._offer.copyAllTo(t, 17);
        }
        e._debug && e._debug("Outbound: Sending KEXINIT");
        t[0] = v.KEXINIT;
        l(t, 1, 16);
        w(t, 0, t.length - 5);
        e._kexinit = t;
        e._packetRW.write.allocStart = 0;
        {
            const r = e._packetRW.write.allocStartKEX;
            const n = e._packetRW.write.alloc(t.length, true);
            n.set(t, r);
            e._cipher.encrypt(e._packetRW.write.finalize(n, true));
        }
    }
    function H(e, t) {
        const r = {
            kex: undefined,
            serverHostKey: undefined,
            cs: {
                cipher: undefined,
                mac: undefined,
                compress: undefined,
                lang: undefined
            },
            sc: {
                cipher: undefined,
                mac: undefined,
                compress: undefined,
                lang: undefined
            }
        };
        I.init(t, 17);
        if ((r.kex = I.readList()) === undefined || (r.serverHostKey = I.readList()) === undefined || (r.cs.cipher = I.readList()) === undefined || (r.sc.cipher = I.readList()) === undefined || (r.cs.mac = I.readList()) === undefined || (r.sc.mac = I.readList()) === undefined || (r.cs.compress = I.readList()) === undefined || (r.sc.compress = I.readList()) === undefined || (r.cs.lang = I.readList()) === undefined || (r.sc.lang = I.readList()) === undefined) {
            I.clear();
            return R(e, "Received malformed KEXINIT", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        const n = I.pos();
        const s = n < t.length && t[n] === 1;
        I.clear();
        const o = e._offer;
        const a = r;
        let l = o.lists.kex.array;
        if (e._compatFlags & u.BAD_DHGEX) {
            let e = false;
            for (let t = 0; t < l.length; ++t) {
                if (l[t].indexOf("group-exchange") !== -1) {
                    if (!e) {
                        e = true;
                        l = l.slice();
                    }
                    l.splice(t--, 1);
                }
            }
        }
        let c;
        let d;
        let h;
        const p = e._debug;
        p && p("Inbound: Handshake in progress");
        p && p(`Handshake: (local) KEX method: ${l}`);
        p && p(`Handshake: (remote) KEX method: ${a.kex}`);
        let g;
        if (e._server) {
            d = l;
            c = a.kex;
            g = c.indexOf("ext-info-c") !== -1;
        } else {
            d = a.kex;
            c = l;
            g = d.indexOf("ext-info-s") !== -1;
        }
        if (e._strictMode === undefined) {
            if (e._server) {
                e._strictMode = c.indexOf("kex-strict-c-v00@openssh.com") !== -1;
            } else {
                e._strictMode = d.indexOf("kex-strict-s-v00@openssh.com") !== -1;
            }
            if (e._strictMode) {
                p && p("Handshake: strict KEX mode enabled");
                if (e._decipher.inSeqno !== 1) {
                    if (p) p("Handshake: KEXINIT not first packet in strict KEX mode");
                    return R(e, "Handshake failed: KEXINIT not first packet in strict KEX mode", "handshake", E.KEY_EXCHANGE_FAILED);
                }
            }
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: no matching key exchange algorithm");
            return R(e, "Handshake failed: no matching key exchange algorithm", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.kex = c[h];
        p && p(`Handshake: KEX algorithm: ${c[h]}`);
        if (s && (!a.kex.length || c[h] !== a.kex[0])) {
            e._skipNextInboundPacket = true;
        }
        const m = o.lists.serverHostKey.array;
        p && p(`Handshake: (local) Host key format: ${m}`);
        p && p(`Handshake: (remote) Host key format: ${a.serverHostKey}`);
        if (e._server) {
            d = m;
            c = a.serverHostKey;
        } else {
            d = a.serverHostKey;
            c = m;
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: No matching host key format");
            return R(e, "Handshake failed: no matching host key format", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.serverHostKey = c[h];
        p && p(`Handshake: Host key format: ${c[h]}`);
        const _ = o.lists.cs.cipher.array;
        p && p(`Handshake: (local) C->S cipher: ${_}`);
        p && p(`Handshake: (remote) C->S cipher: ${a.cs.cipher}`);
        if (e._server) {
            d = _;
            c = a.cs.cipher;
        } else {
            d = a.cs.cipher;
            c = _;
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: No matching C->S cipher");
            return R(e, "Handshake failed: no matching C->S cipher", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.cs.cipher = c[h];
        p && p(`Handshake: C->S Cipher: ${c[h]}`);
        const v = o.lists.sc.cipher.array;
        p && p(`Handshake: (local) S->C cipher: ${v}`);
        p && p(`Handshake: (remote) S->C cipher: ${a.sc.cipher}`);
        if (e._server) {
            d = v;
            c = a.sc.cipher;
        } else {
            d = a.sc.cipher;
            c = v;
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: No matching S->C cipher");
            return R(e, "Handshake failed: no matching S->C cipher", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.sc.cipher = c[h];
        p && p(`Handshake: S->C cipher: ${c[h]}`);
        const S = o.lists.cs.mac.array;
        p && p(`Handshake: (local) C->S MAC: ${S}`);
        p && p(`Handshake: (remote) C->S MAC: ${a.cs.mac}`);
        if (y[r.cs.cipher].authLen > 0) {
            r.cs.mac = "";
            p && p("Handshake: C->S MAC: <implicit>");
        } else {
            if (e._server) {
                d = S;
                c = a.cs.mac;
            } else {
                d = a.cs.mac;
                c = S;
            }
            for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
            if (h === c.length) {
                p && p("Handshake: No matching C->S MAC");
                return R(e, "Handshake failed: no matching C->S MAC", "handshake", E.KEY_EXCHANGE_FAILED);
            }
            r.cs.mac = c[h];
            p && p(`Handshake: C->S MAC: ${c[h]}`);
        }
        const A = o.lists.sc.mac.array;
        p && p(`Handshake: (local) S->C MAC: ${A}`);
        p && p(`Handshake: (remote) S->C MAC: ${a.sc.mac}`);
        if (y[r.sc.cipher].authLen > 0) {
            r.sc.mac = "";
            p && p("Handshake: S->C MAC: <implicit>");
        } else {
            if (e._server) {
                d = A;
                c = a.sc.mac;
            } else {
                d = a.sc.mac;
                c = A;
            }
            for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
            if (h === c.length) {
                p && p("Handshake: No matching S->C MAC");
                return R(e, "Handshake failed: no matching S->C MAC", "handshake", E.KEY_EXCHANGE_FAILED);
            }
            r.sc.mac = c[h];
            p && p(`Handshake: S->C MAC: ${c[h]}`);
        }
        const b = o.lists.cs.compress.array;
        p && p(`Handshake: (local) C->S compression: ${b}`);
        p && p(`Handshake: (remote) C->S compression: ${a.cs.compress}`);
        if (e._server) {
            d = b;
            c = a.cs.compress;
        } else {
            d = a.cs.compress;
            c = b;
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: No matching C->S compression");
            return R(e, "Handshake failed: no matching C->S compression", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.cs.compress = c[h];
        p && p(`Handshake: C->S compression: ${c[h]}`);
        const C = o.lists.sc.compress.array;
        p && p(`Handshake: (local) S->C compression: ${C}`);
        p && p(`Handshake: (remote) S->C compression: ${a.sc.compress}`);
        if (e._server) {
            d = C;
            c = a.sc.compress;
        } else {
            d = a.sc.compress;
            c = C;
        }
        for (h = 0; h < c.length && d.indexOf(c[h]) === -1; ++h) ;
        if (h === c.length) {
            p && p("Handshake: No matching S->C compression");
            return R(e, "Handshake failed: no matching S->C compression", "handshake", E.KEY_EXCHANGE_FAILED);
        }
        r.sc.compress = c[h];
        p && p(`Handshake: S->C compression: ${c[h]}`);
        r.cs.lang = "";
        r.sc.lang = "";
        if (e._kex) {
            if (!e._kexinit) {
                q(e);
            }
            e._decipher._onPayload = K.bind(e, {
                firstPacket: false
            });
        }
        e._kex = W(r, e, t);
        e._kex.remoteExtInfoEnabled = g;
        e._kex.start();
    }
    const W = (() => {
        function l(e) {
            let t = 0;
            let r = e.length;
            while (e[t] === 0) {
                ++t;
                --r;
            }
            let n;
            if (e[t] & 128) {
                n = Buffer.allocUnsafe(1 + r);
                n[0] = 0;
                e.copy(n, 1, t);
                e = n;
            } else if (r !== e.length) {
                n = Buffer.allocUnsafe(r);
                e.copy(n, 0, t);
                e = n;
            }
            return e;
        }
        class KeyExchange {
            constructor(e, t, r) {
                this._protocol = t;
                this.sessionID = t._kex ? t._kex.sessionID : undefined;
                this.negotiated = e;
                this.remoteExtInfoEnabled = false;
                this._step = 1;
                this._public = null;
                this._dh = null;
                this._sentNEWKEYS = false;
                this._receivedNEWKEYS = false;
                this._finished = false;
                this._hostVerified = false;
                this._kexinit = t._kexinit;
                this._remoteKexinit = r;
                this._identRaw = t._identRaw;
                this._remoteIdentRaw = t._remoteIdentRaw;
                this._hostKey = undefined;
                this._dhData = undefined;
                this._sig = undefined;
            }
            finish(e) {
                if (this._finished) return false;
                this._finished = true;
                const t = this._protocol._server;
                const r = this.negotiated;
                const s = this.convertPublicKey(this._dhData);
                let o = this.computeSecret(this._dhData);
                if (o instanceof Error) {
                    o.message = `Error while computing DH secret (${this.type}): ${o.message}`;
                    o.level = "handshake";
                    return R(this._protocol, o, E.KEY_EXCHANGE_FAILED);
                }
                const a = n(this.hashName);
                Q(a, t ? this._remoteIdentRaw : this._identRaw);
                Q(a, t ? this._identRaw : this._remoteIdentRaw);
                Q(a, t ? this._remoteKexinit : this._kexinit);
                Q(a, t ? this._kexinit : this._remoteKexinit);
                const l = t ? this._hostKey.getPublicSSH() : this._hostKey;
                Q(a, l);
                if (this.type === "groupex") {
                    const e = this.getDHParams();
                    const t = Buffer.allocUnsafe(4);
                    $(t, this._minBits, 0);
                    a.update(t);
                    $(t, this._prefBits, 0);
                    a.update(t);
                    $(t, this._maxBits, 0);
                    a.update(t);
                    Q(a, e.prime);
                    Q(a, e.generator);
                }
                Q(a, t ? s : this.getPublicKey());
                const c = t ? this.getPublicKey() : s;
                Q(a, c);
                Q(a, o);
                const u = a.digest();
                if (!t) {
                    I.init(this._sig, 0);
                    const e = I.readString(true);
                    if (!e) {
                        return R(this._protocol, "Malformed packet while reading signature", "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    if (e !== r.serverHostKey) {
                        return R(this._protocol, `Wrong signature type: ${e}, ` + `expected: ${r.serverHostKey}`, "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    let t = I.readString();
                    I.clear();
                    if (t === undefined) {
                        return R(this._protocol, "Malformed packet while reading signature", "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    if (!(t = P(t, e))) {
                        return R(this._protocol, "Malformed signature", "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    let n;
                    {
                        I.init(this._hostKey, 0);
                        const e = I.readString(true);
                        const t = this._hostKey.slice(I.pos());
                        I.clear();
                        n = C(t, e);
                        if (n instanceof Error) {
                            n.level = "handshake";
                            return R(this._protocol, n, E.KEY_EXCHANGE_FAILED);
                        }
                    }
                    let s;
                    switch (this.negotiated.serverHostKey) {
                      case "rsa-sha2-256":
                        s = "sha256";
                        break;

                      case "rsa-sha2-512":
                        s = "sha512";
                        break;
                    }
                    this._protocol._debug && this._protocol._debug("Verifying signature ...");
                    const o = n.verify(u, t, s);
                    if (o !== true) {
                        if (o instanceof Error) {
                            this._protocol._debug && this._protocol._debug(`Signature verification failed: ${o.stack}`);
                        } else {
                            this._protocol._debug && this._protocol._debug("Signature verification failed");
                        }
                        return R(this._protocol, "Handshake failed: signature verification failed", "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    this._protocol._debug && this._protocol._debug("Verified signature");
                } else {
                    let e;
                    switch (this.negotiated.serverHostKey) {
                      case "rsa-sha2-256":
                        e = "sha256";
                        break;

                      case "rsa-sha2-512":
                        e = "sha512";
                        break;
                    }
                    this._protocol._debug && this._protocol._debug("Generating signature ...");
                    let t = this._hostKey.sign(u, e);
                    if (t instanceof Error) {
                        return R(this._protocol, "Handshake failed: signature generation failed for " + `${this._hostKey.type} host key: ${t.message}`, "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    t = T(t, this._hostKey.type);
                    if (t === false) {
                        return R(this._protocol, "Handshake failed: signature conversion failed for " + `${this._hostKey.type} host key`, "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    const r = this.negotiated.serverHostKey;
                    const n = Buffer.byteLength(r);
                    const s = 4 + n + 4 + t.length;
                    let o = this._protocol._packetRW.write.allocStartKEX;
                    const a = this._protocol._packetRW.write.alloc(1 + 4 + l.length + 4 + c.length + 4 + s, true);
                    a[o] = v.KEXDH_REPLY;
                    $(a, l.length, ++o);
                    a.set(l, o += 4);
                    $(a, c.length, o += l.length);
                    a.set(c, o += 4);
                    $(a, s, o += c.length);
                    $(a, n, o += 4);
                    a.utf8Write(r, o += 4, n);
                    $(a, t.length, o += n);
                    a.set(t, o += 4);
                    if (this._protocol._debug) {
                        let e;
                        switch (this.type) {
                          case "group":
                            e = "KEXDH_REPLY";
                            break;

                          case "groupex":
                            e = "KEXDH_GEX_REPLY";
                            break;

                          default:
                            e = "KEXECDH_REPLY";
                        }
                        this._protocol._debug(`Outbound: Sending ${e}`);
                    }
                    this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(a, true));
                }
                if (t || !e) Y(this);
                let d;
                let h;
                const p = e => {
                    if (d) {
                        Y(this);
                        d.outbound.seqno = this._protocol._cipher.outSeqno;
                        this._protocol._cipher.free();
                        this._protocol._cipher = S(d);
                        this._protocol._packetRW.write = h;
                        d = undefined;
                        h = undefined;
                        this._protocol._onHandshakeComplete(r);
                        return false;
                    }
                    if (!this.sessionID) this.sessionID = u;
                    {
                        const e = Buffer.allocUnsafe(4 + o.length);
                        $(e, o.length, 0);
                        e.set(o, 4);
                        o = e;
                    }
                    const n = y[r.cs.cipher];
                    const s = y[r.sc.cipher];
                    const a = G(n.ivLen, this.hashName, o, u, this.sessionID, "A");
                    const l = G(s.ivLen, this.hashName, o, u, this.sessionID, "B");
                    const c = G(n.keyLen, this.hashName, o, u, this.sessionID, "C");
                    const g = G(s.keyLen, this.hashName, o, u, this.sessionID, "D");
                    let m;
                    let _;
                    if (!n.authLen) {
                        m = b[r.cs.mac];
                        _ = G(m.len, this.hashName, o, u, this.sessionID, "E");
                    }
                    let E;
                    let v;
                    if (!s.authLen) {
                        E = b[r.sc.mac];
                        v = G(E.len, this.hashName, o, u, this.sessionID, "F");
                    }
                    const C = {
                        inbound: {
                            onPayload: this._protocol._onPayload,
                            seqno: this._protocol._decipher.inSeqno,
                            decipherInfo: !t ? s : n,
                            decipherIV: !t ? l : a,
                            decipherKey: !t ? g : c,
                            macInfo: !t ? E : m,
                            macKey: !t ? v : _
                        },
                        outbound: {
                            onWrite: this._protocol._onWrite,
                            seqno: this._protocol._cipher.outSeqno,
                            cipherInfo: t ? s : n,
                            cipherIV: t ? l : a,
                            cipherKey: t ? g : c,
                            macInfo: t ? E : m,
                            macKey: t ? v : _
                        }
                    };
                    this._protocol._decipher.free();
                    d = C;
                    this._protocol._decipher = A(C);
                    const w = {
                        read: undefined,
                        write: undefined
                    };
                    switch (r.cs.compress) {
                      case "zlib":
                        if (t) w.read = new N; else w.write = new D(this._protocol);
                        break;

                      case "zlib@openssh.com":
                        if (this._protocol._authenticated) {
                            if (t) w.read = new N; else w.write = new D(this._protocol);
                            break;
                        }

                      default:
                        if (t) w.read = new O; else w.write = new B(this._protocol);
                    }
                    switch (r.sc.compress) {
                      case "zlib":
                        if (t) w.write = new D(this._protocol); else w.read = new N;
                        break;

                      case "zlib@openssh.com":
                        if (this._protocol._authenticated) {
                            if (t) w.write = new D(this._protocol); else w.read = new N;
                            break;
                        }

                      default:
                        if (t) w.write = new B(this._protocol); else w.read = new O;
                    }
                    this._protocol._packetRW.read.cleanup();
                    this._protocol._packetRW.write.cleanup();
                    this._protocol._packetRW.read = w.read;
                    h = w.write;
                    this._public = null;
                    this._dh = null;
                    this._kexinit = this._protocol._kexinit = undefined;
                    this._remoteKexinit = undefined;
                    this._identRaw = undefined;
                    this._remoteIdentRaw = undefined;
                    this._hostKey = undefined;
                    this._dhData = undefined;
                    this._sig = undefined;
                    if (!e) return p();
                    return false;
                };
                if (t || e) this.finish = p;
                if (!t) return p(e);
            }
            start() {
                if (!this._protocol._server) {
                    if (this._protocol._debug) {
                        let e;
                        switch (this.type) {
                          case "group":
                            e = "KEXDH_INIT";
                            break;

                          default:
                            e = "KEXECDH_INIT";
                        }
                        this._protocol._debug(`Outbound: Sending ${e}`);
                    }
                    const e = this.getPublicKey();
                    let t = this._protocol._packetRW.write.allocStartKEX;
                    const r = this._protocol._packetRW.write.alloc(1 + 4 + e.length, true);
                    r[t] = v.KEXDH_INIT;
                    $(r, e.length, ++t);
                    r.set(e, t += 4);
                    this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(r, true));
                }
            }
            getPublicKey() {
                this.generateKeys();
                const e = this._public;
                if (e) return this.convertPublicKey(e);
            }
            convertPublicKey(e) {
                let t;
                let r = 0;
                let n = e.length;
                while (e[r] === 0) {
                    ++r;
                    --n;
                }
                if (e[r] & 128) {
                    t = Buffer.allocUnsafe(1 + n);
                    t[0] = 0;
                    e.copy(t, 1, r);
                    return t;
                }
                if (n !== e.length) {
                    t = Buffer.allocUnsafe(n);
                    e.copy(t, 0, r);
                    e = t;
                }
                return e;
            }
            computeSecret(e) {
                this.generateKeys();
                try {
                    return l(this._dh.computeSecret(e));
                } catch (e) {
                    return e;
                }
            }
            parse(e) {
                const t = e[0];
                switch (this._step) {
                  case 1:
                    if (this._protocol._server) {
                        if (t !== v.KEXDH_INIT) {
                            return R(this._protocol, `Received packet ${t} instead of ${v.KEXDH_INIT}`, "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._protocol._debug && this._protocol._debug("Received DH Init");
                        I.init(e, 1);
                        const r = I.readString();
                        I.clear();
                        if (r === undefined) {
                            return R(this._protocol, "Received malformed KEX*_INIT", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._dhData = r;
                        let n = this._protocol._hostKeys[this.negotiated.serverHostKey];
                        if (Array.isArray(n)) n = n[0];
                        this._hostKey = n;
                        this.finish();
                    } else {
                        if (t !== v.KEXDH_REPLY) {
                            return R(this._protocol, `Received packet ${t} instead of ${v.KEXDH_REPLY}`, "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._protocol._debug && this._protocol._debug("Received DH Reply");
                        I.init(e, 1);
                        let r;
                        let n;
                        let s;
                        if ((r = I.readString()) === undefined || (n = I.readString()) === undefined || (s = I.readString()) === undefined) {
                            I.clear();
                            return R(this._protocol, "Received malformed KEX*_REPLY", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        I.clear();
                        I.init(r, 0);
                        const o = I.readString(true);
                        I.clear();
                        if (o === undefined) {
                            return R(this._protocol, "Received malformed host public key", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        if (o !== this.negotiated.serverHostKey) {
                            switch (this.negotiated.serverHostKey) {
                              case "rsa-sha2-256":
                              case "rsa-sha2-512":
                                if (o === "ssh-rsa") break;

                              default:
                                return R(this._protocol, "Host key does not match negotiated type", "handshake", E.KEY_EXCHANGE_FAILED);
                            }
                        }
                        this._hostKey = r;
                        this._dhData = n;
                        this._sig = s;
                        let a = false;
                        let l;
                        if (this._protocol._hostVerifier === undefined) {
                            l = true;
                            this._protocol._debug && this._protocol._debug("Host accepted by default (no verification)");
                        } else {
                            l = this._protocol._hostVerifier(r, e => {
                                if (a) return;
                                a = true;
                                if (e === false) {
                                    this._protocol._debug && this._protocol._debug("Host denied (verification failed)");
                                    return R(this._protocol, "Host denied (verification failed)", "handshake", E.KEY_EXCHANGE_FAILED);
                                }
                                this._protocol._debug && this._protocol._debug("Host accepted (verified)");
                                this._hostVerified = true;
                                if (this._receivedNEWKEYS) this.finish(); else Y(this);
                            });
                        }
                        if (l === undefined) {
                            ++this._step;
                            return;
                        }
                        a = true;
                        if (l === false) {
                            this._protocol._debug && this._protocol._debug("Host denied (verification failed)");
                            return R(this._protocol, "Host denied (verification failed)", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._protocol._debug && this._protocol._debug("Host accepted (verified)");
                        this._hostVerified = true;
                        Y(this);
                    }
                    ++this._step;
                    break;

                  case 2:
                    if (t !== v.NEWKEYS) {
                        return R(this._protocol, `Received packet ${t} instead of ${v.NEWKEYS}`, "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    this._protocol._debug && this._protocol._debug("Inbound: NEWKEYS");
                    this._receivedNEWKEYS = true;
                    if (this._protocol._strictMode) this._protocol._decipher.inSeqno = 0;
                    ++this._step;
                    return this.finish(!this._protocol._server && !this._hostVerified);

                  default:
                    return R(this._protocol, `Received unexpected packet ${t} after NEWKEYS`, "handshake", E.KEY_EXCHANGE_FAILED);
                }
            }
        }
        class Curve25519Exchange extends KeyExchange {
            constructor(e, ...t) {
                super(...t);
                this.type = "25519";
                this.hashName = e;
                this._keys = null;
            }
            generateKeys() {
                if (!this._keys) this._keys = a("x25519");
            }
            getPublicKey() {
                this.generateKeys();
                const e = this._keys.publicKey.export({
                    type: "spki",
                    format: "der"
                });
                return e.slice(-32);
            }
            convertPublicKey(e) {
                let t;
                let r = 0;
                let n = e.length;
                while (e[r] === 0) {
                    ++r;
                    --n;
                }
                if (e.length === 32) return e;
                if (n !== e.length) {
                    t = Buffer.allocUnsafe(n);
                    e.copy(t, 0, r);
                    e = t;
                }
                return e;
            }
            computeSecret(e) {
                this.generateKeys();
                try {
                    const t = new c.Writer;
                    t.startSequence();
                    t.startSequence();
                    t.writeOID("1.3.101.110");
                    t.endSequence();
                    t.startSequence(c.BitString);
                    t.writeByte(0);
                    t._ensure(e.length);
                    e.copy(t._buf, t._offset, 0, e.length);
                    t._offset += e.length;
                    t.endSequence();
                    t.endSequence();
                    return l(o({
                        privateKey: this._keys.privateKey,
                        publicKey: s({
                            key: t.buffer,
                            type: "spki",
                            format: "der"
                        })
                    }));
                } catch (e) {
                    return e;
                }
            }
        }
        class ECDHExchange extends KeyExchange {
            constructor(e, t, ...r) {
                super(...r);
                this.type = "ecdh";
                this.curveName = e;
                this.hashName = t;
            }
            generateKeys() {
                if (!this._dh) {
                    this._dh = r(this.curveName);
                    this._public = this._dh.generateKeys();
                }
            }
        }
        class DHGroupExchange extends KeyExchange {
            constructor(e, ...t) {
                super(...t);
                this.type = "groupex";
                this.hashName = e;
                this._prime = null;
                this._generator = null;
                this._minBits = U;
                this._prefBits = z(this.negotiated);
                if (this._protocol._compatFlags & u.BUG_DHGEX_LARGE) this._prefBits = Math.min(this._prefBits, 4096);
                this._maxBits = M;
            }
            start() {
                if (this._protocol._server) return;
                this._protocol._debug && this._protocol._debug("Outbound: Sending KEXDH_GEX_REQUEST");
                let e = this._protocol._packetRW.write.allocStartKEX;
                const t = this._protocol._packetRW.write.alloc(1 + 4 + 4 + 4, true);
                t[e] = v.KEXDH_GEX_REQUEST;
                $(t, this._minBits, ++e);
                $(t, this._prefBits, e += 4);
                $(t, this._maxBits, e += 4);
                this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(t, true));
            }
            generateKeys() {
                if (!this._dh && this._prime && this._generator) {
                    this._dh = e(this._prime, this._generator);
                    this._public = this._dh.generateKeys();
                }
            }
            setDHParams(e, t) {
                if (!Buffer.isBuffer(e)) throw new Error("Invalid prime value");
                if (!Buffer.isBuffer(t)) throw new Error("Invalid generator value");
                this._prime = e;
                this._generator = t;
            }
            getDHParams() {
                if (this._dh) {
                    return {
                        prime: l(this._dh.getPrime()),
                        generator: l(this._dh.getGenerator())
                    };
                }
            }
            parse(e) {
                const t = e[0];
                switch (this._step) {
                  case 1:
                    {
                        if (this._protocol._server) {
                            if (t !== v.KEXDH_GEX_REQUEST) {
                                return R(this._protocol, `Received packet ${t} instead of ` + v.KEXDH_GEX_REQUEST, "handshake", E.KEY_EXCHANGE_FAILED);
                            }
                            return R(this._protocol, "Group exchange not implemented for server", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        if (t !== v.KEXDH_GEX_GROUP) {
                            return R(this._protocol, `Received packet ${t} instead of ${v.KEXDH_GEX_GROUP}`, "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._protocol._debug && this._protocol._debug("Received DH GEX Group");
                        I.init(e, 1);
                        let r;
                        let n;
                        if ((r = I.readString()) === undefined || (n = I.readString()) === undefined) {
                            I.clear();
                            return R(this._protocol, "Received malformed KEXDH_GEX_GROUP", "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        I.clear();
                        this.setDHParams(r, n);
                        this.generateKeys();
                        const s = this.getPublicKey();
                        this._protocol._debug && this._protocol._debug("Outbound: Sending KEXDH_GEX_INIT");
                        let o = this._protocol._packetRW.write.allocStartKEX;
                        const a = this._protocol._packetRW.write.alloc(1 + 4 + s.length, true);
                        a[o] = v.KEXDH_GEX_INIT;
                        $(a, s.length, ++o);
                        a.set(s, o += 4);
                        this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(a, true));
                        ++this._step;
                        break;
                    }

                  case 2:
                    if (this._protocol._server) {
                        if (t !== v.KEXDH_GEX_INIT) {
                            return R(this._protocol, `Received packet ${t} instead of ${v.KEXDH_GEX_INIT}`, "handshake", E.KEY_EXCHANGE_FAILED);
                        }
                        this._protocol._debug && this._protocol._debug("Received DH GEX Init");
                        return R(this._protocol, "Group exchange not implemented for server", "handshake", E.KEY_EXCHANGE_FAILED);
                    } else if (t !== v.KEXDH_GEX_REPLY) {
                        return R(this._protocol, `Received packet ${t} instead of ${v.KEXDH_GEX_REPLY}`, "handshake", E.KEY_EXCHANGE_FAILED);
                    }
                    this._protocol._debug && this._protocol._debug("Received DH GEX Reply");
                    this._step = 1;
                    e[0] = v.KEXDH_REPLY;
                    this.parse = KeyExchange.prototype.parse;
                    this.parse(e);
                }
            }
        }
        class DHExchange extends KeyExchange {
            constructor(e, t, ...r) {
                super(...r);
                this.type = "group";
                this.groupName = e;
                this.hashName = t;
            }
            start() {
                if (!this._protocol._server) {
                    this._protocol._debug && this._protocol._debug("Outbound: Sending KEXDH_INIT");
                    const e = this.getPublicKey();
                    let t = this._protocol._packetRW.write.allocStartKEX;
                    const r = this._protocol._packetRW.write.alloc(1 + 4 + e.length, true);
                    r[t] = v.KEXDH_INIT;
                    $(r, e.length, ++t);
                    r.set(e, t += 4);
                    this._protocol._cipher.encrypt(this._protocol._packetRW.write.finalize(r, true));
                }
            }
            generateKeys() {
                if (!this._dh) {
                    this._dh = t(this.groupName);
                    this._public = this._dh.generateKeys();
                }
            }
            getDHParams() {
                if (this._dh) {
                    return {
                        prime: l(this._dh.getPrime()),
                        generator: l(this._dh.getGenerator())
                    };
                }
            }
        }
        return (e, ...t) => {
            if (typeof e !== "object" || e === null) throw new Error("Invalid negotiated argument");
            const r = e.kex;
            if (typeof r === "string") {
                t = [ e, ...t ];
                switch (r) {
                  case "curve25519-sha256":
                  case "curve25519-sha256@libssh.org":
                    if (!d) break;
                    return new Curve25519Exchange("sha256", ...t);

                  case "ecdh-sha2-nistp256":
                    return new ECDHExchange("prime256v1", "sha256", ...t);

                  case "ecdh-sha2-nistp384":
                    return new ECDHExchange("secp384r1", "sha384", ...t);

                  case "ecdh-sha2-nistp521":
                    return new ECDHExchange("secp521r1", "sha512", ...t);

                  case "diffie-hellman-group1-sha1":
                    return new DHExchange("modp2", "sha1", ...t);

                  case "diffie-hellman-group14-sha1":
                    return new DHExchange("modp14", "sha1", ...t);

                  case "diffie-hellman-group14-sha256":
                    return new DHExchange("modp14", "sha256", ...t);

                  case "diffie-hellman-group15-sha512":
                    return new DHExchange("modp15", "sha512", ...t);

                  case "diffie-hellman-group16-sha512":
                    return new DHExchange("modp16", "sha512", ...t);

                  case "diffie-hellman-group17-sha512":
                    return new DHExchange("modp17", "sha512", ...t);

                  case "diffie-hellman-group18-sha512":
                    return new DHExchange("modp18", "sha512", ...t);

                  case "diffie-hellman-group-exchange-sha1":
                    return new DHGroupExchange("sha1", ...t);

                  case "diffie-hellman-group-exchange-sha256":
                    return new DHGroupExchange("sha256", ...t);
                }
                throw new Error(`Unsupported key exchange algorithm: ${r}`);
            }
            throw new Error(`Invalid key exchange type: ${r}`);
        };
    })();
    const j = (() => {
        const e = [ "kex", "serverHostKey", [ "cs", "cipher" ], [ "sc", "cipher" ], [ "cs", "mac" ], [ "sc", "mac" ], [ "cs", "compress" ], [ "sc", "compress" ], [ "cs", "lang" ], [ "sc", "lang" ] ];
        return class KexInit {
            constructor(t) {
                if (typeof t !== "object" || t === null) throw new TypeError("Argument must be an object");
                const r = {
                    kex: undefined,
                    serverHostKey: undefined,
                    cs: {
                        cipher: undefined,
                        mac: undefined,
                        compress: undefined,
                        lang: undefined
                    },
                    sc: {
                        cipher: undefined,
                        mac: undefined,
                        compress: undefined,
                        lang: undefined
                    },
                    all: undefined
                };
                let n = 0;
                for (const s of e) {
                    let e;
                    let o;
                    let a;
                    let l;
                    if (typeof s === "string") {
                        e = r;
                        o = t[s];
                        a = l = s;
                    } else {
                        const n = s[0];
                        e = r[n];
                        l = s[1];
                        o = t[n][l];
                        a = `${n}.${l}`;
                    }
                    const c = {
                        array: undefined,
                        buffer: undefined
                    };
                    if (Buffer.isBuffer(o)) {
                        c.array = ("" + o).split(",");
                        c.buffer = o;
                        n += 4 + o.length;
                    } else {
                        if (typeof o === "string") o = o.split(",");
                        if (Array.isArray(o)) {
                            c.array = o;
                            c.buffer = Buffer.from(o.join(","));
                        } else {
                            throw new TypeError(`Invalid \`${a}\` type: ${typeof o}`);
                        }
                        n += 4 + c.buffer.length;
                    }
                    e[l] = c;
                }
                const s = Buffer.allocUnsafe(n);
                r.all = s;
                let o = 0;
                for (const t of e) {
                    let e;
                    if (typeof t === "string") e = r[t].buffer; else e = r[t[0]][t[1]].buffer;
                    o = $(s, e.length, o);
                    s.set(e, o);
                    o += e.length;
                }
                this.totalSize = n;
                this.lists = r;
            }
            copyAllTo(e, t) {
                const r = this.lists.all;
                if (typeof t !== "number") throw new TypeError(`Invalid offset value: ${typeof t}`);
                if (e.length - t < r.length) throw new Error("Insufficient space to copy list");
                e.set(r, t);
                return r.length;
            }
        };
    })();
    const Q = (() => {
        const e = Buffer.allocUnsafe(4);
        return (t, r) => {
            $(e, r.length, 0);
            t.update(e);
            t.update(r);
        };
    })();
    function G(e, t, r, s, o, a) {
        let l;
        if (e) {
            let c = n(t).update(r).update(s).update(a).update(o).digest();
            while (c.length < e) {
                const e = n(t).update(r).update(s).update(c).digest();
                const o = Buffer.allocUnsafe(c.length + e.length);
                o.set(c, 0);
                o.set(e, c.length);
                c = o;
            }
            if (c.length === e) l = c; else l = new k(c.buffer, c.byteOffset, e);
        } else {
            l = x;
        }
        return l;
    }
    function K(e, t) {
        if (t.length === 0) {
            this._debug && this._debug("Inbound: Skipping empty packet payload");
            return;
        }
        if (this._skipNextInboundPacket) {
            this._skipNextInboundPacket = false;
            return;
        }
        t = this._packetRW.read.read(t);
        const r = t[0];
        if (!this._strictMode) {
            switch (r) {
              case v.IGNORE:
              case v.UNIMPLEMENTED:
              case v.DEBUG:
                if (!L) L = requireHandlers();
                return L[r](this, t);
            }
        }
        switch (r) {
          case v.DISCONNECT:
            if (!L) L = requireHandlers();
            return L[r](this, t);

          case v.KEXINIT:
            if (!e.firstPacket) {
                return R(this, "Received extra KEXINIT during handshake", "handshake", E.KEY_EXCHANGE_FAILED);
            }
            e.firstPacket = false;
            return H(this, t);

          default:
            if (r < 20 || r > 49) {
                return R(this, `Received unexpected packet type ${r}`, "handshake", E.KEY_EXCHANGE_FAILED);
            }
        }
        return this._kex.parse(t);
    }
    function z(e) {
        const t = y[e.cs.cipher];
        const r = y[e.sc.cipher];
        const n = Math.max(0, t.sslName === "des-ede3-cbc" ? 14 : t.keyLen, t.blockLen, t.ivLen, r.sslName === "des-ede3-cbc" ? 14 : r.keyLen, r.blockLen, r.ivLen) * 8;
        if (n <= 112) return 2048;
        if (n <= 128) return 3072;
        if (n <= 192) return 7680;
        return 8192;
    }
    function Y(e) {
        if (!e._sentNEWKEYS) {
            e._protocol._debug && e._protocol._debug("Outbound: Sending NEWKEYS");
            const t = e._protocol._packetRW.write.allocStartKEX;
            const r = e._protocol._packetRW.write.alloc(1, true);
            r[t] = v.NEWKEYS;
            e._protocol._cipher.encrypt(e._protocol._packetRW.write.finalize(r, true));
            e._sentNEWKEYS = true;
            if (e._protocol._strictMode) e._protocol._cipher.outSeqno = 0;
        }
    }
    kex = {
        KexInit: j,
        kexinit: q,
        onKEXPayload: K,
        DEFAULT_KEXINIT_CLIENT: new j({
            kex: h.concat([ "ext-info-c", "kex-strict-c-v00@openssh.com" ]),
            serverHostKey: p,
            cs: {
                cipher: g,
                mac: m,
                compress: _,
                lang: []
            },
            sc: {
                cipher: g,
                mac: m,
                compress: _,
                lang: []
            }
        }),
        DEFAULT_KEXINIT_SERVER: new j({
            kex: h.concat([ "kex-strict-s-v00@openssh.com" ]),
            serverHostKey: p,
            cs: {
                cipher: g,
                mac: m,
                compress: _,
                lang: []
            },
            sc: {
                cipher: g,
                mac: m,
                compress: _,
                lang: []
            }
        }),
        HANDLERS: {
            [v.KEXINIT]: H
        }
    };
    return kex;
}

var version$2 = "1.17.0";

const require$$8 = {
    version: version$2
};

const {inspect: inspect$1} = require$$1__default$1.default;

const {bindingAvailable: bindingAvailable, NullCipher: NullCipher, NullDecipher: NullDecipher} = requireCrypto();

const {COMPAT_CHECKS: COMPAT_CHECKS, DISCONNECT_REASON: DISCONNECT_REASON$2, eddsaSupported: eddsaSupported, MESSAGE: MESSAGE, SIGNALS: SIGNALS, TERMINAL_MODE: TERMINAL_MODE} = requireConstants();

const {DEFAULT_KEXINIT_CLIENT: DEFAULT_KEXINIT_CLIENT, DEFAULT_KEXINIT_SERVER: DEFAULT_KEXINIT_SERVER, KexInit: KexInit$1, kexinit: kexinit, onKEXPayload: onKEXPayload} = requireKex();

const {parseKey: parseKey$3} = keyParser;

const MESSAGE_HANDLERS = requireHandlers();

const {bufferCopy: bufferCopy$2, bufferFill: bufferFill, bufferSlice: bufferSlice$2, convertSignature: convertSignature, sendPacket: sendPacket, writeUInt32BE: writeUInt32BE$3} = requireUtils();

const {PacketReader: PacketReader, PacketWriter: PacketWriter, ZlibPacketReader: ZlibPacketReader, ZlibPacketWriter: ZlibPacketWriter} = zlib$1;

const MODULE_VER = require$$8.version;

const VALID_DISCONNECT_REASONS = new Map(Object.values(DISCONNECT_REASON$2).map(e => [ e, 1 ]));

const IDENT_RAW = Buffer.from(`SSH-2.0-ssh2js${MODULE_VER}`);

const IDENT = Buffer.from(`${IDENT_RAW}\r\n`);

const MAX_LINE_LEN = 8192;

const MAX_LINES = 1024;

const PING_PAYLOAD = Buffer.from([ MESSAGE.GLOBAL_REQUEST, 0, 0, 0, 21, 107, 101, 101, 112, 97, 108, 105, 118, 101, 64, 111, 112, 101, 110, 115, 115, 104, 46, 99, 111, 109, 1 ]);

const NO_TERMINAL_MODES_BUFFER = Buffer.from([ TERMINAL_MODE.TTY_OP_END ]);

function noop$8() {}

let Protocol$2 = class Protocol {
    constructor(e) {
        const t = e.onWrite;
        if (typeof t !== "function") throw new Error("Missing onWrite function");
        this._onWrite = e => {
            t(e);
        };
        const r = e.onError;
        if (typeof r !== "function") throw new Error("Missing onError function");
        this._onError = e => {
            r(e);
        };
        const n = e.debug;
        this._debug = typeof n === "function" ? e => {
            n(e);
        } : undefined;
        const s = e.onHeader;
        this._onHeader = typeof s === "function" ? (...e) => {
            s(...e);
        } : noop$8;
        const o = e.onPacket;
        this._onPacket = typeof o === "function" ? () => {
            o();
        } : noop$8;
        let a = e.onHandshakeComplete;
        if (typeof a !== "function") a = noop$8;
        let l;
        this._onHandshakeComplete = (...e) => {
            this._debug && this._debug("Handshake completed");
            if (l === undefined) l = true; else l = false;
            const t = this._queue;
            if (t) {
                this._queue = undefined;
                this._debug && this._debug(`Draining outbound queue (${t.length}) ...`);
                for (let e = 0; e < t.length; ++e) {
                    const r = t[e];
                    let n = this._packetRW.write.finalize(r);
                    if (n === r) {
                        const e = this._cipher.allocPacket(r.length);
                        e.set(r, 5);
                        n = e;
                    }
                    sendPacket(this, n);
                }
                this._debug && this._debug("... finished draining outbound queue");
            }
            if (l && this._server && this._kex.remoteExtInfoEnabled) sendExtInfo(this);
            a(...e);
        };
        this._queue = undefined;
        const c = e.messageHandlers;
        if (typeof c === "object" && c !== null) this._handlers = c; else this._handlers = {};
        this._onPayload = onPayload.bind(this);
        this._server = !!e.server;
        this._banner = undefined;
        let u;
        if (this._server) {
            if (typeof e.hostKeys !== "object" || e.hostKeys === null) throw new Error("Missing server host key(s)");
            this._hostKeys = e.hostKeys;
            if (typeof e.greeting === "string" && e.greeting.length) {
                u = e.greeting.slice(-2) === "\r\n" ? e.greeting : `${e.greeting}\r\n`;
            }
            if (typeof e.banner === "string" && e.banner.length) {
                this._banner = e.banner.slice(-2) === "\r\n" ? e.banner : `${e.banner}\r\n`;
            }
        } else {
            this._hostKeys = undefined;
        }
        let d = e.offer;
        if (typeof d !== "object" || d === null) {
            d = this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT;
        } else if (d.constructor !== KexInit$1) {
            if (this._server) {
                d.kex = d.kex.concat([ "kex-strict-s-v00@openssh.com" ]);
            } else {
                d.kex = d.kex.concat([ "ext-info-c", "kex-strict-c-v00@openssh.com" ]);
            }
            d = new KexInit$1(d);
        }
        this._kex = undefined;
        this._strictMode = undefined;
        this._kexinit = undefined;
        this._offer = d;
        this._cipher = new NullCipher(0, this._onWrite);
        this._decipher = undefined;
        this._skipNextInboundPacket = false;
        this._packetRW = {
            read: new PacketReader,
            write: new PacketWriter(this)
        };
        this._hostVerifier = !this._server && typeof e.hostVerifier === "function" ? e.hostVerifier : undefined;
        this._parse = parseHeader;
        this._buffer = undefined;
        this._authsQueue = [];
        this._authenticated = false;
        this._remoteIdentRaw = undefined;
        let h;
        if (typeof e.ident === "string") {
            this._identRaw = Buffer.from(`SSH-2.0-${e.ident}`);
            h = Buffer.allocUnsafe(this._identRaw.length + 2);
            h.set(this._identRaw, 0);
            h[h.length - 2] = 13;
            h[h.length - 1] = 10;
        } else if (Buffer.isBuffer(e.ident)) {
            const t = Buffer.allocUnsafe(8 + e.ident.length);
            t.latin1Write("SSH-2.0-", 0, 8);
            t.set(e.ident, 8);
            this._identRaw = t;
            h = Buffer.allocUnsafe(t.length + 2);
            h.set(t, 0);
            h[h.length - 2] = 13;
            h[h.length - 1] = 10;
        } else {
            this._identRaw = IDENT_RAW;
            h = IDENT;
        }
        this._compatFlags = 0;
        if (this._debug) {
            if (bindingAvailable) this._debug("Custom crypto binding available"); else this._debug("Custom crypto binding not available");
        }
        this._debug && this._debug(`Local ident: ${inspect$1(this._identRaw.toString())}`);
        this.start = () => {
            this.start = undefined;
            if (u) this._onWrite(u);
            this._onWrite(h);
        };
    }
    _destruct(e) {
        this._packetRW.read.cleanup();
        this._packetRW.write.cleanup();
        this._cipher && this._cipher.free();
        this._decipher && this._decipher.free();
        if (typeof e !== "string" || e.length === 0) e = "fatal error";
        this.parse = () => {
            throw new Error(`Instance unusable after ${e}`);
        };
        this._onWrite = () => {
            throw new Error(`Instance unusable after ${e}`);
        };
        this._destruct = undefined;
    }
    cleanup() {
        this._destruct && this._destruct();
    }
    parse(e, t, r) {
        while (t < r) t = this._parse(e, t, r);
    }
    disconnect(e) {
        const t = 1 + 4 + 4 + 4;
        let r = this._packetRW.write.allocStartKEX;
        const n = this._packetRW.write.alloc(t, true);
        const s = r + t;
        if (!VALID_DISCONNECT_REASONS.has(e)) e = DISCONNECT_REASON$2.PROTOCOL_ERROR;
        n[r] = MESSAGE.DISCONNECT;
        writeUInt32BE$3(n, e, ++r);
        n.fill(0, r += 4, s);
        this._debug && this._debug(`Outbound: Sending DISCONNECT (${e})`);
        sendPacket(this, this._packetRW.write.finalize(n, true), true);
    }
    ping() {
        const e = this._packetRW.write.allocStart;
        const t = this._packetRW.write.alloc(PING_PAYLOAD.length);
        t.set(PING_PAYLOAD, e);
        this._debug && this._debug("Outbound: Sending ping (GLOBAL_REQUEST: keepalive@openssh.com)");
        sendPacket(this, this._packetRW.write.finalize(t));
    }
    rekey() {
        if (this._kexinit === undefined) {
            this._debug && this._debug("Outbound: Initiated explicit rekey");
            this._queue = [];
            kexinit(this);
        } else {
            this._debug && this._debug("Outbound: Ignoring rekey during handshake");
        }
    }
    requestSuccess(e) {
        let t = this._packetRW.write.allocStart;
        let r;
        if (Buffer.isBuffer(e)) {
            r = this._packetRW.write.alloc(1 + e.length);
            r[t] = MESSAGE.REQUEST_SUCCESS;
            r.set(e, ++t);
        } else {
            r = this._packetRW.write.alloc(1);
            r[t] = MESSAGE.REQUEST_SUCCESS;
        }
        this._debug && this._debug("Outbound: Sending REQUEST_SUCCESS");
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    requestFailure() {
        const e = this._packetRW.write.allocStart;
        const t = this._packetRW.write.alloc(1);
        t[e] = MESSAGE.REQUEST_FAILURE;
        this._debug && this._debug("Outbound: Sending REQUEST_FAILURE");
        sendPacket(this, this._packetRW.write.finalize(t));
    }
    channelSuccess(e) {
        let t = this._packetRW.write.allocStart;
        const r = this._packetRW.write.alloc(1 + 4);
        r[t] = MESSAGE.CHANNEL_SUCCESS;
        writeUInt32BE$3(r, e, ++t);
        this._debug && this._debug(`Outbound: Sending CHANNEL_SUCCESS (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    channelFailure(e) {
        let t = this._packetRW.write.allocStart;
        const r = this._packetRW.write.alloc(1 + 4);
        r[t] = MESSAGE.CHANNEL_FAILURE;
        writeUInt32BE$3(r, e, ++t);
        this._debug && this._debug(`Outbound: Sending CHANNEL_FAILURE (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    channelEOF(e) {
        let t = this._packetRW.write.allocStart;
        const r = this._packetRW.write.alloc(1 + 4);
        r[t] = MESSAGE.CHANNEL_EOF;
        writeUInt32BE$3(r, e, ++t);
        this._debug && this._debug(`Outbound: Sending CHANNEL_EOF (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    channelClose(e) {
        let t = this._packetRW.write.allocStart;
        const r = this._packetRW.write.alloc(1 + 4);
        r[t] = MESSAGE.CHANNEL_CLOSE;
        writeUInt32BE$3(r, e, ++t);
        this._debug && this._debug(`Outbound: Sending CHANNEL_CLOSE (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    channelWindowAdjust(e, t) {
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + 4);
        n[r] = MESSAGE.CHANNEL_WINDOW_ADJUST;
        writeUInt32BE$3(n, e, ++r);
        writeUInt32BE$3(n, t, r += 4);
        this._debug && this._debug(`Outbound: Sending CHANNEL_WINDOW_ADJUST (r:${e}, ${t})`);
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    channelData(e, t) {
        const r = Buffer.isBuffer(t);
        const n = r ? t.length : Buffer.byteLength(t);
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 4 + n);
        o[s] = MESSAGE.CHANNEL_DATA;
        writeUInt32BE$3(o, e, ++s);
        writeUInt32BE$3(o, n, s += 4);
        if (r) o.set(t, s += 4); else o.utf8Write(t, s += 4, n);
        this._debug && this._debug(`Outbound: Sending CHANNEL_DATA (r:${e}, ${n})`);
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    channelExtData(e, t, r) {
        const n = Buffer.isBuffer(t);
        const s = n ? t.length : Buffer.byteLength(t);
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 4 + 4 + s);
        a[o] = MESSAGE.CHANNEL_EXTENDED_DATA;
        writeUInt32BE$3(a, e, ++o);
        writeUInt32BE$3(a, r, o += 4);
        writeUInt32BE$3(a, s, o += 4);
        if (n) a.set(t, o += 4); else a.utf8Write(t, o += 4, s);
        this._debug && this._debug(`Outbound: Sending CHANNEL_EXTENDED_DATA (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    channelOpenConfirm(e, t, r, n) {
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 4);
        o[s] = MESSAGE.CHANNEL_OPEN_CONFIRMATION;
        writeUInt32BE$3(o, e, ++s);
        writeUInt32BE$3(o, t, s += 4);
        writeUInt32BE$3(o, r, s += 4);
        writeUInt32BE$3(o, n, s += 4);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_CONFIRMATION (r:${e}, l:${t})`);
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    channelOpenFail(e, t, r) {
        if (typeof r !== "string") r = "";
        const n = Buffer.byteLength(r);
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 4 + 4 + n + 4);
        o[s] = MESSAGE.CHANNEL_OPEN_FAILURE;
        writeUInt32BE$3(o, e, ++s);
        writeUInt32BE$3(o, t, s += 4);
        writeUInt32BE$3(o, n, s += 4);
        s += 4;
        if (n) {
            o.utf8Write(r, s, n);
            s += n;
        }
        writeUInt32BE$3(o, 0, s);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN_FAILURE (r:${e})`);
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    service(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const t = Buffer.byteLength(e);
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + t);
        n[r] = MESSAGE.SERVICE_REQUEST;
        writeUInt32BE$3(n, t, ++r);
        n.utf8Write(e, r += 4, t);
        this._debug && this._debug(`Outbound: Sending SERVICE_REQUEST (${e})`);
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    authPassword(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(e);
        const s = Buffer.byteLength(t);
        const o = r ? Buffer.byteLength(r) : 0;
        let a = this._packetRW.write.allocStart;
        const l = this._packetRW.write.alloc(1 + 4 + n + 4 + 14 + 4 + 8 + 1 + 4 + s + (r ? 4 + o : 0));
        l[a] = MESSAGE.USERAUTH_REQUEST;
        writeUInt32BE$3(l, n, ++a);
        l.utf8Write(e, a += 4, n);
        writeUInt32BE$3(l, 14, a += n);
        l.utf8Write("ssh-connection", a += 4, 14);
        writeUInt32BE$3(l, 8, a += 14);
        l.utf8Write("password", a += 4, 8);
        l[a += 8] = r ? 1 : 0;
        writeUInt32BE$3(l, s, ++a);
        if (Buffer.isBuffer(t)) bufferCopy$2(t, l, 0, s, a += 4); else l.utf8Write(t, a += 4, s);
        if (r) {
            writeUInt32BE$3(l, o, a += s);
            if (Buffer.isBuffer(r)) bufferCopy$2(r, l, 0, o, a += 4); else l.utf8Write(r, a += 4, o);
            this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (changed password)");
        } else {
            this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (password)");
        }
        this._authsQueue.push("password");
        sendPacket(this, this._packetRW.write.finalize(l));
    }
    authPK(e, t, r, n) {
        if (this._server) throw new Error("Client-only method called in server mode");
        t = parseKey$3(t);
        if (t instanceof Error) throw new Error("Invalid key");
        const s = t.type;
        t = t.getPublicSSH();
        if (typeof r === "function") {
            n = r;
            r = undefined;
        }
        if (!r) r = s;
        const o = Buffer.byteLength(e);
        const a = Buffer.byteLength(r);
        const l = t.length;
        const c = this._kex.sessionID;
        const u = c.length;
        const d = (n ? 4 + u : 0) + 1 + 4 + o + 4 + 14 + 4 + 9 + 1 + 4 + a + 4 + l;
        let h;
        let p;
        if (n) {
            h = Buffer.allocUnsafe(d);
            p = 0;
            writeUInt32BE$3(h, u, p);
            h.set(c, p += 4);
            p += u;
        } else {
            h = this._packetRW.write.alloc(d);
            p = this._packetRW.write.allocStart;
        }
        h[p] = MESSAGE.USERAUTH_REQUEST;
        writeUInt32BE$3(h, o, ++p);
        h.utf8Write(e, p += 4, o);
        writeUInt32BE$3(h, 14, p += o);
        h.utf8Write("ssh-connection", p += 4, 14);
        writeUInt32BE$3(h, 9, p += 14);
        h.utf8Write("publickey", p += 4, 9);
        h[p += 9] = n ? 1 : 0;
        writeUInt32BE$3(h, a, ++p);
        h.utf8Write(r, p += 4, a);
        writeUInt32BE$3(h, l, p += a);
        h.set(t, p += 4);
        if (!n) {
            this._authsQueue.push("publickey");
            this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (publickey -- check)");
            sendPacket(this, this._packetRW.write.finalize(h));
            return;
        }
        n(h, n => {
            n = convertSignature(n, s);
            if (n === false) throw new Error("Error while converting handshake signature");
            const c = n.length;
            p = this._packetRW.write.allocStart;
            h = this._packetRW.write.alloc(1 + 4 + o + 4 + 14 + 4 + 9 + 1 + 4 + a + 4 + l + 4 + 4 + a + 4 + c);
            h[p] = MESSAGE.USERAUTH_REQUEST;
            writeUInt32BE$3(h, o, ++p);
            h.utf8Write(e, p += 4, o);
            writeUInt32BE$3(h, 14, p += o);
            h.utf8Write("ssh-connection", p += 4, 14);
            writeUInt32BE$3(h, 9, p += 14);
            h.utf8Write("publickey", p += 4, 9);
            h[p += 9] = 1;
            writeUInt32BE$3(h, a, ++p);
            h.utf8Write(r, p += 4, a);
            writeUInt32BE$3(h, l, p += a);
            h.set(t, p += 4);
            writeUInt32BE$3(h, 4 + a + 4 + c, p += l);
            writeUInt32BE$3(h, a, p += 4);
            h.utf8Write(r, p += 4, a);
            writeUInt32BE$3(h, c, p += a);
            h.set(n, p += 4);
            this._authsQueue.push("publickey");
            this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (publickey)");
            sendPacket(this, this._packetRW.write.finalize(h));
        });
    }
    authHostbased(e, t, r, n, s, o) {
        if (this._server) throw new Error("Client-only method called in server mode");
        t = parseKey$3(t);
        if (t instanceof Error) throw new Error("Invalid key");
        const a = t.type;
        t = t.getPublicSSH();
        if (typeof s === "function") {
            o = s;
            s = undefined;
        }
        if (!s) s = a;
        const l = Buffer.byteLength(e);
        const c = Buffer.byteLength(s);
        const u = t.length;
        const d = this._kex.sessionID;
        const h = d.length;
        const p = Buffer.byteLength(r);
        const g = Buffer.byteLength(n);
        const m = Buffer.allocUnsafe(4 + h + 1 + 4 + l + 4 + 14 + 4 + 9 + 4 + c + 4 + u + 4 + p + 4 + g);
        let _ = 0;
        writeUInt32BE$3(m, h, _);
        m.set(d, _ += 4);
        m[_ += h] = MESSAGE.USERAUTH_REQUEST;
        writeUInt32BE$3(m, l, ++_);
        m.utf8Write(e, _ += 4, l);
        writeUInt32BE$3(m, 14, _ += l);
        m.utf8Write("ssh-connection", _ += 4, 14);
        writeUInt32BE$3(m, 9, _ += 14);
        m.utf8Write("hostbased", _ += 4, 9);
        writeUInt32BE$3(m, c, _ += 9);
        m.utf8Write(s, _ += 4, c);
        writeUInt32BE$3(m, u, _ += c);
        m.set(t, _ += 4);
        writeUInt32BE$3(m, p, _ += u);
        m.utf8Write(r, _ += 4, p);
        writeUInt32BE$3(m, g, _ += p);
        m.utf8Write(n, _ += 4, g);
        o(m, e => {
            e = convertSignature(e, a);
            if (!e) throw new Error("Error while converting handshake signature");
            const t = e.length;
            const r = m.length - h - 4;
            _ = this._packetRW.write.allocStart;
            const n = this._packetRW.write.alloc(r + 4 + 4 + c + 4 + t);
            bufferCopy$2(m, n, 4 + h, m.length, _);
            writeUInt32BE$3(n, 4 + c + 4 + t, _ += r);
            writeUInt32BE$3(n, c, _ += 4);
            n.utf8Write(s, _ += 4, c);
            writeUInt32BE$3(n, t, _ += c);
            n.set(e, _ += 4);
            this._authsQueue.push("hostbased");
            this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (hostbased)");
            sendPacket(this, this._packetRW.write.finalize(n));
        });
    }
    authKeyboard(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const t = Buffer.byteLength(e);
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + t + 4 + 14 + 4 + 20 + 4 + 4);
        n[r] = MESSAGE.USERAUTH_REQUEST;
        writeUInt32BE$3(n, t, ++r);
        n.utf8Write(e, r += 4, t);
        writeUInt32BE$3(n, 14, r += t);
        n.utf8Write("ssh-connection", r += 4, 14);
        writeUInt32BE$3(n, 20, r += 14);
        n.utf8Write("keyboard-interactive", r += 4, 20);
        writeUInt32BE$3(n, 0, r += 20);
        writeUInt32BE$3(n, 0, r += 4);
        this._authsQueue.push("keyboard-interactive");
        this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (keyboard-interactive)");
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    authNone(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const t = Buffer.byteLength(e);
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + t + 4 + 14 + 4 + 4);
        n[r] = MESSAGE.USERAUTH_REQUEST;
        writeUInt32BE$3(n, t, ++r);
        n.utf8Write(e, r += 4, t);
        writeUInt32BE$3(n, 14, r += t);
        n.utf8Write("ssh-connection", r += 4, 14);
        writeUInt32BE$3(n, 4, r += 14);
        n.utf8Write("none", r += 4, 4);
        this._authsQueue.push("none");
        this._debug && this._debug("Outbound: Sending USERAUTH_REQUEST (none)");
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    authInfoRes(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let t = 0;
        let r;
        if (e) {
            r = new Array(e.length);
            for (let n = 0; n < e.length; ++n) {
                const s = Buffer.byteLength(e[n]);
                r[n] = s;
                t += 4 + s;
            }
        }
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + t);
        s[n] = MESSAGE.USERAUTH_INFO_RESPONSE;
        if (e) {
            writeUInt32BE$3(s, e.length, ++n);
            n += 4;
            for (let t = 0; t < e.length; ++t) {
                const o = r[t];
                writeUInt32BE$3(s, o, n);
                n += 4;
                if (o) {
                    s.utf8Write(e[t], n, o);
                    n += o;
                }
            }
        } else {
            writeUInt32BE$3(s, 0, ++n);
        }
        this._debug && this._debug("Outbound: Sending USERAUTH_INFO_RESPONSE");
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    tcpipForward(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(e);
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 13 + 1 + 4 + n + 4);
        o[s] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(o, 13, ++s);
        o.utf8Write("tcpip-forward", s += 4, 13);
        o[s += 13] = r === undefined || r === true ? 1 : 0;
        writeUInt32BE$3(o, n, ++s);
        o.utf8Write(e, s += 4, n);
        writeUInt32BE$3(o, t, s += n);
        this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (tcpip-forward)");
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    cancelTcpipForward(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(e);
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 20 + 1 + 4 + n + 4);
        o[s] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(o, 20, ++s);
        o.utf8Write("cancel-tcpip-forward", s += 4, 20);
        o[s += 20] = r === undefined || r === true ? 1 : 0;
        writeUInt32BE$3(o, n, ++s);
        o.utf8Write(e, s += 4, n);
        writeUInt32BE$3(o, t, s += n);
        this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (cancel-tcpip-forward)");
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    openssh_streamLocalForward(e, t) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + 31 + 1 + 4 + r);
        s[n] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(s, 31, ++n);
        s.utf8Write("streamlocal-forward@openssh.com", n += 4, 31);
        s[n += 31] = t === undefined || t === true ? 1 : 0;
        writeUInt32BE$3(s, r, ++n);
        s.utf8Write(e, n += 4, r);
        this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (streamlocal-forward@openssh.com)");
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    openssh_cancelStreamLocalForward(e, t) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + 38 + 1 + 4 + r);
        s[n] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(s, 38, ++n);
        s.utf8Write("cancel-streamlocal-forward@openssh.com", n += 4, 38);
        s[n += 38] = t === undefined || t === true ? 1 : 0;
        writeUInt32BE$3(s, r, ++n);
        s.utf8Write(e, n += 4, r);
        if (this._debug) {
            this._debug("Outbound: Sending GLOBAL_REQUEST " + "(cancel-streamlocal-forward@openssh.com)");
        }
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    directTcpip(e, t, r, n) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const s = Buffer.byteLength(n.srcIP);
        const o = Buffer.byteLength(n.dstIP);
        let a = this._packetRW.write.allocStart;
        const l = this._packetRW.write.alloc(1 + 4 + 12 + 4 + 4 + 4 + 4 + s + 4 + 4 + o + 4);
        l[a] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(l, 12, ++a);
        l.utf8Write("direct-tcpip", a += 4, 12);
        writeUInt32BE$3(l, e, a += 12);
        writeUInt32BE$3(l, t, a += 4);
        writeUInt32BE$3(l, r, a += 4);
        writeUInt32BE$3(l, o, a += 4);
        l.utf8Write(n.dstIP, a += 4, o);
        writeUInt32BE$3(l, n.dstPort, a += o);
        writeUInt32BE$3(l, s, a += 4);
        l.utf8Write(n.srcIP, a += 4, s);
        writeUInt32BE$3(l, n.srcPort, a += s);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, direct-tcpip)`);
        sendPacket(this, this._packetRW.write.finalize(l));
    }
    openssh_directStreamLocal(e, t, r, n) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const s = Buffer.byteLength(n.socketPath);
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 30 + 4 + 4 + 4 + 4 + s + 4 + 4);
        a[o] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(a, 30, ++o);
        a.utf8Write("direct-streamlocal@openssh.com", o += 4, 30);
        writeUInt32BE$3(a, e, o += 30);
        writeUInt32BE$3(a, t, o += 4);
        writeUInt32BE$3(a, r, o += 4);
        writeUInt32BE$3(a, s, o += 4);
        a.utf8Write(n.socketPath, o += 4, s);
        bufferFill(a, 0, o += s, o + 8);
        if (this._debug) {
            this._debug("Outbound: Sending CHANNEL_OPEN " + `(r:${e}, direct-streamlocal@openssh.com)`);
        }
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    openssh_noMoreSessions(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let t = this._packetRW.write.allocStart;
        const r = this._packetRW.write.alloc(1 + 4 + 28 + 1);
        r[t] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(r, 28, ++t);
        r.utf8Write("no-more-sessions@openssh.com", t += 4, 28);
        r[t += 28] = e === undefined || e === true ? 1 : 0;
        this._debug && this._debug("Outbound: Sending GLOBAL_REQUEST (no-more-sessions@openssh.com)");
        sendPacket(this, this._packetRW.write.finalize(r));
    }
    session(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + 7 + 4 + 4 + 4);
        s[n] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(s, 7, ++n);
        s.utf8Write("session", n += 4, 7);
        writeUInt32BE$3(s, e, n += 7);
        writeUInt32BE$3(s, t, n += 4);
        writeUInt32BE$3(s, r, n += 4);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, session)`);
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    windowChange(e, t, r, n, s) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 4 + 13 + 1 + 4 + 4 + 4 + 4);
        a[o] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(a, e, ++o);
        writeUInt32BE$3(a, 13, o += 4);
        a.utf8Write("window-change", o += 4, 13);
        a[o += 13] = 0;
        writeUInt32BE$3(a, r, ++o);
        writeUInt32BE$3(a, t, o += 4);
        writeUInt32BE$3(a, s, o += 4);
        writeUInt32BE$3(a, n, o += 4);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, window-change)`);
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    pty(e, t, r, n, s, o, a, l) {
        if (this._server) throw new Error("Client-only method called in server mode");
        if (!o || !o.length) o = "vt100";
        if (a && !Buffer.isBuffer(a) && !Array.isArray(a) && typeof a === "object" && a !== null) {
            a = modesToBytes(a);
        }
        if (!a || !a.length) a = NO_TERMINAL_MODES_BUFFER;
        const c = o.length;
        const u = a.length;
        let d = this._packetRW.write.allocStart;
        const h = this._packetRW.write.alloc(1 + 4 + 4 + 7 + 1 + 4 + c + 4 + 4 + 4 + 4 + 4 + u);
        h[d] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(h, e, ++d);
        writeUInt32BE$3(h, 7, d += 4);
        h.utf8Write("pty-req", d += 4, 7);
        h[d += 7] = l === undefined || l === true ? 1 : 0;
        writeUInt32BE$3(h, c, ++d);
        h.utf8Write(o, d += 4, c);
        writeUInt32BE$3(h, r, d += c);
        writeUInt32BE$3(h, t, d += 4);
        writeUInt32BE$3(h, s, d += 4);
        writeUInt32BE$3(h, n, d += 4);
        writeUInt32BE$3(h, u, d += 4);
        d += 4;
        if (Array.isArray(a)) {
            for (let e = 0; e < u; ++e) h[d++] = a[e];
        } else if (Buffer.isBuffer(a)) {
            h.set(a, d);
        }
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, pty-req)`);
        sendPacket(this, this._packetRW.write.finalize(h));
    }
    shell(e, t) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + 4 + 5 + 1);
        n[r] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(n, e, ++r);
        writeUInt32BE$3(n, 5, r += 4);
        n.utf8Write("shell", r += 4, 5);
        n[r += 5] = t === undefined || t === true ? 1 : 0;
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, shell)`);
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    exec(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = Buffer.isBuffer(t);
        const s = n ? t.length : Buffer.byteLength(t);
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 4 + 4 + 1 + 4 + s);
        a[o] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(a, e, ++o);
        writeUInt32BE$3(a, 4, o += 4);
        a.utf8Write("exec", o += 4, 4);
        a[o += 4] = r === undefined || r === true ? 1 : 0;
        writeUInt32BE$3(a, s, ++o);
        if (n) a.set(t, o += 4); else a.utf8Write(t, o += 4, s);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exec: ${t})`);
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    signal(e, t) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const r = t;
        t = t.toUpperCase();
        if (t.slice(0, 3) === "SIG") t = t.slice(3);
        if (SIGNALS[t] !== 1) throw new Error(`Invalid signal: ${r}`);
        const n = t.length;
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 4 + 6 + 1 + 4 + n);
        o[s] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(o, e, ++s);
        writeUInt32BE$3(o, 6, s += 4);
        o.utf8Write("signal", s += 4, 6);
        o[s += 6] = 0;
        writeUInt32BE$3(o, n, ++s);
        o.utf8Write(t, s += 4, n);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, signal: ${t})`);
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    env(e, t, r, n) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const s = Buffer.byteLength(t);
        const o = Buffer.isBuffer(r);
        const a = o ? r.length : Buffer.byteLength(r);
        let l = this._packetRW.write.allocStart;
        const c = this._packetRW.write.alloc(1 + 4 + 4 + 3 + 1 + 4 + s + 4 + a);
        c[l] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(c, e, ++l);
        writeUInt32BE$3(c, 3, l += 4);
        c.utf8Write("env", l += 4, 3);
        c[l += 3] = n === undefined || n === true ? 1 : 0;
        writeUInt32BE$3(c, s, ++l);
        c.utf8Write(t, l += 4, s);
        writeUInt32BE$3(c, a, l += s);
        if (o) c.set(r, l += 4); else c.utf8Write(r, l += 4, a);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, env: ${t}=${r})`);
        sendPacket(this, this._packetRW.write.finalize(c));
    }
    x11Forward(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = t.protocol;
        const s = t.cookie;
        const o = Buffer.isBuffer(n);
        const a = o ? n.length : Buffer.byteLength(n);
        const l = Buffer.isBuffer(s);
        const c = l ? s.length : Buffer.byteLength(s);
        let u = this._packetRW.write.allocStart;
        const d = this._packetRW.write.alloc(1 + 4 + 4 + 7 + 1 + 1 + 4 + a + 4 + c + 4);
        d[u] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(d, e, ++u);
        writeUInt32BE$3(d, 7, u += 4);
        d.utf8Write("x11-req", u += 4, 7);
        d[u += 7] = r === undefined || r === true ? 1 : 0;
        d[++u] = t.single ? 1 : 0;
        writeUInt32BE$3(d, a, ++u);
        if (o) d.set(n, u += 4); else d.utf8Write(n, u += 4, a);
        writeUInt32BE$3(d, c, u += a);
        if (l) d.set(s, u += 4); else d.latin1Write(s, u += 4, c);
        writeUInt32BE$3(d, t.screen || 0, u += c);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, x11-req)`);
        sendPacket(this, this._packetRW.write.finalize(d));
    }
    subsystem(e, t, r) {
        if (this._server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(t);
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + 4 + 9 + 1 + 4 + n);
        o[s] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(o, e, ++s);
        writeUInt32BE$3(o, 9, s += 4);
        o.utf8Write("subsystem", s += 4, 9);
        o[s += 9] = r === undefined || r === true ? 1 : 0;
        writeUInt32BE$3(o, n, ++s);
        o.utf8Write(t, s += 4, n);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, subsystem: ${t})`);
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    openssh_agentForward(e, t) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + 4 + 26 + 1);
        n[r] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(n, e, ++r);
        writeUInt32BE$3(n, 26, r += 4);
        n.utf8Write("auth-agent-req@openssh.com", r += 4, 26);
        n[r += 26] = t === undefined || t === true ? 1 : 0;
        if (this._debug) {
            this._debug("Outbound: Sending CHANNEL_REQUEST " + `(r:${e}, auth-agent-req@openssh.com)`);
        }
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    openssh_hostKeysProve(e) {
        if (this._server) throw new Error("Client-only method called in server mode");
        let t = 0;
        const r = [];
        for (const n of e) {
            const e = n.getPublicSSH();
            t += 4 + e.length;
            r.push(e);
        }
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + 29 + 1 + t);
        s[n] = MESSAGE.GLOBAL_REQUEST;
        writeUInt32BE$3(s, 29, ++n);
        s.utf8Write("hostkeys-prove-00@openssh.com", n += 4, 29);
        s[n += 29] = 1;
        ++n;
        for (const e of r) {
            writeUInt32BE$3(s, e.length, n);
            bufferCopy$2(e, s, 0, e.length, n += 4);
            n += e.length;
        }
        if (this._debug) {
            this._debug("Outbound: Sending GLOBAL_REQUEST (hostkeys-prove-00@openssh.com)");
        }
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    serviceAccept(e) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const t = Buffer.byteLength(e);
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + t);
        n[r] = MESSAGE.SERVICE_ACCEPT;
        writeUInt32BE$3(n, t, ++r);
        n.utf8Write(e, r += 4, t);
        this._debug && this._debug(`Outbound: Sending SERVICE_ACCEPT (${e})`);
        sendPacket(this, this._packetRW.write.finalize(n));
        if (this._server && this._banner && e === "ssh-userauth") {
            const e = this._banner;
            this._banner = undefined;
            const t = Buffer.byteLength(e);
            r = this._packetRW.write.allocStart;
            const n = this._packetRW.write.alloc(1 + 4 + t + 4);
            n[r] = MESSAGE.USERAUTH_BANNER;
            writeUInt32BE$3(n, t, ++r);
            n.utf8Write(e, r += 4, t);
            writeUInt32BE$3(n, 0, r += t);
            this._debug && this._debug("Outbound: Sending USERAUTH_BANNER");
            sendPacket(this, this._packetRW.write.finalize(n));
        }
    }
    forwardedTcpip(e, t, r, n) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const s = Buffer.byteLength(n.boundAddr);
        const o = Buffer.byteLength(n.remoteAddr);
        let a = this._packetRW.write.allocStart;
        const l = this._packetRW.write.alloc(1 + 4 + 15 + 4 + 4 + 4 + 4 + s + 4 + 4 + o + 4);
        l[a] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(l, 15, ++a);
        l.utf8Write("forwarded-tcpip", a += 4, 15);
        writeUInt32BE$3(l, e, a += 15);
        writeUInt32BE$3(l, t, a += 4);
        writeUInt32BE$3(l, r, a += 4);
        writeUInt32BE$3(l, s, a += 4);
        l.utf8Write(n.boundAddr, a += 4, s);
        writeUInt32BE$3(l, n.boundPort, a += s);
        writeUInt32BE$3(l, o, a += 4);
        l.utf8Write(n.remoteAddr, a += 4, o);
        writeUInt32BE$3(l, n.remotePort, a += o);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, forwarded-tcpip)`);
        sendPacket(this, this._packetRW.write.finalize(l));
    }
    x11(e, t, r, n) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const s = Buffer.byteLength(n.originAddr);
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 3 + 4 + 4 + 4 + 4 + s + 4);
        a[o] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(a, 3, ++o);
        a.utf8Write("x11", o += 4, 3);
        writeUInt32BE$3(a, e, o += 3);
        writeUInt32BE$3(a, t, o += 4);
        writeUInt32BE$3(a, r, o += 4);
        writeUInt32BE$3(a, s, o += 4);
        a.utf8Write(n.originAddr, o += 4, s);
        writeUInt32BE$3(a, n.originPort, o += s);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, x11)`);
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    openssh_authAgent(e, t, r) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        let n = this._packetRW.write.allocStart;
        const s = this._packetRW.write.alloc(1 + 4 + 22 + 4 + 4 + 4);
        s[n] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(s, 22, ++n);
        s.utf8Write("auth-agent@openssh.com", n += 4, 22);
        writeUInt32BE$3(s, e, n += 22);
        writeUInt32BE$3(s, t, n += 4);
        writeUInt32BE$3(s, r, n += 4);
        this._debug && this._debug(`Outbound: Sending CHANNEL_OPEN (r:${e}, auth-agent@openssh.com)`);
        sendPacket(this, this._packetRW.write.finalize(s));
    }
    openssh_forwardedStreamLocal(e, t, r, n) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const s = Buffer.byteLength(n.socketPath);
        let o = this._packetRW.write.allocStart;
        const a = this._packetRW.write.alloc(1 + 4 + 33 + 4 + 4 + 4 + 4 + s + 4);
        a[o] = MESSAGE.CHANNEL_OPEN;
        writeUInt32BE$3(a, 33, ++o);
        a.utf8Write("forwarded-streamlocal@openssh.com", o += 4, 33);
        writeUInt32BE$3(a, e, o += 33);
        writeUInt32BE$3(a, t, o += 4);
        writeUInt32BE$3(a, r, o += 4);
        writeUInt32BE$3(a, s, o += 4);
        a.utf8Write(n.socketPath, o += 4, s);
        writeUInt32BE$3(a, 0, o += s);
        if (this._debug) {
            this._debug("Outbound: Sending CHANNEL_OPEN " + `(r:${e}, forwarded-streamlocal@openssh.com)`);
        }
        sendPacket(this, this._packetRW.write.finalize(a));
    }
    exitStatus(e, t) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4);
        n[r] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(n, e, ++r);
        writeUInt32BE$3(n, 11, r += 4);
        n.utf8Write("exit-status", r += 4, 11);
        n[r += 11] = 0;
        writeUInt32BE$3(n, t, ++r);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exit-status: ${t})`);
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    exitSignal(e, t, r, n) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const s = t;
        if (typeof s !== "string" || !s) throw new Error(`Invalid signal: ${s}`);
        let o = t.toUpperCase();
        if (o.slice(0, 3) === "SIG") o = o.slice(3);
        if (SIGNALS[o] !== 1) throw new Error(`Invalid signal: ${s}`);
        const a = Buffer.byteLength(o);
        const l = n ? Buffer.byteLength(n) : 0;
        let c = this._packetRW.write.allocStart;
        const u = this._packetRW.write.alloc(1 + 4 + 4 + 11 + 1 + 4 + a + 1 + 4 + l + 4);
        u[c] = MESSAGE.CHANNEL_REQUEST;
        writeUInt32BE$3(u, e, ++c);
        writeUInt32BE$3(u, 11, c += 4);
        u.utf8Write("exit-signal", c += 4, 11);
        u[c += 11] = 0;
        writeUInt32BE$3(u, a, ++c);
        u.utf8Write(o, c += 4, a);
        u[c += a] = r ? 1 : 0;
        writeUInt32BE$3(u, l, ++c);
        c += 4;
        if (l) {
            u.utf8Write(n, c, l);
            c += l;
        }
        writeUInt32BE$3(u, 0, c);
        this._debug && this._debug(`Outbound: Sending CHANNEL_REQUEST (r:${e}, exit-signal: ${t})`);
        sendPacket(this, this._packetRW.write.finalize(u));
    }
    authFailure(e, t) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        if (this._authsQueue.length === 0) throw new Error("No auth in progress");
        let r;
        if (typeof e === "boolean") {
            t = e;
            e = undefined;
        }
        if (e) {
            r = [];
            for (let t = 0; t < e.length; ++t) {
                if (e[t].toLowerCase() === "none") continue;
                r.push(e[t]);
            }
            r = r.join(",");
        } else {
            r = "";
        }
        const n = r.length;
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + n + 1);
        o[s] = MESSAGE.USERAUTH_FAILURE;
        writeUInt32BE$3(o, n, ++s);
        o.utf8Write(r, s += 4, n);
        o[s += n] = t === true ? 1 : 0;
        this._authsQueue.shift();
        this._debug && this._debug("Outbound: Sending USERAUTH_FAILURE");
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    authSuccess() {
        if (!this._server) throw new Error("Server-only method called in client mode");
        if (this._authsQueue.length === 0) throw new Error("No auth in progress");
        const e = this._packetRW.write.allocStart;
        const t = this._packetRW.write.alloc(1);
        t[e] = MESSAGE.USERAUTH_SUCCESS;
        this._authsQueue.shift();
        this._authenticated = true;
        this._debug && this._debug("Outbound: Sending USERAUTH_SUCCESS");
        sendPacket(this, this._packetRW.write.finalize(t));
        if (this._kex.negotiated.cs.compress === "zlib@openssh.com") this._packetRW.read = new ZlibPacketReader;
        if (this._kex.negotiated.sc.compress === "zlib@openssh.com") this._packetRW.write = new ZlibPacketWriter(this);
    }
    authPKOK(e, t) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        if (this._authsQueue.length === 0 || this._authsQueue[0] !== "publickey") throw new Error('"publickey" auth not in progress');
        const r = Buffer.byteLength(e);
        const n = t.length;
        let s = this._packetRW.write.allocStart;
        const o = this._packetRW.write.alloc(1 + 4 + r + 4 + n);
        o[s] = MESSAGE.USERAUTH_PK_OK;
        writeUInt32BE$3(o, r, ++s);
        o.utf8Write(e, s += 4, r);
        writeUInt32BE$3(o, n, s += r);
        o.set(t, s += 4);
        this._authsQueue.shift();
        this._debug && this._debug("Outbound: Sending USERAUTH_PK_OK");
        sendPacket(this, this._packetRW.write.finalize(o));
    }
    authPasswdChg(e) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        const t = Buffer.byteLength(e);
        let r = this._packetRW.write.allocStart;
        const n = this._packetRW.write.alloc(1 + 4 + t + 4);
        n[r] = MESSAGE.USERAUTH_PASSWD_CHANGEREQ;
        writeUInt32BE$3(n, t, ++r);
        n.utf8Write(e, r += 4, t);
        writeUInt32BE$3(n, 0, r += t);
        this._debug && this._debug("Outbound: Sending USERAUTH_PASSWD_CHANGEREQ");
        sendPacket(this, this._packetRW.write.finalize(n));
    }
    authInfoReq(e, t, r) {
        if (!this._server) throw new Error("Server-only method called in client mode");
        let n = 0;
        const s = e ? Buffer.byteLength(e) : 0;
        const o = t ? Buffer.byteLength(t) : 0;
        for (let e = 0; e < r.length; ++e) n += 4 + Buffer.byteLength(r[e].prompt) + 1;
        let a = this._packetRW.write.allocStart;
        const l = this._packetRW.write.alloc(1 + 4 + s + 4 + o + 4 + 4 + n);
        l[a] = MESSAGE.USERAUTH_INFO_REQUEST;
        writeUInt32BE$3(l, s, ++a);
        a += 4;
        if (e) {
            l.utf8Write(e, a, s);
            a += s;
        }
        writeUInt32BE$3(l, o, a);
        a += 4;
        if (t) {
            l.utf8Write(t, a, o);
            a += o;
        }
        writeUInt32BE$3(l, 0, a);
        writeUInt32BE$3(l, r.length, a += 4);
        a += 4;
        for (let e = 0; e < r.length; ++e) {
            const t = r[e];
            const n = Buffer.byteLength(t.prompt);
            writeUInt32BE$3(l, n, a);
            a += 4;
            if (n) {
                l.utf8Write(t.prompt, a, n);
                a += n;
            }
            l[a++] = t.echo ? 1 : 0;
        }
        this._debug && this._debug("Outbound: Sending USERAUTH_INFO_REQUEST");
        sendPacket(this, this._packetRW.write.finalize(l));
    }
};

const RE_IDENT = /^SSH-(2\.0|1\.99)-([^ ]+)(?: (.*))?$/;

function parseHeader(e, t, r) {
    let n;
    let s;
    if (this._buffer) {
        n = Buffer.allocUnsafe(this._buffer.length + (r - t));
        n.set(this._buffer, 0);
        if (t === 0) {
            n.set(e, this._buffer.length);
        } else {
            n.set(new Uint8Array(e.buffer, e.byteOffset + t, r - t), this._buffer.length);
        }
        s = this._buffer.length;
        t = 0;
    } else {
        n = e;
        s = 0;
    }
    const o = t;
    let a = t;
    let l = t;
    let c = false;
    let u = 0;
    let d = 0;
    for (;t < n.length; ++t) {
        const e = n[t];
        if (e === 13) {
            c = true;
            continue;
        }
        if (e === 10) {
            if (l > a && l - a > 4 && n[a] === 83 && n[a + 1] === 83 && n[a + 2] === 72 && n[a + 3] === 45) {
                const e = n.latin1Slice(o, l + 1);
                const c = a === o ? e : e.slice(a - o);
                const u = RE_IDENT.exec(c);
                if (!u) throw new Error("Invalid identification string");
                const d = {
                    greeting: a === o ? "" : e.slice(0, a - o),
                    identRaw: c,
                    versions: {
                        protocol: u[1],
                        software: u[2]
                    },
                    comments: u[3]
                };
                this._remoteIdentRaw = Buffer.from(c);
                this._debug && this._debug(`Remote ident: ${inspect$1(c)}`);
                this._compatFlags = getCompatFlags(d);
                this._buffer = undefined;
                this._decipher = new NullDecipher(0, onKEXPayload.bind(this, {
                    firstPacket: true
                }));
                this._parse = parsePacket;
                this._onHeader(d);
                if (!this._destruct) {
                    return r;
                }
                kexinit(this);
                return t + 1 - s;
            }
            if (this._server) throw new Error("Greetings from clients not permitted");
            if (++d > MAX_LINES) throw new Error("Max greeting lines exceeded");
            c = false;
            a = t + 1;
            u = 0;
        } else if (c) {
            throw new Error("Invalid header: expected newline");
        } else if (++u >= MAX_LINE_LEN) {
            throw new Error("Header line too long");
        }
        l = t;
    }
    if (!this._buffer) this._buffer = bufferSlice$2(n, o);
    return t - s;
}

function parsePacket(e, t, r) {
    return this._decipher.decrypt(e, t, r);
}

function onPayload(e) {
    this._onPacket();
    if (e.length === 0) {
        this._debug && this._debug("Inbound: Skipping empty packet payload");
        return;
    }
    e = this._packetRW.read.read(e);
    const t = e[0];
    if (t === MESSAGE.USERAUTH_SUCCESS && !this._server && !this._authenticated) {
        this._authenticated = true;
        if (this._kex.negotiated.cs.compress === "zlib@openssh.com") this._packetRW.write = new ZlibPacketWriter(this);
        if (this._kex.negotiated.sc.compress === "zlib@openssh.com") this._packetRW.read = new ZlibPacketReader;
    }
    const r = MESSAGE_HANDLERS[t];
    if (r === undefined) {
        this._debug && this._debug(`Inbound: Unsupported message type: ${t}`);
        return;
    }
    return r(this, e);
}

function getCompatFlags(e) {
    const t = e.versions.software;
    let r = 0;
    for (const e of COMPAT_CHECKS) {
        if (typeof e[0] === "string") {
            if (t === e[0]) r |= e[1];
        } else if (e[0].test(t)) {
            r |= e[1];
        }
    }
    return r;
}

function modesToBytes(e) {
    const t = Object.keys(e);
    const r = Buffer.allocUnsafe(5 * t.length + 1);
    let n = 0;
    for (let s = 0; s < t.length; ++s) {
        const o = t[s];
        if (o === "TTY_OP_END") continue;
        const a = TERMINAL_MODE[o];
        if (a === undefined) continue;
        const l = e[o];
        if (typeof l === "number" && isFinite(l)) {
            r[n++] = a;
            r[n++] = l >>> 24;
            r[n++] = l >>> 16;
            r[n++] = l >>> 8;
            r[n++] = l;
        }
    }
    r[n++] = TERMINAL_MODE.TTY_OP_END;
    if (n < r.length) return bufferSlice$2(r, 0, n);
    return r;
}

function sendExtInfo(e) {
    let t = "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521" + "rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss";
    if (eddsaSupported) t = `ssh-ed25519,${t}`;
    const r = Buffer.byteLength(t);
    let n = e._packetRW.write.allocStart;
    const s = e._packetRW.write.alloc(1 + 4 + 4 + 15 + 4 + r);
    s[n] = MESSAGE.EXT_INFO;
    writeUInt32BE$3(s, 1, ++n);
    writeUInt32BE$3(s, 15, n += 4);
    s.utf8Write("server-sig-algs", n += 4, 15);
    writeUInt32BE$3(s, r, n += 15);
    s.utf8Write(t, n += 4, r);
    e._debug && e._debug("Outbound: Sending EXT_INFO");
    sendPacket(e, e._packetRW.write.finalize(s));
}

var Protocol_1 = Protocol$2;

var nodeFsCompat = {};

const assert = require$$0__default$2.default;

const {inspect: inspect} = require$$1__default$1.default;

function addNumericalSeparator(e) {
    let t = "";
    let r = e.length;
    const n = e[0] === "-" ? 1 : 0;
    for (;r >= n + 4; r -= 3) t = `_${e.slice(r - 3, r)}${t}`;
    return `${e.slice(0, r)}${t}`;
}

function oneOf(e, t) {
    assert(typeof t === "string", "`thing` has to be of type string");
    if (Array.isArray(e)) {
        const r = e.length;
        assert(r > 0, "At least one expected value needs to be specified");
        e = e.map(e => String(e));
        if (r > 2) {
            return `one of ${t} ${e.slice(0, r - 1).join(", ")}, or ` + e[r - 1];
        } else if (r === 2) {
            return `one of ${t} ${e[0]} or ${e[1]}`;
        }
        return `of ${t} ${e[0]}`;
    }
    return `of ${t} ${String(e)}`;
}

nodeFsCompat.ERR_INTERNAL_ASSERTION = class ERR_INTERNAL_ASSERTION extends Error {
    constructor(e) {
        super();
        Error.captureStackTrace(this, ERR_INTERNAL_ASSERTION);
        const t = "This is caused by either a bug in ssh2 " + "or incorrect usage of ssh2 internals.\n" + "Please open an issue with this stack trace at " + "https://github.com/mscdex/ssh2/issues\n";
        this.message = e === undefined ? t : `${e}\n${t}`;
    }
};

const MAX_32BIT_INT = 2 ** 32;

const MAX_32BIT_BIGINT = (() => {
    try {
        return new Function("return 2n ** 32n")();
    } catch {}
})();

nodeFsCompat.ERR_OUT_OF_RANGE = class ERR_OUT_OF_RANGE extends RangeError {
    constructor(e, t, r, n) {
        super();
        Error.captureStackTrace(this, ERR_OUT_OF_RANGE);
        assert(t, 'Missing "range" argument');
        let s = n ? e : `The value of "${e}" is out of range.`;
        let o;
        if (Number.isInteger(r) && Math.abs(r) > MAX_32BIT_INT) {
            o = addNumericalSeparator(String(r));
        } else if (typeof r === "bigint") {
            o = String(r);
            if (r > MAX_32BIT_BIGINT || r < -MAX_32BIT_BIGINT) o = addNumericalSeparator(o);
            o += "n";
        } else {
            o = inspect(r);
        }
        s += ` It must be ${t}. Received ${o}`;
        this.message = s;
    }
};

let ERR_INVALID_ARG_TYPE$1 = class ERR_INVALID_ARG_TYPE extends TypeError {
    constructor(e, t, r) {
        super();
        Error.captureStackTrace(this, ERR_INVALID_ARG_TYPE);
        assert(typeof e === "string", `'name' must be a string`);
        let n;
        if (typeof t === "string" && t.startsWith("not ")) {
            n = "must not be";
            t = t.replace(/^not /, "");
        } else {
            n = "must be";
        }
        let s;
        if (e.endsWith(" argument")) {
            s = `The ${e} ${n} ${oneOf(t, "type")}`;
        } else {
            const r = e.includes(".") ? "property" : "argument";
            s = `The "${e}" ${r} ${n} ${oneOf(t, "type")}`;
        }
        s += `. Received type ${typeof r}`;
        this.message = s;
    }
};

nodeFsCompat.ERR_INVALID_ARG_TYPE = ERR_INVALID_ARG_TYPE$1;

nodeFsCompat.validateNumber = function e(t, r) {
    if (typeof t !== "number") throw new ERR_INVALID_ARG_TYPE$1(r, "number", t);
};

const EventEmitter$4 = require$$0__default$8.default;

const fs$7 = require$$0__default$5.default;

const {constants: constants$2} = fs$7;

const {Readable: ReadableStream$1, Writable: WritableStream$1} = require$$0__default$7.default;

const {inherits: inherits$2, types: {isDate: isDate}} = require$$1__default$1.default;

const FastBuffer = Buffer[Symbol.species];

const {bufferCopy: bufferCopy$1, bufferSlice: bufferSlice$1, makeBufferParser: makeBufferParser$1, writeUInt32BE: writeUInt32BE$2} = requireUtils();

const ATTR = {
    SIZE: 1,
    UIDGID: 2,
    PERMISSIONS: 4,
    ACMODTIME: 8,
    EXTENDED: 2147483648
};

const ATTRS_BUF = Buffer.alloc(28);

const STATUS_CODE$1 = {
    OK: 0,
    EOF: 1,
    NO_SUCH_FILE: 2,
    PERMISSION_DENIED: 3,
    FAILURE: 4,
    BAD_MESSAGE: 5,
    NO_CONNECTION: 6,
    CONNECTION_LOST: 7,
    OP_UNSUPPORTED: 8
};

const VALID_STATUS_CODES = new Map(Object.values(STATUS_CODE$1).map(e => [ e, 1 ]));

const STATUS_CODE_STR = {
    [STATUS_CODE$1.OK]: "No error",
    [STATUS_CODE$1.EOF]: "End of file",
    [STATUS_CODE$1.NO_SUCH_FILE]: "No such file or directory",
    [STATUS_CODE$1.PERMISSION_DENIED]: "Permission denied",
    [STATUS_CODE$1.FAILURE]: "Failure",
    [STATUS_CODE$1.BAD_MESSAGE]: "Bad message",
    [STATUS_CODE$1.NO_CONNECTION]: "No connection",
    [STATUS_CODE$1.CONNECTION_LOST]: "Connection lost",
    [STATUS_CODE$1.OP_UNSUPPORTED]: "Operation unsupported"
};

const REQUEST = {
    INIT: 1,
    OPEN: 3,
    CLOSE: 4,
    READ: 5,
    WRITE: 6,
    LSTAT: 7,
    FSTAT: 8,
    SETSTAT: 9,
    FSETSTAT: 10,
    OPENDIR: 11,
    READDIR: 12,
    REMOVE: 13,
    MKDIR: 14,
    RMDIR: 15,
    REALPATH: 16,
    STAT: 17,
    RENAME: 18,
    READLINK: 19,
    SYMLINK: 20,
    EXTENDED: 200
};

const RESPONSE = {
    VERSION: 2,
    STATUS: 101,
    HANDLE: 102,
    DATA: 103,
    NAME: 104,
    ATTRS: 105,
    EXTENDED: 201
};

const OPEN_MODE$1 = {
    READ: 1,
    WRITE: 2,
    APPEND: 4,
    CREAT: 8,
    TRUNC: 16,
    EXCL: 32
};

const PKT_RW_OVERHEAD = 2 * 1024;

const MAX_REQID = 2 ** 32 - 1;

const CLIENT_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5, REQUEST.INIT, 0, 0, 0, 3 ]);

const SERVER_VERSION_BUFFER = Buffer.from([ 0, 0, 0, 5, RESPONSE.VERSION, 0, 0, 0, 3 ]);

const RE_OPENSSH$1 = /^SSH-2.0-(?:OpenSSH|dropbear)/;

const OPENSSH_MAX_PKT_LEN = 256 * 1024;

const bufferParser$1 = makeBufferParser$1();

const fakeStderr = {
    readable: false,
    writable: false,
    push: e => {},
    once: () => {},
    on: () => {},
    emit: () => {},
    end: () => {}
};

function noop$7() {}

let SFTP$3 = class SFTP extends EventEmitter$4 {
    constructor(e, t, r) {
        super();
        if (typeof r !== "object" || !r) r = {};
        const n = e._protocol._remoteIdentRaw;
        this.server = !!r.server;
        this._debug = typeof r.debug === "function" ? r.debug : undefined;
        this._isOpenSSH = n && RE_OPENSSH$1.test(n);
        this._version = -1;
        this._extensions = {};
        this._biOpt = r.biOpt;
        this._pktLenBytes = 0;
        this._pktLen = 0;
        this._pktPos = 0;
        this._pktType = 0;
        this._pktData = undefined;
        this._writeReqid = -1;
        this._requests = {};
        this._maxInPktLen = OPENSSH_MAX_PKT_LEN;
        this._maxOutPktLen = 34e3;
        this._maxReadLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD;
        this._maxWriteLen = (this._isOpenSSH ? OPENSSH_MAX_PKT_LEN : 34e3) - PKT_RW_OVERHEAD;
        this.maxOpenHandles = undefined;
        this._client = e;
        this._protocol = e._protocol;
        this._callbacks = [];
        this._hasX11 = false;
        this._exit = {
            code: undefined,
            signal: undefined,
            dump: undefined,
            desc: undefined
        };
        this._waitWindow = false;
        this._chunkcb = undefined;
        this._buffer = [];
        this.type = t.type;
        this.subtype = undefined;
        this.incoming = t.incoming;
        this.outgoing = t.outgoing;
        this.stderr = fakeStderr;
        this.readable = true;
    }
    push(e) {
        if (e === null) {
            cleanupRequests(this);
            if (!this.readable) return;
            this.readable = false;
            this.emit("end");
            return;
        }
        let t = 0;
        while (t < e.length) {
            if (this._pktLenBytes < 4) {
                let r = Math.min(4 - this._pktLenBytes, e.length - t);
                this._pktLenBytes += r;
                while (r--) this._pktLen = (this._pktLen << 8) + e[t++];
                if (this._pktLenBytes < 4) return;
                if (this._pktLen === 0) return doFatalSFTPError(this, "Invalid packet length");
                if (this._pktLen > this._maxInPktLen) {
                    const e = this._maxInPktLen;
                    return doFatalSFTPError(this, `Packet length ${this._pktLen} exceeds max length of ${e}`);
                }
                if (t >= e.length) return;
            }
            if (this._pktPos < this._pktLen) {
                const r = Math.min(this._pktLen - this._pktPos, e.length - t);
                if (t !== 0 || r !== e.length) {
                    if (r === this._pktLen) {
                        this._pkt = new FastBuffer(e.buffer, e.byteOffset + t, r);
                    } else {
                        if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen);
                        this._pkt.set(new Uint8Array(e.buffer, e.byteOffset + t, r), this._pktPos);
                    }
                } else if (r === this._pktLen) {
                    this._pkt = e;
                } else {
                    if (!this._pkt) this._pkt = Buffer.allocUnsafe(this._pktLen);
                    this._pkt.set(e, this._pktPos);
                }
                t += r;
                this._pktPos += r;
                if (this._pktPos < this._pktLen) return;
            }
            const r = this._pkt[0];
            const n = this._pkt;
            this._pktLen = 0;
            this._pktLenBytes = 0;
            this._pkt = undefined;
            this._pktPos = 0;
            const s = this.server ? SERVER_HANDLERS[r] : CLIENT_HANDLERS[r];
            if (!s) return doFatalSFTPError(this, `Unknown packet type ${r}`);
            if (this._version === -1) {
                if (this.server) {
                    if (r !== REQUEST.INIT) return doFatalSFTPError(this, `Expected INIT packet, got ${r}`);
                } else if (r !== RESPONSE.VERSION) {
                    return doFatalSFTPError(this, `Expected VERSION packet, got ${r}`);
                }
            }
            if (s(this, n) === false) return;
        }
    }
    end() {
        this.destroy();
    }
    destroy() {
        if (this.outgoing.state === "open" || this.outgoing.state === "eof") {
            this.outgoing.state = "closing";
            this._protocol.channelClose(this.outgoing.id);
        }
    }
    _init() {
        this._init = noop$7;
        if (!this.server) sendOrBuffer(this, CLIENT_VERSION_BUFFER);
    }
    createReadStream(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        return new ReadStream(this, e, t);
    }
    createWriteStream(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        return new WriteStream(this, e, t);
    }
    open(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (typeof r === "function") {
            n = r;
            r = undefined;
        }
        const s = typeof t === "number" ? t : stringToFlags$1(t);
        if (s === null) throw new Error(`Unknown flags string: ${t}`);
        let o = 0;
        let a = 0;
        if (typeof r === "string" || typeof r === "number") r = {
            mode: r
        };
        if (typeof r === "object" && r !== null) {
            r = attrsToBytes(r);
            o = r.flags;
            a = r.nb;
        }
        const l = Buffer.byteLength(e);
        let c = 9;
        const u = Buffer.allocUnsafe(4 + 1 + 4 + 4 + l + 4 + 4 + a);
        writeUInt32BE$2(u, u.length - 4, 0);
        u[4] = REQUEST.OPEN;
        const d = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(u, d, 5);
        writeUInt32BE$2(u, l, c);
        u.utf8Write(e, c += 4, l);
        writeUInt32BE$2(u, s, c += l);
        writeUInt32BE$2(u, o, c += 4);
        if (a) {
            c += 4;
            if (a === ATTRS_BUF.length) u.set(ATTRS_BUF, c); else bufferCopy$1(ATTRS_BUF, u, 0, a, c);
            c += a;
        }
        this._requests[d] = {
            cb: n
        };
        const h = sendOrBuffer(this, u);
        this._debug && this._debug(`SFTP: Outbound: ${h ? "Buffered" : "Sending"} OPEN`);
    }
    close(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        const r = e.length;
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.CLOSE;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.set(e, n += 4);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} CLOSE`);
    }
    read(e, t, r, n, s, o) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        if (!Buffer.isBuffer(t)) throw new Error("buffer is not a Buffer");
        if (r >= t.length) throw new Error("offset is out of bounds");
        if (r + n > t.length) throw new Error("length extends beyond buffer");
        if (s === null) throw new Error("null position currently unsupported");
        read_(this, e, t, r, n, s, o);
    }
    readData(e, t, r, n, s, o) {
        this.read(e, t, r, n, s, o);
    }
    write(e, t, r, n, s, o) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        if (!Buffer.isBuffer(t)) throw new Error("buffer is not a Buffer");
        if (r > t.length) throw new Error("offset is out of bounds");
        if (r + n > t.length) throw new Error("length extends beyond buffer");
        if (s === null) throw new Error("null position currently unsupported");
        if (!n) {
            o && process.nextTick(o, undefined, 0);
            return;
        }
        const a = this._maxWriteLen;
        const l = Math.max(n - a, 0);
        const c = s;
        if (l) n = a;
        const u = e.length;
        let d = 9;
        const h = Buffer.allocUnsafe(4 + 1 + 4 + 4 + u + 8 + 4 + n);
        writeUInt32BE$2(h, h.length - 4, 0);
        h[4] = REQUEST.WRITE;
        const p = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(h, p, 5);
        writeUInt32BE$2(h, u, d);
        h.set(e, d += 4);
        d += u;
        for (let e = 7; e >= 0; --e) {
            h[d + e] = s & 255;
            s /= 256;
        }
        writeUInt32BE$2(h, n, d += 8);
        bufferCopy$1(t, h, r, r + n, d += 4);
        this._requests[p] = {
            cb: s => {
                if (s) {
                    if (typeof o === "function") o(s);
                } else if (l) {
                    this.write(e, t, r + n, l, c + n, o);
                } else if (typeof o === "function") {
                    o(undefined, r + n);
                }
            }
        };
        const g = sendOrBuffer(this, h);
        if (this._debug) {
            const e = g ? "Sent" : "Buffered";
            this._debug(`SFTP: Outbound: ${e} WRITE (id:${p})`);
        }
    }
    writeData(e, t, r, n, s, o) {
        this.write(e, t, r, n, s, o);
    }
    fastGet(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        fastXfer(this, fs$7, e, t, r, n);
    }
    fastPut(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        fastXfer(fs$7, this, e, t, r, n);
    }
    readFile(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        let n;
        if (typeof r === "function") {
            n = r;
        } else if (typeof t === "function") {
            n = t;
            t = undefined;
        }
        if (typeof t === "string") t = {
            encoding: t,
            flag: "r"
        }; else if (!t) t = {
            encoding: null,
            flag: "r"
        }; else if (typeof t !== "object") throw new TypeError("Bad arguments");
        const s = t.encoding;
        if (s && !Buffer.isEncoding(s)) throw new Error(`Unknown encoding: ${s}`);
        let o;
        let a;
        let l;
        let c = 0;
        let u;
        let d = 0;
        const h = t.flag || "r";
        const p = () => {
            if (o === 0) {
                a = Buffer.allocUnsafe(8192);
                this.read(u, a, 0, 8192, d, g);
            } else {
                this.read(u, a, c, o - c, d, g);
            }
        };
        const g = (e, t) => {
            let r;
            if (e) {
                r = e.code === STATUS_CODE$1.EOF;
                if (!r) {
                    return this.close(u, () => n && n(e));
                }
            } else {
                r = false;
            }
            if (r || o === 0 && t === 0) return m();
            d += t;
            c += t;
            if (o !== 0) {
                if (c === o) m(); else p();
            } else {
                l.push(bufferSlice$1(a, 0, t));
                p();
            }
        };
        g._wantEOFError = true;
        const m = () => {
            this.close(u, e => {
                if (o === 0) {
                    a = Buffer.concat(l, c);
                } else if (c < o) {
                    a = bufferSlice$1(a, 0, c);
                }
                if (s) a = a.toString(s);
                return n && n(e, a);
            });
        };
        this.open(e, h, 438, (t, r) => {
            if (t) return n && n(t);
            u = r;
            const s = (t, r) => {
                if (t) {
                    this.stat(e, (e, r) => {
                        if (e) {
                            return this.close(u, () => {
                                n && n(t);
                            });
                        }
                        s(null, r);
                    });
                    return;
                }
                o = r.size || 0;
                if (o === 0) {
                    l = [];
                    return p();
                }
                a = Buffer.allocUnsafe(o);
                p();
            };
            this.fstat(u, s);
        });
    }
    writeFile(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        let s;
        if (typeof n === "function") {
            s = n;
        } else if (typeof r === "function") {
            s = r;
            r = undefined;
        }
        if (typeof r === "string") r = {
            encoding: r,
            mode: 438,
            flag: "w"
        }; else if (!r) r = {
            encoding: "utf8",
            mode: 438,
            flag: "w"
        }; else if (typeof r !== "object") throw new TypeError("Bad arguments");
        if (r.encoding && !Buffer.isEncoding(r.encoding)) throw new Error(`Unknown encoding: ${r.encoding}`);
        const o = r.flag || "w";
        this.open(e, o, r.mode, (n, a) => {
            if (n) {
                s && s(n);
            } else {
                const n = Buffer.isBuffer(t) ? t : Buffer.from("" + t, r.encoding || "utf8");
                const l = /a/.test(o) ? null : 0;
                if (l === null) {
                    const t = (r, o) => {
                        if (r) {
                            this.stat(e, (e, n) => {
                                if (e) {
                                    return this.close(a, () => {
                                        s && s(r);
                                    });
                                }
                                t(null, n);
                            });
                            return;
                        }
                        writeAll(this, a, n, 0, n.length, o.size, s);
                    };
                    this.fstat(a, t);
                    return;
                }
                writeAll(this, a, n, 0, n.length, l, s);
            }
        });
    }
    appendFile(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        let s;
        if (typeof n === "function") {
            s = n;
        } else if (typeof r === "function") {
            s = r;
            r = undefined;
        }
        if (typeof r === "string") r = {
            encoding: r,
            mode: 438,
            flag: "a"
        }; else if (!r) r = {
            encoding: "utf8",
            mode: 438,
            flag: "a"
        }; else if (typeof r !== "object") throw new TypeError("Bad arguments");
        if (!r.flag) r = Object.assign({
            flag: "a"
        }, r);
        this.writeFile(e, t, r, s);
    }
    exists(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        this.stat(e, e => {
            t && t(e ? false : true);
        });
    }
    unlink(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.REMOVE;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} REMOVE`);
    }
    rename(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(e);
        const s = Buffer.byteLength(t);
        let o = 9;
        const a = Buffer.allocUnsafe(4 + 1 + 4 + 4 + n + 4 + s);
        writeUInt32BE$2(a, a.length - 4, 0);
        a[4] = REQUEST.RENAME;
        const l = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(a, l, 5);
        writeUInt32BE$2(a, n, o);
        a.utf8Write(e, o += 4, n);
        writeUInt32BE$2(a, s, o += n);
        a.utf8Write(t, o += 4, s);
        this._requests[l] = {
            cb: r
        };
        const c = sendOrBuffer(this, a);
        this._debug && this._debug(`SFTP: Outbound: ${c ? "Buffered" : "Sending"} RENAME`);
    }
    mkdir(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        let n = 0;
        let s = 0;
        if (typeof t === "function") {
            r = t;
            t = undefined;
        }
        if (typeof t === "object" && t !== null) {
            t = attrsToBytes(t);
            n = t.flags;
            s = t.nb;
        }
        const o = Buffer.byteLength(e);
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + o + 4 + s);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = REQUEST.MKDIR;
        const c = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(l, c, 5);
        writeUInt32BE$2(l, o, a);
        l.utf8Write(e, a += 4, o);
        writeUInt32BE$2(l, n, a += o);
        if (s) {
            a += 4;
            if (s === ATTRS_BUF.length) l.set(ATTRS_BUF, a); else bufferCopy$1(ATTRS_BUF, l, 0, s, a);
            a += s;
        }
        this._requests[c] = {
            cb: r
        };
        const u = sendOrBuffer(this, l);
        this._debug && this._debug(`SFTP: Outbound: ${u ? "Buffered" : "Sending"} MKDIR`);
    }
    rmdir(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.RMDIR;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} RMDIR`);
    }
    readdir(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (typeof t === "function") {
            r = t;
            t = {};
        }
        if (typeof t !== "object" || t === null) t = {};
        const n = t && t.full ? false : true;
        if (!Buffer.isBuffer(e) && typeof e !== "string") throw new Error("missing directory handle or path");
        if (typeof e === "string") {
            const n = [];
            let s = 0;
            const o = (e, a) => {
                if (e) return r(e);
                this.readdir(a, t, (e, t) => {
                    const l = e && e.code === STATUS_CODE$1.EOF;
                    if (e && !l) return this.close(a, () => r(e));
                    if (l) {
                        return this.close(a, e => {
                            if (e) return r(e);
                            r(undefined, n);
                        });
                    }
                    for (let e = 0; e < t.length; ++e, ++s) n[s] = t[e];
                    o(undefined, a);
                });
            };
            return this.opendir(e, o);
        }
        const s = e.length;
        let o = 9;
        const a = Buffer.allocUnsafe(4 + 1 + 4 + 4 + s);
        writeUInt32BE$2(a, a.length - 4, 0);
        a[4] = REQUEST.READDIR;
        const l = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(a, l, 5);
        writeUInt32BE$2(a, s, o);
        a.set(e, o += 4);
        this._requests[l] = {
            cb: n ? (e, t) => {
                if (typeof r !== "function") return;
                if (e) return r(e);
                for (let e = t.length - 1; e >= 0; --e) {
                    if (t[e].filename === "." || t[e].filename === "..") t.splice(e, 1);
                }
                r(undefined, t);
            } : r
        };
        const c = sendOrBuffer(this, a);
        this._debug && this._debug(`SFTP: Outbound: ${c ? "Buffered" : "Sending"} READDIR`);
    }
    fstat(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        const r = e.length;
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.FSTAT;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.set(e, n += 4);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} FSTAT`);
    }
    stat(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.STAT;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} STAT`);
    }
    lstat(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.LSTAT;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} LSTAT`);
    }
    opendir(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.OPENDIR;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: t
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} OPENDIR`);
    }
    setstat(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        let n = 0;
        let s = 0;
        if (typeof t === "object" && t !== null) {
            t = attrsToBytes(t);
            n = t.flags;
            s = t.nb;
        } else if (typeof t === "function") {
            r = t;
        }
        const o = Buffer.byteLength(e);
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + o + 4 + s);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = REQUEST.SETSTAT;
        const c = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(l, c, 5);
        writeUInt32BE$2(l, o, a);
        l.utf8Write(e, a += 4, o);
        writeUInt32BE$2(l, n, a += o);
        if (s) {
            a += 4;
            if (s === ATTRS_BUF.length) l.set(ATTRS_BUF, a); else bufferCopy$1(ATTRS_BUF, l, 0, s, a);
            a += s;
        }
        this._requests[c] = {
            cb: r
        };
        const u = sendOrBuffer(this, l);
        this._debug && this._debug(`SFTP: Outbound: ${u ? "Buffered" : "Sending"} SETSTAT`);
    }
    fsetstat(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        let n = 0;
        let s = 0;
        if (typeof t === "object" && t !== null) {
            t = attrsToBytes(t);
            n = t.flags;
            s = t.nb;
        } else if (typeof t === "function") {
            r = t;
        }
        const o = e.length;
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + o + 4 + s);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = REQUEST.FSETSTAT;
        const c = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(l, c, 5);
        writeUInt32BE$2(l, o, a);
        l.set(e, a += 4);
        writeUInt32BE$2(l, n, a += o);
        if (s) {
            a += 4;
            if (s === ATTRS_BUF.length) l.set(ATTRS_BUF, a); else bufferCopy$1(ATTRS_BUF, l, 0, s, a);
            a += s;
        }
        this._requests[c] = {
            cb: r
        };
        const u = sendOrBuffer(this, l);
        this._debug && this._debug(`SFTP: Outbound: ${u ? "Buffered" : "Sending"} FSETSTAT`);
    }
    futimes(e, t, r, n) {
        return this.fsetstat(e, {
            atime: toUnixTimestamp(t),
            mtime: toUnixTimestamp(r)
        }, n);
    }
    utimes(e, t, r, n) {
        return this.setstat(e, {
            atime: toUnixTimestamp(t),
            mtime: toUnixTimestamp(r)
        }, n);
    }
    fchown(e, t, r, n) {
        return this.fsetstat(e, {
            uid: t,
            gid: r
        }, n);
    }
    chown(e, t, r, n) {
        return this.setstat(e, {
            uid: t,
            gid: r
        }, n);
    }
    fchmod(e, t, r) {
        return this.fsetstat(e, {
            mode: t
        }, r);
    }
    chmod(e, t, r) {
        return this.setstat(e, {
            mode: t
        }, r);
    }
    readlink(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.READLINK;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: (e, r) => {
                if (typeof t !== "function") return;
                if (e) return t(e);
                if (!r || !r.length) return t(new Error("Response missing link info"));
                t(undefined, r[0].filename);
            }
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} READLINK`);
    }
    symlink(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = Buffer.byteLength(t);
        const s = Buffer.byteLength(e);
        let o = 9;
        const a = Buffer.allocUnsafe(4 + 1 + 4 + 4 + n + 4 + s);
        writeUInt32BE$2(a, a.length - 4, 0);
        a[4] = REQUEST.SYMLINK;
        const l = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(a, l, 5);
        if (this._isOpenSSH) {
            writeUInt32BE$2(a, s, o);
            a.utf8Write(e, o += 4, s);
            writeUInt32BE$2(a, n, o += s);
            a.utf8Write(t, o += 4, n);
        } else {
            writeUInt32BE$2(a, n, o);
            a.utf8Write(t, o += 4, n);
            writeUInt32BE$2(a, s, o += n);
            a.utf8Write(e, o += 4, s);
        }
        this._requests[l] = {
            cb: r
        };
        const c = sendOrBuffer(this, a);
        this._debug && this._debug(`SFTP: Outbound: ${c ? "Buffered" : "Sending"} SYMLINK`);
    }
    realpath(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = Buffer.byteLength(e);
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = REQUEST.REALPATH;
        const o = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(s, o, 5);
        writeUInt32BE$2(s, r, n);
        s.utf8Write(e, n += 4, r);
        this._requests[o] = {
            cb: (e, r) => {
                if (typeof t !== "function") return;
                if (e) return t(e);
                if (!r || !r.length) return t(new Error("Response missing path info"));
                t(undefined, r[0].filename);
            }
        };
        const a = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} REALPATH`);
    }
    ext_openssh_rename(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = this._extensions["posix-rename@openssh.com"];
        if (!n || n !== "1") throw new Error("Server does not support this extended request");
        const s = Buffer.byteLength(e);
        const o = Buffer.byteLength(t);
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 24 + 4 + s + 4 + o);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = REQUEST.EXTENDED;
        const c = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(l, c, 5);
        writeUInt32BE$2(l, 24, a);
        l.utf8Write("posix-rename@openssh.com", a += 4, 24);
        writeUInt32BE$2(l, s, a += 24);
        l.utf8Write(e, a += 4, s);
        writeUInt32BE$2(l, o, a += s);
        l.utf8Write(t, a += 4, o);
        this._requests[c] = {
            cb: r
        };
        const u = sendOrBuffer(this, l);
        if (this._debug) {
            const e = u ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} posix-rename@openssh.com`);
        }
    }
    ext_openssh_statvfs(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = this._extensions["statvfs@openssh.com"];
        if (!r || r !== "2") throw new Error("Server does not support this extended request");
        const n = Buffer.byteLength(e);
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 19 + 4 + n);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = REQUEST.EXTENDED;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, 5);
        writeUInt32BE$2(o, 19, s);
        o.utf8Write("statvfs@openssh.com", s += 4, 19);
        writeUInt32BE$2(o, n, s += 19);
        o.utf8Write(e, s += 4, n);
        this._requests[a] = {
            extended: "statvfs@openssh.com",
            cb: t
        };
        const l = sendOrBuffer(this, o);
        if (this._debug) {
            const e = l ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} statvfs@openssh.com`);
        }
    }
    ext_openssh_fstatvfs(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = this._extensions["fstatvfs@openssh.com"];
        if (!r || r !== "2") throw new Error("Server does not support this extended request");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        const n = e.length;
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + n);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = REQUEST.EXTENDED;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, 5);
        writeUInt32BE$2(o, 20, s);
        o.utf8Write("fstatvfs@openssh.com", s += 4, 20);
        writeUInt32BE$2(o, n, s += 20);
        o.set(e, s += 4);
        this._requests[a] = {
            extended: "fstatvfs@openssh.com",
            cb: t
        };
        const l = sendOrBuffer(this, o);
        if (this._debug) {
            const e = l ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} fstatvfs@openssh.com`);
        }
    }
    ext_openssh_hardlink(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = this._extensions["hardlink@openssh.com"];
        if (n !== "1") throw new Error("Server does not support this extended request");
        const s = Buffer.byteLength(e);
        const o = Buffer.byteLength(t);
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + s + 4 + o);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = REQUEST.EXTENDED;
        const c = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(l, c, 5);
        writeUInt32BE$2(l, 20, a);
        l.utf8Write("hardlink@openssh.com", a += 4, 20);
        writeUInt32BE$2(l, s, a += 20);
        l.utf8Write(e, a += 4, s);
        writeUInt32BE$2(l, o, a += s);
        l.utf8Write(t, a += 4, o);
        this._requests[c] = {
            cb: r
        };
        const u = sendOrBuffer(this, l);
        if (this._debug) {
            const e = u ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} hardlink@openssh.com`);
        }
    }
    ext_openssh_fsync(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = this._extensions["fsync@openssh.com"];
        if (r !== "1") throw new Error("Server does not support this extended request");
        if (!Buffer.isBuffer(e)) throw new Error("handle is not a Buffer");
        const n = e.length;
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 17 + 4 + n);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = REQUEST.EXTENDED;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, 5);
        writeUInt32BE$2(o, 17, s);
        o.utf8Write("fsync@openssh.com", s += 4, 17);
        writeUInt32BE$2(o, n, s += 17);
        o.set(e, s += 4);
        this._requests[a] = {
            cb: t
        };
        const l = sendOrBuffer(this, o);
        this._debug && this._debug(`SFTP: Outbound: ${l ? "Buffered" : "Sending"} fsync@openssh.com`);
    }
    ext_openssh_lsetstat(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = this._extensions["lsetstat@openssh.com"];
        if (n !== "1") throw new Error("Server does not support this extended request");
        let s = 0;
        let o = 0;
        if (typeof t === "object" && t !== null) {
            t = attrsToBytes(t);
            s = t.flags;
            o = t.nb;
        } else if (typeof t === "function") {
            r = t;
        }
        const a = Buffer.byteLength(e);
        let l = 9;
        const c = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 20 + 4 + a + 4 + o);
        writeUInt32BE$2(c, c.length - 4, 0);
        c[4] = REQUEST.EXTENDED;
        const u = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(c, u, 5);
        writeUInt32BE$2(c, 20, l);
        c.utf8Write("lsetstat@openssh.com", l += 4, 20);
        writeUInt32BE$2(c, a, l += 20);
        c.utf8Write(e, l += 4, a);
        writeUInt32BE$2(c, s, l += a);
        if (o) {
            l += 4;
            if (o === ATTRS_BUF.length) c.set(ATTRS_BUF, l); else bufferCopy$1(ATTRS_BUF, c, 0, o, l);
            l += o;
        }
        this._requests[u] = {
            cb: r
        };
        const d = sendOrBuffer(this, c);
        if (this._debug) {
            const e = d ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} lsetstat@openssh.com`);
        }
    }
    ext_openssh_expandPath(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = this._extensions["expand-path@openssh.com"];
        if (r !== "1") throw new Error("Server does not support this extended request");
        const n = Buffer.byteLength(e);
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 23 + 4 + n);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = REQUEST.EXTENDED;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, 5);
        writeUInt32BE$2(o, 23, s);
        o.utf8Write("expand-path@openssh.com", s += 4, 23);
        writeUInt32BE$2(o, n, s += 20);
        o.utf8Write(e, s += 4, n);
        this._requests[a] = {
            cb: (e, r) => {
                if (typeof t !== "function") return;
                if (e) return t(e);
                if (!r || !r.length) return t(new Error("Response missing expanded path"));
                t(undefined, r[0].filename);
            }
        };
        const l = sendOrBuffer(this, o);
        if (this._debug) {
            const e = l ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} expand-path@openssh.com`);
        }
    }
    ext_copy_data(e, t, r, n, s, o) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const a = this._extensions["copy-data"];
        if (a !== "1") throw new Error("Server does not support this extended request");
        if (!Buffer.isBuffer(e)) throw new Error("Source handle is not a Buffer");
        if (!Buffer.isBuffer(n)) throw new Error("Destination handle is not a Buffer");
        let l = 0;
        const c = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 9 + 4 + e.length + 8 + 8 + 4 + n.length + 8);
        writeUInt32BE$2(c, c.length - 4, l);
        l += 4;
        c[l] = REQUEST.EXTENDED;
        ++l;
        const u = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(c, u, l);
        l += 4;
        writeUInt32BE$2(c, 9, l);
        l += 4;
        c.utf8Write("copy-data", l, 9);
        l += 9;
        writeUInt32BE$2(c, e.length, l);
        l += 4;
        c.set(e, l);
        l += e.length;
        for (let e = 7; e >= 0; --e) {
            c[l + e] = t & 255;
            t /= 256;
        }
        l += 8;
        for (let e = 7; e >= 0; --e) {
            c[l + e] = r & 255;
            r /= 256;
        }
        l += 8;
        writeUInt32BE$2(c, n.length, l);
        l += 4;
        c.set(n, l);
        l += n.length;
        for (let e = 7; e >= 0; --e) {
            c[l + e] = s & 255;
            s /= 256;
        }
        this._requests[u] = {
            cb: o
        };
        const d = sendOrBuffer(this, c);
        if (this._debug) {
            const e = d ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} copy-data`);
        }
    }
    ext_home_dir(e, t) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const r = this._extensions["home-directory"];
        if (r !== "1") throw new Error("Server does not support this extended request");
        if (typeof e !== "string") throw new TypeError("username is not a string");
        let n = 0;
        const s = Buffer.byteLength(e);
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 14 + 4 + s);
        writeUInt32BE$2(o, o.length - 4, n);
        n += 4;
        o[n] = REQUEST.EXTENDED;
        ++n;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, n);
        n += 4;
        writeUInt32BE$2(o, 14, n);
        n += 4;
        o.utf8Write("home-directory", n, 14);
        n += 14;
        writeUInt32BE$2(o, s, n);
        n += 4;
        o.utf8Write(e, n, s);
        n += s;
        this._requests[a] = {
            cb: (e, r) => {
                if (typeof t !== "function") return;
                if (e) return t(e);
                if (!r || !r.length) return t(new Error("Response missing home directory"));
                t(undefined, r[0].filename);
            }
        };
        const l = sendOrBuffer(this, o);
        if (this._debug) {
            const e = l ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} home-directory`);
        }
    }
    ext_users_groups(e, t, r) {
        if (this.server) throw new Error("Client-only method called in server mode");
        const n = this._extensions["users-groups-by-id@openssh.com"];
        if (n !== "1") throw new Error("Server does not support this extended request");
        if (!Array.isArray(e)) throw new TypeError("uids is not an array");
        for (const t of e) {
            if (!Number.isInteger(t) || t < 0 || t > 2 ** 32 - 1) throw new Error("uid values must all be 32-bit unsigned integers");
        }
        if (!Array.isArray(t)) throw new TypeError("gids is not an array");
        for (const e of t) {
            if (!Number.isInteger(e) || e < 0 || e > 2 ** 32 - 1) throw new Error("gid values must all be 32-bit unsigned integers");
        }
        let s = 0;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 30 + 4 + 4 * e.length + 4 + 4 * t.length);
        writeUInt32BE$2(o, o.length - 4, s);
        s += 4;
        o[s] = REQUEST.EXTENDED;
        ++s;
        const a = this._writeReqid = this._writeReqid + 1 & MAX_REQID;
        writeUInt32BE$2(o, a, s);
        s += 4;
        writeUInt32BE$2(o, 30, s);
        s += 4;
        o.utf8Write("users-groups-by-id@openssh.com", s, 30);
        s += 30;
        writeUInt32BE$2(o, 4 * e.length, s);
        s += 4;
        for (const t of e) {
            writeUInt32BE$2(o, t, s);
            s += 4;
        }
        writeUInt32BE$2(o, 4 * t.length, s);
        s += 4;
        for (const e of t) {
            writeUInt32BE$2(o, e, s);
            s += 4;
        }
        this._requests[a] = {
            extended: "users-groups-by-id@openssh.com",
            cb: r
        };
        const l = sendOrBuffer(this, o);
        if (this._debug) {
            const e = l ? "Buffered" : "Sending";
            this._debug(`SFTP: Outbound: ${e} users-groups-by-id@openssh.com`);
        }
    }
    handle(e, t) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        if (!Buffer.isBuffer(t)) throw new Error("handle is not a Buffer");
        const r = t.length;
        if (r > 256) throw new Error("handle too large (> 256 bytes)");
        let n = 9;
        const s = Buffer.allocUnsafe(4 + 1 + 4 + 4 + r);
        writeUInt32BE$2(s, s.length - 4, 0);
        s[4] = RESPONSE.HANDLE;
        writeUInt32BE$2(s, e, 5);
        writeUInt32BE$2(s, r, n);
        if (r) s.set(t, n += 4);
        const o = sendOrBuffer(this, s);
        this._debug && this._debug(`SFTP: Outbound: ${o ? "Buffered" : "Sending"} HANDLE`);
    }
    status(e, t, r) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        if (!VALID_STATUS_CODES.has(t)) throw new Error(`Bad status code: ${t}`);
        r || (r = "");
        const n = Buffer.byteLength(r);
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 4 + n + 4);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = RESPONSE.STATUS;
        writeUInt32BE$2(o, e, 5);
        writeUInt32BE$2(o, t, s);
        writeUInt32BE$2(o, n, s += 4);
        s += 4;
        if (n) {
            o.utf8Write(r, s, n);
            s += n;
        }
        writeUInt32BE$2(o, 0, s);
        const a = sendOrBuffer(this, o);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} STATUS`);
    }
    data(e, t, r) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        const n = Buffer.isBuffer(t);
        if (!n && typeof t !== "string") throw new Error("data is not a Buffer or string");
        let s;
        if (!n && !r) {
            r = undefined;
            s = true;
        }
        const o = n ? t.length : Buffer.byteLength(t, r);
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + o);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = RESPONSE.DATA;
        writeUInt32BE$2(l, e, 5);
        writeUInt32BE$2(l, o, a);
        if (o) {
            if (n) l.set(t, a += 4); else if (s) l.utf8Write(t, a += 4, o); else l.write(t, a += 4, o, r);
        }
        const c = sendOrBuffer(this, l);
        this._debug && this._debug(`SFTP: Outbound: ${c ? "Buffered" : "Sending"} DATA`);
    }
    name(e, t) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        if (!Array.isArray(t)) {
            if (typeof t !== "object" || t === null) throw new Error("names is not an object or array");
            t = [ t ];
        }
        const r = t.length;
        let n = 0;
        let s;
        const o = [];
        for (let e = 0; e < r; ++e) {
            const r = t[e];
            const a = !r || !r.filename || typeof r.filename !== "string" ? "" : r.filename;
            n += 4 + Buffer.byteLength(a);
            const l = !r || !r.longname || typeof r.longname !== "string" ? "" : r.longname;
            n += 4 + Buffer.byteLength(l);
            if (typeof r.attrs === "object" && r.attrs !== null) {
                s = attrsToBytes(r.attrs);
                n += 4 + s.nb;
                if (s.nb) {
                    let e;
                    if (s.nb === ATTRS_BUF.length) {
                        e = new Uint8Array(ATTRS_BUF);
                    } else {
                        e = new Uint8Array(s.nb);
                        bufferCopy$1(ATTRS_BUF, e, 0, s.nb, 0);
                    }
                    s.bytes = e;
                }
                o.push(s);
            } else {
                n += 4;
                o.push(null);
            }
        }
        let a = 9;
        const l = Buffer.allocUnsafe(4 + 1 + 4 + 4 + n);
        writeUInt32BE$2(l, l.length - 4, 0);
        l[4] = RESPONSE.NAME;
        writeUInt32BE$2(l, e, 5);
        writeUInt32BE$2(l, r, a);
        a += 4;
        for (let e = 0; e < r; ++e) {
            const r = t[e];
            {
                const e = !r || !r.filename || typeof r.filename !== "string" ? "" : r.filename;
                const t = Buffer.byteLength(e);
                writeUInt32BE$2(l, t, a);
                a += 4;
                if (t) {
                    l.utf8Write(e, a, t);
                    a += t;
                }
            }
            {
                const e = !r || !r.longname || typeof r.longname !== "string" ? "" : r.longname;
                const t = Buffer.byteLength(e);
                writeUInt32BE$2(l, t, a);
                a += 4;
                if (t) {
                    l.utf8Write(e, a, t);
                    a += t;
                }
            }
            const n = o[e];
            if (n) {
                writeUInt32BE$2(l, n.flags, a);
                a += 4;
                if (n.flags && n.bytes) {
                    l.set(n.bytes, a);
                    a += n.nb;
                }
            } else {
                writeUInt32BE$2(l, 0, a);
                a += 4;
            }
        }
        const c = sendOrBuffer(this, l);
        this._debug && this._debug(`SFTP: Outbound: ${c ? "Buffered" : "Sending"} NAME`);
    }
    attrs(e, t) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        if (typeof t !== "object" || t === null) throw new Error("attrs is not an object");
        t = attrsToBytes(t);
        const r = t.flags;
        const n = t.nb;
        let s = 9;
        const o = Buffer.allocUnsafe(4 + 1 + 4 + 4 + n);
        writeUInt32BE$2(o, o.length - 4, 0);
        o[4] = RESPONSE.ATTRS;
        writeUInt32BE$2(o, e, 5);
        writeUInt32BE$2(o, r, s);
        if (n) {
            s += 4;
            if (n === ATTRS_BUF.length) o.set(ATTRS_BUF, s); else bufferCopy$1(ATTRS_BUF, o, 0, n, s);
            s += n;
        }
        const a = sendOrBuffer(this, o);
        this._debug && this._debug(`SFTP: Outbound: ${a ? "Buffered" : "Sending"} ATTRS`);
    }
};

function tryCreateBuffer(e) {
    try {
        return Buffer.allocUnsafe(e);
    } catch (e) {
        return e;
    }
}

function read_(e, t, r, n, s, o, a, l) {
    const c = e._maxReadLen;
    const u = Math.max(s - c, 0);
    if (u) s = c;
    const d = t.length;
    let h = 9;
    let p = o;
    const g = Buffer.allocUnsafe(4 + 1 + 4 + 4 + d + 8 + 4);
    writeUInt32BE$2(g, g.length - 4, 0);
    g[4] = REQUEST.READ;
    const m = e._writeReqid = e._writeReqid + 1 & MAX_REQID;
    writeUInt32BE$2(g, m, 5);
    writeUInt32BE$2(g, d, h);
    g.set(t, h += 4);
    h += d;
    for (let e = 7; e >= 0; --e) {
        g[h + e] = p & 255;
        p /= 256;
    }
    writeUInt32BE$2(g, s, h += 8);
    if (typeof a !== "function") a = noop$7;
    const _ = l || {
        nb: 0,
        position: o,
        off: n,
        origOff: n,
        len: undefined,
        overflow: undefined,
        cb: (n, s, o) => {
            const l = _.len;
            const c = _.overflow;
            if (n) {
                if (a._wantEOFError || n.code !== STATUS_CODE$1.EOF) return a(n);
            } else if (o > l) {
                return a(new Error("Received more data than requested"));
            } else if (o === l && c) {
                _.nb += o;
                _.position += o;
                _.off += o;
                read_(e, t, r, _.off, c, _.position, a, _);
                return;
            }
            o = o || 0;
            if (_.origOff === 0 && r.length === _.nb) s = r; else s = bufferSlice$1(r, _.origOff, _.origOff + _.nb + o);
            a(undefined, _.nb + o, s, _.position);
        },
        buffer: undefined
    };
    _.len = s;
    _.overflow = u;
    _.buffer = bufferSlice$1(r, n, n + s);
    e._requests[m] = _;
    const E = sendOrBuffer(e, g);
    e._debug && e._debug(`SFTP: Outbound: ${E ? "Buffered" : "Sending"} READ`);
}

function fastXfer(e, t, r, n, s, o) {
    let a = 64;
    let l = 32768;
    let c;
    let u;
    let d;
    if (typeof s === "function") {
        o = s;
    } else if (typeof s === "object" && s !== null) {
        if (typeof s.concurrency === "number" && s.concurrency > 0 && !isNaN(s.concurrency)) {
            a = s.concurrency;
        }
        if (typeof s.chunkSize === "number" && s.chunkSize > 0 && !isNaN(s.chunkSize)) {
            l = s.chunkSize;
        }
        if (typeof s.fileSize === "number" && s.fileSize > 0 && !isNaN(s.fileSize)) {
            d = s.fileSize;
        }
        if (typeof s.step === "function") c = s.step;
        if (typeof s.mode === "string" || typeof s.mode === "number") u = modeNum(s.mode);
    }
    let h;
    let p = 0;
    let g = 0;
    let m = false;
    let _;
    let E;
    let v;
    let y = l * a;
    function S(r) {
        if (m) return;
        m = true;
        let n = 0;
        let s;
        if (_ || E) {
            s = () => {
                if (--n === 0) o(r);
            };
            if (_ && (e === fs$7 || e.outgoing.state === "open")) ++n;
            if (E && (t === fs$7 || t.outgoing.state === "open")) ++n;
            if (_ && (e === fs$7 || e.outgoing.state === "open")) e.close(_, s);
            if (E && (t === fs$7 || t.outgoing.state === "open")) t.close(E, s);
        } else {
            o(r);
        }
    }
    e.open(r, "r", (s, m) => {
        if (s) return S(s);
        _ = m;
        if (d === undefined) e.fstat(_, A); else A(null, {
            size: d
        });
        function A(s, d) {
            if (s) {
                if (e !== fs$7) {
                    e.stat(r, (e, t) => {
                        if (e) return S(s);
                        A(null, t);
                    });
                    return;
                }
                return S(s);
            }
            h = d.size;
            t.open(n, "w", (r, s) => {
                if (r) return S(r);
                E = s;
                if (h <= 0) return S();
                while (y > h) {
                    if (a === 1) {
                        y = h;
                        break;
                    }
                    y -= l;
                    --a;
                }
                v = tryCreateBuffer(y);
                if (v instanceof Error) return S(v);
                if (u !== undefined) {
                    t.fchmod(E, u, function e(r) {
                        if (r) {
                            t.chmod(n, u, t => e());
                            return;
                        }
                        b();
                    });
                } else {
                    b();
                }
                function d(r, n, s, a, u, d) {
                    if (r) return S(r);
                    u = u || 0;
                    t.write(E, v, u, n, a, m);
                    function m(r) {
                        if (r) return S(r);
                        g += n;
                        c && c(g, n, h);
                        if (n < d) return A(u, a + n, d - n);
                        if (g === h) {
                            t.close(E, t => {
                                E = undefined;
                                if (t) return S(t);
                                e.close(_, e => {
                                    _ = undefined;
                                    if (e) return S(e);
                                    o();
                                });
                            });
                            return;
                        }
                        if (p >= h) return;
                        const s = p + l > h ? h - p : l;
                        A(u, p, s);
                        p += s;
                    }
                }
                function m(e, t, r) {
                    return (n, s, o) => {
                        d(n, s, o, t, e, r);
                    };
                }
                function A(t, r, n) {
                    e.read(_, v, t, n, r, m(t, r, n));
                }
                function b() {
                    let e = 0;
                    let t = 0;
                    while (p < h && e < a) {
                        const r = p + l > h ? h - p : l;
                        A(t, p, r);
                        t += r;
                        p += r;
                        ++e;
                    }
                }
            });
        }
    });
}

function writeAll(e, t, r, n, s, o, a) {
    const l = typeof a === "function" ? a : undefined;
    e.write(t, r, n, s, o, (a, c) => {
        if (a) {
            return e.close(t, () => {
                l && l(a);
            });
        }
        if (c === s) {
            e.close(t, l);
        } else {
            n += c;
            s -= c;
            o += c;
            writeAll(e, t, r, n, s, o, l);
        }
    });
}

class Stats {
    constructor(e) {
        this.mode = e && e.mode;
        this.uid = e && e.uid;
        this.gid = e && e.gid;
        this.size = e && e.size;
        this.atime = e && e.atime;
        this.mtime = e && e.mtime;
        this.extended = e && e.extended;
    }
    isDirectory() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFDIR;
    }
    isFile() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFREG;
    }
    isBlockDevice() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFBLK;
    }
    isCharacterDevice() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFCHR;
    }
    isSymbolicLink() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFLNK;
    }
    isFIFO() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFIFO;
    }
    isSocket() {
        return (this.mode & constants$2.S_IFMT) === constants$2.S_IFSOCK;
    }
}

function attrsToBytes(e) {
    let t = 0;
    let r = 0;
    if (typeof e === "object" && e !== null) {
        if (typeof e.size === "number") {
            t |= ATTR.SIZE;
            const n = e.size;
            ATTRS_BUF[r++] = n / 72057594037927940;
            ATTRS_BUF[r++] = n / 281474976710656;
            ATTRS_BUF[r++] = n / 1099511627776;
            ATTRS_BUF[r++] = n / 4294967296;
            ATTRS_BUF[r++] = n / 16777216;
            ATTRS_BUF[r++] = n / 65536;
            ATTRS_BUF[r++] = n / 256;
            ATTRS_BUF[r++] = n;
        }
        if (typeof e.uid === "number" && typeof e.gid === "number") {
            t |= ATTR.UIDGID;
            const n = e.uid;
            const s = e.gid;
            ATTRS_BUF[r++] = n >>> 24;
            ATTRS_BUF[r++] = n >>> 16;
            ATTRS_BUF[r++] = n >>> 8;
            ATTRS_BUF[r++] = n;
            ATTRS_BUF[r++] = s >>> 24;
            ATTRS_BUF[r++] = s >>> 16;
            ATTRS_BUF[r++] = s >>> 8;
            ATTRS_BUF[r++] = s;
        }
        if (typeof e.mode === "number" || typeof e.mode === "string") {
            const n = modeNum(e.mode);
            t |= ATTR.PERMISSIONS;
            ATTRS_BUF[r++] = n >>> 24;
            ATTRS_BUF[r++] = n >>> 16;
            ATTRS_BUF[r++] = n >>> 8;
            ATTRS_BUF[r++] = n;
        }
        if ((typeof e.atime === "number" || isDate(e.atime)) && (typeof e.mtime === "number" || isDate(e.mtime))) {
            const n = toUnixTimestamp(e.atime);
            const s = toUnixTimestamp(e.mtime);
            t |= ATTR.ACMODTIME;
            ATTRS_BUF[r++] = n >>> 24;
            ATTRS_BUF[r++] = n >>> 16;
            ATTRS_BUF[r++] = n >>> 8;
            ATTRS_BUF[r++] = n;
            ATTRS_BUF[r++] = s >>> 24;
            ATTRS_BUF[r++] = s >>> 16;
            ATTRS_BUF[r++] = s >>> 8;
            ATTRS_BUF[r++] = s;
        }
    }
    return {
        flags: t,
        nb: r
    };
}

function toUnixTimestamp(e) {
    if (typeof e === "number" && e === e) return e;
    if (isDate(e)) return parseInt(e.getTime() / 1e3, 10);
    throw new Error(`Cannot parse time: ${e}`);
}

function modeNum(e) {
    if (typeof e === "number" && e === e) return e;
    if (typeof e === "string") return modeNum(parseInt(e, 8));
    throw new Error(`Cannot parse mode: ${e}`);
}

const stringFlagMap = {
    r: OPEN_MODE$1.READ,
    "r+": OPEN_MODE$1.READ | OPEN_MODE$1.WRITE,
    w: OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE,
    wx: OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    xw: OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    "w+": OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE,
    "wx+": OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    "xw+": OPEN_MODE$1.TRUNC | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    a: OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE,
    ax: OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    xa: OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    "a+": OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE,
    "ax+": OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL,
    "xa+": OPEN_MODE$1.APPEND | OPEN_MODE$1.CREAT | OPEN_MODE$1.READ | OPEN_MODE$1.WRITE | OPEN_MODE$1.EXCL
};

function stringToFlags$1(e) {
    const t = stringFlagMap[e];
    return t !== undefined ? t : null;
}

const flagsToString$1 = (() => {
    const e = Object.keys(stringFlagMap);
    return t => {
        for (let r = 0; r < e.length; ++r) {
            const n = e[r];
            if (stringFlagMap[n] === t) return n;
        }
        return null;
    };
})();

function readAttrs(e) {
    const t = bufferParser$1.readUInt32BE();
    if (t === undefined) return;
    const r = new Stats;
    if (t & ATTR.SIZE) {
        const t = bufferParser$1.readUInt64BE(e);
        if (t === undefined) return;
        r.size = t;
    }
    if (t & ATTR.UIDGID) {
        const e = bufferParser$1.readUInt32BE();
        const t = bufferParser$1.readUInt32BE();
        if (t === undefined) return;
        r.uid = e;
        r.gid = t;
    }
    if (t & ATTR.PERMISSIONS) {
        const e = bufferParser$1.readUInt32BE();
        if (e === undefined) return;
        r.mode = e;
    }
    if (t & ATTR.ACMODTIME) {
        const e = bufferParser$1.readUInt32BE();
        const t = bufferParser$1.readUInt32BE();
        if (t === undefined) return;
        r.atime = e;
        r.mtime = t;
    }
    if (t & ATTR.EXTENDED) {
        const e = bufferParser$1.readUInt32BE();
        if (e === undefined) return;
        const t = {};
        for (let r = 0; r < e; ++r) {
            const e = bufferParser$1.readString(true);
            const r = bufferParser$1.readString();
            if (r === undefined) return;
            t[e] = r;
        }
        r.extended = t;
    }
    return r;
}

function sendOrBuffer(e, t) {
    const r = tryWritePayload(e, t);
    if (r !== undefined) {
        e._buffer.push(r);
        return false;
    }
    return true;
}

function tryWritePayload(e, t) {
    const r = e.outgoing;
    if (r.state !== "open") return;
    if (r.window === 0) {
        e._waitWindow = true;
        e._chunkcb = drainBuffer;
        return t;
    }
    let n;
    const s = t.length;
    let o = 0;
    while (s - o > 0 && r.window > 0) {
        const n = Math.min(s - o, r.window, r.packetSize);
        r.window -= n;
        if (r.window === 0) {
            e._waitWindow = true;
            e._chunkcb = drainBuffer;
        }
        if (o === 0 && n === s) {
            e._protocol.channelData(e.outgoing.id, t);
        } else {
            e._protocol.channelData(e.outgoing.id, bufferSlice$1(t, o, o + n));
        }
        o += n;
    }
    if (s - o > 0) {
        if (o > 0) n = bufferSlice$1(t, o, s); else n = t;
    }
    return n;
}

function drainBuffer() {
    this._chunkcb = undefined;
    const e = this._buffer;
    let t = 0;
    while (t < e.length) {
        const r = e[t];
        const n = tryWritePayload(this, r);
        if (n !== undefined) {
            if (n !== r) e[t] = n;
            if (t > 0) this._buffer = e.slice(t);
            return;
        }
        ++t;
    }
    if (t > 0) this._buffer = [];
}

function doFatalSFTPError(e, t, r) {
    const n = new Error(t);
    n.level = "sftp-protocol";
    if (e._debug) e._debug(`SFTP: Inbound: ${t}`);
    e.emit("error", n);
    e.destroy();
    cleanupRequests(e);
    return false;
}

function cleanupRequests(e) {
    const t = Object.keys(e._requests);
    if (t.length === 0) return;
    const r = e._requests;
    e._requests = {};
    const n = new Error("No response from server");
    for (let e = 0; e < t.length; ++e) {
        const s = r[t[e]];
        if (typeof s.cb === "function") s.cb(n);
    }
}

function requestLimits(e, t) {
    let r = 9;
    const n = Buffer.allocUnsafe(4 + 1 + 4 + 4 + 18);
    writeUInt32BE$2(n, n.length - 4, 0);
    n[4] = REQUEST.EXTENDED;
    const s = e._writeReqid = e._writeReqid + 1 & MAX_REQID;
    writeUInt32BE$2(n, s, 5);
    writeUInt32BE$2(n, 18, r);
    n.utf8Write("limits@openssh.com", r += 4, 18);
    e._requests[s] = {
        extended: "limits@openssh.com",
        cb: t
    };
    const o = sendOrBuffer(e, n);
    if (e._debug) {
        const t = o ? "Buffered" : "Sending";
        e._debug(`SFTP: Outbound: ${t} limits@openssh.com`);
    }
}

const CLIENT_HANDLERS = {
    [RESPONSE.VERSION]: (e, t) => {
        if (e._version !== -1) return doFatalSFTPError(e, "Duplicate VERSION packet");
        const r = {};
        bufferParser$1.init(t, 1);
        let n = bufferParser$1.readUInt32BE();
        while (bufferParser$1.avail()) {
            const e = bufferParser$1.readString(true);
            const t = bufferParser$1.readString(true);
            if (t === undefined) {
                n = undefined;
                break;
            }
            r[e] = t;
        }
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed VERSION packet");
        if (e._debug) {
            const t = Object.keys(r);
            if (t.length) {
                e._debug(`SFTP: Inbound: Received VERSION (v${n}, exts:${t})`);
            } else {
                e._debug(`SFTP: Inbound: Received VERSION (v${n})`);
            }
        }
        e._version = n;
        e._extensions = r;
        if (r["limits@openssh.com"] === "1") {
            return requestLimits(e, (t, r) => {
                if (!t) {
                    if (r.maxPktLen > 0) e._maxOutPktLen = r.maxPktLen;
                    if (r.maxReadLen > 0) e._maxReadLen = r.maxReadLen;
                    if (r.maxWriteLen > 0) e._maxWriteLen = r.maxWriteLen;
                    e.maxOpenHandles = r.maxOpenHandles > 0 ? r.maxOpenHandles : Infinity;
                }
                e.emit("ready");
            });
        }
        e.emit("ready");
    },
    [RESPONSE.STATUS]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readUInt32BE();
        const s = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (e._debug) {
            const t = JSON.stringify(s);
            e._debug(`SFTP: Inbound: Received STATUS (id:${r}, ${n}, ${t})`);
        }
        const o = e._requests[r];
        delete e._requests[r];
        if (o && typeof o.cb === "function") {
            if (n === STATUS_CODE$1.OK) {
                o.cb();
                return;
            }
            const e = new Error(s || STATUS_CODE_STR[n] || "Unknown status");
            e.code = n;
            o.cb(e);
        }
    },
    [RESPONSE.HANDLE]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        bufferParser$1.clear();
        if (n === undefined) {
            if (r !== undefined) delete e._requests[r];
            return doFatalSFTPError(e, "Malformed HANDLE packet");
        }
        e._debug && e._debug(`SFTP: Inbound: Received HANDLE (id:${r})`);
        const s = e._requests[r];
        delete e._requests[r];
        if (s && typeof s.cb === "function") s.cb(undefined, n);
    },
    [RESPONSE.DATA]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        let n;
        if (r !== undefined) {
            n = e._requests[r];
            delete e._requests[r];
        }
        if (n && typeof n.cb === "function") {
            if (n.buffer) {
                const t = bufferParser$1.readString(n.buffer);
                bufferParser$1.clear();
                if (t !== undefined) {
                    e._debug && e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t})`);
                    n.cb(undefined, n.buffer, t);
                    return;
                }
            } else {
                const t = bufferParser$1.readString();
                bufferParser$1.clear();
                if (t !== undefined) {
                    e._debug && e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t.length})`);
                    n.cb(undefined, t);
                    return;
                }
            }
        } else {
            const t = bufferParser$1.skipString();
            bufferParser$1.clear();
            if (t !== undefined) {
                e._debug && e._debug(`SFTP: Inbound: Received DATA (id:${r}, ${t})`);
                return;
            }
        }
        return doFatalSFTPError(e, "Malformed DATA packet");
    },
    [RESPONSE.NAME]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        let n;
        if (r !== undefined) {
            n = e._requests[r];
            delete e._requests[r];
        }
        const s = bufferParser$1.readUInt32BE();
        if (s !== undefined) {
            let t = [];
            for (let r = 0; r < s; ++r) {
                const r = bufferParser$1.readString(true);
                const n = bufferParser$1.readString(true);
                const s = readAttrs(e._biOpt);
                if (s === undefined) {
                    t = undefined;
                    break;
                }
                t.push({
                    filename: r,
                    longname: n,
                    attrs: s
                });
            }
            if (t !== undefined) {
                e._debug && e._debug(`SFTP: Inbound: Received NAME (id:${r}, ${t.length})`);
                bufferParser$1.clear();
                if (n && typeof n.cb === "function") n.cb(undefined, t);
                return;
            }
        }
        bufferParser$1.clear();
        return doFatalSFTPError(e, "Malformed NAME packet");
    },
    [RESPONSE.ATTRS]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        let n;
        if (r !== undefined) {
            n = e._requests[r];
            delete e._requests[r];
        }
        const s = readAttrs(e._biOpt);
        bufferParser$1.clear();
        if (s !== undefined) {
            e._debug && e._debug(`SFTP: Inbound: Received ATTRS (id:${r})`);
            if (n && typeof n.cb === "function") n.cb(undefined, s);
            return;
        }
        return doFatalSFTPError(e, "Malformed ATTRS packet");
    },
    [RESPONSE.EXTENDED]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        if (r !== undefined) {
            const t = e._requests[r];
            if (t) {
                delete e._requests[r];
                switch (t.extended) {
                  case "statvfs@openssh.com":
                  case "fstatvfs@openssh.com":
                    {
                        const n = e._biOpt;
                        const s = {
                            f_bsize: bufferParser$1.readUInt64BE(n),
                            f_frsize: bufferParser$1.readUInt64BE(n),
                            f_blocks: bufferParser$1.readUInt64BE(n),
                            f_bfree: bufferParser$1.readUInt64BE(n),
                            f_bavail: bufferParser$1.readUInt64BE(n),
                            f_files: bufferParser$1.readUInt64BE(n),
                            f_ffree: bufferParser$1.readUInt64BE(n),
                            f_favail: bufferParser$1.readUInt64BE(n),
                            f_sid: bufferParser$1.readUInt64BE(n),
                            f_flag: bufferParser$1.readUInt64BE(n),
                            f_namemax: bufferParser$1.readUInt64BE(n)
                        };
                        if (s.f_namemax === undefined) break;
                        if (e._debug) {
                            e._debug("SFTP: Inbound: Received EXTENDED_REPLY " + `(id:${r}, ${t.extended})`);
                        }
                        bufferParser$1.clear();
                        if (typeof t.cb === "function") t.cb(undefined, s);
                        return;
                    }

                  case "limits@openssh.com":
                    {
                        const n = {
                            maxPktLen: bufferParser$1.readUInt64BE(),
                            maxReadLen: bufferParser$1.readUInt64BE(),
                            maxWriteLen: bufferParser$1.readUInt64BE(),
                            maxOpenHandles: bufferParser$1.readUInt64BE()
                        };
                        if (n.maxOpenHandles === undefined) break;
                        if (e._debug) {
                            e._debug("SFTP: Inbound: Received EXTENDED_REPLY " + `(id:${r}, ${t.extended})`);
                        }
                        bufferParser$1.clear();
                        if (typeof t.cb === "function") t.cb(undefined, n);
                        return;
                    }

                  case "users-groups-by-id@openssh.com":
                    {
                        const n = bufferParser$1.readUInt32BE();
                        if (n === undefined) break;
                        const s = new Array(n);
                        for (let e = 0; e < s.length; ++e) s[e] = bufferParser$1.readString(true);
                        const o = bufferParser$1.readUInt32BE();
                        if (o === undefined) break;
                        const a = new Array(o);
                        for (let e = 0; e < a.length; ++e) a[e] = bufferParser$1.readString(true);
                        if (a.length > 0 && a[a.length - 1] === undefined) {
                            break;
                        }
                        if (e._debug) {
                            e._debug("SFTP: Inbound: Received EXTENDED_REPLY " + `(id:${r}, ${t.extended})`);
                        }
                        bufferParser$1.clear();
                        if (typeof t.cb === "function") t.cb(undefined, s, a);
                        return;
                    }

                  default:
                    e._debug && e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ???)`);
                    bufferParser$1.clear();
                    if (typeof t.cb === "function") t.cb();
                    return;
                }
            } else {
                e._debug && e._debug(`SFTP: Inbound: Received EXTENDED_REPLY (id:${r}, ???)`);
                bufferParser$1.clear();
                return;
            }
        }
        bufferParser$1.clear();
        return doFatalSFTPError(e, "Malformed EXTENDED_REPLY packet");
    }
};

const SERVER_HANDLERS = {
    [REQUEST.INIT]: (e, t) => {
        if (e._version !== -1) return doFatalSFTPError(e, "Duplicate INIT packet");
        const r = {};
        bufferParser$1.init(t, 1);
        let n = bufferParser$1.readUInt32BE();
        while (bufferParser$1.avail()) {
            const e = bufferParser$1.readString(true);
            const t = bufferParser$1.readString(true);
            if (t === undefined) {
                n = undefined;
                break;
            }
            r[e] = t;
        }
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed INIT packet");
        if (e._debug) {
            const t = Object.keys(r);
            if (t.length) {
                e._debug(`SFTP: Inbound: Received INIT (v${n}, exts:${t})`);
            } else {
                e._debug(`SFTP: Inbound: Received INIT (v${n})`);
            }
        }
        sendOrBuffer(e, SERVER_VERSION_BUFFER);
        e._version = n;
        e._extensions = r;
        e.emit("ready");
    },
    [REQUEST.OPEN]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        const s = bufferParser$1.readUInt32BE();
        const o = readAttrs(e._biOpt);
        bufferParser$1.clear();
        if (o === undefined) return doFatalSFTPError(e, "Malformed OPEN packet");
        e._debug && e._debug(`SFTP: Inbound: Received OPEN (id:${r})`);
        if (!e.emit("OPEN", r, n, s, o)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.CLOSE]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        bufferParser$1.clear();
        if (n === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed CLOSE packet");
        e._debug && e._debug(`SFTP: Inbound: Received CLOSE (id:${r})`);
        if (!e.emit("CLOSE", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.READ]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        const s = bufferParser$1.readUInt64BE(e._biOpt);
        const o = bufferParser$1.readUInt32BE();
        bufferParser$1.clear();
        if (o === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed READ packet");
        e._debug && e._debug(`SFTP: Inbound: Received READ (id:${r})`);
        if (!e.emit("READ", r, n, s, o)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.WRITE]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        const s = bufferParser$1.readUInt64BE(e._biOpt);
        const o = bufferParser$1.readString();
        bufferParser$1.clear();
        if (o === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed WRITE packet");
        e._debug && e._debug(`SFTP: Inbound: Received WRITE (id:${r})`);
        if (!e.emit("WRITE", r, n, s, o)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.LSTAT]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed LSTAT packet");
        e._debug && e._debug(`SFTP: Inbound: Received LSTAT (id:${r})`);
        if (!e.emit("LSTAT", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.FSTAT]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        bufferParser$1.clear();
        if (n === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed FSTAT packet");
        e._debug && e._debug(`SFTP: Inbound: Received FSTAT (id:${r})`);
        if (!e.emit("FSTAT", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.SETSTAT]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        const s = readAttrs(e._biOpt);
        bufferParser$1.clear();
        if (s === undefined) return doFatalSFTPError(e, "Malformed SETSTAT packet");
        e._debug && e._debug(`SFTP: Inbound: Received SETSTAT (id:${r})`);
        if (!e.emit("SETSTAT", r, n, s)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.FSETSTAT]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        const s = readAttrs(e._biOpt);
        bufferParser$1.clear();
        if (s === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed FSETSTAT packet");
        e._debug && e._debug(`SFTP: Inbound: Received FSETSTAT (id:${r})`);
        if (!e.emit("FSETSTAT", r, n, s)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.OPENDIR]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed OPENDIR packet");
        e._debug && e._debug(`SFTP: Inbound: Received OPENDIR (id:${r})`);
        if (!e.emit("OPENDIR", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.READDIR]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString();
        bufferParser$1.clear();
        if (n === undefined || n.length > 256) return doFatalSFTPError(e, "Malformed READDIR packet");
        e._debug && e._debug(`SFTP: Inbound: Received READDIR (id:${r})`);
        if (!e.emit("READDIR", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.REMOVE]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed REMOVE packet");
        e._debug && e._debug(`SFTP: Inbound: Received REMOVE (id:${r})`);
        if (!e.emit("REMOVE", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.MKDIR]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        const s = readAttrs(e._biOpt);
        bufferParser$1.clear();
        if (s === undefined) return doFatalSFTPError(e, "Malformed MKDIR packet");
        e._debug && e._debug(`SFTP: Inbound: Received MKDIR (id:${r})`);
        if (!e.emit("MKDIR", r, n, s)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.RMDIR]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed RMDIR packet");
        e._debug && e._debug(`SFTP: Inbound: Received RMDIR (id:${r})`);
        if (!e.emit("RMDIR", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.REALPATH]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed REALPATH packet");
        e._debug && e._debug(`SFTP: Inbound: Received REALPATH (id:${r})`);
        if (!e.emit("REALPATH", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.STAT]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed STAT packet");
        e._debug && e._debug(`SFTP: Inbound: Received STAT (id:${r})`);
        if (!e.emit("STAT", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.RENAME]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        const s = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (s === undefined) return doFatalSFTPError(e, "Malformed RENAME packet");
        e._debug && e._debug(`SFTP: Inbound: Received RENAME (id:${r})`);
        if (!e.emit("RENAME", r, n, s)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.READLINK]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (n === undefined) return doFatalSFTPError(e, "Malformed READLINK packet");
        e._debug && e._debug(`SFTP: Inbound: Received READLINK (id:${r})`);
        if (!e.emit("READLINK", r, n)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.SYMLINK]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        const s = bufferParser$1.readString(true);
        bufferParser$1.clear();
        if (s === undefined) return doFatalSFTPError(e, "Malformed SYMLINK packet");
        e._debug && e._debug(`SFTP: Inbound: Received SYMLINK (id:${r})`);
        let o;
        if (e._isOpenSSH) {
            o = e.emit("SYMLINK", r, s, n);
        } else {
            o = e.emit("SYMLINK", r, n, s);
        }
        if (!o) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    },
    [REQUEST.EXTENDED]: (e, t) => {
        bufferParser$1.init(t, 1);
        const r = bufferParser$1.readUInt32BE();
        const n = bufferParser$1.readString(true);
        if (n === undefined) {
            bufferParser$1.clear();
            return doFatalSFTPError(e, "Malformed EXTENDED packet");
        }
        let s;
        if (bufferParser$1.avail()) s = bufferParser$1.readRaw();
        bufferParser$1.clear();
        e._debug && e._debug(`SFTP: Inbound: Received EXTENDED (id:${r})`);
        if (!e.emit("EXTENDED", r, n, s)) {
            e.status(r, STATUS_CODE$1.OP_UNSUPPORTED);
        }
    }
};

const {ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE: ERR_OUT_OF_RANGE, validateNumber: validateNumber} = nodeFsCompat;

const kMinPoolSpace = 128;

let pool$1;

const poolFragments = [];

function allocNewPool(e) {
    if (poolFragments.length > 0) pool$1 = poolFragments.pop(); else pool$1 = Buffer.allocUnsafe(e);
    pool$1.used = 0;
}

function checkPosition(e, t) {
    if (!Number.isSafeInteger(e)) {
        validateNumber(e, t);
        if (!Number.isInteger(e)) throw new ERR_OUT_OF_RANGE(t, "an integer", e);
        throw new ERR_OUT_OF_RANGE(t, ">= 0 and <= 2 ** 53 - 1", e);
    }
    if (e < 0) throw new ERR_OUT_OF_RANGE(t, ">= 0 and <= 2 ** 53 - 1", e);
}

function roundUpToMultipleOf8(e) {
    return e + 7 & -8;
}

function ReadStream(e, t, r) {
    if (r === undefined) r = {}; else if (typeof r === "string") r = {
        encoding: r
    }; else if (r === null || typeof r !== "object") throw new TypeError('"options" argument must be a string or an object'); else r = Object.create(r);
    if (r.highWaterMark === undefined) r.highWaterMark = 64 * 1024;
    r.emitClose = false;
    r.autoDestroy = false;
    ReadableStream$1.call(this, r);
    this.path = t;
    this.flags = r.flags === undefined ? "r" : r.flags;
    this.mode = r.mode === undefined ? 438 : r.mode;
    this.start = r.start;
    this.end = r.end;
    this.autoClose = r.autoClose === undefined ? true : r.autoClose;
    this.pos = 0;
    this.bytesRead = 0;
    this.isClosed = false;
    this.handle = r.handle === undefined ? null : r.handle;
    this.sftp = e;
    this._opening = false;
    if (this.start !== undefined) {
        checkPosition(this.start, "start");
        this.pos = this.start;
    }
    if (this.end === undefined) {
        this.end = Infinity;
    } else if (this.end !== Infinity) {
        checkPosition(this.end, "end");
        if (this.start !== undefined && this.start > this.end) {
            throw new ERR_OUT_OF_RANGE("start", `<= "end" (here: ${this.end})`, this.start);
        }
    }
    this.on("end", function() {
        if (this.autoClose) this.destroy();
    });
    if (!Buffer.isBuffer(this.handle)) this.open();
}

inherits$2(ReadStream, ReadableStream$1);

ReadStream.prototype.open = function() {
    if (this._opening) return;
    this._opening = true;
    this.sftp.open(this.path, this.flags, this.mode, (e, t) => {
        this._opening = false;
        if (e) {
            this.emit("error", e);
            if (this.autoClose) this.destroy();
            return;
        }
        this.handle = t;
        this.emit("open", t);
        this.emit("ready");
        this.read();
    });
};

ReadStream.prototype._read = function(e) {
    if (!Buffer.isBuffer(this.handle)) return this.once("open", () => this._read(e));
    if (this.destroyed) return;
    if (!pool$1 || pool$1.length - pool$1.used < kMinPoolSpace) {
        allocNewPool(this.readableHighWaterMark || this._readableState.highWaterMark);
    }
    const t = pool$1;
    let r = Math.min(pool$1.length - pool$1.used, e);
    const n = pool$1.used;
    if (this.end !== undefined) r = Math.min(this.end - this.pos + 1, r);
    if (r <= 0) return this.push(null);
    this.sftp.read(this.handle, pool$1, pool$1.used, r, this.pos, (e, s) => {
        if (e) {
            this.emit("error", e);
            if (this.autoClose) this.destroy();
            return;
        }
        let o = null;
        if (n + r === t.used && t === pool$1) {
            t.used = roundUpToMultipleOf8(t.used + s - r);
        } else {
            const e = n + r & -8;
            const o = roundUpToMultipleOf8(n + s);
            if (e - o >= kMinPoolSpace) poolFragments.push(t.slice(o, e));
        }
        if (s > 0) {
            this.bytesRead += s;
            o = t.slice(n, n + s);
        }
        this.pos += s;
        this.push(o);
    });
    pool$1.used = roundUpToMultipleOf8(pool$1.used + r);
};

ReadStream.prototype._destroy = function(e, t) {
    if (this._opening && !Buffer.isBuffer(this.handle)) {
        this.once("open", closeStream.bind(null, this, t, e));
        return;
    }
    closeStream(this, t, e);
    this.handle = null;
    this._opening = false;
};

function closeStream(e, t, r) {
    if (!e.handle) return n();
    e.sftp.close(e.handle, n);
    function n(n) {
        n = n || r;
        t(n);
        e.isClosed = true;
        if (!n) e.emit("close");
    }
}

ReadStream.prototype.close = function(e) {
    this.destroy(null, e);
};

Object.defineProperty(ReadStream.prototype, "pending", {
    get() {
        return this.handle === null;
    },
    configurable: true
});

function WriteStream(e, t, r) {
    if (r === undefined) r = {}; else if (typeof r === "string") r = {
        encoding: r
    }; else if (r === null || typeof r !== "object") throw new TypeError('"options" argument must be a string or an object'); else r = Object.create(r);
    r.emitClose = false;
    r.autoDestroy = false;
    WritableStream$1.call(this, r);
    this.path = t;
    this.flags = r.flags === undefined ? "w" : r.flags;
    this.mode = r.mode === undefined ? 438 : r.mode;
    this.start = r.start;
    this.autoClose = r.autoClose === undefined ? true : r.autoClose;
    this.pos = 0;
    this.bytesWritten = 0;
    this.isClosed = false;
    this.handle = r.handle === undefined ? null : r.handle;
    this.sftp = e;
    this._opening = false;
    if (this.start !== undefined) {
        checkPosition(this.start, "start");
        this.pos = this.start;
    }
    if (r.encoding) this.setDefaultEncoding(r.encoding);
    this.on("finish", function() {
        if (this._writableState.finalCalled) return;
        if (this.autoClose) this.destroy();
    });
    if (!Buffer.isBuffer(this.handle)) this.open();
}

inherits$2(WriteStream, WritableStream$1);

WriteStream.prototype._final = function(e) {
    if (this.autoClose) this.destroy();
    e();
};

WriteStream.prototype.open = function() {
    if (this._opening) return;
    this._opening = true;
    this.sftp.open(this.path, this.flags, this.mode, (e, t) => {
        this._opening = false;
        if (e) {
            this.emit("error", e);
            if (this.autoClose) this.destroy();
            return;
        }
        this.handle = t;
        const r = e => {
            if (e) {
                this.sftp.chmod(this.path, this.mode, e => r());
                return;
            }
            if (this.flags[0] === "a") {
                const e = (r, n) => {
                    if (r) {
                        this.sftp.stat(this.path, (t, n) => {
                            if (t) {
                                this.destroy();
                                this.emit("error", r);
                                return;
                            }
                            e(null, n);
                        });
                        return;
                    }
                    this.pos = n.size;
                    this.emit("open", t);
                    this.emit("ready");
                };
                this.sftp.fstat(t, e);
                return;
            }
            this.emit("open", t);
            this.emit("ready");
        };
        this.sftp.fchmod(t, this.mode, r);
    });
};

WriteStream.prototype._write = function(e, t, r) {
    if (!Buffer.isBuffer(e)) {
        const t = new ERR_INVALID_ARG_TYPE("data", "Buffer", e);
        return this.emit("error", t);
    }
    if (!Buffer.isBuffer(this.handle)) {
        return this.once("open", function() {
            this._write(e, t, r);
        });
    }
    this.sftp.write(this.handle, e, 0, e.length, this.pos, (e, t) => {
        if (e) {
            if (this.autoClose) this.destroy();
            return r(e);
        }
        this.bytesWritten += t;
        r();
    });
    this.pos += e.length;
};

WriteStream.prototype._writev = function(e, t) {
    if (!Buffer.isBuffer(this.handle)) {
        return this.once("open", function() {
            this._writev(e, t);
        });
    }
    const r = this.sftp;
    const n = this.handle;
    let s = e.length;
    const o = (e, r) => {
        if (e) {
            this.destroy();
            return t(e);
        }
        this.bytesWritten += r;
        if (--s === 0) t();
    };
    for (let t = 0; t < e.length; ++t) {
        const s = e[t].chunk;
        r.write(n, s, 0, s.length, this.pos, o);
        this.pos += s.length;
    }
};

if (typeof WritableStream$1.prototype.destroy !== "function") WriteStream.prototype.destroy = ReadStream.prototype.destroy;

WriteStream.prototype._destroy = ReadStream.prototype._destroy;

WriteStream.prototype.close = function(e) {
    if (e) {
        if (this.isClosed) {
            process.nextTick(e);
            return;
        }
        this.on("close", e);
    }
    if (!this.autoClose) this.on("finish", this.destroy.bind(this));
    this.end();
};

WriteStream.prototype.destroySoon = WriteStream.prototype.end;

Object.defineProperty(WriteStream.prototype, "pending", {
    get() {
        return this.handle === null;
    },
    configurable: true
});

var SFTP_1 = {
    flagsToString: flagsToString$1,
    OPEN_MODE: OPEN_MODE$1,
    SFTP: SFTP$3,
    Stats: Stats,
    STATUS_CODE: STATUS_CODE$1,
    stringToFlags: stringToFlags$1
};

const {Duplex: DuplexStream$1, Readable: ReadableStream, Writable: WritableStream} = require$$0__default$7.default;

const {CHANNEL_EXTENDED_DATATYPE: {STDERR: STDERR$1}} = requireConstants();

const {bufferSlice: bufferSlice} = requireUtils();

const PACKET_SIZE$2 = 32 * 1024;

const MAX_WINDOW$2 = 2 * 1024 * 1024;

const WINDOW_THRESHOLD$2 = MAX_WINDOW$2 / 2;

class ClientStderr extends ReadableStream {
    constructor(e, t) {
        super(t);
        this._channel = e;
    }
    _read(e) {
        if (this._channel._waitChanDrain) {
            this._channel._waitChanDrain = false;
            if (this._channel.incoming.window <= WINDOW_THRESHOLD$2) windowAdjust$2(this._channel);
        }
    }
}

class ServerStderr extends WritableStream {
    constructor(e) {
        super({
            highWaterMark: MAX_WINDOW$2
        });
        this._channel = e;
    }
    _write(e, t, r) {
        const n = this._channel;
        const s = n._client._protocol;
        const o = n.outgoing;
        const a = o.packetSize;
        const l = o.id;
        let c = o.window;
        const u = e.length;
        let d = 0;
        if (o.state !== "open") return;
        while (u - d > 0 && c > 0) {
            let t = u - d;
            if (t > c) t = c;
            if (t > a) t = a;
            if (d === 0 && t === u) s.channelExtData(l, e, STDERR$1); else s.channelExtData(l, bufferSlice(e, d, d + t), STDERR$1);
            d += t;
            c -= t;
        }
        o.window = c;
        if (u - d > 0) {
            if (c === 0) n._waitWindow = true;
            if (d > 0) n._chunkErr = bufferSlice(e, d, u); else n._chunkErr = e;
            n._chunkcbErr = r;
            return;
        }
        r();
    }
}

let Channel$2 = class Channel extends DuplexStream$1 {
    constructor(e, t, r) {
        const n = {
            highWaterMark: MAX_WINDOW$2,
            allowHalfOpen: !r || r && r.allowHalfOpen !== false,
            emitClose: false
        };
        super(n);
        this.allowHalfOpen = n.allowHalfOpen;
        const s = !!(r && r.server);
        this.server = s;
        this.type = t.type;
        this.subtype = undefined;
        this.incoming = t.incoming;
        this.outgoing = t.outgoing;
        this._callbacks = [];
        this._client = e;
        this._hasX11 = false;
        this._exit = {
            code: undefined,
            signal: undefined,
            dump: undefined,
            desc: undefined
        };
        this.stdin = this.stdout = this;
        if (s) this.stderr = new ServerStderr(this); else this.stderr = new ClientStderr(this, n);
        this._waitWindow = false;
        this._waitChanDrain = false;
        this._chunk = undefined;
        this._chunkcb = undefined;
        this._chunkErr = undefined;
        this._chunkcbErr = undefined;
        this.on("finish", onFinish).on("prefinish", onFinish);
        this.on("end", onEnd).on("close", onEnd);
    }
    _read(e) {
        if (this._waitChanDrain) {
            this._waitChanDrain = false;
            if (this.incoming.window <= WINDOW_THRESHOLD$2) windowAdjust$2(this);
        }
    }
    _write(e, t, r) {
        const n = this._client._protocol;
        const s = this.outgoing;
        const o = s.packetSize;
        const a = s.id;
        let l = s.window;
        const c = e.length;
        let u = 0;
        if (s.state !== "open") return;
        while (c - u > 0 && l > 0) {
            let t = c - u;
            if (t > l) t = l;
            if (t > o) t = o;
            if (u === 0 && t === c) n.channelData(a, e); else n.channelData(a, bufferSlice(e, u, u + t));
            u += t;
            l -= t;
        }
        s.window = l;
        if (c - u > 0) {
            if (l === 0) this._waitWindow = true;
            if (u > 0) this._chunk = bufferSlice(e, u, c); else this._chunk = e;
            this._chunkcb = r;
            return;
        }
        r();
    }
    eof() {
        if (this.outgoing.state === "open") {
            this.outgoing.state = "eof";
            this._client._protocol.channelEOF(this.outgoing.id);
        }
    }
    close() {
        if (this.outgoing.state === "open" || this.outgoing.state === "eof") {
            this.outgoing.state = "closing";
            this._client._protocol.channelClose(this.outgoing.id);
        }
    }
    destroy() {
        this.end();
        this.close();
        return this;
    }
    setWindow(e, t, r, n) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (this.type === "session" && (this.subtype === "shell" || this.subtype === "exec") && this.writable && this.outgoing.state === "open") {
            this._client._protocol.windowChange(this.outgoing.id, e, t, r, n);
        }
    }
    signal(e) {
        if (this.server) throw new Error("Client-only method called in server mode");
        if (this.type === "session" && this.writable && this.outgoing.state === "open") {
            this._client._protocol.signal(this.outgoing.id, e);
        }
    }
    exit(e, t, r) {
        if (!this.server) throw new Error("Server-only method called in client mode");
        if (this.type === "session" && this.writable && this.outgoing.state === "open") {
            if (typeof e === "number") {
                this._client._protocol.exitStatus(this.outgoing.id, e);
            } else {
                this._client._protocol.exitSignal(this.outgoing.id, e, t, r);
            }
        }
    }
};

function onFinish() {
    this.eof();
    if (this.server || !this.allowHalfOpen) this.close();
    this.writable = false;
}

function onEnd() {
    this.readable = false;
}

function windowAdjust$2(e) {
    if (e.outgoing.state === "closed") return;
    const t = MAX_WINDOW$2 - e.incoming.window;
    if (t <= 0) return;
    e.incoming.window += t;
    e._client._protocol.channelWindowAdjust(e.outgoing.id, t);
}

var Channel_1 = {
    Channel: Channel$2,
    MAX_WINDOW: MAX_WINDOW$2,
    PACKET_SIZE: PACKET_SIZE$2,
    windowAdjust: windowAdjust$2,
    WINDOW_THRESHOLD: WINDOW_THRESHOLD$2
};

const {SFTP: SFTP$2} = SFTP_1;

const MAX_CHANNEL = 2 ** 32 - 1;

function onChannelOpenFailure$2(e, t, r, n) {
    e._chanMgr.remove(t);
    if (typeof n !== "function") return;
    let s;
    if (r instanceof Error) {
        s = r;
    } else if (typeof r === "object" && r !== null) {
        s = new Error(`(SSH) Channel open failure: ${r.description}`);
        s.reason = r.reason;
    } else {
        s = new Error("(SSH) Channel open failure: server closed channel unexpectedly");
        s.reason = "";
    }
    n(s);
}

function onCHANNEL_CLOSE$2(e, t, r, n, s) {
    if (typeof r === "function") {
        onChannelOpenFailure$2(e, t, n, r);
        return;
    }
    if (typeof r !== "object" || r === null) return;
    if (r.incoming && r.incoming.state === "closed") return;
    e._chanMgr.remove(t);
    if (r.server && r.constructor.name === "Session") return;
    r.incoming.state = "closed";
    if (r.readable) r.push(null);
    if (r.server) {
        if (r.stderr.writable) r.stderr.end();
    } else if (r.stderr.readable) {
        r.stderr.push(null);
    }
    if (r.constructor !== SFTP$2 && (r.outgoing.state === "open" || r.outgoing.state === "eof") && !s) {
        r.close();
    }
    if (r.outgoing.state === "closing") r.outgoing.state = "closed";
    const o = r._readableState;
    const a = r._writableState;
    if (a && !a.ending && !a.finished && !s) r.end();
    const l = r._callbacks;
    r._callbacks = [];
    for (let e = 0; e < l.length; ++e) l[e](true);
    if (r.server) {
        if (!r.readable || r.destroyed || o && o.endEmitted) {
            r.emit("close");
        } else {
            r.once("end", () => r.emit("close"));
        }
    } else {
        let e;
        switch (r.type) {
          case "direct-streamlocal@openssh.com":
          case "direct-tcpip":
            e = () => r.emit("close");
            break;

          default:
            {
                const t = r._exit;
                e = () => {
                    if (t.code === null) r.emit("close", t.code, t.signal, t.dump, t.desc); else r.emit("close", t.code);
                };
            }
        }
        if (!r.readable || r.destroyed || o && o.endEmitted) {
            e();
        } else {
            r.once("end", e);
        }
        const t = r.stderr._readableState;
        if (!r.stderr.readable || r.stderr.destroyed || t && t.endEmitted) {
            r.stderr.emit("close");
        } else {
            r.stderr.once("end", () => r.stderr.emit("close"));
        }
    }
}

let ChannelManager$2 = class ChannelManager {
    constructor(e) {
        this._client = e;
        this._channels = {};
        this._cur = -1;
        this._count = 0;
    }
    add(e) {
        let t;
        if (this._cur < MAX_CHANNEL) {
            t = ++this._cur;
        } else if (this._count === 0) {
            this._cur = 0;
            t = 0;
        } else {
            const e = this._channels;
            for (let r = 0; r < MAX_CHANNEL; ++r) {
                if (e[r] === undefined) {
                    t = r;
                    break;
                }
            }
        }
        if (t === undefined) return -1;
        this._channels[t] = e || true;
        ++this._count;
        return t;
    }
    update(e, t) {
        if (typeof e !== "number" || e < 0 || e >= MAX_CHANNEL || !isFinite(e)) throw new Error(`Invalid channel id: ${e}`);
        if (t && this._channels[e]) this._channels[e] = t;
    }
    get(e) {
        if (typeof e !== "number" || e < 0 || e >= MAX_CHANNEL || !isFinite(e)) throw new Error(`Invalid channel id: ${e}`);
        return this._channels[e];
    }
    remove(e) {
        if (typeof e !== "number" || e < 0 || e >= MAX_CHANNEL || !isFinite(e)) throw new Error(`Invalid channel id: ${e}`);
        if (this._channels[e]) {
            delete this._channels[e];
            if (this._count) --this._count;
        }
    }
    cleanup(e) {
        const t = this._channels;
        this._channels = {};
        this._cur = -1;
        this._count = 0;
        const r = Object.keys(t);
        const n = this._client;
        for (let s = 0; s < r.length; ++s) {
            const o = +r[s];
            const a = t[o];
            onCHANNEL_CLOSE$2(n, o, a._channel || a, e, true);
        }
    }
};

const isRegExp = (() => {
    const e = Object.prototype.toString;
    return t => e.call(t) === "[object RegExp]";
})();

function generateAlgorithmList$2(e, t, r) {
    if (Array.isArray(e) && e.length > 0) {
        for (let t = 0; t < e.length; ++t) {
            if (r.indexOf(e[t]) === -1) throw new Error(`Unsupported algorithm: ${e[t]}`);
        }
        return e;
    }
    if (typeof e === "object" && e !== null) {
        const n = Object.keys(e);
        let s = t;
        for (let o = 0; o < n.length; ++o) {
            const a = n[o];
            let l = e[a];
            switch (a) {
              case "append":
                if (!Array.isArray(l)) l = [ l ];
                if (Array.isArray(l)) {
                    for (let e = 0; e < l.length; ++e) {
                        const n = l[e];
                        if (typeof n === "string") {
                            if (!n || s.indexOf(n) !== -1) continue;
                            if (r.indexOf(n) === -1) throw new Error(`Unsupported algorithm: ${n}`);
                            if (s === t) s = s.slice();
                            s.push(n);
                        } else if (isRegExp(n)) {
                            for (let e = 0; e < r.length; ++e) {
                                const o = r[e];
                                if (n.test(o)) {
                                    if (s.indexOf(o) !== -1) continue;
                                    if (s === t) s = s.slice();
                                    s.push(o);
                                }
                            }
                        }
                    }
                }
                break;

              case "prepend":
                if (!Array.isArray(l)) l = [ l ];
                if (Array.isArray(l)) {
                    for (let e = l.length; e >= 0; --e) {
                        const n = l[e];
                        if (typeof n === "string") {
                            if (!n || s.indexOf(n) !== -1) continue;
                            if (r.indexOf(n) === -1) throw new Error(`Unsupported algorithm: ${n}`);
                            if (s === t) s = s.slice();
                            s.unshift(n);
                        } else if (isRegExp(n)) {
                            for (let e = r.length; e >= 0; --e) {
                                const o = r[e];
                                if (n.test(o)) {
                                    if (s.indexOf(o) !== -1) continue;
                                    if (s === t) s = s.slice();
                                    s.unshift(o);
                                }
                            }
                        }
                    }
                }
                break;

              case "remove":
                if (!Array.isArray(l)) l = [ l ];
                if (Array.isArray(l)) {
                    for (let e = 0; e < l.length; ++e) {
                        const r = l[e];
                        if (typeof r === "string") {
                            if (!r) continue;
                            const e = s.indexOf(r);
                            if (e === -1) continue;
                            if (s === t) s = s.slice();
                            s.splice(e, 1);
                        } else if (isRegExp(r)) {
                            for (let e = 0; e < s.length; ++e) {
                                if (r.test(s[e])) {
                                    if (s === t) s = s.slice();
                                    s.splice(e, 1);
                                    --e;
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
        return s;
    }
    return t;
}

var utils$1 = {
    ChannelManager: ChannelManager$2,
    generateAlgorithmList: generateAlgorithmList$2,
    onChannelOpenFailure: onChannelOpenFailure$2,
    onCHANNEL_CLOSE: onCHANNEL_CLOSE$2,
    isWritable: e => e && e.writable && e._readableState && e._readableState.ended === false
};

const {createHash: createHash, getHashes: getHashes, randomFillSync: randomFillSync} = require$$0__default$3.default;

const {Socket: Socket} = require$$0__default$6.default;

const {lookup: dnsLookup} = require$$2__default.default;

const EventEmitter$3 = require$$0__default$8.default;

const HASHES = getHashes();

const {COMPAT: COMPAT, CHANNEL_EXTENDED_DATATYPE: {STDERR: STDERR}, CHANNEL_OPEN_FAILURE: CHANNEL_OPEN_FAILURE$1, DEFAULT_CIPHER: DEFAULT_CIPHER$1, DEFAULT_COMPRESSION: DEFAULT_COMPRESSION$1, DEFAULT_KEX: DEFAULT_KEX$1, DEFAULT_MAC: DEFAULT_MAC$1, DEFAULT_SERVER_HOST_KEY: DEFAULT_SERVER_HOST_KEY$1, DISCONNECT_REASON: DISCONNECT_REASON$1, DISCONNECT_REASON_BY_VALUE: DISCONNECT_REASON_BY_VALUE$1, SUPPORTED_CIPHER: SUPPORTED_CIPHER$1, SUPPORTED_COMPRESSION: SUPPORTED_COMPRESSION$1, SUPPORTED_KEX: SUPPORTED_KEX$1, SUPPORTED_MAC: SUPPORTED_MAC$1, SUPPORTED_SERVER_HOST_KEY: SUPPORTED_SERVER_HOST_KEY$1} = requireConstants();

const {init: cryptoInit$1} = requireCrypto();

const Protocol$1 = Protocol_1;

const {parseKey: parseKey$2} = keyParser;

const {SFTP: SFTP$1} = SFTP_1;

const {bufferCopy: bufferCopy, makeBufferParser: makeBufferParser, makeError: makeError, readUInt32BE: readUInt32BE, sigSSHToASN1: sigSSHToASN1, writeUInt32BE: writeUInt32BE$1} = requireUtils();

const {AgentContext: AgentContext, createAgent: createAgent$1, isAgent: isAgent} = agent;

const {Channel: Channel$1, MAX_WINDOW: MAX_WINDOW$1, PACKET_SIZE: PACKET_SIZE$1, windowAdjust: windowAdjust$1, WINDOW_THRESHOLD: WINDOW_THRESHOLD$1} = Channel_1;

const {ChannelManager: ChannelManager$1, generateAlgorithmList: generateAlgorithmList$1, isWritable: isWritable$1, onChannelOpenFailure: onChannelOpenFailure$1, onCHANNEL_CLOSE: onCHANNEL_CLOSE$1} = utils$1;

const bufferParser = makeBufferParser();

const sigParser = makeBufferParser();

const RE_OPENSSH = /^OpenSSH_(?:(?![0-4])\d)|(?:\d{2,})/;

const noop$6 = e => {};

let Client$2 = class Client extends EventEmitter$3 {
    constructor() {
        super();
        this.config = {
            host: undefined,
            port: undefined,
            localAddress: undefined,
            localPort: undefined,
            forceIPv4: undefined,
            forceIPv6: undefined,
            keepaliveCountMax: undefined,
            keepaliveInterval: undefined,
            readyTimeout: undefined,
            ident: undefined,
            username: undefined,
            password: undefined,
            privateKey: undefined,
            tryKeyboard: undefined,
            agent: undefined,
            allowAgentFwd: undefined,
            authHandler: undefined,
            hostHashAlgo: undefined,
            hostHashCb: undefined,
            strictVendor: undefined,
            debug: undefined
        };
        this._agent = undefined;
        this._readyTimeout = undefined;
        this._chanMgr = undefined;
        this._callbacks = undefined;
        this._forwarding = undefined;
        this._forwardingUnix = undefined;
        this._acceptX11 = undefined;
        this._agentFwdEnabled = undefined;
        this._remoteVer = undefined;
        this._protocol = undefined;
        this._sock = undefined;
        this._resetKA = undefined;
    }
    connect(e) {
        if (this._sock && isWritable$1(this._sock)) {
            this.once("close", () => {
                this.connect(e);
            });
            this.end();
            return this;
        }
        this.config.host = e.hostname || e.host || "localhost";
        this.config.port = e.port || 22;
        this.config.localAddress = typeof e.localAddress === "string" ? e.localAddress : undefined;
        this.config.localPort = typeof e.localPort === "string" || typeof e.localPort === "number" ? e.localPort : undefined;
        this.config.forceIPv4 = e.forceIPv4 || false;
        this.config.forceIPv6 = e.forceIPv6 || false;
        this.config.keepaliveCountMax = typeof e.keepaliveCountMax === "number" && e.keepaliveCountMax >= 0 ? e.keepaliveCountMax : 3;
        this.config.keepaliveInterval = typeof e.keepaliveInterval === "number" && e.keepaliveInterval > 0 ? e.keepaliveInterval : 0;
        this.config.readyTimeout = typeof e.readyTimeout === "number" && e.readyTimeout >= 0 ? e.readyTimeout : 2e4;
        this.config.ident = typeof e.ident === "string" || Buffer.isBuffer(e.ident) ? e.ident : undefined;
        const t = {
            kex: undefined,
            serverHostKey: undefined,
            cs: {
                cipher: undefined,
                mac: undefined,
                compress: undefined,
                lang: []
            },
            sc: undefined
        };
        let r = true;
        if (typeof e.algorithms === "object" && e.algorithms !== null) {
            t.kex = generateAlgorithmList$1(e.algorithms.kex, DEFAULT_KEX$1, SUPPORTED_KEX$1);
            if (t.kex !== DEFAULT_KEX$1) r = false;
            t.serverHostKey = generateAlgorithmList$1(e.algorithms.serverHostKey, DEFAULT_SERVER_HOST_KEY$1, SUPPORTED_SERVER_HOST_KEY$1);
            if (t.serverHostKey !== DEFAULT_SERVER_HOST_KEY$1) r = false;
            t.cs.cipher = generateAlgorithmList$1(e.algorithms.cipher, DEFAULT_CIPHER$1, SUPPORTED_CIPHER$1);
            if (t.cs.cipher !== DEFAULT_CIPHER$1) r = false;
            t.cs.mac = generateAlgorithmList$1(e.algorithms.hmac, DEFAULT_MAC$1, SUPPORTED_MAC$1);
            if (t.cs.mac !== DEFAULT_MAC$1) r = false;
            t.cs.compress = generateAlgorithmList$1(e.algorithms.compress, DEFAULT_COMPRESSION$1, SUPPORTED_COMPRESSION$1);
            if (t.cs.compress !== DEFAULT_COMPRESSION$1) r = false;
            if (!r) t.sc = t.cs;
        }
        if (typeof e.username === "string") this.config.username = e.username; else if (typeof e.user === "string") this.config.username = e.user; else throw new Error("Invalid username");
        this.config.password = typeof e.password === "string" ? e.password : undefined;
        this.config.privateKey = typeof e.privateKey === "string" || Buffer.isBuffer(e.privateKey) ? e.privateKey : undefined;
        this.config.localHostname = typeof e.localHostname === "string" ? e.localHostname : undefined;
        this.config.localUsername = typeof e.localUsername === "string" ? e.localUsername : undefined;
        this.config.tryKeyboard = e.tryKeyboard === true;
        if (typeof e.agent === "string" && e.agent.length) this.config.agent = createAgent$1(e.agent); else if (isAgent(e.agent)) this.config.agent = e.agent; else this.config.agent = undefined;
        this.config.allowAgentFwd = e.agentForward === true && this.config.agent !== undefined;
        let n = this.config.authHandler = typeof e.authHandler === "function" || Array.isArray(e.authHandler) ? e.authHandler : undefined;
        this.config.strictVendor = typeof e.strictVendor === "boolean" ? e.strictVendor : true;
        const s = this.config.debug = typeof e.debug === "function" ? e.debug : undefined;
        if (e.agentForward === true && !this.config.allowAgentFwd) {
            throw new Error("You must set a valid agent path to allow agent forwarding");
        }
        let o = this._callbacks = [];
        this._chanMgr = new ChannelManager$1(this);
        this._forwarding = {};
        this._forwardingUnix = {};
        this._acceptX11 = 0;
        this._agentFwdEnabled = false;
        this._agent = this.config.agent ? this.config.agent : undefined;
        this._remoteVer = undefined;
        let a;
        if (this.config.privateKey) {
            a = parseKey$2(this.config.privateKey, e.passphrase);
            if (a instanceof Error) throw new Error(`Cannot parse privateKey: ${a.message}`);
            if (Array.isArray(a)) {
                a = a[0];
            }
            if (a.getPrivatePEM() === null) {
                throw new Error("privateKey value does not contain a (valid) private key");
            }
        }
        let l;
        if (typeof e.hostVerifier === "function") {
            const t = e.hostVerifier;
            let r;
            if (HASHES.indexOf(e.hostHash) !== -1) {
                r = e.hostHash;
            }
            l = (e, n) => {
                if (r) e = createHash(r).update(e).digest("hex");
                const s = t(e, n);
                if (s !== undefined) n(s);
            };
        }
        const c = this._sock = e.sock || new Socket;
        let u = false;
        let d = false;
        if (this._protocol) this._protocol.cleanup();
        const h = !s ? undefined : (e, t, r) => {
            s(`Debug output from server: ${JSON.stringify(r)}`);
        };
        let p;
        const g = this._protocol = new Protocol$1({
            ident: this.config.ident,
            offer: r ? undefined : t,
            onWrite: e => {
                if (isWritable$1(c)) c.write(e);
            },
            onError: e => {
                if (e.level === "handshake") clearTimeout(this._readyTimeout);
                if (!g._destruct) c.removeAllListeners("data");
                this.emit("error", e);
                try {
                    c.end();
                } catch {}
            },
            onHeader: e => {
                d = true;
                this._remoteVer = e.versions.software;
                if (e.greeting) this.emit("greeting", e.greeting);
            },
            onHandshakeComplete: e => {
                this.emit("handshake", e);
                if (!u) {
                    u = true;
                    g.service("ssh-userauth");
                }
            },
            debug: s,
            hostVerifier: l,
            messageHandlers: {
                DEBUG: h,
                DISCONNECT: (e, t, r) => {
                    if (t !== DISCONNECT_REASON$1.BY_APPLICATION) {
                        if (!r) {
                            r = DISCONNECT_REASON_BY_VALUE$1[t];
                            if (r === undefined) r = `Unexpected disconnection reason: ${t}`;
                        }
                        const e = new Error(r);
                        e.code = t;
                        this.emit("error", e);
                    }
                    c.end();
                },
                SERVICE_ACCEPT: (e, t) => {
                    if (t === "ssh-userauth") O();
                },
                EXT_INFO: (e, t) => {
                    if (p === undefined) {
                        for (const e of t) {
                            if (e.name === "server-sig-algs") {
                                p = e.algs;
                                return;
                            }
                        }
                        p = null;
                    }
                },
                USERAUTH_BANNER: (e, t) => {
                    this.emit("banner", t);
                },
                USERAUTH_SUCCESS: e => {
                    S();
                    clearTimeout(this._readyTimeout);
                    this.emit("ready");
                },
                USERAUTH_FAILURE: (e, t, r) => {
                    if (w.keyAlgos) {
                        const e = w.keyAlgos[0][0];
                        if (s) s(`Client: ${w.type} (${e}) auth failed`);
                        w.keyAlgos.shift();
                        if (w.keyAlgos.length) {
                            const [e, t] = w.keyAlgos[0];
                            switch (w.type) {
                              case "agent":
                                g.authPK(w.username, w.agentCtx.currentKey(), e);
                                return;

                              case "publickey":
                                g.authPK(w.username, w.key, e);
                                return;

                              case "hostbased":
                                g.authHostbased(w.username, w.key, w.localHostname, w.localUsername, e, (e, r) => {
                                    const n = w.key.sign(e, t);
                                    if (n instanceof Error) {
                                        n.message = `Error while signing with key: ${n.message}`;
                                        n.level = "client-authentication";
                                        this.emit("error", n);
                                        return O();
                                    }
                                    r(n);
                                });
                                return;
                            }
                        } else {
                            w.keyAlgos = undefined;
                        }
                    }
                    if (w.type === "agent") {
                        const e = w.agentCtx.pos();
                        s && s(`Client: Agent key #${e + 1} failed`);
                        return B();
                    }
                    s && s(`Client: ${w.type} auth failed`);
                    I = r;
                    T = t;
                    O();
                },
                USERAUTH_PASSWD_CHANGEREQ: (e, t) => {
                    if (w.type === "password") {
                        this.emit("change password", t, e => {
                            g.authPassword(this.config.username, this.config.password, e);
                        });
                    }
                },
                USERAUTH_PK_OK: e => {
                    let t;
                    let r;
                    if (w.keyAlgos) [t, r] = w.keyAlgos[0];
                    if (w.type === "agent") {
                        const e = w.agentCtx.currentKey();
                        g.authPK(w.username, e, t, (t, n) => {
                            const s = {
                                hash: r
                            };
                            w.agentCtx.sign(e, t, s, (e, t) => {
                                if (e) {
                                    e.level = "agent";
                                    this.emit("error", e);
                                } else {
                                    return n(t);
                                }
                                B();
                            });
                        });
                    } else if (w.type === "publickey") {
                        g.authPK(w.username, w.key, t, (e, t) => {
                            const n = w.key.sign(e, r);
                            if (n instanceof Error) {
                                n.message = `Error signing data with key: ${n.message}`;
                                n.level = "client-authentication";
                                this.emit("error", n);
                                return O();
                            }
                            t(n);
                        });
                    }
                },
                USERAUTH_INFO_REQUEST: (e, t, r, n) => {
                    if (w.type === "keyboard-interactive") {
                        const e = Array.isArray(n) ? n.length : 0;
                        if (e === 0) {
                            s && s("Client: Sending automatic USERAUTH_INFO_RESPONSE");
                            g.authInfoRes();
                            return;
                        }
                        w.prompt(t, r, "", n, e => {
                            g.authInfoRes(e);
                        });
                    }
                },
                REQUEST_SUCCESS: (e, t) => {
                    if (o.length) o.shift()(false, t);
                },
                REQUEST_FAILURE: e => {
                    if (o.length) o.shift()(true);
                },
                GLOBAL_REQUEST: (e, t, r, n) => {
                    switch (t) {
                      case "hostkeys-00@openssh.com":
                        hostKeysProve(this, n, (e, t) => {
                            if (e) return;
                            this.emit("hostkeys", t);
                        });
                        if (r) g.requestSuccess();
                        break;

                      default:
                        if (r) g.requestFailure();
                    }
                },
                CHANNEL_OPEN: (e, t) => {
                    onCHANNEL_OPEN(this, t);
                },
                CHANNEL_OPEN_CONFIRMATION: (e, t) => {
                    const r = this._chanMgr.get(t.recipient);
                    if (typeof r !== "function") return;
                    const n = r.type === "sftp";
                    const o = n ? "session" : r.type;
                    const a = {
                        type: o,
                        incoming: {
                            id: t.recipient,
                            window: MAX_WINDOW$1,
                            packetSize: PACKET_SIZE$1,
                            state: "open"
                        },
                        outgoing: {
                            id: t.sender,
                            window: t.window,
                            packetSize: t.packetSize,
                            state: "open"
                        }
                    };
                    const l = n ? new SFTP$1(this, a, {
                        debug: s
                    }) : new Channel$1(this, a);
                    this._chanMgr.update(t.recipient, l);
                    r(undefined, l);
                },
                CHANNEL_OPEN_FAILURE: (e, t, r, n) => {
                    const s = this._chanMgr.get(t);
                    if (typeof s !== "function") return;
                    const o = {
                        reason: r,
                        description: n
                    };
                    onChannelOpenFailure$1(this, t, o, s);
                },
                CHANNEL_DATA: (e, t, r) => {
                    const n = this._chanMgr.get(t);
                    if (typeof n !== "object" || n === null) return;
                    if (n.incoming.window === 0) return;
                    n.incoming.window -= r.length;
                    if (n.push(r) === false) {
                        n._waitChanDrain = true;
                        return;
                    }
                    if (n.incoming.window <= WINDOW_THRESHOLD$1) windowAdjust$1(n);
                },
                CHANNEL_EXTENDED_DATA: (e, t, r, n) => {
                    if (n !== STDERR) return;
                    const s = this._chanMgr.get(t);
                    if (typeof s !== "object" || s === null) return;
                    if (s.incoming.window === 0) return;
                    s.incoming.window -= r.length;
                    if (!s.stderr.push(r)) {
                        s._waitChanDrain = true;
                        return;
                    }
                    if (s.incoming.window <= WINDOW_THRESHOLD$1) windowAdjust$1(s);
                },
                CHANNEL_WINDOW_ADJUST: (e, t, r) => {
                    const n = this._chanMgr.get(t);
                    if (typeof n !== "object" || n === null) return;
                    n.outgoing.window += r;
                    if (n._waitWindow) {
                        n._waitWindow = false;
                        if (n._chunk) {
                            n._write(n._chunk, null, n._chunkcb);
                        } else if (n._chunkcb) {
                            n._chunkcb();
                        } else if (n._chunkErr) {
                            n.stderr._write(n._chunkErr, null, n._chunkcbErr);
                        } else if (n._chunkcbErr) {
                            n._chunkcbErr();
                        }
                    }
                },
                CHANNEL_SUCCESS: (e, t) => {
                    const r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    this._resetKA();
                    if (r._callbacks.length) r._callbacks.shift()(false);
                },
                CHANNEL_FAILURE: (e, t) => {
                    const r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    this._resetKA();
                    if (r._callbacks.length) r._callbacks.shift()(true);
                },
                CHANNEL_REQUEST: (e, t, r, n, s) => {
                    const o = this._chanMgr.get(t);
                    if (typeof o !== "object" || o === null) return;
                    const a = o._exit;
                    if (a.code !== undefined) return;
                    switch (r) {
                      case "exit-status":
                        o.emit("exit", a.code = s);
                        return;

                      case "exit-signal":
                        o.emit("exit", a.code = null, a.signal = `SIG${s.signal}`, a.dump = s.coreDumped, a.desc = s.errorMessage);
                        return;
                    }
                    if (n) e.channelFailure(o.outgoing.id);
                },
                CHANNEL_EOF: (e, t) => {
                    const r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    if (r.incoming.state !== "open") return;
                    r.incoming.state = "eof";
                    if (r.readable) r.push(null);
                    if (r.stderr.readable) r.stderr.push(null);
                },
                CHANNEL_CLOSE: (e, t) => {
                    onCHANNEL_CLOSE$1(this, t, this._chanMgr.get(t));
                }
            }
        });
        c.pause();
        const m = this.config.keepaliveInterval;
        const _ = this.config.keepaliveCountMax;
        let E = 0;
        let v;
        const y = () => {
            if (++E > _) {
                clearInterval(v);
                if (c.readable) {
                    const e = new Error("Keepalive timeout");
                    e.level = "client-timeout";
                    this.emit("error", e);
                    c.destroy();
                }
                return;
            }
            if (isWritable$1(c)) {
                o.push(S);
                g.ping();
            } else {
                clearInterval(v);
            }
        };
        function S() {
            if (m > 0) {
                E = 0;
                clearInterval(v);
                if (isWritable$1(c)) v = setInterval(y, m);
            }
        }
        this._resetKA = S;
        const A = (() => {
            let e = false;
            return () => {
                if (e) return;
                e = true;
                if (C && !d) {
                    const e = makeError("Connection lost before handshake", "protocol", true);
                    this.emit("error", e);
                }
            };
        })();
        const b = (() => {
            let e = false;
            return () => {
                if (e) return;
                e = true;
                C = true;
                s && s("Socket connected");
                this.emit("connect");
                cryptoInit$1.then(() => {
                    g.start();
                    c.on("data", e => {
                        try {
                            g.parse(e, 0, e.length);
                        } catch (e) {
                            this.emit("error", e);
                            try {
                                if (isWritable$1(c)) c.end();
                            } catch {}
                        }
                    });
                    if (c.stderr && typeof c.stderr.resume === "function") c.stderr.resume();
                    c.resume();
                }).catch(e => {
                    this.emit("error", e);
                    try {
                        if (isWritable$1(c)) c.end();
                    } catch {}
                });
            };
        })();
        let C = false;
        c.on("connect", b).on("timeout", () => {
            this.emit("timeout");
        }).on("error", e => {
            s && s(`Socket error: ${e.message}`);
            clearTimeout(this._readyTimeout);
            e.level = "client-socket";
            this.emit("error", e);
        }).on("end", () => {
            s && s("Socket ended");
            A();
            g.cleanup();
            clearTimeout(this._readyTimeout);
            clearInterval(v);
            this.emit("end");
        }).on("close", () => {
            s && s("Socket closed");
            A();
            g.cleanup();
            clearTimeout(this._readyTimeout);
            clearInterval(v);
            this.emit("close");
            const e = o;
            o = this._callbacks = [];
            const t = new Error("No response from server");
            for (let r = 0; r < e.length; ++r) e[r](t);
            this._chanMgr.cleanup(t);
        });
        let w;
        let I = null;
        let T = null;
        const R = [ "none" ];
        if (this.config.password !== undefined) R.push("password");
        if (a !== undefined) R.push("publickey");
        if (this._agent !== undefined) R.push("agent");
        if (this.config.tryKeyboard) R.push("keyboard-interactive");
        if (a !== undefined && this.config.localHostname !== undefined && this.config.localUsername !== undefined) {
            R.push("hostbased");
        }
        if (Array.isArray(n)) n = makeSimpleAuthHandler(n); else if (typeof n !== "function") n = makeSimpleAuthHandler(R);
        let k = false;
        const P = e => {
            if (k) return;
            k = true;
            if (e === false) {
                const e = new Error("All configured authentication methods failed");
                e.level = "client-authentication";
                this.emit("error", e);
                this.end();
                return;
            }
            if (typeof e === "string") {
                const t = e;
                if (R.indexOf(t) === -1) return $(`Authentication method not allowed: ${t}`);
                const r = this.config.username;
                switch (t) {
                  case "password":
                    e = {
                        type: t,
                        username: r,
                        password: this.config.password
                    };
                    break;

                  case "publickey":
                    e = {
                        type: t,
                        username: r,
                        key: a
                    };
                    break;

                  case "hostbased":
                    e = {
                        type: t,
                        username: r,
                        key: a,
                        localHostname: this.config.localHostname,
                        localUsername: this.config.localUsername
                    };
                    break;

                  case "agent":
                    e = {
                        type: t,
                        username: r,
                        agentCtx: new AgentContext(this._agent)
                    };
                    break;

                  case "keyboard-interactive":
                    e = {
                        type: t,
                        username: r,
                        prompt: (...e) => this.emit("keyboard-interactive", ...e)
                    };
                    break;

                  case "none":
                    e = {
                        type: t,
                        username: r
                    };
                    break;

                  default:
                    return $(`Skipping unsupported authentication method: ${e}`);
                }
            } else if (typeof e !== "object" || e === null) {
                return $(`Skipping invalid authentication attempt: ${e}`);
            } else {
                const t = e.username;
                if (typeof t !== "string") {
                    return $(`Skipping invalid authentication attempt: ${e}`);
                }
                const r = e.type;
                switch (r) {
                  case "password":
                    {
                        const {password: n} = e;
                        if (typeof n !== "string" && !Buffer.isBuffer(n)) return $("Skipping invalid password auth attempt");
                        e = {
                            type: r,
                            username: t,
                            password: n
                        };
                        break;
                    }

                  case "publickey":
                    {
                        const n = parseKey$2(e.key, e.passphrase);
                        if (n instanceof Error) return $("Skipping invalid key auth attempt");
                        if (!n.isPrivateKey()) return $("Skipping non-private key");
                        e = {
                            type: r,
                            username: t,
                            key: n
                        };
                        break;
                    }

                  case "hostbased":
                    {
                        const {localHostname: n, localUsername: s} = e;
                        const o = parseKey$2(e.key, e.passphrase);
                        if (o instanceof Error || typeof n !== "string" || typeof s !== "string") {
                            return $("Skipping invalid hostbased auth attempt");
                        }
                        if (!o.isPrivateKey()) return $("Skipping non-private key");
                        e = {
                            type: r,
                            username: t,
                            key: o,
                            localHostname: n,
                            localUsername: s
                        };
                        break;
                    }

                  case "agent":
                    {
                        let n = e.agent;
                        if (typeof n === "string" && n.length) {
                            n = createAgent$1(n);
                        } else if (!isAgent(n)) {
                            return $(`Skipping invalid agent: ${e.agent}`);
                        }
                        e = {
                            type: r,
                            username: t,
                            agentCtx: new AgentContext(n)
                        };
                        break;
                    }

                  case "keyboard-interactive":
                    {
                        const {prompt: n} = e;
                        if (typeof n !== "function") {
                            return $("Skipping invalid keyboard-interactive auth attempt");
                        }
                        e = {
                            type: r,
                            username: t,
                            prompt: n
                        };
                        break;
                    }

                  case "none":
                    e = {
                        type: r,
                        username: t
                    };
                    break;

                  default:
                    return $(`Skipping unsupported authentication method: ${e}`);
                }
            }
            w = e;
            try {
                const e = w.username;
                switch (w.type) {
                  case "password":
                    g.authPassword(e, w.password);
                    break;

                  case "publickey":
                    {
                        let t;
                        w.keyAlgos = getKeyAlgos(this, w.key, p);
                        if (w.keyAlgos) {
                            if (w.keyAlgos.length) {
                                t = w.keyAlgos[0][0];
                            } else {
                                return $("Skipping key authentication (no mutual hash algorithm)");
                            }
                        }
                        g.authPK(e, w.key, t);
                        break;
                    }

                  case "hostbased":
                    {
                        let t;
                        let r;
                        w.keyAlgos = getKeyAlgos(this, w.key, p);
                        if (w.keyAlgos) {
                            if (w.keyAlgos.length) {
                                [t, r] = w.keyAlgos[0];
                            } else {
                                return $("Skipping hostbased authentication (no mutual hash algorithm)");
                            }
                        }
                        g.authHostbased(e, w.key, w.localHostname, w.localUsername, t, (e, t) => {
                            const n = w.key.sign(e, r);
                            if (n instanceof Error) {
                                n.message = `Error while signing with key: ${n.message}`;
                                n.level = "client-authentication";
                                this.emit("error", n);
                                return O();
                            }
                            t(n);
                        });
                        break;
                    }

                  case "agent":
                    w.agentCtx.init(e => {
                        if (e) {
                            e.level = "agent";
                            this.emit("error", e);
                            return O();
                        }
                        B();
                    });
                    break;

                  case "keyboard-interactive":
                    g.authKeyboard(e);
                    break;

                  case "none":
                    g.authNone(e);
                    break;
                }
            } finally {
                k = false;
            }
        };
        function $(e) {
            s && s(e);
            process.nextTick(O);
        }
        function O() {
            k = false;
            const e = n(T, I, P);
            if (k || e === undefined) return;
            P(e);
        }
        const B = () => {
            if (w.type === "agent") {
                const e = w.agentCtx.nextKey();
                if (e === false) {
                    s && s("Agent: No more keys left to try");
                    s && s("Client: agent auth failed");
                    O();
                } else {
                    const t = w.agentCtx.pos();
                    let r;
                    w.keyAlgos = getKeyAlgos(this, e, p);
                    if (w.keyAlgos) {
                        if (w.keyAlgos.length) {
                            r = w.keyAlgos[0][0];
                        } else {
                            s && s(`Agent: Skipping key #${t + 1} (no mutual hash algorithm)`);
                            B();
                            return;
                        }
                    }
                    s && s(`Agent: Trying key #${t + 1}`);
                    g.authPK(w.username, e, r);
                }
            }
        };
        const N = () => {
            if (this.config.readyTimeout > 0) {
                this._readyTimeout = setTimeout(() => {
                    const e = new Error("Timed out while waiting for handshake");
                    e.level = "client-timeout";
                    this.emit("error", e);
                    c.destroy();
                }, this.config.readyTimeout);
            }
        };
        if (!e.sock) {
            let t = this.config.host;
            const r = this.config.forceIPv4;
            const n = this.config.forceIPv6;
            s && s(`Client: Trying ${t} on port ${this.config.port} ...`);
            const o = () => {
                N();
                c.connect({
                    host: t,
                    port: this.config.port,
                    localAddress: this.config.localAddress,
                    localPort: this.config.localPort
                });
                c.setMaxListeners(0);
                c.setTimeout(typeof e.timeout === "number" ? e.timeout : 0);
            };
            if (!r && !n || r && n) {
                o();
            } else {
                dnsLookup(t, r ? 4 : 6, (e, n, s) => {
                    if (e) {
                        const n = r ? "IPv4" : "IPv6";
                        const s = new Error(`Error while looking up ${n} address for '${t}': ${e}`);
                        clearTimeout(this._readyTimeout);
                        s.level = "client-dns";
                        this.emit("error", s);
                        this.emit("close");
                        return;
                    }
                    t = n;
                    o();
                });
            }
        } else {
            N();
            if (typeof c.connecting === "boolean") {
                if (!c.connecting) {
                    b();
                }
            } else {
                b();
            }
        }
        return this;
    }
    end() {
        if (this._sock && isWritable$1(this._sock)) {
            this._protocol.disconnect(DISCONNECT_REASON$1.BY_APPLICATION);
            this._sock.end();
        }
        return this;
    }
    destroy() {
        this._sock && isWritable$1(this._sock) && this._sock.destroy();
        return this;
    }
    exec(e, t, r) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        if (typeof t === "function") {
            r = t;
            t = {};
        }
        const n = {
            allowHalfOpen: t.allowHalfOpen !== false
        };
        openChannel$1(this, "session", n, (n, s) => {
            if (n) {
                r(n);
                return;
            }
            const o = [];
            function a(e) {
                if (e) {
                    s.close();
                    r(e);
                    return;
                }
                if (o.length) o.shift()();
            }
            if (this.config.allowAgentFwd === true || t && t.agentForward === true && this._agent !== undefined) {
                o.push(() => reqAgentFwd(s, a));
            }
            if (typeof t === "object" && t !== null) {
                if (typeof t.env === "object" && t.env !== null) reqEnv(s, t.env);
                if (typeof t.pty === "object" && t.pty !== null || t.pty === true) {
                    o.push(() => reqPty(s, t.pty, a));
                }
                if (typeof t.x11 === "object" && t.x11 !== null || t.x11 === "number" || t.x11 === true) {
                    o.push(() => reqX11(s, t.x11, a));
                }
            }
            o.push(() => reqExec(s, e, t, r));
            o.shift()();
        });
        return this;
    }
    shell(e, t, r) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        if (typeof e === "function") {
            r = e;
            e = t = undefined;
        } else if (typeof t === "function") {
            r = t;
            t = undefined;
        }
        if (e && (e.x11 !== undefined || e.env !== undefined)) {
            t = e;
            e = undefined;
        }
        openChannel$1(this, "session", (n, s) => {
            if (n) {
                r(n);
                return;
            }
            const o = [];
            function a(e) {
                if (e) {
                    s.close();
                    r(e);
                    return;
                }
                if (o.length) o.shift()();
            }
            if (this.config.allowAgentFwd === true || t && t.agentForward === true && this._agent !== undefined) {
                o.push(() => reqAgentFwd(s, a));
            }
            if (e !== false) o.push(() => reqPty(s, e, a));
            if (typeof t === "object" && t !== null) {
                if (typeof t.env === "object" && t.env !== null) reqEnv(s, t.env);
                if (typeof t.x11 === "object" && t.x11 !== null || t.x11 === "number" || t.x11 === true) {
                    o.push(() => reqX11(s, t.x11, a));
                }
            }
            o.push(() => reqShell(s, r));
            o.shift()();
        });
        return this;
    }
    subsys(e, t) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        openChannel$1(this, "session", (r, n) => {
            if (r) {
                t(r);
                return;
            }
            reqSubsystem(n, e, (e, r) => {
                if (e) {
                    t(e);
                    return;
                }
                t(undefined, r);
            });
        });
        return this;
    }
    forwardIn(e, t, r) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const n = typeof r === "function";
        if (n) {
            this._callbacks.push((n, s) => {
                if (n) {
                    r(n !== true ? n : new Error(`Unable to bind to ${e}:${t}`));
                    return;
                }
                let o = t;
                if (t === 0 && s && s.length >= 4) {
                    o = readUInt32BE(s, 0);
                    if (!(this._protocol._compatFlags & COMPAT.DYN_RPORT_BUG)) t = o;
                }
                this._forwarding[`${e}:${t}`] = o;
                r(undefined, o);
            });
        }
        this._protocol.tcpipForward(e, t, n);
        return this;
    }
    unforwardIn(e, t, r) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const n = typeof r === "function";
        if (n) {
            this._callbacks.push(n => {
                if (n) {
                    r(n !== true ? n : new Error(`Unable to unbind from ${e}:${t}`));
                    return;
                }
                delete this._forwarding[`${e}:${t}`];
                r();
            });
        }
        this._protocol.cancelTcpipForward(e, t, n);
        return this;
    }
    forwardOut(e, t, r, n, s) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const o = {
            srcIP: e,
            srcPort: t,
            dstIP: r,
            dstPort: n
        };
        if (typeof s !== "function") s = noop$6;
        openChannel$1(this, "direct-tcpip", o, s);
        return this;
    }
    openssh_noMoreSessions(e) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const t = typeof e === "function";
        if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) {
            if (t) {
                this._callbacks.push(t => {
                    if (t) {
                        e(t !== true ? t : new Error("Unable to disable future sessions"));
                        return;
                    }
                    e();
                });
            }
            this._protocol.openssh_noMoreSessions(t);
            return this;
        }
        if (!t) return this;
        process.nextTick(e, new Error("strictVendor enabled and server is not OpenSSH or compatible version"));
        return this;
    }
    openssh_forwardInStreamLocal(e, t) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const r = typeof t === "function";
        if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) {
            if (r) {
                this._callbacks.push(r => {
                    if (r) {
                        t(r !== true ? r : new Error(`Unable to bind to ${e}`));
                        return;
                    }
                    this._forwardingUnix[e] = true;
                    t();
                });
            }
            this._protocol.openssh_streamLocalForward(e, r);
            return this;
        }
        if (!r) return this;
        process.nextTick(t, new Error("strictVendor enabled and server is not OpenSSH or compatible version"));
        return this;
    }
    openssh_unforwardInStreamLocal(e, t) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        const r = typeof t === "function";
        if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) {
            if (r) {
                this._callbacks.push(r => {
                    if (r) {
                        t(r !== true ? r : new Error(`Unable to unbind from ${e}`));
                        return;
                    }
                    delete this._forwardingUnix[e];
                    t();
                });
            }
            this._protocol.openssh_cancelStreamLocalForward(e, r);
            return this;
        }
        if (!r) return this;
        process.nextTick(t, new Error("strictVendor enabled and server is not OpenSSH or compatible version"));
        return this;
    }
    openssh_forwardOutStreamLocal(e, t) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        if (typeof t !== "function") t = noop$6;
        if (!this.config.strictVendor || this.config.strictVendor && RE_OPENSSH.test(this._remoteVer)) {
            openChannel$1(this, "direct-streamlocal@openssh.com", {
                socketPath: e
            }, t);
            return this;
        }
        process.nextTick(t, new Error("strictVendor enabled and server is not OpenSSH or compatible version"));
        return this;
    }
    sftp(e, t) {
        if (!this._sock || !isWritable$1(this._sock)) throw new Error("Not connected");
        if (typeof e === "function") {
            t = e;
            e = undefined;
        }
        openChannel$1(this, "sftp", (r, n) => {
            if (r) {
                t(r);
                return;
            }
            const s = (e, r) => {
                if (e) {
                    t(e);
                    return;
                }
                function s() {
                    n.removeListener("ready", o);
                    n.removeListener("error", a);
                    n.removeListener("exit", l);
                    n.removeListener("close", l);
                }
                function o() {
                    s();
                    t(undefined, n);
                }
                function a(e) {
                    s();
                    t(e);
                }
                function l(e, r) {
                    s();
                    let n;
                    if (typeof e === "number") n = `Received exit code ${e} while establishing SFTP session`; else if (r !== undefined) n = `Received signal ${r} while establishing SFTP session`; else n = "Received unexpected SFTP session termination";
                    const o = new Error(n);
                    o.code = e;
                    o.signal = r;
                    t(o);
                }
                n.on("ready", o).on("error", a).on("exit", l).on("close", l);
                n._init();
            };
            if (typeof e === "object" && e !== null) {
                reqEnv(n, e, e => {
                    if (e) {
                        t(e);
                        return;
                    }
                    reqSubsystem(n, "sftp", s);
                });
            } else {
                reqSubsystem(n, "sftp", s);
            }
        });
        return this;
    }
    setNoDelay(e) {
        if (this._sock && typeof this._sock.setNoDelay === "function") this._sock.setNoDelay(e);
        return this;
    }
};

function openChannel$1(e, t, r, n) {
    const s = MAX_WINDOW$1;
    const o = PACKET_SIZE$1;
    if (typeof r === "function") {
        n = r;
        r = {};
    }
    const a = (e, t) => {
        n(e, t);
    };
    a.type = t;
    const l = e._chanMgr.add(a);
    if (l === -1) {
        n(new Error("No free channels available"));
        return;
    }
    switch (t) {
      case "session":
      case "sftp":
        e._protocol.session(l, s, o);
        break;

      case "direct-tcpip":
        e._protocol.directTcpip(l, s, o, r);
        break;

      case "direct-streamlocal@openssh.com":
        e._protocol.openssh_directStreamLocal(l, s, o, r);
        break;

      default:
        throw new Error(`Unsupported channel type: ${t}`);
    }
}

function reqX11(e, t, r) {
    const n = {
        single: false,
        protocol: "MIT-MAGIC-COOKIE-1",
        cookie: undefined,
        screen: 0
    };
    if (typeof t === "function") {
        r = t;
    } else if (typeof t === "object" && t !== null) {
        if (typeof t.single === "boolean") n.single = t.single;
        if (typeof t.screen === "number") n.screen = t.screen;
        if (typeof t.protocol === "string") n.protocol = t.protocol;
        if (typeof t.cookie === "string") n.cookie = t.cookie; else if (Buffer.isBuffer(t.cookie)) n.cookie = t.cookie.hexSlice(0, t.cookie.length);
    }
    if (n.cookie === undefined) n.cookie = randomCookie();
    const s = typeof r === "function";
    if (e.outgoing.state !== "open") {
        if (s) r(new Error("Channel is not open"));
        return;
    }
    if (s) {
        e._callbacks.push(t => {
            if (t) {
                r(t !== true ? t : new Error("Unable to request X11"));
                return;
            }
            e._hasX11 = true;
            ++e._client._acceptX11;
            e.once("close", () => {
                if (e._client._acceptX11) --e._client._acceptX11;
            });
            r();
        });
    }
    e._client._protocol.x11Forward(e.outgoing.id, n, s);
}

function reqPty(e, t, r) {
    let n = 24;
    let s = 80;
    let o = 640;
    let a = 480;
    let l = "vt100";
    let c = null;
    if (typeof t === "function") {
        r = t;
    } else if (typeof t === "object" && t !== null) {
        if (typeof t.rows === "number") n = t.rows;
        if (typeof t.cols === "number") s = t.cols;
        if (typeof t.width === "number") o = t.width;
        if (typeof t.height === "number") a = t.height;
        if (typeof t.term === "string") l = t.term;
        if (typeof t.modes === "object") c = t.modes;
    }
    const u = typeof r === "function";
    if (e.outgoing.state !== "open") {
        if (u) r(new Error("Channel is not open"));
        return;
    }
    if (u) {
        e._callbacks.push(e => {
            if (e) {
                r(e !== true ? e : new Error("Unable to request a pseudo-terminal"));
                return;
            }
            r();
        });
    }
    e._client._protocol.pty(e.outgoing.id, n, s, a, o, l, c, u);
}

function reqAgentFwd(e, t) {
    const r = typeof t === "function";
    if (e.outgoing.state !== "open") {
        r && t(new Error("Channel is not open"));
        return;
    }
    if (e._client._agentFwdEnabled) {
        r && t(false);
        return;
    }
    e._client._agentFwdEnabled = true;
    e._callbacks.push(n => {
        if (n) {
            e._client._agentFwdEnabled = false;
            if (r) {
                t(n !== true ? n : new Error("Unable to request agent forwarding"));
            }
            return;
        }
        if (r) t();
    });
    e._client._protocol.openssh_agentForward(e.outgoing.id, true);
}

function reqShell(e, t) {
    if (e.outgoing.state !== "open") {
        t(new Error("Channel is not open"));
        return;
    }
    e._callbacks.push(r => {
        if (r) {
            t(r !== true ? r : new Error("Unable to open shell"));
            return;
        }
        e.subtype = "shell";
        t(undefined, e);
    });
    e._client._protocol.shell(e.outgoing.id, true);
}

function reqExec(e, t, r, n) {
    if (e.outgoing.state !== "open") {
        n(new Error("Channel is not open"));
        return;
    }
    e._callbacks.push(t => {
        if (t) {
            n(t !== true ? t : new Error("Unable to exec"));
            return;
        }
        e.subtype = "exec";
        e.allowHalfOpen = r.allowHalfOpen !== false;
        n(undefined, e);
    });
    e._client._protocol.exec(e.outgoing.id, t, true);
}

function reqEnv(e, t, r) {
    const n = typeof r === "function";
    if (e.outgoing.state !== "open") {
        if (n) r(new Error("Channel is not open"));
        return;
    }
    if (n) {
        e._callbacks.push(e => {
            if (e) {
                r(e !== true ? e : new Error("Unable to set environment"));
                return;
            }
            r();
        });
    }
    const s = Object.keys(t || {});
    for (let r = 0; r < s.length; ++r) {
        const o = s[r];
        const a = t[o];
        e._client._protocol.env(e.outgoing.id, o, a, n);
    }
}

function reqSubsystem(e, t, r) {
    if (e.outgoing.state !== "open") {
        r(new Error("Channel is not open"));
        return;
    }
    e._callbacks.push(n => {
        if (n) {
            r(n !== true ? n : new Error(`Unable to start subsystem: ${t}`));
            return;
        }
        e.subtype = "subsystem";
        r(undefined, e);
    });
    e._client._protocol.subsystem(e.outgoing.id, t, true);
}

function onCHANNEL_OPEN(e, t) {
    let r = -1;
    let n;
    const s = () => {
        const n = {
            type: t.type,
            incoming: {
                id: r,
                window: MAX_WINDOW$1,
                packetSize: PACKET_SIZE$1,
                state: "open"
            },
            outgoing: {
                id: t.sender,
                window: t.window,
                packetSize: t.packetSize,
                state: "open"
            }
        };
        const s = new Channel$1(e, n);
        e._chanMgr.update(r, s);
        e._protocol.channelOpenConfirm(t.sender, r, MAX_WINDOW$1, PACKET_SIZE$1);
        return s;
    };
    const o = () => {
        if (n === undefined) {
            if (r === -1) n = CHANNEL_OPEN_FAILURE$1.RESOURCE_SHORTAGE; else n = CHANNEL_OPEN_FAILURE$1.CONNECT_FAILED;
        }
        if (r !== -1) e._chanMgr.remove(r);
        e._protocol.channelOpenFail(t.sender, n, "");
    };
    const a = () => {
        r = e._chanMgr.add();
        if (r === -1) {
            n = CHANNEL_OPEN_FAILURE$1.RESOURCE_SHORTAGE;
            if (e.config.debug) {
                e.config.debug("Client: Automatic rejection of incoming channel open: " + "no channels available");
            }
        }
        return r !== -1;
    };
    const l = t.data;
    switch (t.type) {
      case "forwarded-tcpip":
        {
            const t = e._forwarding[`${l.destIP}:${l.destPort}`];
            if (t !== undefined && a()) {
                if (l.destPort === 0) l.destPort = t;
                e.emit("tcp connection", l, s, o);
                return;
            }
            break;
        }

      case "forwarded-streamlocal@openssh.com":
        if (e._forwardingUnix[l.socketPath] !== undefined && a()) {
            e.emit("unix connection", l, s, o);
            return;
        }
        break;

      case "auth-agent@openssh.com":
        if (e._agentFwdEnabled && typeof e._agent.getStream === "function" && a()) {
            e._agent.getStream((e, t) => {
                if (e) return o();
                const r = s();
                r.pipe(t).pipe(r);
            });
            return;
        }
        break;

      case "x11":
        if (e._acceptX11 !== 0 && a()) {
            e.emit("x11", l, s, o);
            return;
        }
        break;

      default:
        n = CHANNEL_OPEN_FAILURE$1.UNKNOWN_CHANNEL_TYPE;
        if (e.config.debug) {
            e.config.debug("Client: Automatic rejection of unsupported incoming channel open " + `type: ${t.type}`);
        }
    }
    if (n === undefined) {
        n = CHANNEL_OPEN_FAILURE$1.ADMINISTRATIVELY_PROHIBITED;
        if (e.config.debug) {
            e.config.debug("Client: Automatic rejection of unexpected incoming channel open for: " + t.type);
        }
    }
    o();
}

const randomCookie = (() => {
    const e = Buffer.allocUnsafe(16);
    return () => {
        randomFillSync(e, 0, 16);
        return e.hexSlice(0, 16);
    };
})();

function makeSimpleAuthHandler(e) {
    if (!Array.isArray(e)) throw new Error("authList must be an array");
    let t = 0;
    return (r, n, s) => {
        if (t === e.length) return false;
        return e[t++];
    };
}

function hostKeysProve(e, t, r) {
    if (!e._sock || !isWritable$1(e._sock)) return;
    if (typeof r !== "function") r = noop$6;
    if (!Array.isArray(t)) throw new TypeError("Invalid keys argument type");
    const n = [];
    for (const e of t) {
        const t = parseKey$2(e);
        if (t instanceof Error) throw t;
        n.push(t);
    }
    if (!e.config.strictVendor || e.config.strictVendor && RE_OPENSSH.test(e._remoteVer)) {
        e._callbacks.push((t, s) => {
            if (t) {
                r(t !== true ? t : new Error("Server failed to prove supplied keys"));
                return;
            }
            const o = [];
            let a = 0;
            bufferParser.init(s, 0);
            while (bufferParser.avail()) {
                if (a === n.length) break;
                const t = n[a++];
                const r = t.getPublicSSH();
                const s = bufferParser.readString();
                sigParser.init(s, 0);
                const l = sigParser.readString(true);
                let c = sigParser.readString();
                let u;
                if (l !== t.type) {
                    if (t.type === "ssh-rsa") {
                        switch (l) {
                          case "rsa-sha2-256":
                            u = "sha256";
                            break;

                          case "rsa-sha2-512":
                            u = "sha512";
                            break;

                          default:
                            continue;
                        }
                    } else {
                        continue;
                    }
                }
                const d = e._protocol._kex.sessionID;
                const h = Buffer.allocUnsafe(4 + 29 + 4 + d.length + 4 + r.length);
                let p = 0;
                writeUInt32BE$1(h, 29, p);
                h.utf8Write("hostkeys-prove-00@openssh.com", p += 4, 29);
                writeUInt32BE$1(h, d.length, p += 29);
                bufferCopy(d, h, 0, d.length, p += 4);
                writeUInt32BE$1(h, r.length, p += d.length);
                bufferCopy(r, h, 0, r.length, p += 4);
                if (!(c = sigSSHToASN1(c, l))) continue;
                if (t.verify(h, c, u) === true) o.push(t);
            }
            sigParser.clear();
            bufferParser.clear();
            r(null, o);
        });
        e._protocol.openssh_hostKeysProve(n);
        return;
    }
    process.nextTick(r, new Error("strictVendor enabled and server is not OpenSSH or compatible version"));
}

function getKeyAlgos(e, t, r) {
    switch (t.type) {
      case "ssh-rsa":
        if (e._protocol._compatFlags & COMPAT.IMPLY_RSA_SHA2_SIGALGS) {
            if (!Array.isArray(r)) r = [ "rsa-sha2-256", "rsa-sha2-512" ]; else r = [ "rsa-sha2-256", "rsa-sha2-512", ...r ];
        }
        if (Array.isArray(r)) {
            if (r.indexOf("rsa-sha2-256") !== -1) return [ [ "rsa-sha2-256", "sha256" ] ];
            if (r.indexOf("rsa-sha2-512") !== -1) return [ [ "rsa-sha2-512", "sha512" ] ];
            if (r.indexOf("ssh-rsa") === -1) return [];
        }
        return [ [ "ssh-rsa", "sha1" ] ];
    }
}

var client$1 = Client$2;

(function(e) {
    const {Agent: t} = require$$1__default.default;
    const {Agent: r} = require$$0__default.default;
    const {connect: n} = require$$2__default$1.default;
    let s;
    for (const n of [ t, r ]) {
        class SSHAgent extends n {
            constructor(e, t) {
                super(t);
                this._connectCfg = e;
                this._defaultSrcIP = t && t.srcIP || "localhost";
            }
            createConnection(e, t) {
                const r = e && e.localAddress || this._defaultSrcIP;
                const o = e && e.localPort || 0;
                const l = e.host;
                const c = e.port;
                if (s === undefined) s = client$1;
                const u = new s;
                let d = false;
                u.on("ready", () => {
                    u.forwardOut(r, o, l, c, (r, s) => {
                        d = true;
                        if (r) {
                            u.end();
                            return t(r);
                        }
                        s.once("close", () => u.end());
                        t(null, a(s, n, e));
                    });
                }).on("error", t).on("close", () => {
                    if (!d) t(new Error("Unexpected connection close"));
                }).connect(this._connectCfg);
            }
        }
        e[n === t ? "SSHTTPAgent" : "SSHTTPSAgent"] = SSHAgent;
    }
    function o() {}
    function a(e, r, s) {
        if (r === t) {
            e.setKeepAlive = o;
            e.setNoDelay = o;
            e.setTimeout = o;
            e.ref = o;
            e.unref = o;
            e.destroySoon = e.destroy;
            return e;
        }
        s.socket = e;
        const a = n(s);
        const l = (() => {
            let t = false;
            return () => {
                if (t) return;
                t = true;
                if (e.isPaused()) e.resume();
            };
        })();
        a.on("end", l).on("close", l);
        return a;
    }
})(httpAgents);

var server$1 = {
    exports: {}
};

server$1.exports;

const {Server: netServer} = require$$0__default$6.default;

const EventEmitter$2 = require$$0__default$8.default;

const {listenerCount: listenerCount} = EventEmitter$2;

const {CHANNEL_OPEN_FAILURE: CHANNEL_OPEN_FAILURE, DEFAULT_CIPHER: DEFAULT_CIPHER, DEFAULT_COMPRESSION: DEFAULT_COMPRESSION, DEFAULT_KEX: DEFAULT_KEX, DEFAULT_MAC: DEFAULT_MAC, DEFAULT_SERVER_HOST_KEY: DEFAULT_SERVER_HOST_KEY, DISCONNECT_REASON: DISCONNECT_REASON, DISCONNECT_REASON_BY_VALUE: DISCONNECT_REASON_BY_VALUE, SUPPORTED_CIPHER: SUPPORTED_CIPHER, SUPPORTED_COMPRESSION: SUPPORTED_COMPRESSION, SUPPORTED_KEX: SUPPORTED_KEX, SUPPORTED_MAC: SUPPORTED_MAC, SUPPORTED_SERVER_HOST_KEY: SUPPORTED_SERVER_HOST_KEY} = requireConstants();

const {init: cryptoInit} = requireCrypto();

const {KexInit: KexInit} = requireKex();

const {parseKey: parseKey$1} = keyParser;

const Protocol = Protocol_1;

const {SFTP: SFTP} = SFTP_1;

const {writeUInt32BE: writeUInt32BE} = requireUtils();

const {Channel: Channel, MAX_WINDOW: MAX_WINDOW, PACKET_SIZE: PACKET_SIZE, windowAdjust: windowAdjust, WINDOW_THRESHOLD: WINDOW_THRESHOLD} = Channel_1;

const {ChannelManager: ChannelManager, generateAlgorithmList: generateAlgorithmList, isWritable: isWritable, onChannelOpenFailure: onChannelOpenFailure, onCHANNEL_CLOSE: onCHANNEL_CLOSE} = utils$1;

const MAX_PENDING_AUTHS = 10;

class AuthContext extends EventEmitter$2 {
    constructor(e, t, r, n, s) {
        super();
        this.username = this.user = t;
        this.service = r;
        this.method = n;
        this._initialResponse = false;
        this._finalResponse = false;
        this._multistep = false;
        this._cbfinal = (e, t, r) => {
            if (!this._finalResponse) {
                this._finalResponse = true;
                s(this, e, t, r);
            }
        };
        this._protocol = e;
    }
    accept() {
        this._cleanup && this._cleanup();
        this._initialResponse = true;
        this._cbfinal(true);
    }
    reject(e, t) {
        this._cleanup && this._cleanup();
        this._initialResponse = true;
        this._cbfinal(false, e, t);
    }
}

class KeyboardAuthContext extends AuthContext {
    constructor(e, t, r, n, s, o) {
        super(e, t, r, n, o);
        this._multistep = true;
        this._cb = undefined;
        this._onInfoResponse = e => {
            const t = this._cb;
            if (t) {
                this._cb = undefined;
                t(e);
            }
        };
        this.submethods = s;
        this.on("abort", () => {
            this._cb && this._cb(new Error("Authentication request aborted"));
        });
    }
    prompt(e, t, r, n) {
        if (!Array.isArray(e)) e = [ e ];
        if (typeof t === "function") {
            n = t;
            t = r = undefined;
        } else if (typeof r === "function") {
            n = r;
            r = undefined;
        } else if (typeof n !== "function") {
            n = undefined;
        }
        for (let t = 0; t < e.length; ++t) {
            if (typeof e[t] === "string") {
                e[t] = {
                    prompt: e[t],
                    echo: true
                };
            }
        }
        this._cb = n;
        this._initialResponse = true;
        this._protocol.authInfoReq(t, r, e);
    }
}

class PKAuthContext extends AuthContext {
    constructor(e, t, r, n, s, o) {
        super(e, t, r, n, o);
        this.key = {
            algo: s.keyAlgo,
            data: s.key
        };
        this.hashAlgo = s.hashAlgo;
        this.signature = s.signature;
        this.blob = s.blob;
    }
    accept() {
        if (!this.signature) {
            this._initialResponse = true;
            this._protocol.authPKOK(this.key.algo, this.key.data);
        } else {
            AuthContext.prototype.accept.call(this);
        }
    }
}

class HostbasedAuthContext extends AuthContext {
    constructor(e, t, r, n, s, o) {
        super(e, t, r, n, o);
        this.key = {
            algo: s.keyAlgo,
            data: s.key
        };
        this.hashAlgo = s.hashAlgo;
        this.signature = s.signature;
        this.blob = s.blob;
        this.localHostname = s.localHostname;
        this.localUsername = s.localUsername;
    }
}

class PwdAuthContext extends AuthContext {
    constructor(e, t, r, n, s, o) {
        super(e, t, r, n, o);
        this.password = s;
        this._changeCb = undefined;
    }
    requestChange(e, t) {
        if (this._changeCb) throw new Error("Change request already in progress");
        if (typeof e !== "string") throw new Error("prompt argument must be a string");
        if (typeof t !== "function") throw new Error("Callback argument must be a function");
        this._changeCb = t;
        this._protocol.authPasswdChg(e);
    }
}

class Session extends EventEmitter$2 {
    constructor(e, t, r) {
        super();
        this.type = "session";
        this.subtype = undefined;
        this.server = true;
        this._ending = false;
        this._channel = undefined;
        this._chanInfo = {
            type: "session",
            incoming: {
                id: r,
                window: MAX_WINDOW,
                packetSize: PACKET_SIZE,
                state: "open"
            },
            outgoing: {
                id: t.sender,
                window: t.window,
                packetSize: t.packetSize,
                state: "open"
            }
        };
    }
}

let Server$1 = class Server extends EventEmitter$2 {
    constructor(e, t) {
        super();
        if (typeof e !== "object" || e === null) throw new Error("Missing configuration object");
        const r = Object.create(null);
        const n = [];
        const s = e.hostKeys;
        if (!Array.isArray(s)) throw new Error("hostKeys must be an array");
        const o = typeof e.algorithms === "object" && e.algorithms !== null ? e.algorithms : {};
        const a = generateAlgorithmList(o.serverHostKey, DEFAULT_SERVER_HOST_KEY, SUPPORTED_SERVER_HOST_KEY);
        for (let e = 0; e < s.length; ++e) {
            let t;
            if (Buffer.isBuffer(s[e]) || typeof s[e] === "string") t = parseKey$1(s[e]); else t = parseKey$1(s[e].key, s[e].passphrase);
            if (t instanceof Error) throw new Error(`Cannot parse privateKey: ${t.message}`);
            if (Array.isArray(t)) {
                t = t[0];
            }
            if (t.getPrivatePEM() === null) throw new Error("privateKey value contains an invalid private key");
            if (n.includes(t.type)) continue;
            if (t.type === "ssh-rsa") {
                let e = a.indexOf("ssh-rsa");
                const s = a.indexOf("rsa-sha2-256");
                const o = a.indexOf("rsa-sha2-512");
                if (e === -1) {
                    e = Infinity;
                }
                [ e, s, o ].sort(compareNumbers).forEach(a => {
                    if (a === -1) return;
                    let l;
                    switch (a) {
                      case e:
                        l = "ssh-rsa";
                        break;

                      case s:
                        l = "rsa-sha2-256";
                        break;

                      case o:
                        l = "rsa-sha2-512";
                        break;

                      default:
                        return;
                    }
                    r[l] = t;
                    n.push(l);
                });
            } else {
                r[t.type] = t;
                n.push(t.type);
            }
        }
        const l = {
            kex: generateAlgorithmList(o.kex, DEFAULT_KEX, SUPPORTED_KEX).concat([ "kex-strict-s-v00@openssh.com" ]),
            serverHostKey: n,
            cs: {
                cipher: generateAlgorithmList(o.cipher, DEFAULT_CIPHER, SUPPORTED_CIPHER),
                mac: generateAlgorithmList(o.hmac, DEFAULT_MAC, SUPPORTED_MAC),
                compress: generateAlgorithmList(o.compress, DEFAULT_COMPRESSION, SUPPORTED_COMPRESSION),
                lang: []
            },
            sc: undefined
        };
        l.sc = l.cs;
        if (typeof t === "function") this.on("connection", t);
        const c = typeof e.debug === "function" ? e.debug : undefined;
        const u = e.ident ? Buffer.from(e.ident) : undefined;
        const d = new KexInit(l);
        this._srv = new netServer(t => {
            if (this._connections >= this.maxConnections) {
                t.destroy();
                return;
            }
            ++this._connections;
            t.once("close", () => {
                --this._connections;
            });
            let n;
            if (c) {
                const e = `[${process.hrtime().join(".")}] `;
                n = t => {
                    c(`${e}${t}`);
                };
            }
            new Client$1(t, r, u, d, n, this, e);
        }).on("error", e => {
            this.emit("error", e);
        }).on("listening", () => {
            this.emit("listening");
        }).on("close", () => {
            this.emit("close");
        });
        this._connections = 0;
        this.maxConnections = Infinity;
    }
    injectSocket(e) {
        this._srv.emit("connection", e);
    }
    listen(...e) {
        this._srv.listen(...e);
        return this;
    }
    address() {
        return this._srv.address();
    }
    getConnections(e) {
        this._srv.getConnections(e);
        return this;
    }
    close(e) {
        this._srv.close(e);
        return this;
    }
    ref() {
        this._srv.ref();
        return this;
    }
    unref() {
        this._srv.unref();
        return this;
    }
};

Server$1.KEEPALIVE_CLIENT_INTERVAL = 15e3;

Server$1.KEEPALIVE_CLIENT_COUNT_MAX = 3;

let Client$1 = class Client extends EventEmitter$2 {
    constructor(e, t, r, n, s, o, a) {
        super();
        let l = 0;
        let c = false;
        let u = [];
        let d;
        let h;
        let p;
        const g = [];
        this._sock = e;
        this._chanMgr = new ChannelManager(this);
        this._debug = s;
        this.noMoreSessions = false;
        this.authenticated = false;
        function m(e) {}
        this.on("error", m);
        const _ = !s ? undefined : (e, t, r) => {
            s(`Debug output from client: ${JSON.stringify(r)}`);
        };
        const E = typeof a.keepaliveInterval === "number" && isFinite(a.keepaliveInterval) && a.keepaliveInterval > 0 ? a.keepaliveInterval : typeof Server$1.KEEPALIVE_CLIENT_INTERVAL === "number" && isFinite(Server$1.KEEPALIVE_CLIENT_INTERVAL) && Server$1.KEEPALIVE_CLIENT_INTERVAL > 0 ? Server$1.KEEPALIVE_CLIENT_INTERVAL : -1;
        const v = typeof a.keepaliveCountMax === "number" && isFinite(a.keepaliveCountMax) && a.keepaliveCountMax >= 0 ? a.keepaliveCountMax : typeof Server$1.KEEPALIVE_CLIENT_COUNT_MAX === "number" && isFinite(Server$1.KEEPALIVE_CLIENT_COUNT_MAX) && Server$1.KEEPALIVE_CLIENT_COUNT_MAX >= 0 ? Server$1.KEEPALIVE_CLIENT_COUNT_MAX : -1;
        let y = 0;
        if (E !== -1 && v !== -1) {
            this.once("ready", () => {
                const e = () => {
                    clearInterval(h);
                };
                this.on("close", e).on("end", e);
                h = setInterval(() => {
                    if (++y > v) {
                        clearInterval(h);
                        const e = new Error("Keepalive timeout");
                        e.level = "client-timeout";
                        this.emit("error", e);
                        this.end();
                    } else {
                        S.ping();
                    }
                }, E);
            });
            p = () => {
                h && h.refresh();
                y = 0;
            };
        }
        const S = this._protocol = new Protocol({
            server: true,
            hostKeys: t,
            ident: r,
            offer: n,
            onPacket: p,
            greeting: a.greeting,
            banner: a.banner,
            onWrite: t => {
                if (isWritable(e)) e.write(t);
            },
            onError: t => {
                if (!S._destruct) e.removeAllListeners("data");
                this.emit("error", t);
                try {
                    e.end();
                } catch {}
            },
            onHeader: t => {
                this.removeListener("error", m);
                const r = {
                    ip: e.remoteAddress,
                    family: e.remoteFamily,
                    port: e.remotePort,
                    header: t
                };
                if (!o.emit("connection", this, r)) {
                    S.disconnect(DISCONNECT_REASON.BY_APPLICATION);
                    e.end();
                    return;
                }
                if (t.greeting) this.emit("greeting", t.greeting);
            },
            onHandshakeComplete: e => {
                if (++l > 1) this.emit("rekey");
                this.emit("handshake", e);
            },
            debug: s,
            messageHandlers: {
                DEBUG: _,
                DISCONNECT: (t, r, n) => {
                    if (r !== DISCONNECT_REASON.BY_APPLICATION) {
                        if (!n) {
                            n = DISCONNECT_REASON_BY_VALUE[r];
                            if (n === undefined) n = `Unexpected disconnection reason: ${r}`;
                        }
                        const e = new Error(n);
                        e.code = r;
                        this.emit("error", e);
                    }
                    e.end();
                },
                CHANNEL_OPEN: (e, t) => {
                    if (t.type === "session" && this.noMoreSessions || !this.authenticated) {
                        const e = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;
                        return S.channelOpenFail(t.sender, e);
                    }
                    let r = -1;
                    let n;
                    let o = false;
                    let a;
                    const l = () => {
                        if (o) return;
                        o = true;
                        if (n === undefined) {
                            if (r === -1) n = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else n = CHANNEL_OPEN_FAILURE.CONNECT_FAILED;
                        }
                        if (r !== -1) this._chanMgr.remove(r);
                        S.channelOpenFail(t.sender, n, "");
                    };
                    const c = () => {
                        r = this._chanMgr.add();
                        if (r === -1) {
                            n = CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE;
                            if (s) {
                                s("Automatic rejection of incoming channel open: " + "no channels available");
                            }
                        }
                        return r !== -1;
                    };
                    const u = t.data;
                    switch (t.type) {
                      case "session":
                        if (listenerCount(this, "session") && c()) {
                            a = () => {
                                if (o) return;
                                o = true;
                                const e = new Session(this, t, r);
                                this._chanMgr.update(r, e);
                                S.channelOpenConfirm(t.sender, r, MAX_WINDOW, PACKET_SIZE);
                                return e;
                            };
                            this.emit("session", a, l);
                            return;
                        }
                        break;

                      case "direct-tcpip":
                        if (listenerCount(this, "tcpip") && c()) {
                            a = () => {
                                if (o) return;
                                o = true;
                                const e = {
                                    type: undefined,
                                    incoming: {
                                        id: r,
                                        window: MAX_WINDOW,
                                        packetSize: PACKET_SIZE,
                                        state: "open"
                                    },
                                    outgoing: {
                                        id: t.sender,
                                        window: t.window,
                                        packetSize: t.packetSize,
                                        state: "open"
                                    }
                                };
                                const n = new Channel(this, e, {
                                    server: true
                                });
                                this._chanMgr.update(r, n);
                                S.channelOpenConfirm(t.sender, r, MAX_WINDOW, PACKET_SIZE);
                                return n;
                            };
                            this.emit("tcpip", a, l, u);
                            return;
                        }
                        break;

                      case "direct-streamlocal@openssh.com":
                        if (listenerCount(this, "openssh.streamlocal") && c()) {
                            a = () => {
                                if (o) return;
                                o = true;
                                const e = {
                                    type: undefined,
                                    incoming: {
                                        id: r,
                                        window: MAX_WINDOW,
                                        packetSize: PACKET_SIZE,
                                        state: "open"
                                    },
                                    outgoing: {
                                        id: t.sender,
                                        window: t.window,
                                        packetSize: t.packetSize,
                                        state: "open"
                                    }
                                };
                                const n = new Channel(this, e, {
                                    server: true
                                });
                                this._chanMgr.update(r, n);
                                S.channelOpenConfirm(t.sender, r, MAX_WINDOW, PACKET_SIZE);
                                return n;
                            };
                            this.emit("openssh.streamlocal", a, l, u);
                            return;
                        }
                        break;

                      default:
                        n = CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE;
                        if (s) {
                            s("Automatic rejection of unsupported incoming channel open" + ` type: ${t.type}`);
                        }
                    }
                    if (n === undefined) {
                        n = CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED;
                        if (s) {
                            s("Automatic rejection of unexpected incoming channel open" + ` for: ${t.type}`);
                        }
                    }
                    l();
                },
                CHANNEL_OPEN_CONFIRMATION: (e, t) => {
                    const r = this._chanMgr.get(t.recipient);
                    if (typeof r !== "function") return;
                    const n = {
                        type: r.type,
                        incoming: {
                            id: t.recipient,
                            window: MAX_WINDOW,
                            packetSize: PACKET_SIZE,
                            state: "open"
                        },
                        outgoing: {
                            id: t.sender,
                            window: t.window,
                            packetSize: t.packetSize,
                            state: "open"
                        }
                    };
                    const s = new Channel(this, n, {
                        server: true
                    });
                    this._chanMgr.update(t.recipient, s);
                    r(undefined, s);
                },
                CHANNEL_OPEN_FAILURE: (e, t, r, n) => {
                    const s = this._chanMgr.get(t);
                    if (typeof s !== "function") return;
                    const o = {
                        reason: r,
                        description: n
                    };
                    onChannelOpenFailure(this, t, o, s);
                },
                CHANNEL_DATA: (e, t, r) => {
                    let n = this._chanMgr.get(t);
                    if (typeof n !== "object" || n === null) return;
                    if (n.constructor === Session) {
                        n = n._channel;
                        if (!n) return;
                    }
                    if (n.incoming.window === 0) return;
                    n.incoming.window -= r.length;
                    if (n.push(r) === false) {
                        n._waitChanDrain = true;
                        return;
                    }
                    if (n.incoming.window <= WINDOW_THRESHOLD) windowAdjust(n);
                },
                CHANNEL_EXTENDED_DATA: (e, t, r, n) => {},
                CHANNEL_WINDOW_ADJUST: (e, t, r) => {
                    let n = this._chanMgr.get(t);
                    if (typeof n !== "object" || n === null) return;
                    if (n.constructor === Session) {
                        n = n._channel;
                        if (!n) return;
                    }
                    n.outgoing.window += r;
                    if (n._waitWindow) {
                        n._waitWindow = false;
                        if (n._chunk) {
                            n._write(n._chunk, null, n._chunkcb);
                        } else if (n._chunkcb) {
                            n._chunkcb();
                        } else if (n._chunkErr) {
                            n.stderr._write(n._chunkErr, null, n._chunkcbErr);
                        } else if (n._chunkcbErr) {
                            n._chunkcbErr();
                        }
                    }
                },
                CHANNEL_SUCCESS: (e, t) => {
                    let r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    if (r.constructor === Session) {
                        r = r._channel;
                        if (!r) return;
                    }
                    if (r._callbacks.length) r._callbacks.shift()(false);
                },
                CHANNEL_FAILURE: (e, t) => {
                    let r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    if (r.constructor === Session) {
                        r = r._channel;
                        if (!r) return;
                    }
                    if (r._callbacks.length) r._callbacks.shift()(true);
                },
                CHANNEL_REQUEST: (e, t, r, n, o) => {
                    const a = this._chanMgr.get(t);
                    if (typeof a !== "object" || a === null) return;
                    let l = false;
                    let c;
                    let u;
                    if (a.constructor !== Session) {
                        if (n) S.channelFailure(a.outgoing.id);
                        return;
                    }
                    if (n) {
                        if (r !== "shell" && r !== "exec" && r !== "subsystem") {
                            c = () => {
                                if (l || a._ending || a._channel) return;
                                l = true;
                                S.channelSuccess(a._chanInfo.outgoing.id);
                            };
                        }
                        u = () => {
                            if (l || a._ending || a._channel) return;
                            l = true;
                            S.channelFailure(a._chanInfo.outgoing.id);
                        };
                    }
                    if (a._ending) {
                        u && u();
                        return;
                    }
                    switch (r) {
                      case "env":
                        if (listenerCount(a, "env")) {
                            a.emit("env", c, u, {
                                key: o.name,
                                val: o.value
                            });
                            return;
                        }
                        break;

                      case "pty-req":
                        if (listenerCount(a, "pty")) {
                            a.emit("pty", c, u, o);
                            return;
                        }
                        break;

                      case "window-change":
                        if (listenerCount(a, "window-change")) a.emit("window-change", c, u, o); else u && u();
                        break;

                      case "x11-req":
                        if (listenerCount(a, "x11")) {
                            a.emit("x11", c, u, o);
                            return;
                        }
                        break;

                      case "signal":
                        if (listenerCount(a, "signal")) {
                            a.emit("signal", c, u, {
                                name: o
                            });
                            return;
                        }
                        break;

                      case "auth-agent-req@openssh.com":
                        if (listenerCount(a, "auth-agent")) {
                            a.emit("auth-agent", c, u);
                            return;
                        }
                        break;

                      case "shell":
                        if (listenerCount(a, "shell")) {
                            c = () => {
                                if (l || a._ending || a._channel) return;
                                l = true;
                                if (n) S.channelSuccess(a._chanInfo.outgoing.id);
                                const e = new Channel(this, a._chanInfo, {
                                    server: true
                                });
                                e.subtype = a.subtype = r;
                                a._channel = e;
                                return e;
                            };
                            a.emit("shell", c, u);
                            return;
                        }
                        break;

                      case "exec":
                        if (listenerCount(a, "exec")) {
                            c = () => {
                                if (l || a._ending || a._channel) return;
                                l = true;
                                if (n) S.channelSuccess(a._chanInfo.outgoing.id);
                                const e = new Channel(this, a._chanInfo, {
                                    server: true
                                });
                                e.subtype = a.subtype = r;
                                a._channel = e;
                                return e;
                            };
                            a.emit("exec", c, u, {
                                command: o
                            });
                            return;
                        }
                        break;

                      case "subsystem":
                        {
                            let e = o === "sftp";
                            c = () => {
                                if (l || a._ending || a._channel) return;
                                l = true;
                                if (n) S.channelSuccess(a._chanInfo.outgoing.id);
                                let t;
                                if (e) {
                                    t = new SFTP(this, a._chanInfo, {
                                        server: true,
                                        debug: s
                                    });
                                } else {
                                    t = new Channel(this, a._chanInfo, {
                                        server: true
                                    });
                                    t.subtype = a.subtype = `${r}:${o}`;
                                }
                                a._channel = t;
                                return t;
                            };
                            if (o === "sftp") {
                                if (listenerCount(a, "sftp")) {
                                    a.emit("sftp", c, u);
                                    return;
                                }
                                e = false;
                            }
                            if (listenerCount(a, "subsystem")) {
                                a.emit("subsystem", c, u, {
                                    name: o
                                });
                                return;
                            }
                            break;
                        }
                    }
                    s && s(`Automatic rejection of incoming channel request: ${r}`);
                    u && u();
                },
                CHANNEL_EOF: (e, t) => {
                    let r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    if (r.constructor === Session) {
                        if (!r._ending) {
                            r._ending = true;
                            r.emit("eof");
                            r.emit("end");
                        }
                        r = r._channel;
                        if (!r) return;
                    }
                    if (r.incoming.state !== "open") return;
                    r.incoming.state = "eof";
                    if (r.readable) r.push(null);
                },
                CHANNEL_CLOSE: (e, t) => {
                    let r = this._chanMgr.get(t);
                    if (typeof r !== "object" || r === null) return;
                    if (r.constructor === Session) {
                        r._ending = true;
                        r.emit("close");
                        r = r._channel;
                        if (!r) return;
                    }
                    onCHANNEL_CLOSE(this, t, r);
                },
                SERVICE_REQUEST: (t, r) => {
                    if (l === 0 || c || this.authenticated || r !== "ssh-userauth") {
                        S.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);
                        e.end();
                        return;
                    }
                    c = true;
                    S.serviceAccept(r);
                },
                USERAUTH_REQUEST: (t, r, n, s, o) => {
                    if (l === 0 || this.authenticated || d && (d.username !== r || d.service !== n) || s !== "password" && s !== "publickey" && s !== "hostbased" && s !== "keyboard-interactive" && s !== "none" || u.length === MAX_PENDING_AUTHS) {
                        S.disconnect(DISCONNECT_REASON.PROTOCOL_ERROR);
                        e.end();
                        return;
                    } else if (n !== "ssh-connection") {
                        S.disconnect(DISCONNECT_REASON.SERVICE_NOT_AVAILABLE);
                        e.end();
                        return;
                    }
                    let a;
                    switch (s) {
                      case "keyboard-interactive":
                        a = new KeyboardAuthContext(S, r, n, s, o, A);
                        break;

                      case "publickey":
                        a = new PKAuthContext(S, r, n, s, o, A);
                        break;

                      case "hostbased":
                        a = new HostbasedAuthContext(S, r, n, s, o, A);
                        break;

                      case "password":
                        if (d && d instanceof PwdAuthContext && d._changeCb) {
                            const e = d._changeCb;
                            d._changeCb = undefined;
                            e(o.newPassword);
                            return;
                        }
                        a = new PwdAuthContext(S, r, n, s, o, A);
                        break;

                      case "none":
                        a = new AuthContext(S, r, n, s, A);
                        break;
                    }
                    if (d) {
                        if (!d._initialResponse) {
                            return u.push(a);
                        } else if (d._multistep && !d._finalResponse) {
                            d._cleanup && d._cleanup();
                            d.emit("abort");
                        }
                    }
                    d = a;
                    if (listenerCount(this, "authentication")) this.emit("authentication", d); else d.reject();
                },
                USERAUTH_INFO_RESPONSE: (e, t) => {
                    if (d && d instanceof KeyboardAuthContext) d._onInfoResponse(t);
                },
                GLOBAL_REQUEST: (e, t, r, n) => {
                    const s = {
                        type: null,
                        buf: null
                    };
                    function o(e, t) {
                        s.type = e;
                        s.buf = t;
                        b();
                    }
                    if (r) g.push(s);
                    if ((t === "tcpip-forward" || t === "cancel-tcpip-forward" || t === "no-more-sessions@openssh.com" || t === "streamlocal-forward@openssh.com" || t === "cancel-streamlocal-forward@openssh.com") && listenerCount(this, "request") && this.authenticated) {
                        let e;
                        let s;
                        if (r) {
                            let r = false;
                            e = e => {
                                if (r) return;
                                r = true;
                                let s;
                                if (t === "tcpip-forward" && n.bindPort === 0 && typeof e === "number") {
                                    s = Buffer.allocUnsafe(4);
                                    writeUInt32BE(s, e, 0);
                                }
                                o("SUCCESS", s);
                            };
                            s = () => {
                                if (r) return;
                                r = true;
                                o("FAILURE");
                            };
                        }
                        if (t === "no-more-sessions@openssh.com") {
                            this.noMoreSessions = true;
                            e && e();
                            return;
                        }
                        this.emit("request", e, s, t, n);
                    } else if (r) {
                        o("FAILURE");
                    }
                }
            }
        });
        e.pause();
        cryptoInit.then(() => {
            S.start();
            e.on("data", t => {
                try {
                    S.parse(t, 0, t.length);
                } catch (t) {
                    this.emit("error", t);
                    try {
                        if (isWritable(e)) e.end();
                    } catch {}
                }
            });
            e.resume();
        }).catch(t => {
            this.emit("error", t);
            try {
                if (isWritable(e)) e.end();
            } catch {}
        });
        e.on("error", e => {
            e.level = "socket";
            this.emit("error", e);
        }).once("end", () => {
            s && s("Socket ended");
            S.cleanup();
            this.emit("end");
        }).once("close", () => {
            s && s("Socket closed");
            S.cleanup();
            this.emit("close");
            const e = new Error("No response from server");
            this._chanMgr.cleanup(e);
        });
        const A = (e, t, r, n) => {
            if (d === e && !this.authenticated) {
                if (t) {
                    d = undefined;
                    this.authenticated = true;
                    S.authSuccess();
                    u = [];
                    this.emit("ready");
                } else {
                    S.authFailure(r, n);
                    if (u.length) {
                        d = u.pop();
                        if (listenerCount(this, "authentication")) this.emit("authentication", d); else d.reject();
                    }
                }
            }
        };
        function b() {
            while (g.length > 0 && g[0].type) {
                const e = g.shift();
                if (e.type === "SUCCESS") S.requestSuccess(e.buf);
                if (e.type === "FAILURE") S.requestFailure();
            }
        }
    }
    end() {
        if (this._sock && isWritable(this._sock)) {
            this._protocol.disconnect(DISCONNECT_REASON.BY_APPLICATION);
            this._sock.end();
        }
        return this;
    }
    x11(e, t, r) {
        const n = {
            originAddr: e,
            originPort: t
        };
        openChannel(this, "x11", n, r);
        return this;
    }
    forwardOut(e, t, r, n, s) {
        const o = {
            boundAddr: e,
            boundPort: t,
            remoteAddr: r,
            remotePort: n
        };
        openChannel(this, "forwarded-tcpip", o, s);
        return this;
    }
    openssh_forwardOutStreamLocal(e, t) {
        const r = {
            socketPath: e
        };
        openChannel(this, "forwarded-streamlocal@openssh.com", r, t);
        return this;
    }
    rekey(e) {
        let t;
        try {
            this._protocol.rekey();
        } catch (e) {
            t = e;
        }
        if (typeof e === "function") {
            if (t) process.nextTick(e, t); else this.once("rekey", e);
        }
    }
    setNoDelay(e) {
        if (this._sock && typeof this._sock.setNoDelay === "function") this._sock.setNoDelay(e);
        return this;
    }
};

function openChannel(e, t, r, n) {
    const s = MAX_WINDOW;
    const o = PACKET_SIZE;
    if (typeof r === "function") {
        n = r;
        r = {};
    }
    const a = (e, t) => {
        n(e, t);
    };
    a.type = t;
    const l = e._chanMgr.add(a);
    if (l === -1) {
        n(new Error("No free channels available"));
        return;
    }
    switch (t) {
      case "forwarded-tcpip":
        e._protocol.forwardedTcpip(l, s, o, r);
        break;

      case "x11":
        e._protocol.x11(l, s, o, r);
        break;

      case "forwarded-streamlocal@openssh.com":
        e._protocol.openssh_forwardedStreamLocal(l, s, o, r);
        break;

      default:
        throw new Error(`Unsupported channel type: ${t}`);
    }
}

function compareNumbers(e, t) {
    return e - t;
}

server$1.exports = Server$1;

server$1.exports.IncomingClient = Client$1;

var serverExports = server$1.exports;

const {createCipheriv: createCipheriv, generateKeyPair: generateKeyPair_, generateKeyPairSync: generateKeyPairSync_, getCurves: getCurves, randomBytes: randomBytes} = require$$0__default$3.default;

const {Ber: Ber} = lib$1;

const bcrypt_pbkdf = bcryptPbkdf.pbkdf;

const {CIPHER_INFO: CIPHER_INFO} = requireCrypto();

const SALT_LEN = 16;

const DEFAULT_ROUNDS = 16;

const curves = getCurves();

const ciphers = new Map(Object.entries(CIPHER_INFO));

function makeArgs(e, t) {
    if (typeof e !== "string") throw new TypeError("Key type must be a string");
    const r = {
        type: "spki",
        format: "der"
    };
    const n = {
        type: "pkcs8",
        format: "der"
    };
    switch (e.toLowerCase()) {
      case "rsa":
        {
            if (typeof t !== "object" || t === null) throw new TypeError("Missing options object for RSA key");
            const e = t.bits;
            if (!Number.isInteger(e)) throw new TypeError("RSA bits must be an integer");
            if (e <= 0 || e > 16384) throw new RangeError("RSA bits must be non-zero and <= 16384");
            return [ "rsa", {
                modulusLength: e,
                publicKeyEncoding: r,
                privateKeyEncoding: n
            } ];
        }

      case "ecdsa":
        {
            if (typeof t !== "object" || t === null) throw new TypeError("Missing options object for ECDSA key");
            if (!Number.isInteger(t.bits)) throw new TypeError("ECDSA bits must be an integer");
            let e;
            switch (t.bits) {
              case 256:
                e = "prime256v1";
                break;

              case 384:
                e = "secp384r1";
                break;

              case 521:
                e = "secp521r1";
                break;

              default:
                throw new Error("ECDSA bits must be 256, 384, or 521");
            }
            if (!curves.includes(e)) throw new Error("Unsupported ECDSA bits value");
            return [ "ec", {
                namedCurve: e,
                publicKeyEncoding: r,
                privateKeyEncoding: n
            } ];
        }

      case "ed25519":
        return [ "ed25519", {
            publicKeyEncoding: r,
            privateKeyEncoding: n
        } ];

      default:
        throw new Error(`Unsupported key type: ${e}`);
    }
}

function parseDERs(e, t, r) {
    switch (e) {
      case "rsa":
        {
            let e = new Ber.Reader(r);
            e.readSequence();
            if (e.readInt() !== 0) throw new Error("Unsupported version in RSA private key");
            e.readSequence();
            if (e.readOID() !== "1.2.840.113549.1.1.1") throw new Error("Bad RSA private OID");
            if (e.readByte() !== Ber.Null) throw new Error("Malformed RSA private key (expected null)");
            if (e.readByte() !== 0) {
                throw new Error("Malformed RSA private key (expected zero-length null)");
            }
            e = new Ber.Reader(e.readString(Ber.OctetString, true));
            e.readSequence();
            if (e.readInt() !== 0) throw new Error("Unsupported version in RSA private key");
            const t = e.readString(Ber.Integer, true);
            const n = e.readString(Ber.Integer, true);
            const s = e.readString(Ber.Integer, true);
            const o = e.readString(Ber.Integer, true);
            const a = e.readString(Ber.Integer, true);
            e.readString(Ber.Integer, true);
            e.readString(Ber.Integer, true);
            const l = e.readString(Ber.Integer, true);
            const c = Buffer.from("ssh-rsa");
            const u = Buffer.allocUnsafe(4 + c.length + 4 + t.length + 4 + n.length + 4 + s.length + 4 + l.length + 4 + o.length + 4 + a.length);
            let d = 0;
            u.writeUInt32BE(c.length, d += 0);
            u.set(c, d += 4);
            u.writeUInt32BE(t.length, d += c.length);
            u.set(t, d += 4);
            u.writeUInt32BE(n.length, d += t.length);
            u.set(n, d += 4);
            u.writeUInt32BE(s.length, d += n.length);
            u.set(s, d += 4);
            u.writeUInt32BE(l.length, d += s.length);
            u.set(l, d += 4);
            u.writeUInt32BE(o.length, d += l.length);
            u.set(o, d += 4);
            u.writeUInt32BE(a.length, d += o.length);
            u.set(a, d += 4);
            const h = Buffer.allocUnsafe(4 + c.length + 4 + n.length + 4 + t.length);
            d = 0;
            h.writeUInt32BE(c.length, d += 0);
            h.set(c, d += 4);
            h.writeUInt32BE(n.length, d += c.length);
            h.set(n, d += 4);
            h.writeUInt32BE(t.length, d += n.length);
            h.set(t, d += 4);
            return {
                sshName: c.toString(),
                priv: u,
                pub: h
            };
        }

      case "ec":
        {
            let e = new Ber.Reader(t);
            e.readSequence();
            e.readSequence();
            if (e.readOID() !== "1.2.840.10045.2.1") throw new Error("Bad ECDSA public OID");
            e.readOID();
            let n = e.readString(Ber.BitString, true);
            {
                let e = 0;
                for (;e < n.length && n[e] === 0; ++e) ;
                if (e > 0) n = n.slice(e);
            }
            e = new Ber.Reader(r);
            e.readSequence();
            if (e.readInt() !== 0) throw new Error("Unsupported version in ECDSA private key");
            e.readSequence();
            if (e.readOID() !== "1.2.840.10045.2.1") throw new Error("Bad ECDSA private OID");
            const s = e.readOID();
            let o;
            switch (s) {
              case "1.2.840.10045.3.1.7":
                o = "nistp256";
                break;

              case "1.3.132.0.34":
                o = "nistp384";
                break;

              case "1.3.132.0.35":
                o = "nistp521";
                break;

              default:
                throw new Error("Unsupported curve in ECDSA private key");
            }
            e = new Ber.Reader(e.readString(Ber.OctetString, true));
            e.readSequence();
            if (e.readInt() !== 1) throw new Error("Unsupported version in ECDSA private key");
            const a = Buffer.concat([ Buffer.from([ 0 ]), e.readString(Ber.OctetString, true) ]);
            const l = Buffer.from(`ecdsa-sha2-${o}`);
            o = Buffer.from(o);
            const c = Buffer.allocUnsafe(4 + l.length + 4 + o.length + 4 + n.length + 4 + a.length);
            let u = 0;
            c.writeUInt32BE(l.length, u += 0);
            c.set(l, u += 4);
            c.writeUInt32BE(o.length, u += l.length);
            c.set(o, u += 4);
            c.writeUInt32BE(n.length, u += o.length);
            c.set(n, u += 4);
            c.writeUInt32BE(a.length, u += n.length);
            c.set(a, u += 4);
            const d = Buffer.allocUnsafe(4 + l.length + 4 + o.length + 4 + n.length);
            u = 0;
            d.writeUInt32BE(l.length, u += 0);
            d.set(l, u += 4);
            d.writeUInt32BE(o.length, u += l.length);
            d.set(o, u += 4);
            d.writeUInt32BE(n.length, u += o.length);
            d.set(n, u += 4);
            return {
                sshName: l.toString(),
                priv: c,
                pub: d
            };
        }

      case "ed25519":
        {
            let e = new Ber.Reader(t);
            e.readSequence();
            e.readSequence();
            if (e.readOID() !== "1.3.101.112") throw new Error("Bad ED25519 public OID");
            let n = e.readString(Ber.BitString, true);
            {
                let e = 0;
                for (;e < n.length && n[e] === 0; ++e) ;
                if (e > 0) n = n.slice(e);
            }
            e = new Ber.Reader(r);
            e.readSequence();
            if (e.readInt() !== 0) throw new Error("Unsupported version in ED25519 private key");
            e.readSequence();
            if (e.readOID() !== "1.3.101.112") throw new Error("Bad ED25519 private OID");
            e = new Ber.Reader(e.readString(Ber.OctetString, true));
            const s = e.readString(Ber.OctetString, true);
            const o = Buffer.from("ssh-ed25519");
            const a = Buffer.allocUnsafe(4 + o.length + 4 + n.length + 4 + (s.length + n.length));
            let l = 0;
            a.writeUInt32BE(o.length, l += 0);
            a.set(o, l += 4);
            a.writeUInt32BE(n.length, l += o.length);
            a.set(n, l += 4);
            a.writeUInt32BE(s.length + n.length, l += n.length);
            a.set(s, l += 4);
            a.set(n, l += s.length);
            const c = Buffer.allocUnsafe(4 + o.length + 4 + n.length);
            l = 0;
            c.writeUInt32BE(o.length, l += 0);
            c.set(o, l += 4);
            c.writeUInt32BE(n.length, l += o.length);
            c.set(n, l += 4);
            return {
                sshName: o.toString(),
                priv: a,
                pub: c
            };
        }
    }
}

function convertKeys(e, t, r, n) {
    let s = "new";
    let o;
    let a = "";
    if (typeof n === "object" && n !== null) {
        if (typeof n.comment === "string" && n.comment) a = n.comment;
        if (typeof n.format === "string" && n.format) s = n.format;
        if (n.passphrase) {
            let e;
            if (typeof n.passphrase === "string") e = Buffer.from(n.passphrase); else if (Buffer.isBuffer(n.passphrase)) e = n.passphrase; else throw new Error("Invalid passphrase");
            if (n.cipher === undefined) throw new Error("Missing cipher name");
            const t = ciphers.get(n.cipher);
            if (t === undefined) throw new Error("Invalid cipher name");
            if (s === "new") {
                let r = DEFAULT_ROUNDS;
                if (n.rounds !== undefined) {
                    if (!Number.isInteger(n.rounds)) throw new TypeError("rounds must be an integer");
                    if (n.rounds > 0) r = n.rounds;
                }
                const s = Buffer.allocUnsafe(t.keyLen + t.ivLen);
                const a = randomBytes(SALT_LEN);
                const l = bcrypt_pbkdf(e, e.length, a, a.length, s, s.length, r);
                if (l !== 0) return new Error("Failed to generate information to encrypt key");
                const c = Buffer.allocUnsafe(4 + a.length + 4);
                {
                    let e = 0;
                    c.writeUInt32BE(a.length, e += 0);
                    c.set(a, e += 4);
                    c.writeUInt32BE(r, e += a.length);
                }
                o = {
                    cipher: t,
                    cipherName: n.cipher,
                    kdfName: "bcrypt",
                    kdfOptions: c,
                    key: s.slice(0, t.keyLen),
                    iv: s.slice(t.keyLen)
                };
            }
        }
    }
    switch (s) {
      case "new":
        {
            let n = "-----BEGIN OPENSSH PRIVATE KEY-----\n";
            let s;
            const l = Buffer.from(o ? o.cipherName : "none");
            const c = Buffer.from(o ? o.kdfName : "none");
            const u = o ? o.kdfOptions : Buffer.alloc(0);
            const d = o ? o.cipher.blockLen : 8;
            const h = parseDERs(e, t, r);
            const p = randomBytes(4);
            const g = Buffer.from(a);
            const m = 4 + 4 + h.priv.length + 4 + g.length;
            let _ = [];
            for (let e = 1; (m + _.length) % d; ++e) _.push(e & 255);
            _ = Buffer.from(_);
            let E = Buffer.allocUnsafe(m + _.length);
            let v;
            {
                let e = 0;
                E.set(p, e += 0);
                E.set(p, e += 4);
                E.set(h.priv, e += 4);
                E.writeUInt32BE(g.length, e += h.priv.length);
                E.set(g, e += 4);
                E.set(_, e += g.length);
            }
            if (o) {
                const e = {
                    authTagLength: o.cipher.authLen
                };
                const t = createCipheriv(o.cipher.sslName, o.key, o.iv, e);
                t.setAutoPadding(false);
                E = Buffer.concat([ t.update(E), t.final() ]);
                if (o.cipher.authLen > 0) v = t.getAuthTag(); else v = Buffer.alloc(0);
                o.key.fill(0);
                o.iv.fill(0);
            } else {
                v = Buffer.alloc(0);
            }
            const y = Buffer.from("openssh-key-v1\0");
            const S = Buffer.allocUnsafe(y.length + 4 + l.length + 4 + c.length + 4 + u.length + 4 + 4 + h.pub.length + 4 + E.length + v.length);
            {
                let e = 0;
                S.set(y, e += 0);
                S.writeUInt32BE(l.length, e += y.length);
                S.set(l, e += 4);
                S.writeUInt32BE(c.length, e += l.length);
                S.set(c, e += 4);
                S.writeUInt32BE(u.length, e += c.length);
                S.set(u, e += 4);
                S.writeUInt32BE(1, e += u.length);
                S.writeUInt32BE(h.pub.length, e += 4);
                S.set(h.pub, e += 4);
                S.writeUInt32BE(E.length, e += h.pub.length);
                S.set(E, e += 4);
                S.set(v, e += E.length);
            }
            {
                const e = S.base64Slice(0, S.length);
                let t = e.replace(/.{64}/g, "$&\n");
                if (e.length & 63) t += "\n";
                n += t;
            }
            {
                const e = h.pub.base64Slice(0, h.pub.length);
                s = `${h.sshName} ${e}${a ? ` ${a}` : ""}`;
            }
            n += "-----END OPENSSH PRIVATE KEY-----\n";
            return {
                private: n,
                public: s
            };
        }

      default:
        throw new Error("Invalid output key format");
    }
}

function noop$5() {}

var keygen = {
    generateKeyPair: (e, t, r) => {
        if (typeof t === "function") {
            r = t;
            t = undefined;
        }
        if (typeof r !== "function") r = noop$5;
        const n = makeArgs(e, t);
        generateKeyPair_(...n, (e, s, o) => {
            if (e) return r(e);
            let a;
            try {
                a = convertKeys(n[0], s, o, t);
            } catch (e) {
                return r(e);
            }
            r(null, a);
        });
    },
    generateKeyPairSync: (e, t) => {
        const r = makeArgs(e, t);
        const {publicKey: n, privateKey: s} = generateKeyPairSync_(...r);
        return convertKeys(r[0], n, s, t);
    }
};

const {AgentProtocol: AgentProtocol, BaseAgent: BaseAgent, createAgent: createAgent, CygwinAgent: CygwinAgent, OpenSSHAgent: OpenSSHAgent, PageantAgent: PageantAgent} = agent;

const {SSHTTPAgent: HTTPAgent, SSHTTPSAgent: HTTPSAgent} = httpAgents;

const {parseKey: parseKey} = keyParser;

const {flagsToString: flagsToString, OPEN_MODE: OPEN_MODE, STATUS_CODE: STATUS_CODE, stringToFlags: stringToFlags} = SFTP_1;

var lib = {
    AgentProtocol: AgentProtocol,
    BaseAgent: BaseAgent,
    createAgent: createAgent,
    Client: client$1,
    CygwinAgent: CygwinAgent,
    HTTPAgent: HTTPAgent,
    HTTPSAgent: HTTPSAgent,
    OpenSSHAgent: OpenSSHAgent,
    PageantAgent: PageantAgent,
    Server: serverExports,
    utils: {
        parseKey: parseKey,
        ...keygen,
        sftp: {
            flagsToString: flagsToString,
            OPEN_MODE: OPEN_MODE,
            STATUS_CODE: STATUS_CODE,
            stringToFlags: stringToFlags
        }
    }
};

var Client = lib.Client, http$2 = require$$1__default.default;

var ssh$1 = function(e) {
    var t = new Client;
    var r = new http$2.Agent;
    r.createConnection = function(s, o) {
        try {
            t.once("ready", function() {
                t.exec("docker system dial-stdio", function(e, s) {
                    if (e) {
                        n(e, o);
                    }
                    o(null, s);
                    s.addListener("error", e => {
                        n(e, o);
                    });
                    s.once("close", () => {
                        t.end();
                        r.destroy();
                    });
                });
            }).on("error", e => {
                n(e, o);
            }).connect(e);
            t.once("end", () => r.destroy());
        } catch (e) {
            n(e);
        }
    };
    function n(e, n) {
        t.end();
        r.destroy();
        if (n) {
            n(e);
        } else {
            throw e;
        }
    }
    return r;
};

var readable = {
    exports: {}
};

var stream$2;

var hasRequiredStream;

function requireStream() {
    if (hasRequiredStream) return stream$2;
    hasRequiredStream = 1;
    stream$2 = require$$0__default$7.default;
    return stream$2;
}

var buffer_list;

var hasRequiredBuffer_list;

function requireBuffer_list() {
    if (hasRequiredBuffer_list) return buffer_list;
    hasRequiredBuffer_list = 1;
    function e(e, t) {
        var r = Object.keys(e);
        if (Object.getOwnPropertySymbols) {
            var n = Object.getOwnPropertySymbols(e);
            t && (n = n.filter(function(t) {
                return Object.getOwnPropertyDescriptor(e, t).enumerable;
            })), r.push.apply(r, n);
        }
        return r;
    }
    function t(t) {
        for (var n = 1; n < arguments.length; n++) {
            var s = null != arguments[n] ? arguments[n] : {};
            n % 2 ? e(Object(s), true).forEach(function(e) {
                r(t, e, s[e]);
            }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(s)) : e(Object(s)).forEach(function(e) {
                Object.defineProperty(t, e, Object.getOwnPropertyDescriptor(s, e));
            });
        }
        return t;
    }
    function r(e, t, r) {
        t = a(t);
        if (t in e) {
            Object.defineProperty(e, t, {
                value: r,
                enumerable: true,
                configurable: true,
                writable: true
            });
        } else {
            e[t] = r;
        }
        return e;
    }
    function n(e, t) {
        if (!(e instanceof t)) {
            throw new TypeError("Cannot call a class as a function");
        }
    }
    function s(e, t) {
        for (var r = 0; r < t.length; r++) {
            var n = t[r];
            n.enumerable = n.enumerable || false;
            n.configurable = true;
            if ("value" in n) n.writable = true;
            Object.defineProperty(e, a(n.key), n);
        }
    }
    function o(e, t, r) {
        if (t) s(e.prototype, t);
        Object.defineProperty(e, "prototype", {
            writable: false
        });
        return e;
    }
    function a(e) {
        var t = l(e, "string");
        return typeof t === "symbol" ? t : String(t);
    }
    function l(e, t) {
        if (typeof e !== "object" || e === null) return e;
        var r = e[Symbol.toPrimitive];
        if (r !== undefined) {
            var n = r.call(e, t);
            if (typeof n !== "object") return n;
            throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return String(e);
    }
    var c = require$$0__default$1.default, u = c.Buffer;
    var d = require$$1__default$1.default, h = d.inspect;
    var p = h && h.custom || "inspect";
    function g(e, t, r) {
        u.prototype.copy.call(e, t, r);
    }
    buffer_list = function() {
        function e() {
            n(this, e);
            this.head = null;
            this.tail = null;
            this.length = 0;
        }
        o(e, [ {
            key: "push",
            value: function e(t) {
                var r = {
                    data: t,
                    next: null
                };
                if (this.length > 0) this.tail.next = r; else this.head = r;
                this.tail = r;
                ++this.length;
            }
        }, {
            key: "unshift",
            value: function e(t) {
                var r = {
                    data: t,
                    next: this.head
                };
                if (this.length === 0) this.tail = r;
                this.head = r;
                ++this.length;
            }
        }, {
            key: "shift",
            value: function e() {
                if (this.length === 0) return;
                var t = this.head.data;
                if (this.length === 1) this.head = this.tail = null; else this.head = this.head.next;
                --this.length;
                return t;
            }
        }, {
            key: "clear",
            value: function e() {
                this.head = this.tail = null;
                this.length = 0;
            }
        }, {
            key: "join",
            value: function e(t) {
                if (this.length === 0) return "";
                var r = this.head;
                var n = "" + r.data;
                while (r = r.next) n += t + r.data;
                return n;
            }
        }, {
            key: "concat",
            value: function e(t) {
                if (this.length === 0) return u.alloc(0);
                var r = u.allocUnsafe(t >>> 0);
                var n = this.head;
                var s = 0;
                while (n) {
                    g(n.data, r, s);
                    s += n.data.length;
                    n = n.next;
                }
                return r;
            }
        }, {
            key: "consume",
            value: function e(t, r) {
                var n;
                if (t < this.head.data.length) {
                    n = this.head.data.slice(0, t);
                    this.head.data = this.head.data.slice(t);
                } else if (t === this.head.data.length) {
                    n = this.shift();
                } else {
                    n = r ? this._getString(t) : this._getBuffer(t);
                }
                return n;
            }
        }, {
            key: "first",
            value: function e() {
                return this.head.data;
            }
        }, {
            key: "_getString",
            value: function e(t) {
                var r = this.head;
                var n = 1;
                var s = r.data;
                t -= s.length;
                while (r = r.next) {
                    var o = r.data;
                    var a = t > o.length ? o.length : t;
                    if (a === o.length) s += o; else s += o.slice(0, t);
                    t -= a;
                    if (t === 0) {
                        if (a === o.length) {
                            ++n;
                            if (r.next) this.head = r.next; else this.head = this.tail = null;
                        } else {
                            this.head = r;
                            r.data = o.slice(a);
                        }
                        break;
                    }
                    ++n;
                }
                this.length -= n;
                return s;
            }
        }, {
            key: "_getBuffer",
            value: function e(t) {
                var r = u.allocUnsafe(t);
                var n = this.head;
                var s = 1;
                n.data.copy(r);
                t -= n.data.length;
                while (n = n.next) {
                    var o = n.data;
                    var a = t > o.length ? o.length : t;
                    o.copy(r, r.length - t, 0, a);
                    t -= a;
                    if (t === 0) {
                        if (a === o.length) {
                            ++s;
                            if (n.next) this.head = n.next; else this.head = this.tail = null;
                        } else {
                            this.head = n;
                            n.data = o.slice(a);
                        }
                        break;
                    }
                    ++s;
                }
                this.length -= s;
                return r;
            }
        }, {
            key: p,
            value: function e(r, n) {
                return h(this, t(t({}, n), {}, {
                    depth: 0,
                    customInspect: false
                }));
            }
        } ]);
        return e;
    }();
    return buffer_list;
}

var destroy_1;

var hasRequiredDestroy;

function requireDestroy() {
    if (hasRequiredDestroy) return destroy_1;
    hasRequiredDestroy = 1;
    function e(e, n) {
        var o = this;
        var a = this._readableState && this._readableState.destroyed;
        var l = this._writableState && this._writableState.destroyed;
        if (a || l) {
            if (n) {
                n(e);
            } else if (e) {
                if (!this._writableState) {
                    process.nextTick(s, this, e);
                } else if (!this._writableState.errorEmitted) {
                    this._writableState.errorEmitted = true;
                    process.nextTick(s, this, e);
                }
            }
            return this;
        }
        if (this._readableState) {
            this._readableState.destroyed = true;
        }
        if (this._writableState) {
            this._writableState.destroyed = true;
        }
        this._destroy(e || null, function(e) {
            if (!n && e) {
                if (!o._writableState) {
                    process.nextTick(t, o, e);
                } else if (!o._writableState.errorEmitted) {
                    o._writableState.errorEmitted = true;
                    process.nextTick(t, o, e);
                } else {
                    process.nextTick(r, o);
                }
            } else if (n) {
                process.nextTick(r, o);
                n(e);
            } else {
                process.nextTick(r, o);
            }
        });
        return this;
    }
    function t(e, t) {
        s(e, t);
        r(e);
    }
    function r(e) {
        if (e._writableState && !e._writableState.emitClose) return;
        if (e._readableState && !e._readableState.emitClose) return;
        e.emit("close");
    }
    function n() {
        if (this._readableState) {
            this._readableState.destroyed = false;
            this._readableState.reading = false;
            this._readableState.ended = false;
            this._readableState.endEmitted = false;
        }
        if (this._writableState) {
            this._writableState.destroyed = false;
            this._writableState.ended = false;
            this._writableState.ending = false;
            this._writableState.finalCalled = false;
            this._writableState.prefinished = false;
            this._writableState.finished = false;
            this._writableState.errorEmitted = false;
        }
    }
    function s(e, t) {
        e.emit("error", t);
    }
    function o(e, t) {
        var r = e._readableState;
        var n = e._writableState;
        if (r && r.autoDestroy || n && n.autoDestroy) e.destroy(t); else e.emit("error", t);
    }
    destroy_1 = {
        destroy: e,
        undestroy: n,
        errorOrDestroy: o
    };
    return destroy_1;
}

var errors = {};

var hasRequiredErrors;

function requireErrors() {
    if (hasRequiredErrors) return errors;
    hasRequiredErrors = 1;
    const e = {};
    function t(t, r, n) {
        if (!n) {
            n = Error;
        }
        function s(e, t, n) {
            if (typeof r === "string") {
                return r;
            } else {
                return r(e, t, n);
            }
        }
        class NodeError extends n {
            constructor(e, t, r) {
                super(s(e, t, r));
            }
        }
        NodeError.prototype.name = n.name;
        NodeError.prototype.code = t;
        e[t] = NodeError;
    }
    function r(e, t) {
        if (Array.isArray(e)) {
            const r = e.length;
            e = e.map(e => String(e));
            if (r > 2) {
                return `one of ${t} ${e.slice(0, r - 1).join(", ")}, or ` + e[r - 1];
            } else if (r === 2) {
                return `one of ${t} ${e[0]} or ${e[1]}`;
            } else {
                return `of ${t} ${e[0]}`;
            }
        } else {
            return `of ${t} ${String(e)}`;
        }
    }
    function n(e, t, r) {
        return e.substr(0, t.length) === t;
    }
    function s(e, t, r) {
        if (r === undefined || r > e.length) {
            r = e.length;
        }
        return e.substring(r - t.length, r) === t;
    }
    function o(e, t, r) {
        if (typeof r !== "number") {
            r = 0;
        }
        if (r + t.length > e.length) {
            return false;
        } else {
            return e.indexOf(t, r) !== -1;
        }
    }
    t("ERR_INVALID_OPT_VALUE", function(e, t) {
        return 'The value "' + t + '" is invalid for option "' + e + '"';
    }, TypeError);
    t("ERR_INVALID_ARG_TYPE", function(e, t, a) {
        let l;
        if (typeof t === "string" && n(t, "not ")) {
            l = "must not be";
            t = t.replace(/^not /, "");
        } else {
            l = "must be";
        }
        let c;
        if (s(e, " argument")) {
            c = `The ${e} ${l} ${r(t, "type")}`;
        } else {
            const n = o(e, ".") ? "property" : "argument";
            c = `The "${e}" ${n} ${l} ${r(t, "type")}`;
        }
        c += `. Received type ${typeof a}`;
        return c;
    }, TypeError);
    t("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF");
    t("ERR_METHOD_NOT_IMPLEMENTED", function(e) {
        return "The " + e + " method is not implemented";
    });
    t("ERR_STREAM_PREMATURE_CLOSE", "Premature close");
    t("ERR_STREAM_DESTROYED", function(e) {
        return "Cannot call " + e + " after a stream was destroyed";
    });
    t("ERR_MULTIPLE_CALLBACK", "Callback called multiple times");
    t("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable");
    t("ERR_STREAM_WRITE_AFTER_END", "write after end");
    t("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
    t("ERR_UNKNOWN_ENCODING", function(e) {
        return "Unknown encoding: " + e;
    }, TypeError);
    t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event");
    errors.codes = e;
    return errors;
}

var state;

var hasRequiredState;

function requireState() {
    if (hasRequiredState) return state;
    hasRequiredState = 1;
    var e = requireErrors().codes.ERR_INVALID_OPT_VALUE;
    function t(e, t, r) {
        return e.highWaterMark != null ? e.highWaterMark : t ? e[r] : null;
    }
    function r(r, n, s, o) {
        var a = t(n, o, s);
        if (a != null) {
            if (!(isFinite(a) && Math.floor(a) === a) || a < 0) {
                var l = o ? s : "highWaterMark";
                throw new e(l, a);
            }
            return Math.floor(a);
        }
        return r.objectMode ? 16 : 16 * 1024;
    }
    state = {
        getHighWaterMark: r
    };
    return state;
}

var node$1;

var hasRequiredNode;

function requireNode() {
    if (hasRequiredNode) return node$1;
    hasRequiredNode = 1;
    node$1 = require$$1__default$1.default.deprecate;
    return node$1;
}

var _stream_writable;

var hasRequired_stream_writable;

function require_stream_writable() {
    if (hasRequired_stream_writable) return _stream_writable;
    hasRequired_stream_writable = 1;
    _stream_writable = I;
    function e(e) {
        var t = this;
        this.next = null;
        this.entry = null;
        this.finish = function() {
            j(t, e);
        };
    }
    var t;
    I.WritableState = C;
    var r = {
        deprecate: requireNode()
    };
    var n = requireStream();
    var s = require$$0__default$1.default.Buffer;
    var o = (typeof _commonjsHelpers.commonjsGlobal !== "undefined" ? _commonjsHelpers.commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {};
    function a(e) {
        return s.from(e);
    }
    function l(e) {
        return s.isBuffer(e) || e instanceof o;
    }
    var c = requireDestroy();
    var u = requireState(), d = u.getHighWaterMark;
    var h = requireErrors().codes, p = h.ERR_INVALID_ARG_TYPE, g = h.ERR_METHOD_NOT_IMPLEMENTED, m = h.ERR_MULTIPLE_CALLBACK, _ = h.ERR_STREAM_CANNOT_PIPE, E = h.ERR_STREAM_DESTROYED, v = h.ERR_STREAM_NULL_VALUES, y = h.ERR_STREAM_WRITE_AFTER_END, S = h.ERR_UNKNOWN_ENCODING;
    var A = c.errorOrDestroy;
    index.requireInherits()(I, n);
    function b() {}
    function C(r, n, s) {
        t = t || require_stream_duplex();
        r = r || {};
        if (typeof s !== "boolean") s = n instanceof t;
        this.objectMode = !!r.objectMode;
        if (s) this.objectMode = this.objectMode || !!r.writableObjectMode;
        this.highWaterMark = d(this, r, "writableHighWaterMark", s);
        this.finalCalled = false;
        this.needDrain = false;
        this.ending = false;
        this.ended = false;
        this.finished = false;
        this.destroyed = false;
        var o = r.decodeStrings === false;
        this.decodeStrings = !o;
        this.defaultEncoding = r.defaultEncoding || "utf8";
        this.length = 0;
        this.writing = false;
        this.corked = 0;
        this.sync = true;
        this.bufferProcessing = false;
        this.onwrite = function(e) {
            N(n, e);
        };
        this.writecb = null;
        this.writelen = 0;
        this.bufferedRequest = null;
        this.lastBufferedRequest = null;
        this.pendingcb = 0;
        this.prefinished = false;
        this.errorEmitted = false;
        this.emitClose = r.emitClose !== false;
        this.autoDestroy = !!r.autoDestroy;
        this.bufferedRequestCount = 0;
        this.corkedRequestsFree = new e(this);
    }
    C.prototype.getBuffer = function e() {
        var t = this.bufferedRequest;
        var r = [];
        while (t) {
            r.push(t);
            t = t.next;
        }
        return r;
    };
    (function() {
        try {
            Object.defineProperty(C.prototype, "buffer", {
                get: r.deprecate(function e() {
                    return this.getBuffer();
                }, "_writableState.buffer is deprecated. Use _writableState.getBuffer " + "instead.", "DEP0003")
            });
        } catch (e) {}
    })();
    var w;
    if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") {
        w = Function.prototype[Symbol.hasInstance];
        Object.defineProperty(I, Symbol.hasInstance, {
            value: function e(t) {
                if (w.call(this, t)) return true;
                if (this !== I) return false;
                return t && t._writableState instanceof C;
            }
        });
    } else {
        w = function e(t) {
            return t instanceof this;
        };
    }
    function I(e) {
        t = t || require_stream_duplex();
        var r = this instanceof t;
        if (!r && !w.call(I, this)) return new I(e);
        this._writableState = new C(e, this, r);
        this.writable = true;
        if (e) {
            if (typeof e.write === "function") this._write = e.write;
            if (typeof e.writev === "function") this._writev = e.writev;
            if (typeof e.destroy === "function") this._destroy = e.destroy;
            if (typeof e.final === "function") this._final = e.final;
        }
        n.call(this);
    }
    I.prototype.pipe = function() {
        A(this, new _);
    };
    function T(e, t) {
        var r = new y;
        A(e, r);
        process.nextTick(t, r);
    }
    function R(e, t, r, n) {
        var s;
        if (r === null) {
            s = new v;
        } else if (typeof r !== "string" && !t.objectMode) {
            s = new p("chunk", [ "string", "Buffer" ], r);
        }
        if (s) {
            A(e, s);
            process.nextTick(n, s);
            return false;
        }
        return true;
    }
    I.prototype.write = function(e, t, r) {
        var n = this._writableState;
        var o = false;
        var c = !n.objectMode && l(e);
        if (c && !s.isBuffer(e)) {
            e = a(e);
        }
        if (typeof t === "function") {
            r = t;
            t = null;
        }
        if (c) t = "buffer"; else if (!t) t = n.defaultEncoding;
        if (typeof r !== "function") r = b;
        if (n.ending) T(this, r); else if (c || R(this, n, e, r)) {
            n.pendingcb++;
            o = P(this, n, c, e, t, r);
        }
        return o;
    };
    I.prototype.cork = function() {
        this._writableState.corked++;
    };
    I.prototype.uncork = function() {
        var e = this._writableState;
        if (e.corked) {
            e.corked--;
            if (!e.writing && !e.corked && !e.bufferProcessing && e.bufferedRequest) U(this, e);
        }
    };
    I.prototype.setDefaultEncoding = function e(t) {
        if (typeof t === "string") t = t.toLowerCase();
        if (!([ "hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw" ].indexOf((t + "").toLowerCase()) > -1)) throw new S(t);
        this._writableState.defaultEncoding = t;
        return this;
    };
    Object.defineProperty(I.prototype, "writableBuffer", {
        enumerable: false,
        get: function e() {
            return this._writableState && this._writableState.getBuffer();
        }
    });
    function k(e, t, r) {
        if (!e.objectMode && e.decodeStrings !== false && typeof t === "string") {
            t = s.from(t, r);
        }
        return t;
    }
    Object.defineProperty(I.prototype, "writableHighWaterMark", {
        enumerable: false,
        get: function e() {
            return this._writableState.highWaterMark;
        }
    });
    function P(e, t, r, n, s, o) {
        if (!r) {
            var a = k(t, n, s);
            if (n !== a) {
                r = true;
                s = "buffer";
                n = a;
            }
        }
        var l = t.objectMode ? 1 : n.length;
        t.length += l;
        var c = t.length < t.highWaterMark;
        if (!c) t.needDrain = true;
        if (t.writing || t.corked) {
            var u = t.lastBufferedRequest;
            t.lastBufferedRequest = {
                chunk: n,
                encoding: s,
                isBuf: r,
                callback: o,
                next: null
            };
            if (u) {
                u.next = t.lastBufferedRequest;
            } else {
                t.bufferedRequest = t.lastBufferedRequest;
            }
            t.bufferedRequestCount += 1;
        } else {
            $(e, t, false, l, n, s, o);
        }
        return c;
    }
    function $(e, t, r, n, s, o, a) {
        t.writelen = n;
        t.writecb = a;
        t.writing = true;
        t.sync = true;
        if (t.destroyed) t.onwrite(new E("write")); else if (r) e._writev(s, t.onwrite); else e._write(s, o, t.onwrite);
        t.sync = false;
    }
    function O(e, t, r, n, s) {
        --t.pendingcb;
        if (r) {
            process.nextTick(s, n);
            process.nextTick(H, e, t);
            e._writableState.errorEmitted = true;
            A(e, n);
        } else {
            s(n);
            e._writableState.errorEmitted = true;
            A(e, n);
            H(e, t);
        }
    }
    function B(e) {
        e.writing = false;
        e.writecb = null;
        e.length -= e.writelen;
        e.writelen = 0;
    }
    function N(e, t) {
        var r = e._writableState;
        var n = r.sync;
        var s = r.writecb;
        if (typeof s !== "function") throw new m;
        B(r);
        if (t) O(e, r, n, t, s); else {
            var o = M(r) || e.destroyed;
            if (!o && !r.corked && !r.bufferProcessing && r.bufferedRequest) {
                U(e, r);
            }
            if (n) {
                process.nextTick(D, e, r, o, s);
            } else {
                D(e, r, o, s);
            }
        }
    }
    function D(e, t, r, n) {
        if (!r) L(e, t);
        t.pendingcb--;
        n();
        H(e, t);
    }
    function L(e, t) {
        if (t.length === 0 && t.needDrain) {
            t.needDrain = false;
            e.emit("drain");
        }
    }
    function U(t, r) {
        r.bufferProcessing = true;
        var n = r.bufferedRequest;
        if (t._writev && n && n.next) {
            var s = r.bufferedRequestCount;
            var o = new Array(s);
            var a = r.corkedRequestsFree;
            a.entry = n;
            var l = 0;
            var c = true;
            while (n) {
                o[l] = n;
                if (!n.isBuf) c = false;
                n = n.next;
                l += 1;
            }
            o.allBuffers = c;
            $(t, r, true, r.length, o, "", a.finish);
            r.pendingcb++;
            r.lastBufferedRequest = null;
            if (a.next) {
                r.corkedRequestsFree = a.next;
                a.next = null;
            } else {
                r.corkedRequestsFree = new e(r);
            }
            r.bufferedRequestCount = 0;
        } else {
            while (n) {
                var u = n.chunk;
                var d = n.encoding;
                var h = n.callback;
                var p = r.objectMode ? 1 : u.length;
                $(t, r, false, p, u, d, h);
                n = n.next;
                r.bufferedRequestCount--;
                if (r.writing) {
                    break;
                }
            }
            if (n === null) r.lastBufferedRequest = null;
        }
        r.bufferedRequest = n;
        r.bufferProcessing = false;
    }
    I.prototype._write = function(e, t, r) {
        r(new g("_write()"));
    };
    I.prototype._writev = null;
    I.prototype.end = function(e, t, r) {
        var n = this._writableState;
        if (typeof e === "function") {
            r = e;
            e = null;
            t = null;
        } else if (typeof t === "function") {
            r = t;
            t = null;
        }
        if (e !== null && e !== undefined) this.write(e, t);
        if (n.corked) {
            n.corked = 1;
            this.uncork();
        }
        if (!n.ending) W(this, n, r);
        return this;
    };
    Object.defineProperty(I.prototype, "writableLength", {
        enumerable: false,
        get: function e() {
            return this._writableState.length;
        }
    });
    function M(e) {
        return e.ending && e.length === 0 && e.bufferedRequest === null && !e.finished && !e.writing;
    }
    function x(e, t) {
        e._final(function(r) {
            t.pendingcb--;
            if (r) {
                A(e, r);
            }
            t.prefinished = true;
            e.emit("prefinish");
            H(e, t);
        });
    }
    function q(e, t) {
        if (!t.prefinished && !t.finalCalled) {
            if (typeof e._final === "function" && !t.destroyed) {
                t.pendingcb++;
                t.finalCalled = true;
                process.nextTick(x, e, t);
            } else {
                t.prefinished = true;
                e.emit("prefinish");
            }
        }
    }
    function H(e, t) {
        var r = M(t);
        if (r) {
            q(e, t);
            if (t.pendingcb === 0) {
                t.finished = true;
                e.emit("finish");
                if (t.autoDestroy) {
                    var n = e._readableState;
                    if (!n || n.autoDestroy && n.endEmitted) {
                        e.destroy();
                    }
                }
            }
        }
        return r;
    }
    function W(e, t, r) {
        t.ending = true;
        H(e, t);
        if (r) {
            if (t.finished) process.nextTick(r); else e.once("finish", r);
        }
        t.ended = true;
        e.writable = false;
    }
    function j(e, t, r) {
        var n = e.entry;
        e.entry = null;
        while (n) {
            var s = n.callback;
            t.pendingcb--;
            s(r);
            n = n.next;
        }
        t.corkedRequestsFree.next = e;
    }
    Object.defineProperty(I.prototype, "destroyed", {
        enumerable: false,
        get: function e() {
            if (this._writableState === undefined) {
                return false;
            }
            return this._writableState.destroyed;
        },
        set: function e(t) {
            if (!this._writableState) {
                return;
            }
            this._writableState.destroyed = t;
        }
    });
    I.prototype.destroy = c.destroy;
    I.prototype._undestroy = c.undestroy;
    I.prototype._destroy = function(e, t) {
        t(e);
    };
    return _stream_writable;
}

var _stream_duplex;

var hasRequired_stream_duplex;

function require_stream_duplex() {
    if (hasRequired_stream_duplex) return _stream_duplex;
    hasRequired_stream_duplex = 1;
    var e = Object.keys || function(e) {
        var t = [];
        for (var r in e) t.push(r);
        return t;
    };
    _stream_duplex = a;
    var t = require_stream_readable();
    var r = require_stream_writable();
    index.requireInherits()(a, t);
    {
        var n = e(r.prototype);
        for (var s = 0; s < n.length; s++) {
            var o = n[s];
            if (!a.prototype[o]) a.prototype[o] = r.prototype[o];
        }
    }
    function a(e) {
        if (!(this instanceof a)) return new a(e);
        t.call(this, e);
        r.call(this, e);
        this.allowHalfOpen = true;
        if (e) {
            if (e.readable === false) this.readable = false;
            if (e.writable === false) this.writable = false;
            if (e.allowHalfOpen === false) {
                this.allowHalfOpen = false;
                this.once("end", l);
            }
        }
    }
    Object.defineProperty(a.prototype, "writableHighWaterMark", {
        enumerable: false,
        get: function e() {
            return this._writableState.highWaterMark;
        }
    });
    Object.defineProperty(a.prototype, "writableBuffer", {
        enumerable: false,
        get: function e() {
            return this._writableState && this._writableState.getBuffer();
        }
    });
    Object.defineProperty(a.prototype, "writableLength", {
        enumerable: false,
        get: function e() {
            return this._writableState.length;
        }
    });
    function l() {
        if (this._writableState.ended) return;
        process.nextTick(c, this);
    }
    function c(e) {
        e.end();
    }
    Object.defineProperty(a.prototype, "destroyed", {
        enumerable: false,
        get: function e() {
            if (this._readableState === undefined || this._writableState === undefined) {
                return false;
            }
            return this._readableState.destroyed && this._writableState.destroyed;
        },
        set: function e(t) {
            if (this._readableState === undefined || this._writableState === undefined) {
                return;
            }
            this._readableState.destroyed = t;
            this._writableState.destroyed = t;
        }
    });
    return _stream_duplex;
}

var string_decoder = {};

var hasRequiredString_decoder;

function requireString_decoder() {
    if (hasRequiredString_decoder) return string_decoder;
    hasRequiredString_decoder = 1;
    var e = index.requireSafeBuffer().Buffer;
    var t = e.isEncoding || function(e) {
        e = "" + e;
        switch (e && e.toLowerCase()) {
          case "hex":
          case "utf8":
          case "utf-8":
          case "ascii":
          case "binary":
          case "base64":
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
          case "raw":
            return true;

          default:
            return false;
        }
    };
    function r(e) {
        if (!e) return "utf8";
        var t;
        while (true) {
            switch (e) {
              case "utf8":
              case "utf-8":
                return "utf8";

              case "ucs2":
              case "ucs-2":
              case "utf16le":
              case "utf-16le":
                return "utf16le";

              case "latin1":
              case "binary":
                return "latin1";

              case "base64":
              case "ascii":
              case "hex":
                return e;

              default:
                if (t) return;
                e = ("" + e).toLowerCase();
                t = true;
            }
        }
    }
    function n(n) {
        var s = r(n);
        if (typeof s !== "string" && (e.isEncoding === t || !t(n))) throw new Error("Unknown encoding: " + n);
        return s || n;
    }
    string_decoder.StringDecoder = s;
    function s(t) {
        this.encoding = n(t);
        var r;
        switch (this.encoding) {
          case "utf16le":
            this.text = h;
            this.end = p;
            r = 4;
            break;

          case "utf8":
            this.fillLast = c;
            r = 4;
            break;

          case "base64":
            this.text = g;
            this.end = m;
            r = 3;
            break;

          default:
            this.write = _;
            this.end = E;
            return;
        }
        this.lastNeed = 0;
        this.lastTotal = 0;
        this.lastChar = e.allocUnsafe(r);
    }
    s.prototype.write = function(e) {
        if (e.length === 0) return "";
        var t;
        var r;
        if (this.lastNeed) {
            t = this.fillLast(e);
            if (t === undefined) return "";
            r = this.lastNeed;
            this.lastNeed = 0;
        } else {
            r = 0;
        }
        if (r < e.length) return t ? t + this.text(e, r) : this.text(e, r);
        return t || "";
    };
    s.prototype.end = d;
    s.prototype.text = u;
    s.prototype.fillLast = function(e) {
        if (this.lastNeed <= e.length) {
            e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
            return this.lastChar.toString(this.encoding, 0, this.lastTotal);
        }
        e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e.length);
        this.lastNeed -= e.length;
    };
    function o(e) {
        if (e <= 127) return 0; else if (e >> 5 === 6) return 2; else if (e >> 4 === 14) return 3; else if (e >> 3 === 30) return 4;
        return e >> 6 === 2 ? -1 : -2;
    }
    function a(e, t, r) {
        var n = t.length - 1;
        if (n < r) return 0;
        var s = o(t[n]);
        if (s >= 0) {
            if (s > 0) e.lastNeed = s - 1;
            return s;
        }
        if (--n < r || s === -2) return 0;
        s = o(t[n]);
        if (s >= 0) {
            if (s > 0) e.lastNeed = s - 2;
            return s;
        }
        if (--n < r || s === -2) return 0;
        s = o(t[n]);
        if (s >= 0) {
            if (s > 0) {
                if (s === 2) s = 0; else e.lastNeed = s - 3;
            }
            return s;
        }
        return 0;
    }
    function l(e, t, r) {
        if ((t[0] & 192) !== 128) {
            e.lastNeed = 0;
            return "�";
        }
        if (e.lastNeed > 1 && t.length > 1) {
            if ((t[1] & 192) !== 128) {
                e.lastNeed = 1;
                return "�";
            }
            if (e.lastNeed > 2 && t.length > 2) {
                if ((t[2] & 192) !== 128) {
                    e.lastNeed = 2;
                    return "�";
                }
            }
        }
    }
    function c(e) {
        var t = this.lastTotal - this.lastNeed;
        var r = l(this, e);
        if (r !== undefined) return r;
        if (this.lastNeed <= e.length) {
            e.copy(this.lastChar, t, 0, this.lastNeed);
            return this.lastChar.toString(this.encoding, 0, this.lastTotal);
        }
        e.copy(this.lastChar, t, 0, e.length);
        this.lastNeed -= e.length;
    }
    function u(e, t) {
        var r = a(this, e, t);
        if (!this.lastNeed) return e.toString("utf8", t);
        this.lastTotal = r;
        var n = e.length - (r - this.lastNeed);
        e.copy(this.lastChar, 0, n);
        return e.toString("utf8", t, n);
    }
    function d(e) {
        var t = e && e.length ? this.write(e) : "";
        if (this.lastNeed) return t + "�";
        return t;
    }
    function h(e, t) {
        if ((e.length - t) % 2 === 0) {
            var r = e.toString("utf16le", t);
            if (r) {
                var n = r.charCodeAt(r.length - 1);
                if (n >= 55296 && n <= 56319) {
                    this.lastNeed = 2;
                    this.lastTotal = 4;
                    this.lastChar[0] = e[e.length - 2];
                    this.lastChar[1] = e[e.length - 1];
                    return r.slice(0, -1);
                }
            }
            return r;
        }
        this.lastNeed = 1;
        this.lastTotal = 2;
        this.lastChar[0] = e[e.length - 1];
        return e.toString("utf16le", t, e.length - 1);
    }
    function p(e) {
        var t = e && e.length ? this.write(e) : "";
        if (this.lastNeed) {
            var r = this.lastTotal - this.lastNeed;
            return t + this.lastChar.toString("utf16le", 0, r);
        }
        return t;
    }
    function g(e, t) {
        var r = (e.length - t) % 3;
        if (r === 0) return e.toString("base64", t);
        this.lastNeed = 3 - r;
        this.lastTotal = 3;
        if (r === 1) {
            this.lastChar[0] = e[e.length - 1];
        } else {
            this.lastChar[0] = e[e.length - 2];
            this.lastChar[1] = e[e.length - 1];
        }
        return e.toString("base64", t, e.length - r);
    }
    function m(e) {
        var t = e && e.length ? this.write(e) : "";
        if (this.lastNeed) return t + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
        return t;
    }
    function _(e) {
        return e.toString(this.encoding);
    }
    function E(e) {
        return e && e.length ? this.write(e) : "";
    }
    return string_decoder;
}

var endOfStream;

var hasRequiredEndOfStream;

function requireEndOfStream() {
    if (hasRequiredEndOfStream) return endOfStream;
    hasRequiredEndOfStream = 1;
    var e = requireErrors().codes.ERR_STREAM_PREMATURE_CLOSE;
    function t(e) {
        var t = false;
        return function() {
            if (t) return;
            t = true;
            for (var r = arguments.length, n = new Array(r), s = 0; s < r; s++) {
                n[s] = arguments[s];
            }
            e.apply(this, n);
        };
    }
    function r() {}
    function n(e) {
        return e.setHeader && typeof e.abort === "function";
    }
    function s(o, a, l) {
        if (typeof a === "function") return s(o, null, a);
        if (!a) a = {};
        l = t(l || r);
        var c = a.readable || a.readable !== false && o.readable;
        var u = a.writable || a.writable !== false && o.writable;
        var d = function e() {
            if (!o.writable) p();
        };
        var h = o._writableState && o._writableState.finished;
        var p = function e() {
            u = false;
            h = true;
            if (!c) l.call(o);
        };
        var g = o._readableState && o._readableState.endEmitted;
        var m = function e() {
            c = false;
            g = true;
            if (!u) l.call(o);
        };
        var _ = function e(t) {
            l.call(o, t);
        };
        var E = function t() {
            var r;
            if (c && !g) {
                if (!o._readableState || !o._readableState.ended) r = new e;
                return l.call(o, r);
            }
            if (u && !h) {
                if (!o._writableState || !o._writableState.ended) r = new e;
                return l.call(o, r);
            }
        };
        var v = function e() {
            o.req.on("finish", p);
        };
        if (n(o)) {
            o.on("complete", p);
            o.on("abort", E);
            if (o.req) v(); else o.on("request", v);
        } else if (u && !o._writableState) {
            o.on("end", d);
            o.on("close", d);
        }
        o.on("end", m);
        o.on("finish", p);
        if (a.error !== false) o.on("error", _);
        o.on("close", E);
        return function() {
            o.removeListener("complete", p);
            o.removeListener("abort", E);
            o.removeListener("request", v);
            if (o.req) o.req.removeListener("finish", p);
            o.removeListener("end", d);
            o.removeListener("close", d);
            o.removeListener("finish", p);
            o.removeListener("end", m);
            o.removeListener("error", _);
            o.removeListener("close", E);
        };
    }
    endOfStream = s;
    return endOfStream;
}

var async_iterator;

var hasRequiredAsync_iterator;

function requireAsync_iterator() {
    if (hasRequiredAsync_iterator) return async_iterator;
    hasRequiredAsync_iterator = 1;
    var e;
    function t(e, t, n) {
        t = r(t);
        if (t in e) {
            Object.defineProperty(e, t, {
                value: n,
                enumerable: true,
                configurable: true,
                writable: true
            });
        } else {
            e[t] = n;
        }
        return e;
    }
    function r(e) {
        var t = n(e, "string");
        return typeof t === "symbol" ? t : String(t);
    }
    function n(e, t) {
        if (typeof e !== "object" || e === null) return e;
        var r = e[Symbol.toPrimitive];
        if (r !== undefined) {
            var n = r.call(e, t);
            if (typeof n !== "object") return n;
            throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return String(e);
    }
    var s = requireEndOfStream();
    var o = Symbol("lastResolve");
    var a = Symbol("lastReject");
    var l = Symbol("error");
    var c = Symbol("ended");
    var u = Symbol("lastPromise");
    var d = Symbol("handlePromise");
    var h = Symbol("stream");
    function p(e, t) {
        return {
            value: e,
            done: t
        };
    }
    function g(e) {
        var t = e[o];
        if (t !== null) {
            var r = e[h].read();
            if (r !== null) {
                e[u] = null;
                e[o] = null;
                e[a] = null;
                t(p(r, false));
            }
        }
    }
    function m(e) {
        process.nextTick(g, e);
    }
    function _(e, t) {
        return function(r, n) {
            e.then(function() {
                if (t[c]) {
                    r(p(undefined, true));
                    return;
                }
                t[d](r, n);
            }, n);
        };
    }
    var E = Object.getPrototypeOf(function() {});
    var v = Object.setPrototypeOf((e = {
        get stream() {
            return this[h];
        },
        next: function e() {
            var t = this;
            var r = this[l];
            if (r !== null) {
                return Promise.reject(r);
            }
            if (this[c]) {
                return Promise.resolve(p(undefined, true));
            }
            if (this[h].destroyed) {
                return new Promise(function(e, r) {
                    process.nextTick(function() {
                        if (t[l]) {
                            r(t[l]);
                        } else {
                            e(p(undefined, true));
                        }
                    });
                });
            }
            var n = this[u];
            var s;
            if (n) {
                s = new Promise(_(n, this));
            } else {
                var o = this[h].read();
                if (o !== null) {
                    return Promise.resolve(p(o, false));
                }
                s = new Promise(this[d]);
            }
            this[u] = s;
            return s;
        }
    }, t(e, Symbol.asyncIterator, function() {
        return this;
    }), t(e, "return", function e() {
        var t = this;
        return new Promise(function(e, r) {
            t[h].destroy(null, function(t) {
                if (t) {
                    r(t);
                    return;
                }
                e(p(undefined, true));
            });
        });
    }), e), E);
    var y = function e(r) {
        var n;
        var g = Object.create(v, (n = {}, t(n, h, {
            value: r,
            writable: true
        }), t(n, o, {
            value: null,
            writable: true
        }), t(n, a, {
            value: null,
            writable: true
        }), t(n, l, {
            value: null,
            writable: true
        }), t(n, c, {
            value: r._readableState.endEmitted,
            writable: true
        }), t(n, d, {
            value: function e(t, r) {
                var n = g[h].read();
                if (n) {
                    g[u] = null;
                    g[o] = null;
                    g[a] = null;
                    t(p(n, false));
                } else {
                    g[o] = t;
                    g[a] = r;
                }
            },
            writable: true
        }), n));
        g[u] = null;
        s(r, function(e) {
            if (e && e.code !== "ERR_STREAM_PREMATURE_CLOSE") {
                var t = g[a];
                if (t !== null) {
                    g[u] = null;
                    g[o] = null;
                    g[a] = null;
                    t(e);
                }
                g[l] = e;
                return;
            }
            var r = g[o];
            if (r !== null) {
                g[u] = null;
                g[o] = null;
                g[a] = null;
                r(p(undefined, true));
            }
            g[c] = true;
        });
        r.on("readable", m.bind(null, g));
        return g;
    };
    async_iterator = y;
    return async_iterator;
}

var from_1;

var hasRequiredFrom;

function requireFrom() {
    if (hasRequiredFrom) return from_1;
    hasRequiredFrom = 1;
    function e(e, t, r, n, s, o, a) {
        try {
            var l = e[o](a);
            var c = l.value;
        } catch (e) {
            r(e);
            return;
        }
        if (l.done) {
            t(c);
        } else {
            Promise.resolve(c).then(n, s);
        }
    }
    function t(t) {
        return function() {
            var r = this, n = arguments;
            return new Promise(function(s, o) {
                var a = t.apply(r, n);
                function l(t) {
                    e(a, s, o, l, c, "next", t);
                }
                function c(t) {
                    e(a, s, o, l, c, "throw", t);
                }
                l(undefined);
            });
        };
    }
    function r(e, t) {
        var r = Object.keys(e);
        if (Object.getOwnPropertySymbols) {
            var n = Object.getOwnPropertySymbols(e);
            t && (n = n.filter(function(t) {
                return Object.getOwnPropertyDescriptor(e, t).enumerable;
            })), r.push.apply(r, n);
        }
        return r;
    }
    function n(e) {
        for (var t = 1; t < arguments.length; t++) {
            var n = null != arguments[t] ? arguments[t] : {};
            t % 2 ? r(Object(n), true).forEach(function(t) {
                s(e, t, n[t]);
            }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : r(Object(n)).forEach(function(t) {
                Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
            });
        }
        return e;
    }
    function s(e, t, r) {
        t = o(t);
        if (t in e) {
            Object.defineProperty(e, t, {
                value: r,
                enumerable: true,
                configurable: true,
                writable: true
            });
        } else {
            e[t] = r;
        }
        return e;
    }
    function o(e) {
        var t = a(e, "string");
        return typeof t === "symbol" ? t : String(t);
    }
    function a(e, t) {
        if (typeof e !== "object" || e === null) return e;
        var r = e[Symbol.toPrimitive];
        if (r !== undefined) {
            var n = r.call(e, t);
            if (typeof n !== "object") return n;
            throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return String(e);
    }
    var l = requireErrors().codes.ERR_INVALID_ARG_TYPE;
    function c(e, r, s) {
        var o;
        if (r && typeof r.next === "function") {
            o = r;
        } else if (r && r[Symbol.asyncIterator]) o = r[Symbol.asyncIterator](); else if (r && r[Symbol.iterator]) o = r[Symbol.iterator](); else throw new l("iterable", [ "Iterable" ], r);
        var a = new e(n({
            objectMode: true
        }, s));
        var c = false;
        a._read = function() {
            if (!c) {
                c = true;
                u();
            }
        };
        function u() {
            return d.apply(this, arguments);
        }
        function d() {
            d = t(function*() {
                try {
                    var e = yield o.next(), t = e.value, r = e.done;
                    if (r) {
                        a.push(null);
                    } else if (a.push(yield t)) {
                        u();
                    } else {
                        c = false;
                    }
                } catch (e) {
                    a.destroy(e);
                }
            });
            return d.apply(this, arguments);
        }
        return a;
    }
    from_1 = c;
    return from_1;
}

var _stream_readable;

var hasRequired_stream_readable;

function require_stream_readable() {
    if (hasRequired_stream_readable) return _stream_readable;
    hasRequired_stream_readable = 1;
    _stream_readable = T;
    var e;
    T.ReadableState = I;
    require$$0__default$8.default.EventEmitter;
    var t = function e(t, r) {
        return t.listeners(r).length;
    };
    var r = requireStream();
    var n = require$$0__default$1.default.Buffer;
    var s = (typeof _commonjsHelpers.commonjsGlobal !== "undefined" ? _commonjsHelpers.commonjsGlobal : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {};
    function o(e) {
        return n.from(e);
    }
    function a(e) {
        return n.isBuffer(e) || e instanceof s;
    }
    var l = require$$1__default$1.default;
    var c;
    if (l && l.debuglog) {
        c = l.debuglog("stream");
    } else {
        c = function e() {};
    }
    var u = requireBuffer_list();
    var d = requireDestroy();
    var h = requireState(), p = h.getHighWaterMark;
    var g = requireErrors().codes, m = g.ERR_INVALID_ARG_TYPE, _ = g.ERR_STREAM_PUSH_AFTER_EOF, E = g.ERR_METHOD_NOT_IMPLEMENTED, v = g.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
    var y;
    var S;
    var A;
    index.requireInherits()(T, r);
    var b = d.errorOrDestroy;
    var C = [ "error", "close", "destroy", "pause", "resume" ];
    function w(e, t, r) {
        if (typeof e.prependListener === "function") return e.prependListener(t, r);
        if (!e._events || !e._events[t]) e.on(t, r); else if (Array.isArray(e._events[t])) e._events[t].unshift(r); else e._events[t] = [ r, e._events[t] ];
    }
    function I(t, r, n) {
        e = e || require_stream_duplex();
        t = t || {};
        if (typeof n !== "boolean") n = r instanceof e;
        this.objectMode = !!t.objectMode;
        if (n) this.objectMode = this.objectMode || !!t.readableObjectMode;
        this.highWaterMark = p(this, t, "readableHighWaterMark", n);
        this.buffer = new u;
        this.length = 0;
        this.pipes = null;
        this.pipesCount = 0;
        this.flowing = null;
        this.ended = false;
        this.endEmitted = false;
        this.reading = false;
        this.sync = true;
        this.needReadable = false;
        this.emittedReadable = false;
        this.readableListening = false;
        this.resumeScheduled = false;
        this.paused = true;
        this.emitClose = t.emitClose !== false;
        this.autoDestroy = !!t.autoDestroy;
        this.destroyed = false;
        this.defaultEncoding = t.defaultEncoding || "utf8";
        this.awaitDrain = 0;
        this.readingMore = false;
        this.decoder = null;
        this.encoding = null;
        if (t.encoding) {
            if (!y) y = requireString_decoder().StringDecoder;
            this.decoder = new y(t.encoding);
            this.encoding = t.encoding;
        }
    }
    function T(t) {
        e = e || require_stream_duplex();
        if (!(this instanceof T)) return new T(t);
        var n = this instanceof e;
        this._readableState = new I(t, this, n);
        this.readable = true;
        if (t) {
            if (typeof t.read === "function") this._read = t.read;
            if (typeof t.destroy === "function") this._destroy = t.destroy;
        }
        r.call(this);
    }
    Object.defineProperty(T.prototype, "destroyed", {
        enumerable: false,
        get: function e() {
            if (this._readableState === undefined) {
                return false;
            }
            return this._readableState.destroyed;
        },
        set: function e(t) {
            if (!this._readableState) {
                return;
            }
            this._readableState.destroyed = t;
        }
    });
    T.prototype.destroy = d.destroy;
    T.prototype._undestroy = d.undestroy;
    T.prototype._destroy = function(e, t) {
        t(e);
    };
    T.prototype.push = function(e, t) {
        var r = this._readableState;
        var s;
        if (!r.objectMode) {
            if (typeof e === "string") {
                t = t || r.defaultEncoding;
                if (t !== r.encoding) {
                    e = n.from(e, t);
                    t = "";
                }
                s = true;
            }
        } else {
            s = true;
        }
        return R(this, e, t, false, s);
    };
    T.prototype.unshift = function(e) {
        return R(this, e, null, true, false);
    };
    function R(e, t, r, s, a) {
        c("readableAddChunk", t);
        var l = e._readableState;
        if (t === null) {
            l.reading = false;
            N(e, l);
        } else {
            var u;
            if (!a) u = P(l, t);
            if (u) {
                b(e, u);
            } else if (l.objectMode || t && t.length > 0) {
                if (typeof t !== "string" && !l.objectMode && Object.getPrototypeOf(t) !== n.prototype) {
                    t = o(t);
                }
                if (s) {
                    if (l.endEmitted) b(e, new v); else k(e, l, t, true);
                } else if (l.ended) {
                    b(e, new _);
                } else if (l.destroyed) {
                    return false;
                } else {
                    l.reading = false;
                    if (l.decoder && !r) {
                        t = l.decoder.write(t);
                        if (l.objectMode || t.length !== 0) k(e, l, t, false); else U(e, l);
                    } else {
                        k(e, l, t, false);
                    }
                }
            } else if (!s) {
                l.reading = false;
                U(e, l);
            }
        }
        return !l.ended && (l.length < l.highWaterMark || l.length === 0);
    }
    function k(e, t, r, n) {
        if (t.flowing && t.length === 0 && !t.sync) {
            t.awaitDrain = 0;
            e.emit("data", r);
        } else {
            t.length += t.objectMode ? 1 : r.length;
            if (n) t.buffer.unshift(r); else t.buffer.push(r);
            if (t.needReadable) D(e);
        }
        U(e, t);
    }
    function P(e, t) {
        var r;
        if (!a(t) && typeof t !== "string" && t !== undefined && !e.objectMode) {
            r = new m("chunk", [ "string", "Buffer", "Uint8Array" ], t);
        }
        return r;
    }
    T.prototype.isPaused = function() {
        return this._readableState.flowing === false;
    };
    T.prototype.setEncoding = function(e) {
        if (!y) y = requireString_decoder().StringDecoder;
        var t = new y(e);
        this._readableState.decoder = t;
        this._readableState.encoding = this._readableState.decoder.encoding;
        var r = this._readableState.buffer.head;
        var n = "";
        while (r !== null) {
            n += t.write(r.data);
            r = r.next;
        }
        this._readableState.buffer.clear();
        if (n !== "") this._readableState.buffer.push(n);
        this._readableState.length = n.length;
        return this;
    };
    var $ = 1073741824;
    function O(e) {
        if (e >= $) {
            e = $;
        } else {
            e--;
            e |= e >>> 1;
            e |= e >>> 2;
            e |= e >>> 4;
            e |= e >>> 8;
            e |= e >>> 16;
            e++;
        }
        return e;
    }
    function B(e, t) {
        if (e <= 0 || t.length === 0 && t.ended) return 0;
        if (t.objectMode) return 1;
        if (e !== e) {
            if (t.flowing && t.length) return t.buffer.head.data.length; else return t.length;
        }
        if (e > t.highWaterMark) t.highWaterMark = O(e);
        if (e <= t.length) return e;
        if (!t.ended) {
            t.needReadable = true;
            return 0;
        }
        return t.length;
    }
    T.prototype.read = function(e) {
        c("read", e);
        e = parseInt(e, 10);
        var t = this._readableState;
        var r = e;
        if (e !== 0) t.emittedReadable = false;
        if (e === 0 && t.needReadable && ((t.highWaterMark !== 0 ? t.length >= t.highWaterMark : t.length > 0) || t.ended)) {
            c("read: emitReadable", t.length, t.ended);
            if (t.length === 0 && t.ended) K(this); else D(this);
            return null;
        }
        e = B(e, t);
        if (e === 0 && t.ended) {
            if (t.length === 0) K(this);
            return null;
        }
        var n = t.needReadable;
        c("need readable", n);
        if (t.length === 0 || t.length - e < t.highWaterMark) {
            n = true;
            c("length less than watermark", n);
        }
        if (t.ended || t.reading) {
            n = false;
            c("reading or ended", n);
        } else if (n) {
            c("do read");
            t.reading = true;
            t.sync = true;
            if (t.length === 0) t.needReadable = true;
            this._read(t.highWaterMark);
            t.sync = false;
            if (!t.reading) e = B(r, t);
        }
        var s;
        if (e > 0) s = G(e, t); else s = null;
        if (s === null) {
            t.needReadable = t.length <= t.highWaterMark;
            e = 0;
        } else {
            t.length -= e;
            t.awaitDrain = 0;
        }
        if (t.length === 0) {
            if (!t.ended) t.needReadable = true;
            if (r !== e && t.ended) K(this);
        }
        if (s !== null) this.emit("data", s);
        return s;
    };
    function N(e, t) {
        c("onEofChunk");
        if (t.ended) return;
        if (t.decoder) {
            var r = t.decoder.end();
            if (r && r.length) {
                t.buffer.push(r);
                t.length += t.objectMode ? 1 : r.length;
            }
        }
        t.ended = true;
        if (t.sync) {
            D(e);
        } else {
            t.needReadable = false;
            if (!t.emittedReadable) {
                t.emittedReadable = true;
                L(e);
            }
        }
    }
    function D(e) {
        var t = e._readableState;
        c("emitReadable", t.needReadable, t.emittedReadable);
        t.needReadable = false;
        if (!t.emittedReadable) {
            c("emitReadable", t.flowing);
            t.emittedReadable = true;
            process.nextTick(L, e);
        }
    }
    function L(e) {
        var t = e._readableState;
        c("emitReadable_", t.destroyed, t.length, t.ended);
        if (!t.destroyed && (t.length || t.ended)) {
            e.emit("readable");
            t.emittedReadable = false;
        }
        t.needReadable = !t.flowing && !t.ended && t.length <= t.highWaterMark;
        Q(e);
    }
    function U(e, t) {
        if (!t.readingMore) {
            t.readingMore = true;
            process.nextTick(M, e, t);
        }
    }
    function M(e, t) {
        while (!t.reading && !t.ended && (t.length < t.highWaterMark || t.flowing && t.length === 0)) {
            var r = t.length;
            c("maybeReadMore read 0");
            e.read(0);
            if (r === t.length) break;
        }
        t.readingMore = false;
    }
    T.prototype._read = function(e) {
        b(this, new E("_read()"));
    };
    T.prototype.pipe = function(e, r) {
        var n = this;
        var s = this._readableState;
        switch (s.pipesCount) {
          case 0:
            s.pipes = e;
            break;

          case 1:
            s.pipes = [ s.pipes, e ];
            break;

          default:
            s.pipes.push(e);
            break;
        }
        s.pipesCount += 1;
        c("pipe count=%d opts=%j", s.pipesCount, r);
        var o = (!r || r.end !== false) && e !== process.stdout && e !== process.stderr;
        var a = o ? u : v;
        if (s.endEmitted) process.nextTick(a); else n.once("end", a);
        e.on("unpipe", l);
        function l(e, t) {
            c("onunpipe");
            if (e === n) {
                if (t && t.hasUnpiped === false) {
                    t.hasUnpiped = true;
                    p();
                }
            }
        }
        function u() {
            c("onend");
            e.end();
        }
        var d = x(n);
        e.on("drain", d);
        var h = false;
        function p() {
            c("cleanup");
            e.removeListener("close", _);
            e.removeListener("finish", E);
            e.removeListener("drain", d);
            e.removeListener("error", m);
            e.removeListener("unpipe", l);
            n.removeListener("end", u);
            n.removeListener("end", v);
            n.removeListener("data", g);
            h = true;
            if (s.awaitDrain && (!e._writableState || e._writableState.needDrain)) d();
        }
        n.on("data", g);
        function g(t) {
            c("ondata");
            var r = e.write(t);
            c("dest.write", r);
            if (r === false) {
                if ((s.pipesCount === 1 && s.pipes === e || s.pipesCount > 1 && Y(s.pipes, e) !== -1) && !h) {
                    c("false write response, pause", s.awaitDrain);
                    s.awaitDrain++;
                }
                n.pause();
            }
        }
        function m(r) {
            c("onerror", r);
            v();
            e.removeListener("error", m);
            if (t(e, "error") === 0) b(e, r);
        }
        w(e, "error", m);
        function _() {
            e.removeListener("finish", E);
            v();
        }
        e.once("close", _);
        function E() {
            c("onfinish");
            e.removeListener("close", _);
            v();
        }
        e.once("finish", E);
        function v() {
            c("unpipe");
            n.unpipe(e);
        }
        e.emit("pipe", n);
        if (!s.flowing) {
            c("pipe resume");
            n.resume();
        }
        return e;
    };
    function x(e) {
        return function r() {
            var n = e._readableState;
            c("pipeOnDrain", n.awaitDrain);
            if (n.awaitDrain) n.awaitDrain--;
            if (n.awaitDrain === 0 && t(e, "data")) {
                n.flowing = true;
                Q(e);
            }
        };
    }
    T.prototype.unpipe = function(e) {
        var t = this._readableState;
        var r = {
            hasUnpiped: false
        };
        if (t.pipesCount === 0) return this;
        if (t.pipesCount === 1) {
            if (e && e !== t.pipes) return this;
            if (!e) e = t.pipes;
            t.pipes = null;
            t.pipesCount = 0;
            t.flowing = false;
            if (e) e.emit("unpipe", this, r);
            return this;
        }
        if (!e) {
            var n = t.pipes;
            var s = t.pipesCount;
            t.pipes = null;
            t.pipesCount = 0;
            t.flowing = false;
            for (var o = 0; o < s; o++) n[o].emit("unpipe", this, {
                hasUnpiped: false
            });
            return this;
        }
        var a = Y(t.pipes, e);
        if (a === -1) return this;
        t.pipes.splice(a, 1);
        t.pipesCount -= 1;
        if (t.pipesCount === 1) t.pipes = t.pipes[0];
        e.emit("unpipe", this, r);
        return this;
    };
    T.prototype.on = function(e, t) {
        var n = r.prototype.on.call(this, e, t);
        var s = this._readableState;
        if (e === "data") {
            s.readableListening = this.listenerCount("readable") > 0;
            if (s.flowing !== false) this.resume();
        } else if (e === "readable") {
            if (!s.endEmitted && !s.readableListening) {
                s.readableListening = s.needReadable = true;
                s.flowing = false;
                s.emittedReadable = false;
                c("on readable", s.length, s.reading);
                if (s.length) {
                    D(this);
                } else if (!s.reading) {
                    process.nextTick(H, this);
                }
            }
        }
        return n;
    };
    T.prototype.addListener = T.prototype.on;
    T.prototype.removeListener = function(e, t) {
        var n = r.prototype.removeListener.call(this, e, t);
        if (e === "readable") {
            process.nextTick(q, this);
        }
        return n;
    };
    T.prototype.removeAllListeners = function(e) {
        var t = r.prototype.removeAllListeners.apply(this, arguments);
        if (e === "readable" || e === undefined) {
            process.nextTick(q, this);
        }
        return t;
    };
    function q(e) {
        var t = e._readableState;
        t.readableListening = e.listenerCount("readable") > 0;
        if (t.resumeScheduled && !t.paused) {
            t.flowing = true;
        } else if (e.listenerCount("data") > 0) {
            e.resume();
        }
    }
    function H(e) {
        c("readable nexttick read 0");
        e.read(0);
    }
    T.prototype.resume = function() {
        var e = this._readableState;
        if (!e.flowing) {
            c("resume");
            e.flowing = !e.readableListening;
            W(this, e);
        }
        e.paused = false;
        return this;
    };
    function W(e, t) {
        if (!t.resumeScheduled) {
            t.resumeScheduled = true;
            process.nextTick(j, e, t);
        }
    }
    function j(e, t) {
        c("resume", t.reading);
        if (!t.reading) {
            e.read(0);
        }
        t.resumeScheduled = false;
        e.emit("resume");
        Q(e);
        if (t.flowing && !t.reading) e.read(0);
    }
    T.prototype.pause = function() {
        c("call pause flowing=%j", this._readableState.flowing);
        if (this._readableState.flowing !== false) {
            c("pause");
            this._readableState.flowing = false;
            this.emit("pause");
        }
        this._readableState.paused = true;
        return this;
    };
    function Q(e) {
        var t = e._readableState;
        c("flow", t.flowing);
        while (t.flowing && e.read() !== null) ;
    }
    T.prototype.wrap = function(e) {
        var t = this;
        var r = this._readableState;
        var n = false;
        e.on("end", function() {
            c("wrapped end");
            if (r.decoder && !r.ended) {
                var e = r.decoder.end();
                if (e && e.length) t.push(e);
            }
            t.push(null);
        });
        e.on("data", function(s) {
            c("wrapped data");
            if (r.decoder) s = r.decoder.write(s);
            if (r.objectMode && (s === null || s === undefined)) return; else if (!r.objectMode && (!s || !s.length)) return;
            var o = t.push(s);
            if (!o) {
                n = true;
                e.pause();
            }
        });
        for (var s in e) {
            if (this[s] === undefined && typeof e[s] === "function") {
                this[s] = function t(r) {
                    return function t() {
                        return e[r].apply(e, arguments);
                    };
                }(s);
            }
        }
        for (var o = 0; o < C.length; o++) {
            e.on(C[o], this.emit.bind(this, C[o]));
        }
        this._read = function(t) {
            c("wrapped _read", t);
            if (n) {
                n = false;
                e.resume();
            }
        };
        return this;
    };
    if (typeof Symbol === "function") {
        T.prototype[Symbol.asyncIterator] = function() {
            if (S === undefined) {
                S = requireAsync_iterator();
            }
            return S(this);
        };
    }
    Object.defineProperty(T.prototype, "readableHighWaterMark", {
        enumerable: false,
        get: function e() {
            return this._readableState.highWaterMark;
        }
    });
    Object.defineProperty(T.prototype, "readableBuffer", {
        enumerable: false,
        get: function e() {
            return this._readableState && this._readableState.buffer;
        }
    });
    Object.defineProperty(T.prototype, "readableFlowing", {
        enumerable: false,
        get: function e() {
            return this._readableState.flowing;
        },
        set: function e(t) {
            if (this._readableState) {
                this._readableState.flowing = t;
            }
        }
    });
    T._fromList = G;
    Object.defineProperty(T.prototype, "readableLength", {
        enumerable: false,
        get: function e() {
            return this._readableState.length;
        }
    });
    function G(e, t) {
        if (t.length === 0) return null;
        var r;
        if (t.objectMode) r = t.buffer.shift(); else if (!e || e >= t.length) {
            if (t.decoder) r = t.buffer.join(""); else if (t.buffer.length === 1) r = t.buffer.first(); else r = t.buffer.concat(t.length);
            t.buffer.clear();
        } else {
            r = t.buffer.consume(e, t.decoder);
        }
        return r;
    }
    function K(e) {
        var t = e._readableState;
        c("endReadable", t.endEmitted);
        if (!t.endEmitted) {
            t.ended = true;
            process.nextTick(z, t, e);
        }
    }
    function z(e, t) {
        c("endReadableNT", e.endEmitted, e.length);
        if (!e.endEmitted && e.length === 0) {
            e.endEmitted = true;
            t.readable = false;
            t.emit("end");
            if (e.autoDestroy) {
                var r = t._writableState;
                if (!r || r.autoDestroy && r.finished) {
                    t.destroy();
                }
            }
        }
    }
    if (typeof Symbol === "function") {
        T.from = function(e, t) {
            if (A === undefined) {
                A = requireFrom();
            }
            return A(T, e, t);
        };
    }
    function Y(e, t) {
        for (var r = 0, n = e.length; r < n; r++) {
            if (e[r] === t) return r;
        }
        return -1;
    }
    return _stream_readable;
}

var _stream_transform;

var hasRequired_stream_transform;

function require_stream_transform() {
    if (hasRequired_stream_transform) return _stream_transform;
    hasRequired_stream_transform = 1;
    _stream_transform = l;
    var e = requireErrors().codes, t = e.ERR_METHOD_NOT_IMPLEMENTED, r = e.ERR_MULTIPLE_CALLBACK, n = e.ERR_TRANSFORM_ALREADY_TRANSFORMING, s = e.ERR_TRANSFORM_WITH_LENGTH_0;
    var o = require_stream_duplex();
    index.requireInherits()(l, o);
    function a(e, t) {
        var n = this._transformState;
        n.transforming = false;
        var s = n.writecb;
        if (s === null) {
            return this.emit("error", new r);
        }
        n.writechunk = null;
        n.writecb = null;
        if (t != null) this.push(t);
        s(e);
        var o = this._readableState;
        o.reading = false;
        if (o.needReadable || o.length < o.highWaterMark) {
            this._read(o.highWaterMark);
        }
    }
    function l(e) {
        if (!(this instanceof l)) return new l(e);
        o.call(this, e);
        this._transformState = {
            afterTransform: a.bind(this),
            needTransform: false,
            transforming: false,
            writecb: null,
            writechunk: null,
            writeencoding: null
        };
        this._readableState.needReadable = true;
        this._readableState.sync = false;
        if (e) {
            if (typeof e.transform === "function") this._transform = e.transform;
            if (typeof e.flush === "function") this._flush = e.flush;
        }
        this.on("prefinish", c);
    }
    function c() {
        var e = this;
        if (typeof this._flush === "function" && !this._readableState.destroyed) {
            this._flush(function(t, r) {
                u(e, t, r);
            });
        } else {
            u(this, null, null);
        }
    }
    l.prototype.push = function(e, t) {
        this._transformState.needTransform = false;
        return o.prototype.push.call(this, e, t);
    };
    l.prototype._transform = function(e, r, n) {
        n(new t("_transform()"));
    };
    l.prototype._write = function(e, t, r) {
        var n = this._transformState;
        n.writecb = r;
        n.writechunk = e;
        n.writeencoding = t;
        if (!n.transforming) {
            var s = this._readableState;
            if (n.needTransform || s.needReadable || s.length < s.highWaterMark) this._read(s.highWaterMark);
        }
    };
    l.prototype._read = function(e) {
        var t = this._transformState;
        if (t.writechunk !== null && !t.transforming) {
            t.transforming = true;
            this._transform(t.writechunk, t.writeencoding, t.afterTransform);
        } else {
            t.needTransform = true;
        }
    };
    l.prototype._destroy = function(e, t) {
        o.prototype._destroy.call(this, e, function(e) {
            t(e);
        });
    };
    function u(e, t, r) {
        if (t) return e.emit("error", t);
        if (r != null) e.push(r);
        if (e._writableState.length) throw new s;
        if (e._transformState.transforming) throw new n;
        return e.push(null);
    }
    return _stream_transform;
}

var _stream_passthrough;

var hasRequired_stream_passthrough;

function require_stream_passthrough() {
    if (hasRequired_stream_passthrough) return _stream_passthrough;
    hasRequired_stream_passthrough = 1;
    _stream_passthrough = t;
    var e = require_stream_transform();
    index.requireInherits()(t, e);
    function t(r) {
        if (!(this instanceof t)) return new t(r);
        e.call(this, r);
    }
    t.prototype._transform = function(e, t, r) {
        r(null, e);
    };
    return _stream_passthrough;
}

var pipeline_1;

var hasRequiredPipeline;

function requirePipeline() {
    if (hasRequiredPipeline) return pipeline_1;
    hasRequiredPipeline = 1;
    var e;
    function t(e) {
        var t = false;
        return function() {
            if (t) return;
            t = true;
            e.apply(void 0, arguments);
        };
    }
    var r = requireErrors().codes, n = r.ERR_MISSING_ARGS, s = r.ERR_STREAM_DESTROYED;
    function o(e) {
        if (e) throw e;
    }
    function a(e) {
        return e.setHeader && typeof e.abort === "function";
    }
    function l(r, n, o, l) {
        l = t(l);
        var c = false;
        r.on("close", function() {
            c = true;
        });
        if (e === undefined) e = requireEndOfStream();
        e(r, {
            readable: n,
            writable: o
        }, function(e) {
            if (e) return l(e);
            c = true;
            l();
        });
        var u = false;
        return function(e) {
            if (c) return;
            if (u) return;
            u = true;
            if (a(r)) return r.abort();
            if (typeof r.destroy === "function") return r.destroy();
            l(e || new s("pipe"));
        };
    }
    function c(e) {
        e();
    }
    function u(e, t) {
        return e.pipe(t);
    }
    function d(e) {
        if (!e.length) return o;
        if (typeof e[e.length - 1] !== "function") return o;
        return e.pop();
    }
    function h() {
        for (var e = arguments.length, t = new Array(e), r = 0; r < e; r++) {
            t[r] = arguments[r];
        }
        var s = d(t);
        if (Array.isArray(t[0])) t = t[0];
        if (t.length < 2) {
            throw new n("streams");
        }
        var o;
        var a = t.map(function(e, r) {
            var n = r < t.length - 1;
            var u = r > 0;
            return l(e, n, u, function(e) {
                if (!o) o = e;
                if (e) a.forEach(c);
                if (n) return;
                a.forEach(c);
                s(o);
            });
        });
        return t.reduce(u);
    }
    pipeline_1 = h;
    return pipeline_1;
}

readable.exports;

(function(e, t) {
    var r = require$$0__default$7.default;
    if (process.env.READABLE_STREAM === "disable" && r) {
        e.exports = r.Readable;
        Object.assign(e.exports, r);
        e.exports.Stream = r;
    } else {
        t = e.exports = require_stream_readable();
        t.Stream = r || t;
        t.Readable = t;
        t.Writable = require_stream_writable();
        t.Duplex = require_stream_duplex();
        t.Transform = require_stream_transform();
        t.PassThrough = require_stream_passthrough();
        t.finished = requireEndOfStream();
        t.pipeline = requirePipeline();
    }
})(readable, readable.exports);

var readableExports = readable.exports;

var http_duplex = HttpDuplex$1;

var util$q = require$$1__default$1.default, stream$1 = readableExports;

util$q.inherits(HttpDuplex$1, stream$1.Duplex);

function HttpDuplex$1(e, t, r) {
    var n = this;
    if (!(n instanceof HttpDuplex$1)) return new HttpDuplex$1(e, t, r);
    stream$1.Duplex.call(n, r);
    n._output = null;
    n.connect(e, t);
}

HttpDuplex$1.prototype.connect = function(e, t) {
    var r = this;
    r.req = e;
    r._output = t;
    r.emit("response", t);
    t.on("data", function(e) {
        if (!r.push(e)) r._output.pause();
    });
    t.on("end", function() {
        r.push(null);
    });
};

HttpDuplex$1.prototype._read = function(e) {
    if (this._output) this._output.resume();
};

HttpDuplex$1.prototype._write = function(e, t, r) {
    this.req.write(e, t);
    r();
};

HttpDuplex$1.prototype.end = function(e, t, r) {
    this._output.socket.destroySoon();
    return this.req.end(e, t, r);
};

HttpDuplex$1.prototype.destroy = function() {
    this.req.destroy();
    this._output.socket.destroy();
};

HttpDuplex$1.prototype.destroySoon = function() {
    this.req.destroy();
    this._output.socket.destroy();
};

var fs$6 = require$$0__default$5.default;

var splitCa = function(e, t, r) {
    t = typeof t !== "undefined" ? t : "\n";
    r = typeof r !== "undefined" ? r : "utf8";
    var n = [];
    var s = fs$6.readFileSync(e, r);
    if (s.indexOf("-END CERTIFICATE-") < 0 || s.indexOf("-BEGIN CERTIFICATE-") < 0) {
        throw Error("File does not contain 'BEGIN CERTIFICATE' or 'END CERTIFICATE'");
    }
    s = s.split(t);
    var o = [];
    var a, l;
    for (a = 0, l = s.length; a < l; a++) {
        var c = s[a];
        if (!(c.length !== 0)) {
            continue;
        }
        o.push(c);
        if (c.match(/-END CERTIFICATE-/)) {
            n.push(o.join(t));
            o = [];
        }
    }
    return n;
};

var querystring = require$$0__default$9.default, http$1 = httpExports, fs$5 = require$$0__default$5.default, path$6 = require$$0__default$4.default, url = require$$4__default.default, ssh = ssh$1, HttpDuplex = http_duplex, debug = index.srcExports("modem"), utils = utils$3, util$p = require$$1__default$1.default, splitca = splitCa, os$2 = require$$1__default$2.default, isWin = os$2.type() === "Windows_NT", stream = require$$0__default$7.default;

var defaultOpts = function() {
    var e;
    var t = {};
    if (!process.env.DOCKER_HOST) {
        t.socketPath = isWin ? "//./pipe/docker_engine" : findDefaultUnixSocket;
    } else if (process.env.DOCKER_HOST.indexOf("unix://") === 0) {
        t.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket;
    } else if (process.env.DOCKER_HOST.indexOf("npipe://") === 0) {
        t.socketPath = process.env.DOCKER_HOST.substring(8) || "//./pipe/docker_engine";
    } else {
        var r = process.env.DOCKER_HOST;
        if (r.indexOf("//") < 0) {
            r = "tcp://" + r;
        }
        try {
            e = new url.URL(r);
        } catch (e) {
            throw new Error("DOCKER_HOST env variable should be something like tcp://localhost:1234");
        }
        t.port = e.port;
        if (process.env.DOCKER_TLS_VERIFY === "1" || t.port === "2376") {
            t.protocol = "https";
        } else if (e.protocol === "ssh:") {
            t.protocol = "ssh";
            t.username = e.username;
            t.sshOptions = {
                agent: process.env.SSH_AUTH_SOCK
            };
        } else {
            t.protocol = "http";
        }
        if (process.env.DOCKER_PATH_PREFIX) {
            t.pathPrefix = process.env.DOCKER_PATH_PREFIX;
        } else {
            t.pathPrefix = "/";
        }
        t.host = e.hostname;
        if (process.env.DOCKER_CERT_PATH) {
            t.ca = splitca(path$6.join(process.env.DOCKER_CERT_PATH, "ca.pem"));
            t.cert = fs$5.readFileSync(path$6.join(process.env.DOCKER_CERT_PATH, "cert.pem"));
            t.key = fs$5.readFileSync(path$6.join(process.env.DOCKER_CERT_PATH, "key.pem"));
        }
        if (process.env.DOCKER_CLIENT_TIMEOUT) {
            t.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);
        }
    }
    return t;
};

var findDefaultUnixSocket = function() {
    return new Promise(function(e) {
        var t = path$6.join(os$2.homedir(), ".docker", "run", "docker.sock");
        fs$5.access(t, function(r) {
            if (r) e("/var/run/docker.sock"); else e(t);
        });
    });
};

var Modem$1 = function(e) {
    var t = defaultOpts();
    var r = Object.assign({}, t, e);
    this.host = r.host;
    if (!this.host) {
        this.socketPath = r.socketPath;
    }
    this.port = r.port;
    this.pathPrefix = r.pathPrefix;
    this.username = r.username;
    this.password = r.password;
    this.version = r.version;
    this.key = r.key;
    this.cert = r.cert;
    this.ca = r.ca;
    this.timeout = r.timeout;
    this.connectionTimeout = r.connectionTimeout;
    this.checkServerIdentity = r.checkServerIdentity;
    this.agent = r.agent;
    this.headers = r.headers || {};
    this.sshOptions = Object.assign({}, e ? e.sshOptions : {}, t.sshOptions);
    if (this.sshOptions.agentForward === undefined) {
        this.sshOptions.agentForward = r.agentForward;
    }
    if (this.key && this.cert && this.ca) {
        this.protocol = "https";
    }
    this.protocol = r.protocol || this.protocol || "http";
};

Modem$1.prototype.dial = function(e, t) {
    var r, n, s;
    if (e.options) {
        r = e.options;
    }
    if (r && r.authconfig) {
        delete r.authconfig;
    }
    if (r && r.abortSignal) {
        delete r.abortSignal;
    }
    if (this.version) {
        e.path = "/" + this.version + e.path;
    }
    if (this.host) {
        var o = url.parse(this.host);
        n = url.format({
            protocol: o.protocol || this.protocol,
            hostname: o.hostname || this.host,
            port: this.port,
            pathname: o.pathname || this.pathPrefix
        });
        n = url.resolve(n, e.path);
    } else {
        n = e.path;
    }
    if (e.path.indexOf("?") !== -1) {
        if (r && Object.keys(r).length > 0) {
            n += this.buildQuerystring(r._query || r);
        } else {
            n = n.substring(0, n.length - 1);
        }
    }
    var a = {
        path: n,
        method: e.method,
        headers: e.headers || Object.assign({}, this.headers),
        key: this.key,
        cert: this.cert,
        ca: this.ca
    };
    if (this.checkServerIdentity) {
        a.checkServerIdentity = this.checkServerIdentity;
    }
    if (this.agent) {
        a.agent = this.agent;
    }
    if (e.authconfig) {
        a.headers["X-Registry-Auth"] = e.authconfig.key || e.authconfig.base64 || Buffer.from(JSON.stringify(e.authconfig)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_");
    }
    if (e.registryconfig) {
        a.headers["X-Registry-Config"] = e.registryconfig.base64 || Buffer.from(JSON.stringify(e.registryconfig)).toString("base64");
    }
    if (e.abortSignal) {
        a.signal = e.abortSignal;
    }
    if (e.file) {
        if (typeof e.file === "string") {
            s = fs$5.createReadStream(path$6.resolve(e.file));
        } else {
            s = e.file;
        }
        a.headers["Content-Type"] = "application/tar";
    } else if (r && e.method === "POST") {
        s = JSON.stringify(r._body || r);
        if (e.allowEmpty) {
            a.headers["Content-Type"] = "application/json";
        } else {
            if (s !== "{}" && s !== '""') {
                a.headers["Content-Type"] = "application/json";
            } else {
                s = undefined;
            }
        }
    }
    if (typeof s === "string") {
        a.headers["Content-Length"] = Buffer.byteLength(s);
    } else if (Buffer.isBuffer(s) === true) {
        a.headers["Content-Length"] = s.length;
    } else if (a.method === "PUT" || e.hijack || e.openStdin) {
        a.headers["Transfer-Encoding"] = "chunked";
    }
    if (e.hijack) {
        a.headers.Connection = "Upgrade";
        a.headers.Upgrade = a.headers.Upgrade ?? "tcp";
    }
    if (this.socketPath) {
        this.getSocketPath().then(r => {
            a.socketPath = r;
            this.buildRequest(a, e, s, t);
        });
    } else {
        var l = url.parse(n);
        a.hostname = l.hostname;
        a.port = l.port;
        a.path = l.path;
        this.buildRequest(a, e, s, t);
    }
};

Modem$1.prototype.getSocketPath = function() {
    if (!this.socketPath) return;
    if (this.socketPathCache) return Promise.resolve(this.socketPathCache);
    var e = typeof this.socketPath === "function" ? this.socketPath() : this.socketPath;
    this.socketPathCache = e;
    return Promise.resolve(e);
};

Modem$1.prototype.buildRequest = function(e, t, r, n) {
    var s = this;
    var o;
    var a = false;
    var l = s.protocol === "ssh" ? Object.assign(e, {
        agent: ssh(Object.assign({}, s.sshOptions, {
            host: s.host,
            port: s.port,
            username: s.username,
            password: s.password
        })),
        protocol: "http:"
    }) : e;
    var c = http$1[s.protocol === "ssh" ? "http" : s.protocol].request(l, function() {});
    debug("Sending: %s", util$p.inspect(e, {
        showHidden: true,
        depth: null
    }));
    if (s.connectionTimeout) {
        o = setTimeout(function() {
            debug("Connection Timeout of %s ms exceeded", s.connectionTimeout);
            c.destroy();
        }, s.connectionTimeout);
    }
    if (s.timeout) {
        c.setTimeout(s.timeout);
        c.on("timeout", function() {
            debug("Timeout of %s ms exceeded", s.timeout);
            c.destroy();
        });
    }
    if (t.hijack === true) {
        clearTimeout(o);
        c.on("upgrade", function(e, t, r) {
            if (a === false) {
                a = true;
                if (r.length > 0) {
                    t.unshift(r);
                }
                return n(null, t);
            }
        });
    }
    c.on("connect", function() {
        clearTimeout(o);
    });
    c.on("disconnect", function() {
        clearTimeout(o);
    });
    c.on("response", function(r) {
        clearTimeout(o);
        if (t.isStream === true) {
            if (a === false) {
                a = true;
                s.buildPayload(null, t.isStream, t.statusCodes, t.openStdin, c, r, null, n);
            }
        } else {
            if (e.signal != null) {
                stream.addAbortSignal(e.signal, r);
            }
            var l = [];
            r.on("data", function(e) {
                l.push(e);
            });
            r.on("end", function() {
                var e = Buffer.concat(l);
                var o = e.toString();
                debug("Received: %s", o);
                var u = utils.parseJSON(o) || e;
                if (a === false) {
                    a = true;
                    s.buildPayload(null, t.isStream, t.statusCodes, false, c, r, u, n);
                }
            });
        }
    });
    c.on("error", function(e) {
        clearTimeout(o);
        if (a === false) {
            a = true;
            s.buildPayload(e, t.isStream, t.statusCodes, false, {}, {}, null, n);
        }
    });
    if (typeof r === "string" || Buffer.isBuffer(r)) {
        c.write(r);
    } else if (r) {
        r.on("error", function(e) {
            c.destroy(e);
        });
        r.pipe(c);
    }
    if (!t.openStdin && (typeof r === "string" || r === undefined || Buffer.isBuffer(r))) {
        c.end();
    }
};

Modem$1.prototype.buildPayload = function(e, t, r, n, s, o, a, l) {
    if (e) return l(e, null);
    if (r[o.statusCode] !== true) {
        c(t, o, a, function(e, t) {
            if (e) {
                return l(e, null);
            }
            var n = new Error("(HTTP code " + o.statusCode + ") " + (r[o.statusCode] || "unexpected") + " - " + (t.message || t.error || t) + " ");
            n.reason = r[o.statusCode];
            n.statusCode = o.statusCode;
            n.json = a;
            l(n, null);
        });
    } else {
        if (n) {
            l(null, new HttpDuplex(s, o));
        } else if (t) {
            l(null, o);
        } else {
            l(null, a);
        }
    }
    function c(e, t, r, n) {
        var s = "";
        var o = false;
        if (e) {
            t.on("data", function(e) {
                s += e;
            });
            t.on("error", function(e) {
                a(e, null);
            });
            t.on("end", function() {
                a(null, utils.parseJSON(s) || s);
            });
        } else {
            n(null, r);
        }
        function a(e, t) {
            if (o === false) {
                if (e) {
                    n(e);
                } else {
                    n(null, t);
                }
            }
            o = true;
        }
    }
};

Modem$1.prototype.demuxStream = function(e, t, r) {
    var n = null;
    var s = null;
    var o = Buffer.from("");
    function a(e) {
        if (e) {
            o = Buffer.concat([ o, e ]);
        }
        if (!n) {
            if (o.length >= 8) {
                var c = l(8);
                n = c.readUInt8(0);
                s = c.readUInt32BE(4);
                a();
            }
        } else {
            if (o.length >= s) {
                var u = l(s);
                if (n === 1) {
                    t.write(u);
                } else {
                    r.write(u);
                }
                n = null;
                a();
            }
        }
    }
    function l(e) {
        var t = o.subarray(0, e);
        o = Buffer.from(o.subarray(e, o.length));
        return t;
    }
    e.on("data", a);
};

Modem$1.prototype.followProgress = function(e, t, r) {
    var n = "";
    var s = [];
    var o = false;
    e.on("data", a);
    e.on("error", l);
    e.on("end", c);
    e.on("close", c);
    function a(e) {
        n += e.toString();
        t();
        function t() {
            var e;
            while ((e = n.indexOf("\n")) >= 0) {
                if (e == 0) {
                    n = n.slice(1);
                    continue;
                }
                o(n.slice(0, e));
                n = n.slice(e + 1);
            }
        }
        function o(e) {
            if (e[e.length - 1] == "\r") e = e.substr(0, e.length - 1);
            if (e.length > 0) {
                var t = JSON.parse(e);
                s.push(t);
                if (r) {
                    r(t);
                }
            }
        }
    }
    function l(r) {
        o = true;
        e.removeListener("data", a);
        e.removeListener("error", l);
        e.removeListener("end", c);
        e.removeListener("close", c);
        t(r, s);
    }
    function c() {
        if (!o) t(null, s);
        o = true;
    }
};

Modem$1.prototype.buildQuerystring = function(e) {
    var t = {};
    Object.keys(e).map(function(r, n) {
        if (e[r] && typeof e[r] === "object" && !Array.isArray(e[r])) {
            t[r] = JSON.stringify(e[r]);
        } else {
            t[r] = e[r];
        }
    });
    return querystring.stringify(t);
};

var modem = Modem$1;

var util$o = {
    exports: {}
};

const path$5 = require$$0__default$4.default;

const factory$1 = e => new IgnoreBase(e);

factory$1.default = factory$1;

var ignore = factory$1;

function make_array(e) {
    return Array.isArray(e) ? e : [ e ];
}

const REGEX_TRAILING_SLASH = /(?<=.)\/$/;

const REGEX_TRAILING_BACKSLASH = /(?<=.)\\$/;

const REGEX_TRAILING_PATH_SEP = path$5.sep === "\\" ? REGEX_TRAILING_BACKSLASH : REGEX_TRAILING_SLASH;

const KEY_IGNORE = typeof Symbol !== "undefined" ? Symbol.for("dockerignore") : "dockerignore";

function cleanPath(e) {
    return path$5.normalize(e).replace(REGEX_TRAILING_PATH_SEP, "");
}

function toSlash(e) {
    if (path$5.sep === "/") {
        return e;
    }
    return e.replace(/\\/g, "/");
}

function fromSlash(e) {
    if (path$5.sep === "/") {
        return e;
    }
    return e.replace(/\//g, path$5.sep);
}

class IgnoreBase {
    constructor({ignorecase: e = true} = {}) {
        this._rules = [];
        this._ignorecase = e;
        this[KEY_IGNORE] = true;
        this._initCache();
    }
    _initCache() {
        this._cache = {};
    }
    add(e) {
        this._added = false;
        if (typeof e === "string") {
            e = e.split(/\r?\n/g);
        }
        make_array(e).forEach(this._addPattern, this);
        if (this._added) {
            this._initCache();
        }
        return this;
    }
    addPattern(e) {
        return this.add(e);
    }
    _addPattern(e) {
        if (e && e[KEY_IGNORE]) {
            this._rules = this._rules.concat(e._rules);
            this._added = true;
            return;
        }
        if (this._checkPattern(e)) {
            const t = this._createRule(e.trim());
            if (t !== null) {
                this._added = true;
                this._rules.push(t);
            }
        }
    }
    _checkPattern(e) {
        return e && typeof e === "string" && e.indexOf("#") !== 0 && e.trim() !== "";
    }
    filter(e) {
        return make_array(e).filter(e => this._filter(e));
    }
    createFilter() {
        return e => this._filter(e);
    }
    ignores(e) {
        return !this._filter(e);
    }
    _createRule(e) {
        const t = e;
        let r = false;
        if (e[0] === "!") {
            r = true;
            e = e.substring(1).trim();
        }
        if (e.length > 0) {
            e = cleanPath(e);
            e = toSlash(e);
            if (e.length > 1 && e[0] === "/") {
                e = e.slice(1);
            }
        }
        if (r) {
            e = "!" + e;
        }
        e = e.trim();
        if (e === "") {
            return null;
        }
        e = cleanPath(e);
        if (e[0] === "!") {
            if (e.length === 1) {
                return null;
            }
            r = true;
            e = e.substring(1);
        } else {
            r = false;
        }
        return {
            origin: t,
            pattern: e,
            dirs: e.split(path$5.sep),
            negative: r
        };
    }
    _filter(e) {
        if (!e) {
            return false;
        }
        if (e in this._cache) {
            return this._cache[e];
        }
        return this._cache[e] = this._test(e);
    }
    _test(e) {
        e = fromSlash(e);
        const t = cleanPath(path$5.dirname(e));
        const r = t.split(path$5.sep);
        let n = false;
        this._rules.forEach(s => {
            let o = this._match(e, s);
            if (!o && t !== ".") {
                if (s.dirs.includes("**")) {
                    for (let e = s.dirs.filter(e => e !== "**").length; e <= r.length; e++) {
                        o = o || this._match(r.slice(0, e).join(path$5.sep), s);
                    }
                } else if (s.dirs.length <= r.length) {
                    o = this._match(r.slice(0, s.dirs.length).join(path$5.sep), s);
                }
            }
            if (o) {
                n = !s.negative;
            }
        });
        return !n;
    }
    _match(e, t) {
        return this._compile(t).regexp.test(e);
    }
    _compile(e) {
        if (e.regexp) {
            return e;
        }
        let t = "^";
        let r = path$5.sep === "\\" ? "\\\\" : path$5.sep;
        for (let n = 0; n < e.pattern.length; n++) {
            const s = e.pattern[n];
            if (s === "*") {
                if (e.pattern[n + 1] === "*") {
                    n++;
                    if (e.pattern[n + 1] === path$5.sep) {
                        n++;
                    }
                    if (e.pattern[n + 1] === undefined) {
                        t += ".*";
                    } else {
                        t += `(.*${r})?`;
                    }
                } else {
                    t += `[^${r}]*`;
                }
            } else if (s === "?") {
                t += `[^${r}]`;
            } else if (s === "." || s === "$") {
                t += `\\${s}`;
            } else if (s === "\\") {
                if (path$5.sep === "\\") {
                    t += r;
                    continue;
                }
                if (e.pattern[n + 1] !== undefined) {
                    t += "\\" + e.pattern[n + 1];
                    n++;
                } else {
                    t += "\\";
                }
            } else {
                t += s;
            }
        }
        t += "$";
        e.regexp = new RegExp(t, this._ignorecase ? "i" : "");
        return e;
    }
}

var tarFs = {};

const fs$4 = require$$0__default$5.default;

const path$4 = require$$0__default$4.default;

const LCHOWN = fs$4.lchown ? "lchown" : "chown";

const LCHOWNSYNC = fs$4.lchownSync ? "lchownSync" : "chownSync";

const needEISDIRHandled = fs$4.lchown && !process.version.match(/v1[1-9]+\./) && !process.version.match(/v10\.[6-9]/);

const lchownSync = (e, t, r) => {
    try {
        return fs$4[LCHOWNSYNC](e, t, r);
    } catch (e) {
        if (e.code !== "ENOENT") throw e;
    }
};

const chownSync = (e, t, r) => {
    try {
        return fs$4.chownSync(e, t, r);
    } catch (e) {
        if (e.code !== "ENOENT") throw e;
    }
};

const handleEISDIR = needEISDIRHandled ? (e, t, r, n) => s => {
    if (!s || s.code !== "EISDIR") n(s); else fs$4.chown(e, t, r, n);
} : (e, t, r, n) => n;

const handleEISDirSync = needEISDIRHandled ? (e, t, r) => {
    try {
        return lchownSync(e, t, r);
    } catch (n) {
        if (n.code !== "EISDIR") throw n;
        chownSync(e, t, r);
    }
} : (e, t, r) => lchownSync(e, t, r);

const nodeVersion = process.version;

let readdir = (e, t, r) => fs$4.readdir(e, t, r);

let readdirSync = (e, t) => fs$4.readdirSync(e, t);

if (/^v4\./.test(nodeVersion)) readdir = (e, t, r) => fs$4.readdir(e, r);

const chown = (e, t, r, n) => {
    fs$4[LCHOWN](e, t, r, handleEISDIR(e, t, r, e => {
        n(e && e.code !== "ENOENT" ? e : null);
    }));
};

const chownrKid = (e, t, r, n, s) => {
    if (typeof t === "string") return fs$4.lstat(path$4.resolve(e, t), (o, a) => {
        if (o) return s(o.code !== "ENOENT" ? o : null);
        a.name = t;
        chownrKid(e, a, r, n, s);
    });
    if (t.isDirectory()) {
        chownr$1(path$4.resolve(e, t.name), r, n, o => {
            if (o) return s(o);
            const a = path$4.resolve(e, t.name);
            chown(a, r, n, s);
        });
    } else {
        const o = path$4.resolve(e, t.name);
        chown(o, r, n, s);
    }
};

const chownr$1 = (e, t, r, n) => {
    readdir(e, {
        withFileTypes: true
    }, (s, o) => {
        if (s) {
            if (s.code === "ENOENT") return n(); else if (s.code !== "ENOTDIR" && s.code !== "ENOTSUP") return n(s);
        }
        if (s || !o.length) return chown(e, t, r, n);
        let a = o.length;
        let l = null;
        const c = s => {
            if (l) return;
            if (s) return n(l = s);
            if (--a === 0) return chown(e, t, r, n);
        };
        o.forEach(n => chownrKid(e, n, t, r, c));
    });
};

const chownrKidSync = (e, t, r, n) => {
    if (typeof t === "string") {
        try {
            const r = fs$4.lstatSync(path$4.resolve(e, t));
            r.name = t;
            t = r;
        } catch (e) {
            if (e.code === "ENOENT") return; else throw e;
        }
    }
    if (t.isDirectory()) chownrSync(path$4.resolve(e, t.name), r, n);
    handleEISDirSync(path$4.resolve(e, t.name), r, n);
};

const chownrSync = (e, t, r) => {
    let n;
    try {
        n = readdirSync(e, {
            withFileTypes: true
        });
    } catch (n) {
        if (n.code === "ENOENT") return; else if (n.code === "ENOTDIR" || n.code === "ENOTSUP") return handleEISDirSync(e, t, r); else throw n;
    }
    if (n && n.length) n.forEach(n => chownrKidSync(e, n, t, r));
    return handleEISDirSync(e, t, r);
};

var chownr_1 = chownr$1;

chownr$1.sync = chownrSync;

var tarStream = {};

var bl$1 = {
    exports: {}
};

const {Buffer: Buffer$1} = require$$0__default$1.default;

const symbol = Symbol.for("BufferList");

function BufferList$1(e) {
    if (!(this instanceof BufferList$1)) {
        return new BufferList$1(e);
    }
    BufferList$1._init.call(this, e);
}

BufferList$1._init = function e(t) {
    Object.defineProperty(this, symbol, {
        value: true
    });
    this._bufs = [];
    this.length = 0;
    if (t) {
        this.append(t);
    }
};

BufferList$1.prototype._new = function e(t) {
    return new BufferList$1(t);
};

BufferList$1.prototype._offset = function e(t) {
    if (t === 0) {
        return [ 0, 0 ];
    }
    let r = 0;
    for (let e = 0; e < this._bufs.length; e++) {
        const n = r + this._bufs[e].length;
        if (t < n || e === this._bufs.length - 1) {
            return [ e, t - r ];
        }
        r = n;
    }
};

BufferList$1.prototype._reverseOffset = function(e) {
    const t = e[0];
    let r = e[1];
    for (let e = 0; e < t; e++) {
        r += this._bufs[e].length;
    }
    return r;
};

BufferList$1.prototype.get = function e(t) {
    if (t > this.length || t < 0) {
        return undefined;
    }
    const r = this._offset(t);
    return this._bufs[r[0]][r[1]];
};

BufferList$1.prototype.slice = function e(t, r) {
    if (typeof t === "number" && t < 0) {
        t += this.length;
    }
    if (typeof r === "number" && r < 0) {
        r += this.length;
    }
    return this.copy(null, 0, t, r);
};

BufferList$1.prototype.copy = function e(t, r, n, s) {
    if (typeof n !== "number" || n < 0) {
        n = 0;
    }
    if (typeof s !== "number" || s > this.length) {
        s = this.length;
    }
    if (n >= this.length) {
        return t || Buffer$1.alloc(0);
    }
    if (s <= 0) {
        return t || Buffer$1.alloc(0);
    }
    const e = !!t;
    const o = this._offset(n);
    const a = s - n;
    let l = a;
    let c = e && r || 0;
    let u = o[1];
    if (n === 0 && s === this.length) {
        if (!e) {
            return this._bufs.length === 1 ? this._bufs[0] : Buffer$1.concat(this._bufs, this.length);
        }
        for (let e = 0; e < this._bufs.length; e++) {
            this._bufs[e].copy(t, c);
            c += this._bufs[e].length;
        }
        return t;
    }
    if (l <= this._bufs[o[0]].length - u) {
        return e ? this._bufs[o[0]].copy(t, r, u, u + l) : this._bufs[o[0]].slice(u, u + l);
    }
    if (!e) {
        t = Buffer$1.allocUnsafe(a);
    }
    for (let e = o[0]; e < this._bufs.length; e++) {
        const r = this._bufs[e].length - u;
        if (l > r) {
            this._bufs[e].copy(t, c, u);
            c += r;
        } else {
            this._bufs[e].copy(t, c, u, u + l);
            c += r;
            break;
        }
        l -= r;
        if (u) {
            u = 0;
        }
    }
    if (t.length > c) return t.slice(0, c);
    return t;
};

BufferList$1.prototype.shallowSlice = function e(t, r) {
    t = t || 0;
    r = typeof r !== "number" ? this.length : r;
    if (t < 0) {
        t += this.length;
    }
    if (r < 0) {
        r += this.length;
    }
    if (t === r) {
        return this._new();
    }
    const n = this._offset(t);
    const s = this._offset(r);
    const o = this._bufs.slice(n[0], s[0] + 1);
    if (s[1] === 0) {
        o.pop();
    } else {
        o[o.length - 1] = o[o.length - 1].slice(0, s[1]);
    }
    if (n[1] !== 0) {
        o[0] = o[0].slice(n[1]);
    }
    return this._new(o);
};

BufferList$1.prototype.toString = function e(t, r, n) {
    return this.slice(r, n).toString(t);
};

BufferList$1.prototype.consume = function e(t) {
    t = Math.trunc(t);
    if (Number.isNaN(t) || t <= 0) return this;
    while (this._bufs.length) {
        if (t >= this._bufs[0].length) {
            t -= this._bufs[0].length;
            this.length -= this._bufs[0].length;
            this._bufs.shift();
        } else {
            this._bufs[0] = this._bufs[0].slice(t);
            this.length -= t;
            break;
        }
    }
    return this;
};

BufferList$1.prototype.duplicate = function e() {
    const t = this._new();
    for (let e = 0; e < this._bufs.length; e++) {
        t.append(this._bufs[e]);
    }
    return t;
};

BufferList$1.prototype.append = function e(t) {
    if (t == null) {
        return this;
    }
    if (t.buffer) {
        this._appendBuffer(Buffer$1.from(t.buffer, t.byteOffset, t.byteLength));
    } else if (Array.isArray(t)) {
        for (let e = 0; e < t.length; e++) {
            this.append(t[e]);
        }
    } else if (this._isBufferList(t)) {
        for (let e = 0; e < t._bufs.length; e++) {
            this.append(t._bufs[e]);
        }
    } else {
        if (typeof t === "number") {
            t = t.toString();
        }
        this._appendBuffer(Buffer$1.from(t));
    }
    return this;
};

BufferList$1.prototype._appendBuffer = function e(t) {
    this._bufs.push(t);
    this.length += t.length;
};

BufferList$1.prototype.indexOf = function(e, t, r) {
    if (r === undefined && typeof t === "string") {
        r = t;
        t = undefined;
    }
    if (typeof e === "function" || Array.isArray(e)) {
        throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');
    } else if (typeof e === "number") {
        e = Buffer$1.from([ e ]);
    } else if (typeof e === "string") {
        e = Buffer$1.from(e, r);
    } else if (this._isBufferList(e)) {
        e = e.slice();
    } else if (Array.isArray(e.buffer)) {
        e = Buffer$1.from(e.buffer, e.byteOffset, e.byteLength);
    } else if (!Buffer$1.isBuffer(e)) {
        e = Buffer$1.from(e);
    }
    t = Number(t || 0);
    if (isNaN(t)) {
        t = 0;
    }
    if (t < 0) {
        t = this.length + t;
    }
    if (t < 0) {
        t = 0;
    }
    if (e.length === 0) {
        return t > this.length ? this.length : t;
    }
    const n = this._offset(t);
    let s = n[0];
    let o = n[1];
    for (;s < this._bufs.length; s++) {
        const t = this._bufs[s];
        while (o < t.length) {
            const r = t.length - o;
            if (r >= e.length) {
                const r = t.indexOf(e, o);
                if (r !== -1) {
                    return this._reverseOffset([ s, r ]);
                }
                o = t.length - e.length + 1;
            } else {
                const t = this._reverseOffset([ s, o ]);
                if (this._match(t, e)) {
                    return t;
                }
                o++;
            }
        }
        o = 0;
    }
    return -1;
};

BufferList$1.prototype._match = function(e, t) {
    if (this.length - e < t.length) {
        return false;
    }
    for (let r = 0; r < t.length; r++) {
        if (this.get(e + r) !== t[r]) {
            return false;
        }
    }
    return true;
};

(function() {
    const e = {
        readDoubleBE: 8,
        readDoubleLE: 8,
        readFloatBE: 4,
        readFloatLE: 4,
        readInt32BE: 4,
        readInt32LE: 4,
        readUInt32BE: 4,
        readUInt32LE: 4,
        readInt16BE: 2,
        readInt16LE: 2,
        readUInt16BE: 2,
        readUInt16LE: 2,
        readInt8: 1,
        readUInt8: 1,
        readIntBE: null,
        readIntLE: null,
        readUIntBE: null,
        readUIntLE: null
    };
    for (const t in e) {
        (function(t) {
            if (e[t] === null) {
                BufferList$1.prototype[t] = function(e, r) {
                    return this.slice(e, e + r)[t](0, r);
                };
            } else {
                BufferList$1.prototype[t] = function(r = 0) {
                    return this.slice(r, r + e[t])[t](0);
                };
            }
        })(t);
    }
})();

BufferList$1.prototype._isBufferList = function e(t) {
    return t instanceof BufferList$1 || BufferList$1.isBufferList(t);
};

BufferList$1.isBufferList = function e(t) {
    return t != null && t[symbol];
};

var BufferList_1 = BufferList$1;

bl$1.exports;

const DuplexStream = readableExports.Duplex;

const inherits$1 = index.requireInherits();

const BufferList = BufferList_1;

function BufferListStream(e) {
    if (!(this instanceof BufferListStream)) {
        return new BufferListStream(e);
    }
    if (typeof e === "function") {
        this._callback = e;
        const t = function e(t) {
            if (this._callback) {
                this._callback(t);
                this._callback = null;
            }
        }.bind(this);
        this.on("pipe", function e(r) {
            r.on("error", t);
        });
        this.on("unpipe", function e(r) {
            r.removeListener("error", t);
        });
        e = null;
    }
    BufferList._init.call(this, e);
    DuplexStream.call(this);
}

inherits$1(BufferListStream, DuplexStream);

Object.assign(BufferListStream.prototype, BufferList.prototype);

BufferListStream.prototype._new = function e(t) {
    return new BufferListStream(t);
};

BufferListStream.prototype._write = function e(t, r, n) {
    this._appendBuffer(t);
    if (typeof n === "function") {
        n();
    }
};

BufferListStream.prototype._read = function e(t) {
    if (!this.length) {
        return this.push(null);
    }
    t = Math.min(t, this.length);
    this.push(this.slice(0, t));
    this.consume(t);
};

BufferListStream.prototype.end = function e(t) {
    DuplexStream.prototype.end.call(this, t);
    if (this._callback) {
        this._callback(null, this.slice());
        this._callback = null;
    }
};

BufferListStream.prototype._destroy = function e(t, r) {
    this._bufs.length = 0;
    this.length = 0;
    r(t);
};

BufferListStream.prototype._isBufferList = function e(t) {
    return t instanceof BufferListStream || t instanceof BufferList || BufferListStream.isBufferList(t);
};

BufferListStream.isBufferList = BufferList.isBufferList;

bl$1.exports = BufferListStream;

bl$1.exports.BufferListStream = BufferListStream;

bl$1.exports.BufferList = BufferList;

var blExports = bl$1.exports;

var headers$2 = {};

var alloc$1 = Buffer.alloc;

var ZEROS = "0000000000000000000";

var SEVENS = "7777777777777777777";

var ZERO_OFFSET = "0".charCodeAt(0);

var USTAR_MAGIC = Buffer.from("ustar\0", "binary");

var USTAR_VER = Buffer.from("00", "binary");

var GNU_MAGIC = Buffer.from("ustar ", "binary");

var GNU_VER = Buffer.from(" \0", "binary");

var MASK = parseInt("7777", 8);

var MAGIC_OFFSET = 257;

var VERSION_OFFSET = 263;

var clamp = function(e, t, r) {
    if (typeof e !== "number") return r;
    e = ~~e;
    if (e >= t) return t;
    if (e >= 0) return e;
    e += t;
    if (e >= 0) return e;
    return 0;
};

var toType = function(e) {
    switch (e) {
      case 0:
        return "file";

      case 1:
        return "link";

      case 2:
        return "symlink";

      case 3:
        return "character-device";

      case 4:
        return "block-device";

      case 5:
        return "directory";

      case 6:
        return "fifo";

      case 7:
        return "contiguous-file";

      case 72:
        return "pax-header";

      case 55:
        return "pax-global-header";

      case 27:
        return "gnu-long-link-path";

      case 28:
      case 30:
        return "gnu-long-path";
    }
    return null;
};

var toTypeflag = function(e) {
    switch (e) {
      case "file":
        return 0;

      case "link":
        return 1;

      case "symlink":
        return 2;

      case "character-device":
        return 3;

      case "block-device":
        return 4;

      case "directory":
        return 5;

      case "fifo":
        return 6;

      case "contiguous-file":
        return 7;

      case "pax-header":
        return 72;
    }
    return 0;
};

var indexOf = function(e, t, r, n) {
    for (;r < n; r++) {
        if (e[r] === t) return r;
    }
    return n;
};

var cksum = function(e) {
    var t = 8 * 32;
    for (var r = 0; r < 148; r++) t += e[r];
    for (var n = 156; n < 512; n++) t += e[n];
    return t;
};

var encodeOct = function(e, t) {
    e = e.toString(8);
    if (e.length > t) return SEVENS.slice(0, t) + " "; else return ZEROS.slice(0, t - e.length) + e + " ";
};

function parse256(e) {
    var t;
    if (e[0] === 128) t = true; else if (e[0] === 255) t = false; else return null;
    var r = [];
    for (var n = e.length - 1; n > 0; n--) {
        var s = e[n];
        if (t) r.push(s); else r.push(255 - s);
    }
    var o = 0;
    var a = r.length;
    for (n = 0; n < a; n++) {
        o += r[n] * Math.pow(256, n);
    }
    return t ? o : -1 * o;
}

var decodeOct = function(e, t, r) {
    e = e.slice(t, t + r);
    t = 0;
    if (e[t] & 128) {
        return parse256(e);
    } else {
        while (t < e.length && e[t] === 32) t++;
        var n = clamp(indexOf(e, 32, t, e.length), e.length, e.length);
        while (t < n && e[t] === 0) t++;
        if (n === t) return 0;
        return parseInt(e.slice(t, n).toString(), 8);
    }
};

var decodeStr = function(e, t, r, n) {
    return e.slice(t, indexOf(e, 0, t, t + r)).toString(n);
};

var addLength = function(e) {
    var t = Buffer.byteLength(e);
    var r = Math.floor(Math.log(t) / Math.log(10)) + 1;
    if (t + r >= Math.pow(10, r)) r++;
    return t + r + e;
};

headers$2.decodeLongPath = function(e, t) {
    return decodeStr(e, 0, e.length, t);
};

headers$2.encodePax = function(e) {
    var t = "";
    if (e.name) t += addLength(" path=" + e.name + "\n");
    if (e.linkname) t += addLength(" linkpath=" + e.linkname + "\n");
    var r = e.pax;
    if (r) {
        for (var n in r) {
            t += addLength(" " + n + "=" + r[n] + "\n");
        }
    }
    return Buffer.from(t);
};

headers$2.decodePax = function(e) {
    var t = {};
    while (e.length) {
        var r = 0;
        while (r < e.length && e[r] !== 32) r++;
        var n = parseInt(e.slice(0, r).toString(), 10);
        if (!n) return t;
        var s = e.slice(r + 1, n - 1).toString();
        var o = s.indexOf("=");
        if (o === -1) return t;
        t[s.slice(0, o)] = s.slice(o + 1);
        e = e.slice(n);
    }
    return t;
};

headers$2.encode = function(e) {
    var t = alloc$1(512);
    var r = e.name;
    var n = "";
    if (e.typeflag === 5 && r[r.length - 1] !== "/") r += "/";
    if (Buffer.byteLength(r) !== r.length) return null;
    while (Buffer.byteLength(r) > 100) {
        var s = r.indexOf("/");
        if (s === -1) return null;
        n += n ? "/" + r.slice(0, s) : r.slice(0, s);
        r = r.slice(s + 1);
    }
    if (Buffer.byteLength(r) > 100 || Buffer.byteLength(n) > 155) return null;
    if (e.linkname && Buffer.byteLength(e.linkname) > 100) return null;
    t.write(r);
    t.write(encodeOct(e.mode & MASK, 6), 100);
    t.write(encodeOct(e.uid, 6), 108);
    t.write(encodeOct(e.gid, 6), 116);
    t.write(encodeOct(e.size, 11), 124);
    t.write(encodeOct(e.mtime.getTime() / 1e3 | 0, 11), 136);
    t[156] = ZERO_OFFSET + toTypeflag(e.type);
    if (e.linkname) t.write(e.linkname, 157);
    USTAR_MAGIC.copy(t, MAGIC_OFFSET);
    USTAR_VER.copy(t, VERSION_OFFSET);
    if (e.uname) t.write(e.uname, 265);
    if (e.gname) t.write(e.gname, 297);
    t.write(encodeOct(e.devmajor || 0, 6), 329);
    t.write(encodeOct(e.devminor || 0, 6), 337);
    if (n) t.write(n, 345);
    t.write(encodeOct(cksum(t), 6), 148);
    return t;
};

headers$2.decode = function(e, t, r) {
    var n = e[156] === 0 ? 0 : e[156] - ZERO_OFFSET;
    var s = decodeStr(e, 0, 100, t);
    var o = decodeOct(e, 100, 8);
    var a = decodeOct(e, 108, 8);
    var l = decodeOct(e, 116, 8);
    var c = decodeOct(e, 124, 12);
    var u = decodeOct(e, 136, 12);
    var d = toType(n);
    var h = e[157] === 0 ? null : decodeStr(e, 157, 100, t);
    var p = decodeStr(e, 265, 32);
    var g = decodeStr(e, 297, 32);
    var m = decodeOct(e, 329, 8);
    var _ = decodeOct(e, 337, 8);
    var E = cksum(e);
    if (E === 8 * 32) return null;
    if (E !== decodeOct(e, 148, 8)) throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");
    if (USTAR_MAGIC.compare(e, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0) {
        if (e[345]) s = decodeStr(e, 345, 155, t) + "/" + s;
    } else if (GNU_MAGIC.compare(e, MAGIC_OFFSET, MAGIC_OFFSET + 6) === 0 && GNU_VER.compare(e, VERSION_OFFSET, VERSION_OFFSET + 2) === 0) ; else {
        if (!r) {
            throw new Error("Invalid tar header: unknown format.");
        }
    }
    if (n === 0 && s && s[s.length - 1] === "/") n = 5;
    return {
        name: s,
        mode: o,
        uid: a,
        gid: l,
        size: c,
        mtime: new Date(1e3 * u),
        type: d,
        linkname: h,
        uname: p,
        gname: g,
        devmajor: m,
        devminor: _
    };
};

var util$n = require$$1__default$1.default;

var bl = blExports;

var headers$1 = headers$2;

var Writable$1 = readableExports.Writable;

var PassThrough = readableExports.PassThrough;

var noop$4 = function() {};

var overflow$1 = function(e) {
    e &= 511;
    return e && 512 - e;
};

var emptyStream = function(e, t) {
    var r = new Source(e, t);
    r.end();
    return r;
};

var mixinPax = function(e, t) {
    if (t.path) e.name = t.path;
    if (t.linkpath) e.linkname = t.linkpath;
    if (t.size) e.size = parseInt(t.size, 10);
    e.pax = t;
    return e;
};

var Source = function(e, t) {
    this._parent = e;
    this.offset = t;
    PassThrough.call(this, {
        autoDestroy: false
    });
};

util$n.inherits(Source, PassThrough);

Source.prototype.destroy = function(e) {
    this._parent.destroy(e);
};

var Extract = function(e) {
    if (!(this instanceof Extract)) return new Extract(e);
    Writable$1.call(this, e);
    e = e || {};
    this._offset = 0;
    this._buffer = bl();
    this._missing = 0;
    this._partial = false;
    this._onparse = noop$4;
    this._header = null;
    this._stream = null;
    this._overflow = null;
    this._cb = null;
    this._locked = false;
    this._destroyed = false;
    this._pax = null;
    this._paxGlobal = null;
    this._gnuLongPath = null;
    this._gnuLongLinkPath = null;
    var t = this;
    var r = t._buffer;
    var n = function() {
        t._continue();
    };
    var s = function(e) {
        t._locked = false;
        if (e) return t.destroy(e);
        if (!t._stream) n();
    };
    var o = function() {
        t._stream = null;
        var e = overflow$1(t._header.size);
        if (e) t._parse(e, a); else t._parse(512, h);
        if (!t._locked) n();
    };
    var a = function() {
        t._buffer.consume(overflow$1(t._header.size));
        t._parse(512, h);
        n();
    };
    var l = function() {
        var e = t._header.size;
        t._paxGlobal = headers$1.decodePax(r.slice(0, e));
        r.consume(e);
        o();
    };
    var c = function() {
        var e = t._header.size;
        t._pax = headers$1.decodePax(r.slice(0, e));
        if (t._paxGlobal) t._pax = Object.assign({}, t._paxGlobal, t._pax);
        r.consume(e);
        o();
    };
    var u = function() {
        var n = t._header.size;
        this._gnuLongPath = headers$1.decodeLongPath(r.slice(0, n), e.filenameEncoding);
        r.consume(n);
        o();
    };
    var d = function() {
        var n = t._header.size;
        this._gnuLongLinkPath = headers$1.decodeLongPath(r.slice(0, n), e.filenameEncoding);
        r.consume(n);
        o();
    };
    var h = function() {
        var a = t._offset;
        var p;
        try {
            p = t._header = headers$1.decode(r.slice(0, 512), e.filenameEncoding, e.allowUnknownFormat);
        } catch (e) {
            t.emit("error", e);
        }
        r.consume(512);
        if (!p) {
            t._parse(512, h);
            n();
            return;
        }
        if (p.type === "gnu-long-path") {
            t._parse(p.size, u);
            n();
            return;
        }
        if (p.type === "gnu-long-link-path") {
            t._parse(p.size, d);
            n();
            return;
        }
        if (p.type === "pax-global-header") {
            t._parse(p.size, l);
            n();
            return;
        }
        if (p.type === "pax-header") {
            t._parse(p.size, c);
            n();
            return;
        }
        if (t._gnuLongPath) {
            p.name = t._gnuLongPath;
            t._gnuLongPath = null;
        }
        if (t._gnuLongLinkPath) {
            p.linkname = t._gnuLongLinkPath;
            t._gnuLongLinkPath = null;
        }
        if (t._pax) {
            t._header = p = mixinPax(p, t._pax);
            t._pax = null;
        }
        t._locked = true;
        if (!p.size || p.type === "directory") {
            t._parse(512, h);
            t.emit("entry", p, emptyStream(t, a), s);
            return;
        }
        t._stream = new Source(t, a);
        t.emit("entry", p, t._stream, s);
        t._parse(p.size, o);
        n();
    };
    this._onheader = h;
    this._parse(512, h);
};

util$n.inherits(Extract, Writable$1);

Extract.prototype.destroy = function(e) {
    if (this._destroyed) return;
    this._destroyed = true;
    if (e) this.emit("error", e);
    this.emit("close");
    if (this._stream) this._stream.emit("close");
};

Extract.prototype._parse = function(e, t) {
    if (this._destroyed) return;
    this._offset += e;
    this._missing = e;
    if (t === this._onheader) this._partial = false;
    this._onparse = t;
};

Extract.prototype._continue = function() {
    if (this._destroyed) return;
    var e = this._cb;
    this._cb = noop$4;
    if (this._overflow) this._write(this._overflow, undefined, e); else e();
};

Extract.prototype._write = function(e, t, r) {
    if (this._destroyed) return;
    var n = this._stream;
    var s = this._buffer;
    var o = this._missing;
    if (e.length) this._partial = true;
    if (e.length < o) {
        this._missing -= e.length;
        this._overflow = null;
        if (n) return n.write(e, r);
        s.append(e);
        return r();
    }
    this._cb = r;
    this._missing = 0;
    var a = null;
    if (e.length > o) {
        a = e.slice(o);
        e = e.slice(0, o);
    }
    if (n) n.end(e); else s.append(e);
    this._overflow = a;
    this._onparse();
};

Extract.prototype._final = function(e) {
    if (this._partial) return this.destroy(new Error("Unexpected end of data"));
    e();
};

var extract = Extract;

var fsConstants = require$$0__default$5.default.constants || require$$1__default$3.default;

var constants$1 = fsConstants;

var eos = Logger.endOfStream;

var inherits = index.requireInherits();

var alloc = Buffer.alloc;

var Readable = readableExports.Readable;

var Writable = readableExports.Writable;

var StringDecoder = require$$1__default$4.default.StringDecoder;

var headers = headers$2;

var DMODE = parseInt("755", 8);

var FMODE = parseInt("644", 8);

var END_OF_TAR = alloc(1024);

var noop$3 = function() {};

var overflow = function(e, t) {
    t &= 511;
    if (t) e.push(END_OF_TAR.slice(0, 512 - t));
};

function modeToType(e) {
    switch (e & constants$1.S_IFMT) {
      case constants$1.S_IFBLK:
        return "block-device";

      case constants$1.S_IFCHR:
        return "character-device";

      case constants$1.S_IFDIR:
        return "directory";

      case constants$1.S_IFIFO:
        return "fifo";

      case constants$1.S_IFLNK:
        return "symlink";
    }
    return "file";
}

var Sink = function(e) {
    Writable.call(this);
    this.written = 0;
    this._to = e;
    this._destroyed = false;
};

inherits(Sink, Writable);

Sink.prototype._write = function(e, t, r) {
    this.written += e.length;
    if (this._to.push(e)) return r();
    this._to._drain = r;
};

Sink.prototype.destroy = function() {
    if (this._destroyed) return;
    this._destroyed = true;
    this.emit("close");
};

var LinkSink = function() {
    Writable.call(this);
    this.linkname = "";
    this._decoder = new StringDecoder("utf-8");
    this._destroyed = false;
};

inherits(LinkSink, Writable);

LinkSink.prototype._write = function(e, t, r) {
    this.linkname += this._decoder.write(e);
    r();
};

LinkSink.prototype.destroy = function() {
    if (this._destroyed) return;
    this._destroyed = true;
    this.emit("close");
};

var Void = function() {
    Writable.call(this);
    this._destroyed = false;
};

inherits(Void, Writable);

Void.prototype._write = function(e, t, r) {
    r(new Error("No body allowed for this entry"));
};

Void.prototype.destroy = function() {
    if (this._destroyed) return;
    this._destroyed = true;
    this.emit("close");
};

var Pack = function(e) {
    if (!(this instanceof Pack)) return new Pack(e);
    Readable.call(this, e);
    this._drain = noop$3;
    this._finalized = false;
    this._finalizing = false;
    this._destroyed = false;
    this._stream = null;
};

inherits(Pack, Readable);

Pack.prototype.entry = function(e, t, r) {
    if (this._stream) throw new Error("already piping an entry");
    if (this._finalized || this._destroyed) return;
    if (typeof t === "function") {
        r = t;
        t = null;
    }
    if (!r) r = noop$3;
    var n = this;
    if (!e.size || e.type === "symlink") e.size = 0;
    if (!e.type) e.type = modeToType(e.mode);
    if (!e.mode) e.mode = e.type === "directory" ? DMODE : FMODE;
    if (!e.uid) e.uid = 0;
    if (!e.gid) e.gid = 0;
    if (!e.mtime) e.mtime = new Date;
    if (typeof t === "string") t = Buffer.from(t);
    if (Buffer.isBuffer(t)) {
        e.size = t.length;
        this._encode(e);
        var s = this.push(t);
        overflow(n, e.size);
        if (s) process.nextTick(r); else this._drain = r;
        return new Void;
    }
    if (e.type === "symlink" && !e.linkname) {
        var o = new LinkSink;
        eos(o, function(t) {
            if (t) {
                n.destroy();
                return r(t);
            }
            e.linkname = o.linkname;
            n._encode(e);
            r();
        });
        return o;
    }
    this._encode(e);
    if (e.type !== "file" && e.type !== "contiguous-file") {
        process.nextTick(r);
        return new Void;
    }
    var a = new Sink(this);
    this._stream = a;
    eos(a, function(t) {
        n._stream = null;
        if (t) {
            n.destroy();
            return r(t);
        }
        if (a.written !== e.size) {
            n.destroy();
            return r(new Error("size mismatch"));
        }
        overflow(n, e.size);
        if (n._finalizing) n.finalize();
        r();
    });
    return a;
};

Pack.prototype.finalize = function() {
    if (this._stream) {
        this._finalizing = true;
        return;
    }
    if (this._finalized) return;
    this._finalized = true;
    this.push(END_OF_TAR);
    this.push(null);
};

Pack.prototype.destroy = function(e) {
    if (this._destroyed) return;
    this._destroyed = true;
    if (e) this.emit("error", e);
    this.emit("close");
    if (this._stream && this._stream.destroy) this._stream.destroy();
};

Pack.prototype._encode = function(e) {
    if (!e.pax) {
        var t = headers.encode(e);
        if (t) {
            this.push(t);
            return;
        }
    }
    this._encodePax(e);
};

Pack.prototype._encodePax = function(e) {
    var t = headers.encodePax({
        name: e.name,
        linkname: e.linkname,
        pax: e.pax
    });
    var r = {
        name: "PaxHeader",
        mode: e.mode,
        uid: e.uid,
        gid: e.gid,
        size: t.length,
        mtime: e.mtime,
        type: "pax-header",
        linkname: e.linkname && "PaxHeader",
        uname: e.uname,
        gname: e.gname,
        devmajor: e.devmajor,
        devminor: e.devminor
    };
    this.push(headers.encode(r));
    this.push(t);
    overflow(this, t.length);
    r.size = e.size;
    r.type = e.type;
    this.push(headers.encode(r));
};

Pack.prototype._read = function(e) {
    var t = this._drain;
    this._drain = noop$3;
    t();
};

var pack = Pack;

tarStream.extract = extract;

tarStream.pack = pack;

var path$3 = require$$0__default$4.default;

var fs$3 = require$$0__default$5.default;

var _0777 = parseInt("0777", 8);

var mkdirpClassic = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;

function mkdirP(e, t, r, n) {
    if (typeof t === "function") {
        r = t;
        t = {};
    } else if (!t || typeof t !== "object") {
        t = {
            mode: t
        };
    }
    var s = t.mode;
    var o = t.fs || fs$3;
    if (s === undefined) {
        s = _0777 & ~process.umask();
    }
    if (!n) n = null;
    var a = r || function() {};
    e = path$3.resolve(e);
    o.mkdir(e, s, function(r) {
        if (!r) {
            n = n || e;
            return a(null, n);
        }
        switch (r.code) {
          case "ENOENT":
            mkdirP(path$3.dirname(e), t, function(r, n) {
                if (r) a(r, n); else mkdirP(e, t, a, n);
            });
            break;

          default:
            o.stat(e, function(e, t) {
                if (e || !t.isDirectory()) a(r, n); else a(null, n);
            });
            break;
        }
    });
}

mkdirP.sync = function e(t, r, n) {
    if (!r || typeof r !== "object") {
        r = {
            mode: r
        };
    }
    var s = r.mode;
    var o = r.fs || fs$3;
    if (s === undefined) {
        s = _0777 & ~process.umask();
    }
    if (!n) n = null;
    t = path$3.resolve(t);
    try {
        o.mkdirSync(t, s);
        n = n || t;
    } catch (s) {
        switch (s.code) {
          case "ENOENT":
            n = e(path$3.dirname(t), r, n);
            e(t, r, n);
            break;

          default:
            var a;
            try {
                a = o.statSync(t);
            } catch (e) {
                throw s;
            }
            if (!a.isDirectory()) throw s;
            break;
        }
    }
    return n;
};

var chownr = chownr_1;

var tar = tarStream;

var pump = Logger.pump_1;

var mkdirp = mkdirpClassic;

var fs$2 = require$$0__default$5.default;

var path$2 = require$$0__default$4.default;

var os$1 = require$$1__default$2.default;

var win32 = os$1.platform() === "win32";

var noop$2 = function() {};

var echo = function(e) {
    return e;
};

var normalize = !win32 ? echo : function(e) {
    return e.replace(/\\/g, "/").replace(/[:?<>|]/g, "_");
};

var statAll = function(e, t, r, n, s, o) {
    var a = s || [ "." ];
    return function s(l) {
        if (!a.length) return l();
        var c = a.shift();
        var u = path$2.join(r, c);
        t.call(e, u, function(t, s) {
            if (t) return l(t);
            if (!s.isDirectory()) return l(null, c, s);
            e.readdir(u, function(e, t) {
                if (e) return l(e);
                if (o) t.sort();
                for (var u = 0; u < t.length; u++) {
                    if (!n(path$2.join(r, c, t[u]))) a.push(path$2.join(c, t[u]));
                }
                l(null, c, s);
            });
        });
    };
};

var strip = function(e, t) {
    return function(r) {
        r.name = r.name.split("/").slice(t).join("/");
        var n = r.linkname;
        if (n && (r.type === "link" || path$2.isAbsolute(n))) {
            r.linkname = n.split("/").slice(t).join("/");
        }
        return e(r);
    };
};

tarFs.pack = function(e, t) {
    if (!e) e = ".";
    if (!t) t = {};
    var r = t.fs || fs$2;
    var n = t.ignore || t.filter || noop$2;
    var s = t.map || noop$2;
    var o = t.mapStream || echo;
    var a = statAll(r, t.dereference ? r.stat : r.lstat, e, n, t.entries, t.sort);
    var l = t.strict !== false;
    var c = typeof t.umask === "number" ? ~t.umask : ~processUmask();
    var u = typeof t.dmode === "number" ? t.dmode : 0;
    var d = typeof t.fmode === "number" ? t.fmode : 0;
    var h = t.pack || tar.pack();
    var p = t.finish || noop$2;
    if (t.strip) s = strip(s, t.strip);
    if (t.readable) {
        u |= parseInt(555, 8);
        d |= parseInt(444, 8);
    }
    if (t.writable) {
        u |= parseInt(333, 8);
        d |= parseInt(222, 8);
    }
    var g = function(t, n) {
        r.readlink(path$2.join(e, t), function(e, t) {
            if (e) return h.destroy(e);
            n.linkname = normalize(t);
            h.entry(n, _);
        });
    };
    var m = function(n, a, m) {
        if (n) return h.destroy(n);
        if (!a) {
            if (t.finalize !== false) h.finalize();
            return p(h);
        }
        if (m.isSocket()) return _();
        var E = {
            name: normalize(a),
            mode: (m.mode | (m.isDirectory() ? u : d)) & c,
            mtime: m.mtime,
            size: m.size,
            type: "file",
            uid: m.uid,
            gid: m.gid
        };
        if (m.isDirectory()) {
            E.size = 0;
            E.type = "directory";
            E = s(E) || E;
            return h.entry(E, _);
        }
        if (m.isSymbolicLink()) {
            E.size = 0;
            E.type = "symlink";
            E = s(E) || E;
            return g(a, E);
        }
        E = s(E) || E;
        if (!m.isFile()) {
            if (l) return h.destroy(new Error("unsupported type for " + a));
            return _();
        }
        var v = h.entry(E, _);
        if (!v) return;
        var y = o(r.createReadStream(path$2.join(e, a), {
            start: 0,
            end: E.size > 0 ? E.size - 1 : E.size
        }), E);
        y.on("error", function(e) {
            v.destroy(e);
        });
        pump(y, v);
    };
    var _ = function(e) {
        if (e) return h.destroy(e);
        a(m);
    };
    _();
    return h;
};

var head = function(e) {
    return e.length ? e[e.length - 1] : null;
};

var processGetuid = function() {
    return process.getuid ? process.getuid() : -1;
};

var processUmask = function() {
    return process.umask ? process.umask() : 0;
};

tarFs.extract = function(e, t) {
    if (!e) e = ".";
    if (!t) t = {};
    var r = t.fs || fs$2;
    var n = t.ignore || t.filter || noop$2;
    var s = t.map || noop$2;
    var o = t.mapStream || echo;
    var a = t.chown !== false && !win32 && processGetuid() === 0;
    var l = t.extract || tar.extract();
    var c = [];
    var u = new Date;
    var d = typeof t.umask === "number" ? ~t.umask : ~processUmask();
    var h = typeof t.dmode === "number" ? t.dmode : 0;
    var p = typeof t.fmode === "number" ? t.fmode : 0;
    var g = t.strict !== false;
    if (t.strip) s = strip(s, t.strip);
    if (t.readable) {
        h |= parseInt(555, 8);
        p |= parseInt(444, 8);
    }
    if (t.writable) {
        h |= parseInt(333, 8);
        p |= parseInt(222, 8);
    }
    var m = function(e, t) {
        var n;
        while ((n = head(c)) && e.slice(0, n[0].length) !== n[0]) c.pop();
        if (!n) return t();
        r.utimes(n[0], u, n[1], t);
    };
    var _ = function(e, n, s) {
        if (t.utimes === false) return s();
        if (n.type === "directory") return r.utimes(e, u, n.mtime, s);
        if (n.type === "symlink") return m(e, s);
        r.utimes(e, u, n.mtime, function(t) {
            if (t) return s(t);
            m(e, s);
        });
    };
    var E = function(e, t, n) {
        var s = t.type === "symlink";
        var o = s ? r.lchmod : r.chmod;
        var l = s ? r.lchown : r.chown;
        if (!o) return n();
        var c = (t.mode | (t.type === "directory" ? h : p)) & d;
        if (l && a) l.call(r, e, t.uid, t.gid, u); else u(null);
        function u(t) {
            if (t) return n(t);
            if (!o) return n();
            o.call(r, e, c, n);
        }
    };
    l.on("entry", function(l, u, d) {
        l = s(l) || l;
        l.name = normalize(l.name);
        var h = path$2.join(e, path$2.join("/", l.name));
        if (n(h, l)) {
            u.resume();
            return d();
        }
        var p = function(e) {
            if (e) return d(e);
            _(h, l, function(e) {
                if (e) return d(e);
                if (win32) return d();
                E(h, l, d);
            });
        };
        var m = function() {
            if (win32) return d();
            r.unlink(h, function() {
                var t = path$2.resolve(path$2.dirname(h), l.linkname);
                if (!inCwd(t, e)) return d(new Error(h + " is not a valid symlink"));
                r.symlink(l.linkname, h, p);
            });
        };
        var v = function() {
            if (win32) return d();
            r.unlink(h, function() {
                var n = path$2.join(e, path$2.join("/", l.linkname));
                r.realpath(n, function(s, o) {
                    if (s || !inCwd(o, e)) return d(new Error(h + " is not a valid hardlink"));
                    r.link(o, h, function(e) {
                        if (e && e.code === "EPERM" && t.hardlinkAsFilesFallback) {
                            u = r.createReadStream(n);
                            return y();
                        }
                        p(e);
                    });
                });
            });
        };
        var y = function() {
            var e = r.createWriteStream(h);
            var t = o(u, l);
            e.on("error", function(e) {
                t.destroy(e);
            });
            pump(t, e, function(t) {
                if (t) return d(t);
                e.on("close", p);
            });
        };
        if (l.type === "directory") {
            c.push([ h, l.mtime ]);
            return mkdirfix(h, {
                fs: r,
                own: a,
                uid: l.uid,
                gid: l.gid
            }, p);
        }
        var S = path$2.dirname(h);
        validate$2(r, S, path$2.join(e, "."), function(e, t) {
            if (e) return d(e);
            if (!t) return d(new Error(S + " is not a valid path"));
            mkdirfix(S, {
                fs: r,
                own: a,
                uid: l.uid,
                gid: l.gid
            }, function(e) {
                if (e) return d(e);
                switch (l.type) {
                  case "file":
                    return y();

                  case "link":
                    return v();

                  case "symlink":
                    return m();
                }
                if (g) return d(new Error("unsupported type for " + h + " (" + l.type + ")"));
                u.resume();
                d();
            });
        });
    });
    if (t.finish) l.on("finish", t.finish);
    return l;
};

function validate$2(e, t, r, n) {
    if (t === r) return n(null, true);
    e.lstat(t, function(s, o) {
        if (s && s.code !== "ENOENT") return n(s);
        if (s || o.isDirectory()) return validate$2(e, path$2.join(t, ".."), r, n);
        n(null, false);
    });
}

function mkdirfix(e, t, r) {
    mkdirp(e, {
        fs: t.fs
    }, function(e, n) {
        if (!e && n && t.own) {
            chownr(n, t.uid, t.gid, r);
        } else {
            r(e);
        }
    });
}

function inCwd(e, t) {
    t = path$2.resolve(t);
    return t === e || e.startsWith(t + path$2.sep);
}

util$o.exports;

(function(e) {
    var t = ignore;
    var r = require$$0__default$5.default;
    var n = require$$0__default$4.default;
    var s = tarFs;
    var o = require$$4__default$2.default;
    var a = [];
    var l = a.forEach;
    var c = a.slice;
    e.exports.extend = function(e) {
        l.call(c.call(arguments, 1), function(t) {
            if (t) {
                for (var r in t) {
                    e[r] = t[r];
                }
            }
        });
        return e;
    };
    e.exports.processArgs = function(t, r, n) {
        if (!r && typeof t === "function") {
            r = t;
            t = null;
        }
        return {
            callback: r,
            opts: e.exports.extend({}, n, t)
        };
    };
    e.exports.parseRepositoryTag = function(e) {
        var t;
        var r = e.indexOf("@");
        var n = e.lastIndexOf(":");
        if (r >= 0) {
            t = r;
        } else if (n >= 0) {
            t = n;
        } else {
            return {
                repository: e
            };
        }
        var s = e.slice(t + 1);
        if (s.indexOf("/") === -1) {
            return {
                repository: e.slice(0, t),
                tag: s
            };
        }
        return {
            repository: e
        };
    };
    e.exports.prepareBuildContext = function(e, a) {
        if (e && e.context) {
            r.readFile(n.join(e.context, ".dockerignore"), (r, n) => {
                let l;
                let c;
                if (!r) {
                    const e = t({
                        ignorecase: false
                    }).add(n.toString());
                    c = e.createFilter();
                    l = e => !c(e);
                }
                const u = e.src.slice() || [];
                const d = s.pack(e.context, {
                    entries: c ? u.filter(c) : u,
                    ignore: l
                });
                a(d.pipe(o.createGzip()));
            });
        } else {
            a(e);
        }
    };
})(util$o);

var utilExports = util$o.exports;

var util$m = utilExports;

var Exec$2 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Exec$2.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Exec$2.prototype.start = function(e, t) {
    var r = this;
    var n = util$m.processArgs(e, t);
    var s = {
        path: "/exec/" + this.id + "/start",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        allowEmpty: true,
        hijack: n.opts.hijack,
        openStdin: n.opts.stdin,
        statusCodes: {
            200: true,
            204: true,
            404: "no such exec",
            409: "container stopped/paused",
            500: "container not running"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, t);
        });
    }
};

Exec$2.prototype.resize = function(e, t) {
    var r = this;
    var n = util$m.processArgs(e, t);
    var s = {
        path: "/exec/" + this.id + "/resize?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such exec",
            500: "container not running"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, t);
        });
    }
};

Exec$2.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$m.processArgs(e, t);
    var s = {
        path: "/exec/" + this.id + "/json",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such exec",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, t);
        });
    }
};

var exec = Exec$2;

utilExports.extend;

var Exec$1 = exec, util$l = utilExports;

var Container$2 = function(e, t) {
    this.modem = e;
    this.id = t;
    this.defaultOptions = {
        top: {},
        start: {},
        commit: {},
        stop: {},
        pause: {},
        unpause: {},
        restart: {},
        resize: {},
        attach: {},
        remove: {},
        copy: {},
        kill: {},
        exec: {},
        rename: {},
        log: {},
        stats: {},
        getArchive: {},
        infoArchive: {},
        putArchive: {},
        update: {},
        wait: {}
    };
};

Container$2.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Container$2.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t);
    var s = {
        path: "/containers/" + this.id + "/json?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.rename = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.rename);
    var s = {
        path: "/containers/" + this.id + "/rename?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.update = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.update);
    var s = {
        path: "/containers/" + this.id + "/update",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            400: "bad parameter",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.top = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.top);
    var s = {
        path: "/containers/" + this.id + "/top?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.changes = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t);
    var s = {
        path: "/containers/" + this.id + "/changes",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.listCheckpoint = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t);
    var s = {
        path: "/containers/" + this.id + "/checkpoints?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.deleteCheckpoint = function(e, t, r) {
    var n = this;
    var s = util$l.processArgs(t, r);
    var o = {
        path: "/containers/" + this.id + "/checkpoints/" + e + "?",
        method: "DELETE",
        abortSignal: s.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: s.opts
    };
    if (s.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(o, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(o, function(e, t) {
            s.callback(e, t);
        });
    }
};

Container$2.prototype.createCheckpoint = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t);
    var s = {
        path: "/containers/" + this.id + "/checkpoints",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        allowEmpty: true,
        statusCodes: {
            200: true,
            201: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.export = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t);
    var s = {
        path: "/containers/" + this.id + "/export",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.start = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.start);
    var s = {
        path: "/containers/" + this.id + "/start?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            304: "container already started",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.pause = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.pause);
    var s = {
        path: "/containers/" + this.id + "/pause",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.unpause = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.unpause);
    var s = {
        path: "/containers/" + this.id + "/unpause",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.exec = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.exec);
    var s = {
        path: "/containers/" + this.id + "/exec",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            404: "no such container",
            409: "container stopped/paused",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(n, s) {
                if (n) {
                    return t(n);
                }
                e(new Exec$1(r.modem, s.Id));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, new Exec$1(r.modem, t.Id));
        });
    }
};

Container$2.prototype.commit = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.commit);
    n.opts.container = this.id;
    var s = {
        path: "/commit?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.stop = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.stop);
    var s = {
        path: "/containers/" + this.id + "/stop?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            304: "container already stopped",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.restart = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.restart);
    var s = {
        path: "/containers/" + this.id + "/restart?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.kill = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.kill);
    var s = {
        path: "/containers/" + this.id + "/kill?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.resize = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.resize);
    var s = {
        path: "/containers/" + this.id + "/resize?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.attach = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.attach);
    var s = {
        path: "/containers/" + this.id + "/attach?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        hijack: n.opts.hijack,
        openStdin: n.opts.stdin,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.wait = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.wait);
    var s = {
        path: "/containers/" + this.id + "/wait?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.remove = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.remove);
    var s = {
        path: "/containers/" + this.id + "?",
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            400: "bad parameter",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.copy = function(e, t) {
    var r = this;
    console.log("container.copy is deprecated since Docker v1.8.x");
    var n = util$l.processArgs(e, t, this.defaultOptions.copy);
    var s = {
        path: "/containers/" + this.id + "/copy",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.getArchive = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.getArchive);
    var s = {
        path: "/containers/" + this.id + "/archive?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            400: "client error, bad parameters",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.infoArchive = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.infoArchive);
    var s = {
        path: "/containers/" + this.id + "/archive?",
        method: "HEAD",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            400: "client error, bad parameters",
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.putArchive = function(e, t, r) {
    var n = this;
    var s = util$l.processArgs(t, r, this.defaultOptions.putArchive);
    var o = {
        path: "/containers/" + this.id + "/archive?",
        method: "PUT",
        file: e,
        abortSignal: s.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "client error, bad parameters",
            403: "client error, permission denied",
            404: "no such container",
            500: "server error"
        },
        options: s.opts
    };
    if (s.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(o, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(o, function(e, t) {
            s.callback(e, t);
        });
    }
};

Container$2.prototype.logs = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.log);
    var s = {
        path: "/containers/" + this.id + "/logs?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: n.opts.follow || false,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Container$2.prototype.stats = function(e, t) {
    var r = this;
    var n = util$l.processArgs(e, t, this.defaultOptions.stats);
    var s = true;
    if (n.opts.stream === false) {
        s = false;
    }
    var o = {
        path: "/containers/" + this.id + "/stats?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: s,
        statusCodes: {
            200: true,
            404: "no such container",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(o, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(o, function(e, t) {
            n.callback(e, t);
        });
    }
};

var container = Container$2;

var util$k = utilExports;

var Image$1 = function(e, t) {
    this.modem = e;
    this.name = t;
};

Image$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Image$1.prototype.inspect = function(e, t) {
    var r = util$k.processArgs(e, t);
    var n = this;
    var e = {
        path: "/images/" + this.name + "/json",
        method: "GET",
        options: r.opts,
        statusCodes: {
            200: true,
            404: "no such image",
            500: "server error"
        }
    };
    if (r.callback === undefined) {
        return new this.modem.Promise(function(t, r) {
            n.modem.dial(e, function(e, n) {
                if (e) {
                    return r(e);
                }
                t(n);
            });
        });
    } else {
        this.modem.dial(e, function(e, t) {
            if (e) return r.callback(e, t);
            r.callback(e, t);
        });
    }
};

Image$1.prototype.distribution = function(e, t) {
    var r = util$k.processArgs(e, t);
    var n = this;
    var s = {
        path: "/distribution/" + this.name + "/json",
        method: "GET",
        statusCodes: {
            200: true,
            401: "no such image",
            500: "server error"
        },
        authconfig: r.opts ? r.opts.authconfig : undefined
    };
    if (r.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return r.callback(e, t);
            r.callback(e, t);
        });
    }
};

Image$1.prototype.history = function(e) {
    var t = this;
    var r = {
        path: "/images/" + this.name + "/history",
        method: "GET",
        statusCodes: {
            200: true,
            404: "no such image",
            500: "server error"
        }
    };
    if (e === undefined) {
        return new this.modem.Promise(function(e, n) {
            t.modem.dial(r, function(t, r) {
                if (t) {
                    return n(t);
                }
                e(r);
            });
        });
    } else {
        this.modem.dial(r, function(t, r) {
            if (t) return e(t, r);
            e(t, r);
        });
    }
};

Image$1.prototype.get = function(e) {
    var t = this;
    var r = {
        path: "/images/" + this.name + "/get",
        method: "GET",
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (e === undefined) {
        return new this.modem.Promise(function(e, n) {
            t.modem.dial(r, function(t, r) {
                if (t) {
                    return n(t);
                }
                e(r);
            });
        });
    } else {
        this.modem.dial(r, function(t, r) {
            if (t) return e(t, r);
            e(t, r);
        });
    }
};

Image$1.prototype.push = function(e, t, r) {
    var n = this;
    var s = util$k.processArgs(e, t);
    var o = true;
    if (s.opts.stream === false) {
        o = false;
    }
    var a = {
        path: "/images/" + this.name + "/push?",
        method: "POST",
        options: s.opts,
        authconfig: s.opts.authconfig || r,
        abortSignal: s.opts.abortSignal,
        isStream: o,
        statusCodes: {
            200: true,
            404: "no such image",
            500: "server error"
        }
    };
    delete a.options.authconfig;
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(a, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(a, function(e, r) {
            t(e, r);
        });
    }
};

Image$1.prototype.tag = function(e, t) {
    var r = this;
    var n = {
        path: "/images/" + this.name + "/tag?",
        method: "POST",
        options: e,
        abortSignal: e && e.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            400: "bad parameter",
            404: "no such image",
            409: "conflict",
            500: "server error"
        }
    };
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(n, function(e, r) {
            t(e, r);
        });
    }
};

Image$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$k.processArgs(e, t);
    var s = {
        path: "/images/" + this.name + "?",
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such image",
            409: "conflict",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var image = Image$1;

var util$j = utilExports;

var Volume$1 = function(e, t) {
    this.modem = e;
    this.name = t;
};

Volume$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Volume$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$j.processArgs(e, t);
    var s = {
        path: "/volumes/" + this.name,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such volume",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Volume$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$j.processArgs(e, t);
    var s = {
        path: "/volumes/" + this.name,
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            204: true,
            404: "no such volume",
            409: "conflict",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var volume = Volume$1;

var util$i = utilExports;

var Network$1 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Network$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Network$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$i.processArgs(e, t);
    var e = {
        path: "/networks/" + this.id + "?",
        method: "GET",
        statusCodes: {
            200: true,
            404: "no such network",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(t, n) {
            r.modem.dial(e, function(e, r) {
                if (e) {
                    return n(e);
                }
                t(r);
            });
        });
    } else {
        this.modem.dial(e, function(e, t) {
            n.callback(e, t);
        });
    }
};

Network$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$i.processArgs(e, t);
    var s = {
        path: "/networks/" + this.id,
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such network",
            409: "conflict",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Network$1.prototype.connect = function(e, t) {
    var r = this;
    var n = util$i.processArgs(e, t);
    var s = {
        path: "/networks/" + this.id + "/connect",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            404: "network or container is not found",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Network$1.prototype.disconnect = function(e, t) {
    var r = this;
    var n = util$i.processArgs(e, t);
    var s = {
        path: "/networks/" + this.id + "/disconnect",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            404: "network or container is not found",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var network = Network$1;

var util$h = utilExports;

var Service$3 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Service$3.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Service$3.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$h.processArgs(e, t);
    var s = {
        path: "/services/" + this.id,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such service",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Service$3.prototype.remove = function(e, t) {
    var r = this;
    var n = util$h.processArgs(e, t);
    var s = {
        path: "/services/" + this.id,
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "no such service",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Service$3.prototype.update = function(e, t, r) {
    var n = this;
    if (!r) {
        var s = typeof t;
        if (s === "function") {
            r = t;
            t = e;
            e = t.authconfig || undefined;
        } else if (s === "undefined") {
            t = e;
            e = t.authconfig || undefined;
        }
    }
    var o = {
        path: "/services/" + this.id + "/update?",
        method: "POST",
        abortSignal: t && t.abortSignal,
        statusCodes: {
            200: true,
            404: "no such service",
            500: "server error"
        },
        authconfig: e,
        options: t
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(o, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(o, function(e, t) {
            r(e, t);
        });
    }
};

Service$3.prototype.logs = function(e, t) {
    var r = this;
    var n = util$h.processArgs(e, t, {});
    var s = {
        path: "/services/" + this.id + "/logs?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: n.opts.follow || false,
        statusCodes: {
            200: true,
            404: "no such service",
            500: "server error",
            503: "node is not part of a swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var service$2 = Service$3;

var util$g = utilExports;

var Plugin$1 = function(e, t, r) {
    this.modem = e;
    this.name = t;
    this.remote = r || t;
};

Plugin$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Plugin$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "/json",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "plugin is not installed",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "?",
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "plugin is not installed",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.privileges = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/privileges?",
        method: "GET",
        options: {
            remote: this.remote
        },
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.pull = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    if (n.opts._query && !n.opts._query.name) {
        n.opts._query.name = this.name;
    }
    if (n.opts._query && !n.opts._query.remote) {
        n.opts._query.remote = this.remote;
    }
    var s = {
        path: "/plugins/pull?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        isStream: true,
        options: n.opts,
        statusCodes: {
            200: true,
            204: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.enable = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "/enable?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.disable = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "/disable",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.push = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "/push",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "plugin not installed",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.configure = function(e, t) {
    var r = this;
    var n = util$g.processArgs(e, t);
    var s = {
        path: "/plugins/" + this.name + "/set",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "plugin not installed",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Plugin$1.prototype.upgrade = function(e, t, r) {
    var n = this;
    if (!r && typeof t === "function") {
        r = t;
        t = e;
        e = t.authconfig || undefined;
    }
    var s = {
        path: "/plugins/" + this.name + "/upgrade?",
        method: "POST",
        abortSignal: t && t.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "plugin not installed",
            500: "server error"
        },
        authconfig: e,
        options: t
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            r(e, t);
        });
    }
};

var plugin = Plugin$1;

var util$f = utilExports;

var Secret$1 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Secret$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Secret$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$f.processArgs(e, t);
    var s = {
        path: "/secrets/" + this.id,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "secret not found",
            406: "node is not part of a swarm",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Secret$1.prototype.update = function(e, t) {
    var r = this;
    if (!t && typeof e === "function") {
        t = e;
    }
    var n = {
        path: "/secrets/" + this.id + "/update?",
        method: "POST",
        abortSignal: e && e.abortSignal,
        statusCodes: {
            200: true,
            404: "secret not found",
            500: "server error"
        },
        options: e
    };
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(n, function(e, r) {
            t(e, r);
        });
    }
};

Secret$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$f.processArgs(e, t);
    var s = {
        path: "/secrets/" + this.id,
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "secret not found",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var secret = Secret$1;

var util$e = utilExports;

var Config$1 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Config$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Config$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$e.processArgs(e, t);
    var s = {
        path: "/configs/" + this.id,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "config not found",
            500: "server error",
            503: "node is not part of a swarm"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Config$1.prototype.update = function(e, t) {
    var r = this;
    var n = util$e.processArgs(e, t);
    var s = {
        path: "/configs/" + this.id + "/update?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "config not found",
            500: "server error",
            503: "node is not part of a swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Config$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$e.processArgs(e, t);
    var s = {
        path: "/configs/" + this.id,
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            404: "config not found",
            500: "server error",
            503: "node is not part of a swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var config = Config$1;

var util$d = utilExports;

var Task$1 = function(e, t) {
    this.modem = e;
    this.id = t;
    this.defaultOptions = {
        log: {}
    };
};

Task$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Task$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$d.processArgs(e, t);
    var s = {
        path: "/tasks/" + this.id,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "unknown task",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Task$1.prototype.logs = function(e, t) {
    var r = this;
    var n = util$d.processArgs(e, t, this.defaultOptions.log);
    var s = {
        path: "/tasks/" + this.id + "/logs?",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        isStream: n.opts.follow || false,
        statusCodes: {
            101: true,
            200: true,
            404: "no such container",
            500: "server error",
            503: "node is not part of a swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var task = Task$1;

var util$c = utilExports;

var Node$1 = function(e, t) {
    this.modem = e;
    this.id = t;
};

Node$1.prototype[require$$1__default$1.default.inspect.custom] = function() {
    return this;
};

Node$1.prototype.inspect = function(e, t) {
    var r = this;
    var n = util$c.processArgs(e, t);
    var s = {
        path: "/nodes/" + this.id,
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such node",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Node$1.prototype.update = function(e, t) {
    var r = this;
    if (!t && typeof e === "function") {
        t = e;
    }
    var n = {
        path: "/nodes/" + this.id + "/update?",
        method: "POST",
        abortSignal: e && e.abortSignal,
        statusCodes: {
            200: true,
            404: "no such node",
            406: "node is not part of a swarm",
            500: "server error"
        },
        options: e
    };
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(n, function(e, r) {
            t(e, r);
        });
    }
};

Node$1.prototype.remove = function(e, t) {
    var r = this;
    var n = util$c.processArgs(e, t);
    var s = {
        path: "/nodes/" + this.id + "?",
        method: "DELETE",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            404: "no such node",
            500: "server error"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

var node = Node$1;

var src$3 = {};

var callCredentials = {};

var metadata = {};

var logging$8 = {};

var constants = {};

Object.defineProperty(constants, "__esModule", {
    value: true
});

constants.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = constants.DEFAULT_MAX_SEND_MESSAGE_LENGTH = constants.Propagate = constants.LogVerbosity = constants.Status = void 0;

var Status;

(function(e) {
    e[e["OK"] = 0] = "OK";
    e[e["CANCELLED"] = 1] = "CANCELLED";
    e[e["UNKNOWN"] = 2] = "UNKNOWN";
    e[e["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT";
    e[e["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED";
    e[e["NOT_FOUND"] = 5] = "NOT_FOUND";
    e[e["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS";
    e[e["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
    e[e["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
    e[e["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION";
    e[e["ABORTED"] = 10] = "ABORTED";
    e[e["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE";
    e[e["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED";
    e[e["INTERNAL"] = 13] = "INTERNAL";
    e[e["UNAVAILABLE"] = 14] = "UNAVAILABLE";
    e[e["DATA_LOSS"] = 15] = "DATA_LOSS";
    e[e["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
})(Status || (constants.Status = Status = {}));

var LogVerbosity;

(function(e) {
    e[e["DEBUG"] = 0] = "DEBUG";
    e[e["INFO"] = 1] = "INFO";
    e[e["ERROR"] = 2] = "ERROR";
    e[e["NONE"] = 3] = "NONE";
})(LogVerbosity || (constants.LogVerbosity = LogVerbosity = {}));

var Propagate;

(function(e) {
    e[e["DEADLINE"] = 1] = "DEADLINE";
    e[e["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT";
    e[e["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT";
    e[e["CANCELLATION"] = 8] = "CANCELLATION";
    e[e["DEFAULTS"] = 65535] = "DEFAULTS";
})(Propagate || (constants.Propagate = Propagate = {}));

constants.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1;

constants.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024;

var version$1 = "1.14.1";

const require$$12 = {
    version: version$1
};

(function(e) {
    var t, r, n, s;
    Object.defineProperty(e, "__esModule", {
        value: true
    });
    e.log = e.setLoggerVerbosity = e.setLogger = e.getLogger = void 0;
    e.trace = A;
    e.isTracerEnabled = b;
    const o = constants;
    const a = require$$1__default$5.default;
    const l = require$$12.version;
    const c = {
        error: (e, ...t) => {
            console.error("E " + e, ...t);
        },
        info: (e, ...t) => {
            console.error("I " + e, ...t);
        },
        debug: (e, ...t) => {
            console.error("D " + e, ...t);
        }
    };
    let u = c;
    let d = o.LogVerbosity.ERROR;
    const h = (r = (t = process.env.GRPC_NODE_VERBOSITY) !== null && t !== void 0 ? t : process.env.GRPC_VERBOSITY) !== null && r !== void 0 ? r : "";
    switch (h.toUpperCase()) {
      case "DEBUG":
        d = o.LogVerbosity.DEBUG;
        break;

      case "INFO":
        d = o.LogVerbosity.INFO;
        break;

      case "ERROR":
        d = o.LogVerbosity.ERROR;
        break;

      case "NONE":
        d = o.LogVerbosity.NONE;
        break;
    }
    const p = () => u;
    e.getLogger = p;
    const g = e => {
        u = e;
    };
    e.setLogger = g;
    const m = e => {
        d = e;
    };
    e.setLoggerVerbosity = m;
    const _ = (e, ...t) => {
        let r;
        if (e >= d) {
            switch (e) {
              case o.LogVerbosity.DEBUG:
                r = u.debug;
                break;

              case o.LogVerbosity.INFO:
                r = u.info;
                break;

              case o.LogVerbosity.ERROR:
                r = u.error;
                break;
            }
            if (!r) {
                r = u.error;
            }
            if (r) {
                r.bind(u)(...t);
            }
        }
    };
    e.log = _;
    const E = (s = (n = process.env.GRPC_NODE_TRACE) !== null && n !== void 0 ? n : process.env.GRPC_TRACE) !== null && s !== void 0 ? s : "";
    const v = new Set;
    const y = new Set;
    for (const e of E.split(",")) {
        if (e.startsWith("-")) {
            y.add(e.substring(1));
        } else {
            v.add(e);
        }
    }
    const S = v.has("all");
    function A(t, r, n) {
        if (b(r)) {
            (0, e.log)(t, (new Date).toISOString() + " | v" + l + " " + a.pid + " | " + r + " | " + n);
        }
    }
    function b(e) {
        return !y.has(e) && (S || v.has(e));
    }
})(logging$8);

var error = {};

Object.defineProperty(error, "__esModule", {
    value: true
});

error.getErrorMessage = getErrorMessage;

error.getErrorCode = getErrorCode;

function getErrorMessage(e) {
    if (e instanceof Error) {
        return e.message;
    } else {
        return String(e);
    }
}

function getErrorCode(e) {
    if (typeof e === "object" && e !== null && "code" in e && typeof e.code === "number") {
        return e.code;
    } else {
        return null;
    }
}

Object.defineProperty(metadata, "__esModule", {
    value: true
});

metadata.Metadata = void 0;

const logging_1$2 = logging$8;

const constants_1$c = constants;

const error_1 = error;

const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/;

const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/;

function isLegalKey(e) {
    return LEGAL_KEY_REGEX.test(e);
}

function isLegalNonBinaryValue(e) {
    return LEGAL_NON_BINARY_VALUE_REGEX.test(e);
}

function isBinaryKey(e) {
    return e.endsWith("-bin");
}

function isCustomMetadata(e) {
    return !e.startsWith("grpc-");
}

function normalizeKey(e) {
    return e.toLowerCase();
}

function validate$1(e, t) {
    if (!isLegalKey(e)) {
        throw new Error('Metadata key "' + e + '" contains illegal characters');
    }
    if (t !== null && t !== undefined) {
        if (isBinaryKey(e)) {
            if (!Buffer.isBuffer(t)) {
                throw new Error("keys that end with '-bin' must have Buffer values");
            }
        } else {
            if (Buffer.isBuffer(t)) {
                throw new Error("keys that don't end with '-bin' must have String values");
            }
            if (!isLegalNonBinaryValue(t)) {
                throw new Error('Metadata string value "' + t + '" contains illegal characters');
            }
        }
    }
}

class Metadata {
    constructor(e = {}) {
        this.internalRepr = new Map;
        this.opaqueData = new Map;
        this.options = e;
    }
    set(e, t) {
        e = normalizeKey(e);
        validate$1(e, t);
        this.internalRepr.set(e, [ t ]);
    }
    add(e, t) {
        e = normalizeKey(e);
        validate$1(e, t);
        const r = this.internalRepr.get(e);
        if (r === undefined) {
            this.internalRepr.set(e, [ t ]);
        } else {
            r.push(t);
        }
    }
    remove(e) {
        e = normalizeKey(e);
        this.internalRepr.delete(e);
    }
    get(e) {
        e = normalizeKey(e);
        return this.internalRepr.get(e) || [];
    }
    getMap() {
        const e = {};
        for (const [t, r] of this.internalRepr) {
            if (r.length > 0) {
                const n = r[0];
                e[t] = Buffer.isBuffer(n) ? Buffer.from(n) : n;
            }
        }
        return e;
    }
    clone() {
        const e = new Metadata(this.options);
        const t = e.internalRepr;
        for (const [e, r] of this.internalRepr) {
            const n = r.map(e => {
                if (Buffer.isBuffer(e)) {
                    return Buffer.from(e);
                } else {
                    return e;
                }
            });
            t.set(e, n);
        }
        return e;
    }
    merge(e) {
        for (const [t, r] of e.internalRepr) {
            const e = (this.internalRepr.get(t) || []).concat(r);
            this.internalRepr.set(t, e);
        }
    }
    setOptions(e) {
        this.options = e;
    }
    getOptions() {
        return this.options;
    }
    toHttp2Headers() {
        const e = {};
        for (const [t, r] of this.internalRepr) {
            if (t.startsWith(":")) {
                continue;
            }
            e[t] = r.map(bufToString);
        }
        return e;
    }
    toJSON() {
        const e = {};
        for (const [t, r] of this.internalRepr) {
            e[t] = r;
        }
        return e;
    }
    setOpaque(e, t) {
        this.opaqueData.set(e, t);
    }
    getOpaque(e) {
        return this.opaqueData.get(e);
    }
    static fromHttp2Headers(e) {
        const t = new Metadata;
        for (const r of Object.keys(e)) {
            if (r.charAt(0) === ":") {
                continue;
            }
            const n = e[r];
            try {
                if (isBinaryKey(r)) {
                    if (Array.isArray(n)) {
                        n.forEach(e => {
                            t.add(r, Buffer.from(e, "base64"));
                        });
                    } else if (n !== undefined) {
                        if (isCustomMetadata(r)) {
                            n.split(",").forEach(e => {
                                t.add(r, Buffer.from(e.trim(), "base64"));
                            });
                        } else {
                            t.add(r, Buffer.from(n, "base64"));
                        }
                    }
                } else {
                    if (Array.isArray(n)) {
                        n.forEach(e => {
                            t.add(r, e);
                        });
                    } else if (n !== undefined) {
                        t.add(r, n);
                    }
                }
            } catch (e) {
                const t = `Failed to add metadata entry ${r}: ${n}. ${(0, error_1.getErrorMessage)(e)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;
                (0, logging_1$2.log)(constants_1$c.LogVerbosity.ERROR, t);
            }
        }
        return t;
    }
}

metadata.Metadata = Metadata;

const bufToString = e => Buffer.isBuffer(e) ? e.toString("base64") : e;

Object.defineProperty(callCredentials, "__esModule", {
    value: true
});

callCredentials.CallCredentials = void 0;

const metadata_1$6 = metadata;

function isCurrentOauth2Client(e) {
    return "getRequestHeaders" in e && typeof e.getRequestHeaders === "function";
}

class CallCredentials {
    static createFromMetadataGenerator(e) {
        return new SingleCallCredentials(e);
    }
    static createFromGoogleCredential(e) {
        return CallCredentials.createFromMetadataGenerator((t, r) => {
            let n;
            if (isCurrentOauth2Client(e)) {
                n = e.getRequestHeaders(t.service_url);
            } else {
                n = new Promise((r, n) => {
                    e.getRequestMetadata(t.service_url, (e, t) => {
                        if (e) {
                            n(e);
                            return;
                        }
                        if (!t) {
                            n(new Error("Headers not set by metadata plugin"));
                            return;
                        }
                        r(t);
                    });
                });
            }
            n.then(e => {
                const t = new metadata_1$6.Metadata;
                for (const r of Object.keys(e)) {
                    t.add(r, e[r]);
                }
                r(null, t);
            }, e => {
                r(e);
            });
        });
    }
    static createEmpty() {
        return new EmptyCallCredentials;
    }
}

callCredentials.CallCredentials = CallCredentials;

class ComposedCallCredentials extends CallCredentials {
    constructor(e) {
        super();
        this.creds = e;
    }
    async generateMetadata(e) {
        const t = new metadata_1$6.Metadata;
        const r = await Promise.all(this.creds.map(t => t.generateMetadata(e)));
        for (const e of r) {
            t.merge(e);
        }
        return t;
    }
    compose(e) {
        return new ComposedCallCredentials(this.creds.concat([ e ]));
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (e instanceof ComposedCallCredentials) {
            return this.creds.every((t, r) => t._equals(e.creds[r]));
        } else {
            return false;
        }
    }
}

class SingleCallCredentials extends CallCredentials {
    constructor(e) {
        super();
        this.metadataGenerator = e;
    }
    generateMetadata(e) {
        return new Promise((t, r) => {
            this.metadataGenerator(e, (e, n) => {
                if (n !== undefined) {
                    t(n);
                } else {
                    r(e);
                }
            });
        });
    }
    compose(e) {
        return new ComposedCallCredentials([ this, e ]);
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (e instanceof SingleCallCredentials) {
            return this.metadataGenerator === e.metadataGenerator;
        } else {
            return false;
        }
    }
}

class EmptyCallCredentials extends CallCredentials {
    generateMetadata(e) {
        return Promise.resolve(new metadata_1$6.Metadata);
    }
    compose(e) {
        return e;
    }
    _equals(e) {
        return e instanceof EmptyCallCredentials;
    }
}

var channel = {};

var channelCredentials = {};

var tlsHelpers = {};

Object.defineProperty(tlsHelpers, "__esModule", {
    value: true
});

tlsHelpers.CIPHER_SUITES = void 0;

tlsHelpers.getDefaultRootsData = getDefaultRootsData;

const fs$1 = require$$0__default$5.default;

tlsHelpers.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES;

const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH;

let defaultRootsData = null;

function getDefaultRootsData() {
    if (DEFAULT_ROOTS_FILE_PATH) {
        if (defaultRootsData === null) {
            defaultRootsData = fs$1.readFileSync(DEFAULT_ROOTS_FILE_PATH);
        }
        return defaultRootsData;
    }
    return null;
}

var uriParser = {};

Object.defineProperty(uriParser, "__esModule", {
    value: true
});

uriParser.parseUri = parseUri;

uriParser.splitHostPort = splitHostPort;

uriParser.combineHostPort = combineHostPort;

uriParser.uriToString = uriToString;

const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;

function parseUri(e) {
    const t = URI_REGEX.exec(e);
    if (t === null) {
        return null;
    }
    return {
        scheme: t[1],
        authority: t[2],
        path: t[3]
    };
}

const NUMBER_REGEX = /^\d+$/;

function splitHostPort(e) {
    if (e.startsWith("[")) {
        const t = e.indexOf("]");
        if (t === -1) {
            return null;
        }
        const r = e.substring(1, t);
        if (r.indexOf(":") === -1) {
            return null;
        }
        if (e.length > t + 1) {
            if (e[t + 1] === ":") {
                const n = e.substring(t + 2);
                if (NUMBER_REGEX.test(n)) {
                    return {
                        host: r,
                        port: +n
                    };
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return {
                host: r
            };
        }
    } else {
        const t = e.split(":");
        if (t.length === 2) {
            if (NUMBER_REGEX.test(t[1])) {
                return {
                    host: t[0],
                    port: +t[1]
                };
            } else {
                return null;
            }
        } else {
            return {
                host: e
            };
        }
    }
}

function combineHostPort(e) {
    if (e.port === undefined) {
        return e.host;
    } else {
        if (e.host.includes(":")) {
            return `[${e.host}]:${e.port}`;
        } else {
            return `${e.host}:${e.port}`;
        }
    }
}

function uriToString(e) {
    let t = "";
    if (e.scheme !== undefined) {
        t += e.scheme + ":";
    }
    if (e.authority !== undefined) {
        t += "//" + e.authority + "/";
    }
    t += e.path;
    return t;
}

var resolver = {};

Object.defineProperty(resolver, "__esModule", {
    value: true
});

resolver.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0;

resolver.registerResolver = registerResolver;

resolver.registerDefaultScheme = registerDefaultScheme;

resolver.createResolver = createResolver;

resolver.getDefaultAuthority = getDefaultAuthority;

resolver.mapUriDefaultScheme = mapUriDefaultScheme;

const uri_parser_1$5 = uriParser;

resolver.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector";

const registeredResolvers = {};

let defaultScheme = null;

function registerResolver(e, t) {
    registeredResolvers[e] = t;
}

function registerDefaultScheme(e) {
    defaultScheme = e;
}

function createResolver(e, t, r) {
    if (e.scheme !== undefined && e.scheme in registeredResolvers) {
        return new registeredResolvers[e.scheme](e, t, r);
    } else {
        throw new Error(`No resolver could be created for target ${(0, uri_parser_1$5.uriToString)(e)}`);
    }
}

function getDefaultAuthority(e) {
    if (e.scheme !== undefined && e.scheme in registeredResolvers) {
        return registeredResolvers[e.scheme].getDefaultAuthority(e);
    } else {
        throw new Error(`Invalid target ${(0, uri_parser_1$5.uriToString)(e)}`);
    }
}

function mapUriDefaultScheme(e) {
    if (e.scheme === undefined || !(e.scheme in registeredResolvers)) {
        if (defaultScheme !== null) {
            return {
                scheme: defaultScheme,
                authority: undefined,
                path: (0, uri_parser_1$5.uriToString)(e)
            };
        } else {
            return null;
        }
    }
    return e;
}

Object.defineProperty(channelCredentials, "__esModule", {
    value: true
});

channelCredentials.ChannelCredentials = void 0;

channelCredentials.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials;

const tls_1 = require$$2__default$1.default;

const call_credentials_1$1 = callCredentials;

const tls_helpers_1$1 = tlsHelpers;

const uri_parser_1$4 = uriParser;

const resolver_1$2 = resolver;

const logging_1$1 = logging$8;

const constants_1$b = constants;

function verifyIsBufferOrNull(e, t) {
    if (e && !(e instanceof Buffer)) {
        throw new TypeError(`${t}, if provided, must be a Buffer.`);
    }
}

class ChannelCredentials {
    compose(e) {
        return new ComposedChannelCredentialsImpl(this, e);
    }
    static createSsl(e, t, r, n) {
        var s;
        verifyIsBufferOrNull(e, "Root certificate");
        verifyIsBufferOrNull(t, "Private key");
        verifyIsBufferOrNull(r, "Certificate chain");
        if (t && !r) {
            throw new Error("Private key must be given with accompanying certificate chain");
        }
        if (!t && r) {
            throw new Error("Certificate chain must be given with accompanying private key");
        }
        const o = (0, tls_1.createSecureContext)({
            ca: (s = e !== null && e !== void 0 ? e : (0, tls_helpers_1$1.getDefaultRootsData)()) !== null && s !== void 0 ? s : undefined,
            key: t !== null && t !== void 0 ? t : undefined,
            cert: r !== null && r !== void 0 ? r : undefined,
            ciphers: tls_helpers_1$1.CIPHER_SUITES
        });
        return new SecureChannelCredentialsImpl(o, n !== null && n !== void 0 ? n : {});
    }
    static createFromSecureContext(e, t) {
        return new SecureChannelCredentialsImpl(e, t !== null && t !== void 0 ? t : {});
    }
    static createInsecure() {
        return new InsecureChannelCredentialsImpl;
    }
}

channelCredentials.ChannelCredentials = ChannelCredentials;

class InsecureChannelCredentialsImpl extends ChannelCredentials {
    constructor() {
        super();
    }
    compose(e) {
        throw new Error("Cannot compose insecure credentials");
    }
    _isSecure() {
        return false;
    }
    _equals(e) {
        return e instanceof InsecureChannelCredentialsImpl;
    }
    _createSecureConnector(e, t, r) {
        return {
            connect(e) {
                return Promise.resolve({
                    socket: e,
                    secure: false
                });
            },
            waitForReady: () => Promise.resolve(),
            getCallCredentials: () => r !== null && r !== void 0 ? r : call_credentials_1$1.CallCredentials.createEmpty(),
            destroy() {}
        };
    }
}

function getConnectionOptions(e, t, r, n) {
    var s, o;
    const a = {
        secureContext: e
    };
    let l = r;
    if ("grpc.http_connect_target" in n) {
        const e = (0, uri_parser_1$4.parseUri)(n["grpc.http_connect_target"]);
        if (e) {
            l = e;
        }
    }
    const c = (0, resolver_1$2.getDefaultAuthority)(l);
    const u = (0, uri_parser_1$4.splitHostPort)(c);
    const d = (s = u === null || u === void 0 ? void 0 : u.host) !== null && s !== void 0 ? s : c;
    a.host = d;
    if (t.checkServerIdentity) {
        a.checkServerIdentity = t.checkServerIdentity;
    }
    if (t.rejectUnauthorized !== undefined) {
        a.rejectUnauthorized = t.rejectUnauthorized;
    }
    a.ALPNProtocols = [ "h2" ];
    if (n["grpc.ssl_target_name_override"]) {
        const e = n["grpc.ssl_target_name_override"];
        const t = (o = a.checkServerIdentity) !== null && o !== void 0 ? o : tls_1.checkServerIdentity;
        a.checkServerIdentity = (r, n) => t(e, n);
        a.servername = e;
    } else {
        a.servername = d;
    }
    if (n["grpc-node.tls_enable_trace"]) {
        a.enableTrace = true;
    }
    return a;
}

class SecureConnectorImpl {
    constructor(e, t) {
        this.connectionOptions = e;
        this.callCredentials = t;
    }
    connect(e) {
        const t = Object.assign({
            socket: e
        }, this.connectionOptions);
        return new Promise((e, r) => {
            const n = (0, tls_1.connect)(t, () => {
                var t;
                if (((t = this.connectionOptions.rejectUnauthorized) !== null && t !== void 0 ? t : true) && !n.authorized) {
                    r(n.authorizationError);
                    return;
                }
                e({
                    socket: n,
                    secure: true
                });
            });
            n.on("error", e => {
                r(e);
            });
        });
    }
    waitForReady() {
        return Promise.resolve();
    }
    getCallCredentials() {
        return this.callCredentials;
    }
    destroy() {}
}

class SecureChannelCredentialsImpl extends ChannelCredentials {
    constructor(e, t) {
        super();
        this.secureContext = e;
        this.verifyOptions = t;
    }
    _isSecure() {
        return true;
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (e instanceof SecureChannelCredentialsImpl) {
            return this.secureContext === e.secureContext && this.verifyOptions.checkServerIdentity === e.verifyOptions.checkServerIdentity;
        } else {
            return false;
        }
    }
    _createSecureConnector(e, t, r) {
        const n = getConnectionOptions(this.secureContext, this.verifyOptions, e, t);
        return new SecureConnectorImpl(n, r !== null && r !== void 0 ? r : call_credentials_1$1.CallCredentials.createEmpty());
    }
}

class CertificateProviderChannelCredentialsImpl extends ChannelCredentials {
    constructor(e, t, r) {
        super();
        this.caCertificateProvider = e;
        this.identityCertificateProvider = t;
        this.verifyOptions = r;
        this.refcount = 0;
        this.latestCaUpdate = undefined;
        this.latestIdentityUpdate = undefined;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
        this.secureContextWatchers = [];
    }
    _isSecure() {
        return true;
    }
    _equals(e) {
        var t, r;
        if (this === e) {
            return true;
        }
        if (e instanceof CertificateProviderChannelCredentialsImpl) {
            return this.caCertificateProvider === e.caCertificateProvider && this.identityCertificateProvider === e.identityCertificateProvider && ((t = this.verifyOptions) === null || t === void 0 ? void 0 : t.checkServerIdentity) === ((r = e.verifyOptions) === null || r === void 0 ? void 0 : r.checkServerIdentity);
        } else {
            return false;
        }
    }
    ref() {
        var e;
        if (this.refcount === 0) {
            this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener);
            (e = this.identityCertificateProvider) === null || e === void 0 ? void 0 : e.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        this.refcount += 1;
    }
    unref() {
        var e;
        this.refcount -= 1;
        if (this.refcount === 0) {
            this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener);
            (e = this.identityCertificateProvider) === null || e === void 0 ? void 0 : e.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
    }
    _createSecureConnector(e, t, r) {
        this.ref();
        return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, e, t, r !== null && r !== void 0 ? r : call_credentials_1$1.CallCredentials.createEmpty());
    }
    maybeUpdateWatchers() {
        if (this.hasReceivedUpdates()) {
            for (const e of this.secureContextWatchers) {
                e(this.getLatestSecureContext());
            }
            this.secureContextWatchers = [];
        }
    }
    handleCaCertificateUpdate(e) {
        this.latestCaUpdate = e;
        this.maybeUpdateWatchers();
    }
    handleIdentityCertitificateUpdate(e) {
        this.latestIdentityUpdate = e;
        this.maybeUpdateWatchers();
    }
    hasReceivedUpdates() {
        if (this.latestCaUpdate === undefined) {
            return false;
        }
        if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) {
            return false;
        }
        return true;
    }
    getSecureContext() {
        if (this.hasReceivedUpdates()) {
            return Promise.resolve(this.getLatestSecureContext());
        } else {
            return new Promise(e => {
                this.secureContextWatchers.push(e);
            });
        }
    }
    getLatestSecureContext() {
        var e, t;
        if (!this.latestCaUpdate) {
            return null;
        }
        if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) {
            return null;
        }
        try {
            return (0, tls_1.createSecureContext)({
                ca: this.latestCaUpdate.caCertificate,
                key: (e = this.latestIdentityUpdate) === null || e === void 0 ? void 0 : e.privateKey,
                cert: (t = this.latestIdentityUpdate) === null || t === void 0 ? void 0 : t.certificate,
                ciphers: tls_helpers_1$1.CIPHER_SUITES
            });
        } catch (e) {
            (0, logging_1$1.log)(constants_1$b.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e.message);
            return null;
        }
    }
}

CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class {
    constructor(e, t, r, n) {
        this.parent = e;
        this.channelTarget = t;
        this.options = r;
        this.callCredentials = n;
    }
    connect(e) {
        return new Promise((t, r) => {
            const n = this.parent.getLatestSecureContext();
            if (!n) {
                r(new Error("Failed to load credentials"));
                return;
            }
            if (e.closed) {
                r(new Error("Socket closed while loading credentials"));
            }
            const s = getConnectionOptions(n, this.parent.verifyOptions, this.channelTarget, this.options);
            const o = Object.assign({
                socket: e
            }, s);
            const a = () => {
                r(new Error("Socket closed"));
            };
            const l = e => {
                r(e);
            };
            const c = (0, tls_1.connect)(o, () => {
                var e;
                c.removeListener("close", a);
                c.removeListener("error", l);
                if (((e = this.parent.verifyOptions.rejectUnauthorized) !== null && e !== void 0 ? e : true) && !c.authorized) {
                    r(c.authorizationError);
                    return;
                }
                t({
                    socket: c,
                    secure: true
                });
            });
            c.once("close", a);
            c.once("error", l);
        });
    }
    async waitForReady() {
        await this.parent.getSecureContext();
    }
    getCallCredentials() {
        return this.callCredentials;
    }
    destroy() {
        this.parent.unref();
    }
};

function createCertificateProviderChannelCredentials(e, t, r) {
    return new CertificateProviderChannelCredentialsImpl(e, t, r !== null && r !== void 0 ? r : {});
}

class ComposedChannelCredentialsImpl extends ChannelCredentials {
    constructor(e, t) {
        super();
        this.channelCredentials = e;
        this.callCredentials = t;
        if (!e._isSecure()) {
            throw new Error("Cannot compose insecure credentials");
        }
    }
    compose(e) {
        const t = this.callCredentials.compose(e);
        return new ComposedChannelCredentialsImpl(this.channelCredentials, t);
    }
    _isSecure() {
        return true;
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (e instanceof ComposedChannelCredentialsImpl) {
            return this.channelCredentials._equals(e.channelCredentials) && this.callCredentials._equals(e.callCredentials);
        } else {
            return false;
        }
    }
    _createSecureConnector(e, t, r) {
        const n = this.callCredentials.compose(r !== null && r !== void 0 ? r : call_credentials_1$1.CallCredentials.createEmpty());
        return this.channelCredentials._createSecureConnector(e, t, n);
    }
}

var internalChannel = {};

var resolvingLoadBalancer = {};

var loadBalancer = {};

var hasRequiredLoadBalancer;

function requireLoadBalancer() {
    if (hasRequiredLoadBalancer) return loadBalancer;
    hasRequiredLoadBalancer = 1;
    Object.defineProperty(loadBalancer, "__esModule", {
        value: true
    });
    loadBalancer.createChildChannelControlHelper = r;
    loadBalancer.registerLoadBalancerType = o;
    loadBalancer.registerDefaultLoadBalancerType = a;
    loadBalancer.createLoadBalancer = l;
    loadBalancer.isLoadBalancerNameRegistered = c;
    loadBalancer.parseLoadBalancingConfig = u;
    loadBalancer.getDefaultConfig = d;
    loadBalancer.selectLbConfigFromList = h;
    const e = logging$8;
    const t = constants;
    function r(e, t) {
        var r, n, s, o, a, l, c, u, d, h;
        return {
            createSubchannel: (n = (r = t.createSubchannel) === null || r === void 0 ? void 0 : r.bind(t)) !== null && n !== void 0 ? n : e.createSubchannel.bind(e),
            updateState: (o = (s = t.updateState) === null || s === void 0 ? void 0 : s.bind(t)) !== null && o !== void 0 ? o : e.updateState.bind(e),
            requestReresolution: (l = (a = t.requestReresolution) === null || a === void 0 ? void 0 : a.bind(t)) !== null && l !== void 0 ? l : e.requestReresolution.bind(e),
            addChannelzChild: (u = (c = t.addChannelzChild) === null || c === void 0 ? void 0 : c.bind(t)) !== null && u !== void 0 ? u : e.addChannelzChild.bind(e),
            removeChannelzChild: (h = (d = t.removeChannelzChild) === null || d === void 0 ? void 0 : d.bind(t)) !== null && h !== void 0 ? h : e.removeChannelzChild.bind(e)
        };
    }
    const n = {};
    let s = null;
    function o(e, t, r) {
        n[e] = {
            LoadBalancer: t,
            LoadBalancingConfig: r
        };
    }
    function a(e) {
        s = e;
    }
    function l(e, t) {
        const r = e.getLoadBalancerName();
        if (r in n) {
            return new n[r].LoadBalancer(t);
        } else {
            return null;
        }
    }
    function c(e) {
        return e in n;
    }
    function u(e) {
        const t = Object.keys(e);
        if (t.length !== 1) {
            throw new Error("Provided load balancing config has multiple conflicting entries");
        }
        const r = t[0];
        if (r in n) {
            try {
                return n[r].LoadBalancingConfig.createFromJson(e[r]);
            } catch (e) {
                throw new Error(`${r}: ${e.message}`);
            }
        } else {
            throw new Error(`Unrecognized load balancing config name ${r}`);
        }
    }
    function d() {
        if (!s) {
            throw new Error("No default load balancer type registered");
        }
        return new n[s].LoadBalancingConfig;
    }
    function h(r, o = false) {
        for (const n of r) {
            try {
                return u(n);
            } catch (r) {
                (0, e.log)(t.LogVerbosity.DEBUG, "Config parsing failed with error", r.message);
                continue;
            }
        }
        if (o) {
            if (s) {
                return new n[s].LoadBalancingConfig;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    return loadBalancer;
}

var serviceConfig = {};

var hasRequiredServiceConfig;

function requireServiceConfig() {
    if (hasRequiredServiceConfig) return serviceConfig;
    hasRequiredServiceConfig = 1;
    Object.defineProperty(serviceConfig, "__esModule", {
        value: true
    });
    serviceConfig.validateRetryThrottling = c;
    serviceConfig.validateServiceConfig = d;
    serviceConfig.extractAndSelectServiceConfig = g;
    const e = require$$1__default$2.default;
    const t = constants;
    const r = /^\d+(\.\d{1,9})?s$/;
    const n = "node";
    function s(e) {
        if ("service" in e && e.service !== "") {
            if (typeof e.service !== "string") {
                throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);
            }
            if ("method" in e && e.method !== "") {
                if (typeof e.method !== "string") {
                    throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);
                }
                return {
                    service: e.service,
                    method: e.method
                };
            } else {
                return {
                    service: e.service
                };
            }
        } else {
            if ("method" in e && e.method !== undefined) {
                throw new Error(`Invalid method config name: method set with empty or unset service`);
            }
            return {};
        }
    }
    function o(e) {
        if (!("maxAttempts" in e) || !Number.isInteger(e.maxAttempts) || e.maxAttempts < 2) {
            throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");
        }
        if (!("initialBackoff" in e) || typeof e.initialBackoff !== "string" || !r.test(e.initialBackoff)) {
            throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");
        }
        if (!("maxBackoff" in e) || typeof e.maxBackoff !== "string" || !r.test(e.maxBackoff)) {
            throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");
        }
        if (!("backoffMultiplier" in e) || typeof e.backoffMultiplier !== "number" || e.backoffMultiplier <= 0) {
            throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");
        }
        if (!("retryableStatusCodes" in e && Array.isArray(e.retryableStatusCodes))) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes is required");
        }
        if (e.retryableStatusCodes.length === 0) {
            throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");
        }
        for (const r of e.retryableStatusCodes) {
            if (typeof r === "number") {
                if (!Object.values(t.Status).includes(r)) {
                    throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range");
                }
            } else if (typeof r === "string") {
                if (!Object.values(t.Status).includes(r.toUpperCase())) {
                    throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name");
                }
            } else {
                throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");
            }
        }
        return {
            maxAttempts: e.maxAttempts,
            initialBackoff: e.initialBackoff,
            maxBackoff: e.maxBackoff,
            backoffMultiplier: e.backoffMultiplier,
            retryableStatusCodes: e.retryableStatusCodes
        };
    }
    function a(e) {
        if (!("maxAttempts" in e) || !Number.isInteger(e.maxAttempts) || e.maxAttempts < 2) {
            throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");
        }
        if ("hedgingDelay" in e && (typeof e.hedgingDelay !== "string" || !r.test(e.hedgingDelay))) {
            throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");
        }
        if ("nonFatalStatusCodes" in e && Array.isArray(e.nonFatalStatusCodes)) {
            for (const r of e.nonFatalStatusCodes) {
                if (typeof r === "number") {
                    if (!Object.values(t.Status).includes(r)) {
                        throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range");
                    }
                } else if (typeof r === "string") {
                    if (!Object.values(t.Status).includes(r.toUpperCase())) {
                        throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name");
                    }
                } else {
                    throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");
                }
            }
        }
        const n = {
            maxAttempts: e.maxAttempts
        };
        if (e.hedgingDelay) {
            n.hedgingDelay = e.hedgingDelay;
        }
        if (e.nonFatalStatusCodes) {
            n.nonFatalStatusCodes = e.nonFatalStatusCodes;
        }
        return n;
    }
    function l(e) {
        var t;
        const n = {
            name: []
        };
        if (!("name" in e) || !Array.isArray(e.name)) {
            throw new Error("Invalid method config: invalid name array");
        }
        for (const t of e.name) {
            n.name.push(s(t));
        }
        if ("waitForReady" in e) {
            if (typeof e.waitForReady !== "boolean") {
                throw new Error("Invalid method config: invalid waitForReady");
            }
            n.waitForReady = e.waitForReady;
        }
        if ("timeout" in e) {
            if (typeof e.timeout === "object") {
                if (!("seconds" in e.timeout) || !(typeof e.timeout.seconds === "number")) {
                    throw new Error("Invalid method config: invalid timeout.seconds");
                }
                if (!("nanos" in e.timeout) || !(typeof e.timeout.nanos === "number")) {
                    throw new Error("Invalid method config: invalid timeout.nanos");
                }
                n.timeout = e.timeout;
            } else if (typeof e.timeout === "string" && r.test(e.timeout)) {
                const r = e.timeout.substring(0, e.timeout.length - 1).split(".");
                n.timeout = {
                    seconds: r[0] | 0,
                    nanos: ((t = r[1]) !== null && t !== void 0 ? t : 0) | 0
                };
            } else {
                throw new Error("Invalid method config: invalid timeout");
            }
        }
        if ("maxRequestBytes" in e) {
            if (typeof e.maxRequestBytes !== "number") {
                throw new Error("Invalid method config: invalid maxRequestBytes");
            }
            n.maxRequestBytes = e.maxRequestBytes;
        }
        if ("maxResponseBytes" in e) {
            if (typeof e.maxResponseBytes !== "number") {
                throw new Error("Invalid method config: invalid maxRequestBytes");
            }
            n.maxResponseBytes = e.maxResponseBytes;
        }
        if ("retryPolicy" in e) {
            if ("hedgingPolicy" in e) {
                throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");
            } else {
                n.retryPolicy = o(e.retryPolicy);
            }
        } else if ("hedgingPolicy" in e) {
            n.hedgingPolicy = a(e.hedgingPolicy);
        }
        return n;
    }
    function c(e) {
        if (!("maxTokens" in e) || typeof e.maxTokens !== "number" || e.maxTokens <= 0 || e.maxTokens > 1e3) {
            throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");
        }
        if (!("tokenRatio" in e) || typeof e.tokenRatio !== "number" || e.tokenRatio <= 0) {
            throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");
        }
        return {
            maxTokens: +e.maxTokens.toFixed(3),
            tokenRatio: +e.tokenRatio.toFixed(3)
        };
    }
    function u(e) {
        if (!(typeof e === "object" && e !== null)) {
            throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);
        }
        const t = Object.keys(e);
        if (t.length > 1) {
            throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);
        }
        if (t.length === 0) {
            throw new Error("Invalid loadBalancingConfig: load balancing policy name required");
        }
        return {
            [t[0]]: e[t[0]]
        };
    }
    function d(e) {
        const t = {
            loadBalancingConfig: [],
            methodConfig: []
        };
        if ("loadBalancingPolicy" in e) {
            if (typeof e.loadBalancingPolicy === "string") {
                t.loadBalancingPolicy = e.loadBalancingPolicy;
            } else {
                throw new Error("Invalid service config: invalid loadBalancingPolicy");
            }
        }
        if ("loadBalancingConfig" in e) {
            if (Array.isArray(e.loadBalancingConfig)) {
                for (const r of e.loadBalancingConfig) {
                    t.loadBalancingConfig.push(u(r));
                }
            } else {
                throw new Error("Invalid service config: invalid loadBalancingConfig");
            }
        }
        if ("methodConfig" in e) {
            if (Array.isArray(e.methodConfig)) {
                for (const r of e.methodConfig) {
                    t.methodConfig.push(l(r));
                }
            }
        }
        if ("retryThrottling" in e) {
            t.retryThrottling = c(e.retryThrottling);
        }
        const r = [];
        for (const e of t.methodConfig) {
            for (const t of e.name) {
                for (const e of r) {
                    if (t.service === e.service && t.method === e.method) {
                        throw new Error(`Invalid service config: duplicate name ${t.service}/${t.method}`);
                    }
                }
                r.push(t);
            }
        }
        return t;
    }
    function h(e) {
        if (!("serviceConfig" in e)) {
            throw new Error("Invalid service config choice: missing service config");
        }
        const t = {
            serviceConfig: d(e.serviceConfig)
        };
        if ("clientLanguage" in e) {
            if (Array.isArray(e.clientLanguage)) {
                t.clientLanguage = [];
                for (const r of e.clientLanguage) {
                    if (typeof r === "string") {
                        t.clientLanguage.push(r);
                    } else {
                        throw new Error("Invalid service config choice: invalid clientLanguage");
                    }
                }
            } else {
                throw new Error("Invalid service config choice: invalid clientLanguage");
            }
        }
        if ("clientHostname" in e) {
            if (Array.isArray(e.clientHostname)) {
                t.clientHostname = [];
                for (const r of e.clientHostname) {
                    if (typeof r === "string") {
                        t.clientHostname.push(r);
                    } else {
                        throw new Error("Invalid service config choice: invalid clientHostname");
                    }
                }
            } else {
                throw new Error("Invalid service config choice: invalid clientHostname");
            }
        }
        if ("percentage" in e) {
            if (typeof e.percentage === "number" && 0 <= e.percentage && e.percentage <= 100) {
                t.percentage = e.percentage;
            } else {
                throw new Error("Invalid service config choice: invalid percentage");
            }
        }
        const r = [ "clientLanguage", "percentage", "clientHostname", "serviceConfig" ];
        for (const t in e) {
            if (!r.includes(t)) {
                throw new Error(`Invalid service config choice: unexpected field ${t}`);
            }
        }
        return t;
    }
    function p(t, r) {
        if (!Array.isArray(t)) {
            throw new Error("Invalid service config list");
        }
        for (const s of t) {
            const t = h(s);
            if (typeof t.percentage === "number" && r > t.percentage) {
                continue;
            }
            if (Array.isArray(t.clientHostname)) {
                let r = false;
                for (const n of t.clientHostname) {
                    if (n === e.hostname()) {
                        r = true;
                    }
                }
                if (!r) {
                    continue;
                }
            }
            if (Array.isArray(t.clientLanguage)) {
                let e = false;
                for (const r of t.clientLanguage) {
                    if (r === n) {
                        e = true;
                    }
                }
                if (!e) {
                    continue;
                }
            }
            return t.serviceConfig;
        }
        throw new Error("No matching service config found");
    }
    function g(e, t) {
        for (const r of e) {
            if (r.length > 0 && r[0].startsWith("grpc_config=")) {
                const e = r.join("").substring("grpc_config=".length);
                const n = JSON.parse(e);
                return p(n, t);
            }
        }
        return null;
    }
    return serviceConfig;
}

var connectivityState = {};

Object.defineProperty(connectivityState, "__esModule", {
    value: true
});

connectivityState.ConnectivityState = void 0;

var ConnectivityState;

(function(e) {
    e[e["IDLE"] = 0] = "IDLE";
    e[e["CONNECTING"] = 1] = "CONNECTING";
    e[e["READY"] = 2] = "READY";
    e[e["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE";
    e[e["SHUTDOWN"] = 4] = "SHUTDOWN";
})(ConnectivityState || (connectivityState.ConnectivityState = ConnectivityState = {}));

var picker = {};

var hasRequiredPicker;

function requirePicker() {
    if (hasRequiredPicker) return picker;
    hasRequiredPicker = 1;
    Object.defineProperty(picker, "__esModule", {
        value: true
    });
    picker.QueuePicker = picker.UnavailablePicker = picker.PickResultType = void 0;
    const e = metadata;
    const t = constants;
    var r;
    (function(e) {
        e[e["COMPLETE"] = 0] = "COMPLETE";
        e[e["QUEUE"] = 1] = "QUEUE";
        e[e["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE";
        e[e["DROP"] = 3] = "DROP";
    })(r || (picker.PickResultType = r = {}));
    class UnavailablePicker {
        constructor(r) {
            this.status = Object.assign({
                code: t.Status.UNAVAILABLE,
                details: "No connection established",
                metadata: new e.Metadata
            }, r);
        }
        pick(e) {
            return {
                pickResultType: r.TRANSIENT_FAILURE,
                subchannel: null,
                status: this.status,
                onCallStarted: null,
                onCallEnded: null
            };
        }
    }
    picker.UnavailablePicker = UnavailablePicker;
    class QueuePicker {
        constructor(e, t) {
            this.loadBalancer = e;
            this.childPicker = t;
            this.calledExitIdle = false;
        }
        pick(e) {
            if (!this.calledExitIdle) {
                process.nextTick(() => {
                    this.loadBalancer.exitIdle();
                });
                this.calledExitIdle = true;
            }
            if (this.childPicker) {
                return this.childPicker.pick(e);
            } else {
                return {
                    pickResultType: r.QUEUE,
                    subchannel: null,
                    status: null,
                    onCallStarted: null,
                    onCallEnded: null
                };
            }
        }
    }
    picker.QueuePicker = QueuePicker;
    return picker;
}

var backoffTimeout = {};

var hasRequiredBackoffTimeout;

function requireBackoffTimeout() {
    if (hasRequiredBackoffTimeout) return backoffTimeout;
    hasRequiredBackoffTimeout = 1;
    Object.defineProperty(backoffTimeout, "__esModule", {
        value: true
    });
    backoffTimeout.BackoffTimeout = void 0;
    const e = constants;
    const t = logging$8;
    const r = "backoff";
    const n = 1e3;
    const s = 1.6;
    const o = 12e4;
    const a = .2;
    function l(e, t) {
        return Math.random() * (t - e) + e;
    }
    class BackoffTimeout {
        constructor(e, t) {
            this.callback = e;
            this.initialDelay = n;
            this.multiplier = s;
            this.maxDelay = o;
            this.jitter = a;
            this.running = false;
            this.hasRef = true;
            this.startTime = new Date;
            this.endTime = new Date;
            this.id = BackoffTimeout.getNextId();
            if (t) {
                if (t.initialDelay) {
                    this.initialDelay = t.initialDelay;
                }
                if (t.multiplier) {
                    this.multiplier = t.multiplier;
                }
                if (t.jitter) {
                    this.jitter = t.jitter;
                }
                if (t.maxDelay) {
                    this.maxDelay = t.maxDelay;
                }
            }
            this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay);
            this.nextDelay = this.initialDelay;
            this.timerId = setTimeout(() => {}, 0);
            clearTimeout(this.timerId);
        }
        static getNextId() {
            return this.nextId++;
        }
        trace(n) {
            t.trace(e.LogVerbosity.DEBUG, r, "{" + this.id + "} " + n);
        }
        runTimer(e) {
            var t, r;
            this.trace("runTimer(delay=" + e + ")");
            this.endTime = this.startTime;
            this.endTime.setMilliseconds(this.endTime.getMilliseconds() + e);
            clearTimeout(this.timerId);
            this.timerId = setTimeout(() => {
                this.trace("timer fired");
                this.running = false;
                this.callback();
            }, e);
            if (!this.hasRef) {
                (r = (t = this.timerId).unref) === null || r === void 0 ? void 0 : r.call(t);
            }
        }
        runOnce() {
            this.trace("runOnce()");
            this.running = true;
            this.startTime = new Date;
            this.runTimer(this.nextDelay);
            const e = Math.min(this.nextDelay * this.multiplier, this.maxDelay);
            const t = e * this.jitter;
            this.nextDelay = e + l(-t, t);
        }
        stop() {
            this.trace("stop()");
            clearTimeout(this.timerId);
            this.running = false;
        }
        reset() {
            this.trace("reset() running=" + this.running);
            this.nextDelay = this.initialDelay;
            if (this.running) {
                const e = new Date;
                const t = this.startTime;
                t.setMilliseconds(t.getMilliseconds() + this.nextDelay);
                clearTimeout(this.timerId);
                if (e < t) {
                    this.runTimer(t.getTime() - e.getTime());
                } else {
                    this.running = false;
                }
            }
        }
        isRunning() {
            return this.running;
        }
        ref() {
            var e, t;
            this.hasRef = true;
            (t = (e = this.timerId).ref) === null || t === void 0 ? void 0 : t.call(e);
        }
        unref() {
            var e, t;
            this.hasRef = false;
            (t = (e = this.timerId).unref) === null || t === void 0 ? void 0 : t.call(e);
        }
        getEndTime() {
            return this.endTime;
        }
    }
    backoffTimeout.BackoffTimeout = BackoffTimeout;
    BackoffTimeout.nextId = 0;
    return backoffTimeout;
}

var loadBalancerChildHandler = {};

var hasRequiredLoadBalancerChildHandler;

function requireLoadBalancerChildHandler() {
    if (hasRequiredLoadBalancerChildHandler) return loadBalancerChildHandler;
    hasRequiredLoadBalancerChildHandler = 1;
    Object.defineProperty(loadBalancerChildHandler, "__esModule", {
        value: true
    });
    loadBalancerChildHandler.ChildLoadBalancerHandler = void 0;
    const e = requireLoadBalancer();
    const t = connectivityState;
    const r = "child_load_balancer_helper";
    class ChildLoadBalancerHandler {
        constructor(e) {
            this.channelControlHelper = e;
            this.currentChild = null;
            this.pendingChild = null;
            this.latestConfig = null;
            this.ChildPolicyHelper = class {
                constructor(e) {
                    this.parent = e;
                    this.child = null;
                }
                createSubchannel(e, t) {
                    return this.parent.channelControlHelper.createSubchannel(e, t);
                }
                updateState(e, r, n) {
                    var s;
                    if (this.calledByPendingChild()) {
                        if (e === t.ConnectivityState.CONNECTING) {
                            return;
                        }
                        (s = this.parent.currentChild) === null || s === void 0 ? void 0 : s.destroy();
                        this.parent.currentChild = this.parent.pendingChild;
                        this.parent.pendingChild = null;
                    } else if (!this.calledByCurrentChild()) {
                        return;
                    }
                    this.parent.channelControlHelper.updateState(e, r, n);
                }
                requestReresolution() {
                    var e;
                    const t = (e = this.parent.pendingChild) !== null && e !== void 0 ? e : this.parent.currentChild;
                    if (this.child === t) {
                        this.parent.channelControlHelper.requestReresolution();
                    }
                }
                setChild(e) {
                    this.child = e;
                }
                addChannelzChild(e) {
                    this.parent.channelControlHelper.addChannelzChild(e);
                }
                removeChannelzChild(e) {
                    this.parent.channelControlHelper.removeChannelzChild(e);
                }
                calledByPendingChild() {
                    return this.child === this.parent.pendingChild;
                }
                calledByCurrentChild() {
                    return this.child === this.parent.currentChild;
                }
            };
        }
        configUpdateRequiresNewPolicyInstance(e, t) {
            return e.getLoadBalancerName() !== t.getLoadBalancerName();
        }
        updateAddressList(t, r, n, s) {
            let o;
            if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, r)) {
                const t = new this.ChildPolicyHelper(this);
                const n = (0, e.createLoadBalancer)(r, t);
                t.setChild(n);
                if (this.currentChild === null) {
                    this.currentChild = n;
                    o = this.currentChild;
                } else {
                    if (this.pendingChild) {
                        this.pendingChild.destroy();
                    }
                    this.pendingChild = n;
                    o = this.pendingChild;
                }
            } else {
                if (this.pendingChild === null) {
                    o = this.currentChild;
                } else {
                    o = this.pendingChild;
                }
            }
            this.latestConfig = r;
            return o.updateAddressList(t, r, n, s);
        }
        exitIdle() {
            if (this.currentChild) {
                this.currentChild.exitIdle();
                if (this.pendingChild) {
                    this.pendingChild.exitIdle();
                }
            }
        }
        resetBackoff() {
            if (this.currentChild) {
                this.currentChild.resetBackoff();
                if (this.pendingChild) {
                    this.pendingChild.resetBackoff();
                }
            }
        }
        destroy() {
            if (this.currentChild) {
                this.currentChild.destroy();
                this.currentChild = null;
            }
            if (this.pendingChild) {
                this.pendingChild.destroy();
                this.pendingChild = null;
            }
        }
        getTypeName() {
            return r;
        }
    }
    loadBalancerChildHandler.ChildLoadBalancerHandler = ChildLoadBalancerHandler;
    return loadBalancerChildHandler;
}

Object.defineProperty(resolvingLoadBalancer, "__esModule", {
    value: true
});

resolvingLoadBalancer.ResolvingLoadBalancer = void 0;

const load_balancer_1 = requireLoadBalancer();

const service_config_1 = requireServiceConfig();

const connectivity_state_1$1 = connectivityState;

const resolver_1$1 = resolver;

const picker_1$1 = requirePicker();

const backoff_timeout_1 = requireBackoffTimeout();

const constants_1$a = constants;

const metadata_1$5 = metadata;

const logging$7 = logging$8;

const constants_2$1 = constants;

const uri_parser_1$3 = uriParser;

const load_balancer_child_handler_1 = requireLoadBalancerChildHandler();

const TRACER_NAME$6 = "resolving_load_balancer";

function trace$1(e) {
    logging$7.trace(constants_2$1.LogVerbosity.DEBUG, TRACER_NAME$6, e);
}

const NAME_MATCH_LEVEL_ORDER = [ "SERVICE_AND_METHOD", "SERVICE", "EMPTY" ];

function hasMatchingName(e, t, r, n) {
    for (const s of r.name) {
        switch (n) {
          case "EMPTY":
            if (!s.service && !s.method) {
                return true;
            }
            break;

          case "SERVICE":
            if (s.service === e && !s.method) {
                return true;
            }
            break;

          case "SERVICE_AND_METHOD":
            if (s.service === e && s.method === t) {
                return true;
            }
        }
    }
    return false;
}

function findMatchingConfig(e, t, r, n) {
    for (const s of r) {
        if (hasMatchingName(e, t, s, n)) {
            return s;
        }
    }
    return null;
}

function getDefaultConfigSelector(e) {
    return {
        invoke(t, r) {
            var n, s;
            const o = t.split("/").filter(e => e.length > 0);
            const a = (n = o[0]) !== null && n !== void 0 ? n : "";
            const l = (s = o[1]) !== null && s !== void 0 ? s : "";
            if (e && e.methodConfig) {
                for (const t of NAME_MATCH_LEVEL_ORDER) {
                    const r = findMatchingConfig(a, l, e.methodConfig, t);
                    if (r) {
                        return {
                            methodConfig: r,
                            pickInformation: {},
                            status: constants_1$a.Status.OK,
                            dynamicFilterFactories: []
                        };
                    }
                }
            }
            return {
                methodConfig: {
                    name: []
                },
                pickInformation: {},
                status: constants_1$a.Status.OK,
                dynamicFilterFactories: []
            };
        },
        unref() {}
    };
}

class ResolvingLoadBalancer {
    constructor(e, t, r, n, s) {
        this.target = e;
        this.channelControlHelper = t;
        this.channelOptions = r;
        this.onSuccessfulResolution = n;
        this.onFailedResolution = s;
        this.latestChildState = connectivity_state_1$1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1$1.QueuePicker(this);
        this.latestChildErrorMessage = null;
        this.currentState = connectivity_state_1$1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
        if (r["grpc.service_config"]) {
            this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(r["grpc.service_config"]));
        } else {
            this.defaultServiceConfig = {
                loadBalancingConfig: [],
                methodConfig: []
            };
        }
        this.updateState(connectivity_state_1$1.ConnectivityState.IDLE, new picker_1$1.QueuePicker(this), null);
        this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({
            createSubchannel: t.createSubchannel.bind(t),
            requestReresolution: () => {
                if (this.backoffTimeout.isRunning()) {
                    trace$1("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString());
                    this.continueResolving = true;
                } else {
                    this.updateResolution();
                }
            },
            updateState: (e, t, r) => {
                this.latestChildState = e;
                this.latestChildPicker = t;
                this.latestChildErrorMessage = r;
                this.updateState(e, t, r);
            },
            addChannelzChild: t.addChannelzChild.bind(t),
            removeChannelzChild: t.removeChannelzChild.bind(t)
        });
        this.innerResolver = (0, resolver_1$1.createResolver)(e, this.handleResolverResult.bind(this), r);
        const o = {
            initialDelay: r["grpc.initial_reconnect_backoff_ms"],
            maxDelay: r["grpc.max_reconnect_backoff_ms"]
        };
        this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => {
            if (this.continueResolving) {
                this.updateResolution();
                this.continueResolving = false;
            } else {
                this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage);
            }
        }, o);
        this.backoffTimeout.unref();
    }
    handleResolverResult(e, t, r, n) {
        var s, o;
        this.backoffTimeout.stop();
        this.backoffTimeout.reset();
        let a = true;
        let l = null;
        if (r === null) {
            l = this.defaultServiceConfig;
        } else if (r.ok) {
            l = r.value;
        } else {
            if (this.previousServiceConfig !== null) {
                l = this.previousServiceConfig;
            } else {
                a = false;
                this.handleResolutionFailure(r.error);
            }
        }
        if (l !== null) {
            const r = (s = l === null || l === void 0 ? void 0 : l.loadBalancingConfig) !== null && s !== void 0 ? s : [];
            const o = (0, load_balancer_1.selectLbConfigFromList)(r, true);
            if (o === null) {
                a = false;
                this.handleResolutionFailure({
                    code: constants_1$a.Status.UNAVAILABLE,
                    details: "All load balancer options in service config are not compatible",
                    metadata: new metadata_1$5.Metadata
                });
            } else {
                a = this.childLoadBalancer.updateAddressList(e, o, Object.assign(Object.assign({}, this.channelOptions), t), n);
            }
        }
        if (a) {
            this.onSuccessfulResolution(l, (o = t[resolver_1$1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && o !== void 0 ? o : getDefaultConfigSelector(l));
        }
        return a;
    }
    updateResolution() {
        this.innerResolver.updateResolution();
        if (this.currentState === connectivity_state_1$1.ConnectivityState.IDLE) {
            this.updateState(connectivity_state_1$1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage);
        }
        this.backoffTimeout.runOnce();
    }
    updateState(e, t, r) {
        trace$1((0, uri_parser_1$3.uriToString)(this.target) + " " + connectivity_state_1$1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1$1.ConnectivityState[e]);
        if (e === connectivity_state_1$1.ConnectivityState.IDLE) {
            t = new picker_1$1.QueuePicker(this, t);
        }
        this.currentState = e;
        this.channelControlHelper.updateState(e, t, r);
    }
    handleResolutionFailure(e) {
        if (this.latestChildState === connectivity_state_1$1.ConnectivityState.IDLE) {
            this.updateState(connectivity_state_1$1.ConnectivityState.TRANSIENT_FAILURE, new picker_1$1.UnavailablePicker(e), e.details);
            this.onFailedResolution(e);
        }
    }
    exitIdle() {
        if (this.currentState === connectivity_state_1$1.ConnectivityState.IDLE || this.currentState === connectivity_state_1$1.ConnectivityState.TRANSIENT_FAILURE) {
            if (this.backoffTimeout.isRunning()) {
                this.continueResolving = true;
            } else {
                this.updateResolution();
            }
        }
        this.childLoadBalancer.exitIdle();
    }
    updateAddressList(e, t) {
        throw new Error("updateAddressList not supported on ResolvingLoadBalancer");
    }
    resetBackoff() {
        this.backoffTimeout.reset();
        this.childLoadBalancer.resetBackoff();
    }
    destroy() {
        this.childLoadBalancer.destroy();
        this.innerResolver.destroy();
        this.backoffTimeout.reset();
        this.backoffTimeout.stop();
        this.latestChildState = connectivity_state_1$1.ConnectivityState.IDLE;
        this.latestChildPicker = new picker_1$1.QueuePicker(this);
        this.currentState = connectivity_state_1$1.ConnectivityState.IDLE;
        this.previousServiceConfig = null;
        this.continueResolving = false;
    }
    getTypeName() {
        return "resolving_load_balancer";
    }
}

resolvingLoadBalancer.ResolvingLoadBalancer = ResolvingLoadBalancer;

var subchannelPool = {};

var channelOptions = {};

Object.defineProperty(channelOptions, "__esModule", {
    value: true
});

channelOptions.recognizedOptions = void 0;

channelOptions.channelOptionsEqual = channelOptionsEqual;

channelOptions.recognizedOptions = {
    "grpc.ssl_target_name_override": true,
    "grpc.primary_user_agent": true,
    "grpc.secondary_user_agent": true,
    "grpc.default_authority": true,
    "grpc.keepalive_time_ms": true,
    "grpc.keepalive_timeout_ms": true,
    "grpc.keepalive_permit_without_calls": true,
    "grpc.service_config": true,
    "grpc.max_concurrent_streams": true,
    "grpc.initial_reconnect_backoff_ms": true,
    "grpc.max_reconnect_backoff_ms": true,
    "grpc.use_local_subchannel_pool": true,
    "grpc.max_send_message_length": true,
    "grpc.max_receive_message_length": true,
    "grpc.enable_http_proxy": true,
    "grpc.enable_channelz": true,
    "grpc.dns_min_time_between_resolutions_ms": true,
    "grpc.enable_retries": true,
    "grpc.per_rpc_retry_buffer_size": true,
    "grpc.retry_buffer_size": true,
    "grpc.max_connection_age_ms": true,
    "grpc.max_connection_age_grace_ms": true,
    "grpc-node.max_session_memory": true,
    "grpc.service_config_disable_resolution": true,
    "grpc.client_idle_timeout_ms": true,
    "grpc-node.tls_enable_trace": true,
    "grpc.lb.ring_hash.ring_size_cap": true,
    "grpc-node.retry_max_attempts_limit": true,
    "grpc-node.flow_control_window": true,
    "grpc.server_call_metric_recording": true
};

function channelOptionsEqual(e, t) {
    const r = Object.keys(e).sort();
    const n = Object.keys(t).sort();
    if (r.length !== n.length) {
        return false;
    }
    for (let s = 0; s < r.length; s += 1) {
        if (r[s] !== n[s]) {
            return false;
        }
        if (e[r[s]] !== t[n[s]]) {
            return false;
        }
    }
    return true;
}

var subchannel = {};

var subchannelAddress = {};

Object.defineProperty(subchannelAddress, "__esModule", {
    value: true
});

subchannelAddress.EndpointMap = void 0;

subchannelAddress.isTcpSubchannelAddress = isTcpSubchannelAddress;

subchannelAddress.subchannelAddressEqual = subchannelAddressEqual;

subchannelAddress.subchannelAddressToString = subchannelAddressToString;

subchannelAddress.stringToSubchannelAddress = stringToSubchannelAddress;

subchannelAddress.endpointEqual = endpointEqual;

subchannelAddress.endpointToString = endpointToString;

subchannelAddress.endpointHasAddress = endpointHasAddress;

const net_1$1 = require$$0__default$6.default;

function isTcpSubchannelAddress(e) {
    return "port" in e;
}

function subchannelAddressEqual(e, t) {
    if (!e && !t) {
        return true;
    }
    if (!e || !t) {
        return false;
    }
    if (isTcpSubchannelAddress(e)) {
        return isTcpSubchannelAddress(t) && e.host === t.host && e.port === t.port;
    } else {
        return !isTcpSubchannelAddress(t) && e.path === t.path;
    }
}

function subchannelAddressToString(e) {
    if (isTcpSubchannelAddress(e)) {
        if ((0, net_1$1.isIPv6)(e.host)) {
            return "[" + e.host + "]:" + e.port;
        } else {
            return e.host + ":" + e.port;
        }
    } else {
        return e.path;
    }
}

const DEFAULT_PORT = 443;

function stringToSubchannelAddress(e, t) {
    if ((0, net_1$1.isIP)(e)) {
        return {
            host: e,
            port: t !== null && t !== void 0 ? t : DEFAULT_PORT
        };
    } else {
        return {
            path: e
        };
    }
}

function endpointEqual(e, t) {
    if (e.addresses.length !== t.addresses.length) {
        return false;
    }
    for (let r = 0; r < e.addresses.length; r++) {
        if (!subchannelAddressEqual(e.addresses[r], t.addresses[r])) {
            return false;
        }
    }
    return true;
}

function endpointToString(e) {
    return "[" + e.addresses.map(subchannelAddressToString).join(", ") + "]";
}

function endpointHasAddress(e, t) {
    for (const r of e.addresses) {
        if (subchannelAddressEqual(r, t)) {
            return true;
        }
    }
    return false;
}

function endpointEqualUnordered(e, t) {
    if (e.addresses.length !== t.addresses.length) {
        return false;
    }
    for (const r of e.addresses) {
        let e = false;
        for (const n of t.addresses) {
            if (subchannelAddressEqual(r, n)) {
                e = true;
                break;
            }
        }
        if (!e) {
            return false;
        }
    }
    return true;
}

class EndpointMap {
    constructor() {
        this.map = new Set;
    }
    get size() {
        return this.map.size;
    }
    getForSubchannelAddress(e) {
        for (const t of this.map) {
            if (endpointHasAddress(t.key, e)) {
                return t.value;
            }
        }
        return undefined;
    }
    deleteMissing(e) {
        const t = [];
        for (const r of this.map) {
            let n = false;
            for (const t of e) {
                if (endpointEqualUnordered(t, r.key)) {
                    n = true;
                }
            }
            if (!n) {
                t.push(r.value);
                this.map.delete(r);
            }
        }
        return t;
    }
    get(e) {
        for (const t of this.map) {
            if (endpointEqualUnordered(e, t.key)) {
                return t.value;
            }
        }
        return undefined;
    }
    set(e, t) {
        for (const r of this.map) {
            if (endpointEqualUnordered(e, r.key)) {
                r.value = t;
                return;
            }
        }
        this.map.add({
            key: e,
            value: t
        });
    }
    delete(e) {
        for (const t of this.map) {
            if (endpointEqualUnordered(e, t.key)) {
                this.map.delete(t);
                return;
            }
        }
    }
    has(e) {
        for (const t of this.map) {
            if (endpointEqualUnordered(e, t.key)) {
                return true;
            }
        }
        return false;
    }
    clear() {
        this.map.clear();
    }
    * keys() {
        for (const e of this.map) {
            yield e.key;
        }
    }
    * values() {
        for (const e of this.map) {
            yield e.value;
        }
    }
    * entries() {
        for (const e of this.map) {
            yield [ e.key, e.value ];
        }
    }
}

subchannelAddress.EndpointMap = EndpointMap;

var channelz = {};

var extendStatics = function(e, t) {
    extendStatics = Object.setPrototypeOf || {
        __proto__: []
    } instanceof Array && function(e, t) {
        e.__proto__ = t;
    } || function(e, t) {
        for (var r in t) if (Object.prototype.hasOwnProperty.call(t, r)) e[r] = t[r];
    };
    return extendStatics(e, t);
};

function __extends(e, t) {
    if (typeof t !== "function" && t !== null) throw new TypeError("Class extends value " + String(t) + " is not a constructor or null");
    extendStatics(e, t);
    function r() {
        this.constructor = e;
    }
    e.prototype = t === null ? Object.create(t) : (r.prototype = t.prototype, new r);
}

function __generator(e, t) {
    var r = {
        label: 0,
        sent: function() {
            if (o[0] & 1) throw o[1];
            return o[1];
        },
        trys: [],
        ops: []
    }, n, s, o, a;
    return a = {
        next: l(0),
        throw: l(1),
        return: l(2)
    }, typeof Symbol === "function" && (a[Symbol.iterator] = function() {
        return this;
    }), a;
    function l(e) {
        return function(t) {
            return c([ e, t ]);
        };
    }
    function c(l) {
        if (n) throw new TypeError("Generator is already executing.");
        while (a && (a = 0, l[0] && (r = 0)), r) try {
            if (n = 1, s && (o = l[0] & 2 ? s["return"] : l[0] ? s["throw"] || ((o = s["return"]) && o.call(s), 
            0) : s.next) && !(o = o.call(s, l[1])).done) return o;
            if (s = 0, o) l = [ l[0] & 2, o.value ];
            switch (l[0]) {
              case 0:
              case 1:
                o = l;
                break;

              case 4:
                r.label++;
                return {
                    value: l[1],
                    done: false
                };

              case 5:
                r.label++;
                s = l[1];
                l = [ 0 ];
                continue;

              case 7:
                l = r.ops.pop();
                r.trys.pop();
                continue;

              default:
                if (!(o = r.trys, o = o.length > 0 && o[o.length - 1]) && (l[0] === 6 || l[0] === 2)) {
                    r = 0;
                    continue;
                }
                if (l[0] === 3 && (!o || l[1] > o[0] && l[1] < o[3])) {
                    r.label = l[1];
                    break;
                }
                if (l[0] === 6 && r.label < o[1]) {
                    r.label = o[1];
                    o = l;
                    break;
                }
                if (o && r.label < o[2]) {
                    r.label = o[2];
                    r.ops.push(l);
                    break;
                }
                if (o[2]) r.ops.pop();
                r.trys.pop();
                continue;
            }
            l = t.call(e, r);
        } catch (e) {
            l = [ 6, e ];
            s = 0;
        } finally {
            n = o = 0;
        }
        if (l[0] & 5) throw l[1];
        return {
            value: l[0] ? l[1] : void 0,
            done: true
        };
    }
}

typeof SuppressedError === "function" ? SuppressedError : function(e, t, r) {
    var n = new Error(r);
    return n.name = "SuppressedError", n.error = e, n.suppressed = t, n;
};

var TreeNode = function() {
    function e(e, t, r) {
        if (r === void 0) {
            r = 1;
        }
        this.t = undefined;
        this.i = undefined;
        this.h = undefined;
        this.u = e;
        this.o = t;
        this.l = r;
    }
    e.prototype.v = function() {
        var e = this;
        var t = e.h.h === e;
        if (t && e.l === 1) {
            e = e.i;
        } else if (e.t) {
            e = e.t;
            while (e.i) {
                e = e.i;
            }
        } else {
            if (t) {
                return e.h;
            }
            var r = e.h;
            while (r.t === e) {
                e = r;
                r = e.h;
            }
            e = r;
        }
        return e;
    };
    e.prototype.p = function() {
        var e = this;
        if (e.i) {
            e = e.i;
            while (e.t) {
                e = e.t;
            }
            return e;
        } else {
            var t = e.h;
            while (t.i === e) {
                e = t;
                t = e.h;
            }
            if (e.i !== t) {
                return t;
            } else return e;
        }
    };
    e.prototype.T = function() {
        var e = this.h;
        var t = this.i;
        var r = t.t;
        if (e.h === this) e.h = t; else if (e.t === this) e.t = t; else e.i = t;
        t.h = e;
        t.t = this;
        this.h = t;
        this.i = r;
        if (r) r.h = this;
        return t;
    };
    e.prototype.I = function() {
        var e = this.h;
        var t = this.t;
        var r = t.i;
        if (e.h === this) e.h = t; else if (e.t === this) e.t = t; else e.i = t;
        t.h = e;
        t.i = this;
        this.h = t;
        this.t = r;
        if (r) r.h = this;
        return t;
    };
    return e;
}();

var TreeNodeEnableIndex = function(e) {
    __extends(t, e);
    function t() {
        var t = e !== null && e.apply(this, arguments) || this;
        t.O = 1;
        return t;
    }
    t.prototype.T = function() {
        var t = e.prototype.T.call(this);
        this.M();
        t.M();
        return t;
    };
    t.prototype.I = function() {
        var t = e.prototype.I.call(this);
        this.M();
        t.M();
        return t;
    };
    t.prototype.M = function() {
        this.O = 1;
        if (this.t) {
            this.O += this.t.O;
        }
        if (this.i) {
            this.O += this.i.O;
        }
    };
    return t;
}(TreeNode);

var ContainerIterator = function() {
    function e(e) {
        if (e === void 0) {
            e = 0;
        }
        this.iteratorType = e;
    }
    e.prototype.equals = function(e) {
        return this.C === e.C;
    };
    return e;
}();

var Base = function() {
    function e() {
        this._ = 0;
    }
    Object.defineProperty(e.prototype, "length", {
        get: function() {
            return this._;
        },
        enumerable: false,
        configurable: true
    });
    e.prototype.size = function() {
        return this._;
    };
    e.prototype.empty = function() {
        return this._ === 0;
    };
    return e;
}();

var Container$1 = function(e) {
    __extends(t, e);
    function t() {
        return e !== null && e.apply(this, arguments) || this;
    }
    return t;
}(Base);

function throwIteratorAccessError() {
    throw new RangeError("Iterator access denied!");
}

var TreeContainer = function(e) {
    __extends(t, e);
    function t(t, r) {
        if (t === void 0) {
            t = function(e, t) {
                if (e < t) return -1;
                if (e > t) return 1;
                return 0;
            };
        }
        if (r === void 0) {
            r = false;
        }
        var n = e.call(this) || this;
        n.N = undefined;
        n.g = t;
        n.enableIndex = r;
        n.S = r ? TreeNodeEnableIndex : TreeNode;
        n.A = new n.S;
        return n;
    }
    t.prototype.m = function(e, t) {
        var r = this.A;
        while (e) {
            var n = this.g(e.u, t);
            if (n < 0) {
                e = e.i;
            } else if (n > 0) {
                r = e;
                e = e.t;
            } else return e;
        }
        return r;
    };
    t.prototype.B = function(e, t) {
        var r = this.A;
        while (e) {
            var n = this.g(e.u, t);
            if (n <= 0) {
                e = e.i;
            } else {
                r = e;
                e = e.t;
            }
        }
        return r;
    };
    t.prototype.j = function(e, t) {
        var r = this.A;
        while (e) {
            var n = this.g(e.u, t);
            if (n < 0) {
                r = e;
                e = e.i;
            } else if (n > 0) {
                e = e.t;
            } else return e;
        }
        return r;
    };
    t.prototype.k = function(e, t) {
        var r = this.A;
        while (e) {
            var n = this.g(e.u, t);
            if (n < 0) {
                r = e;
                e = e.i;
            } else {
                e = e.t;
            }
        }
        return r;
    };
    t.prototype.R = function(e) {
        while (true) {
            var t = e.h;
            if (t === this.A) return;
            if (e.l === 1) {
                e.l = 0;
                return;
            }
            if (e === t.t) {
                var r = t.i;
                if (r.l === 1) {
                    r.l = 0;
                    t.l = 1;
                    if (t === this.N) {
                        this.N = t.T();
                    } else t.T();
                } else {
                    if (r.i && r.i.l === 1) {
                        r.l = t.l;
                        t.l = 0;
                        r.i.l = 0;
                        if (t === this.N) {
                            this.N = t.T();
                        } else t.T();
                        return;
                    } else if (r.t && r.t.l === 1) {
                        r.l = 1;
                        r.t.l = 0;
                        r.I();
                    } else {
                        r.l = 1;
                        e = t;
                    }
                }
            } else {
                var r = t.t;
                if (r.l === 1) {
                    r.l = 0;
                    t.l = 1;
                    if (t === this.N) {
                        this.N = t.I();
                    } else t.I();
                } else {
                    if (r.t && r.t.l === 1) {
                        r.l = t.l;
                        t.l = 0;
                        r.t.l = 0;
                        if (t === this.N) {
                            this.N = t.I();
                        } else t.I();
                        return;
                    } else if (r.i && r.i.l === 1) {
                        r.l = 1;
                        r.i.l = 0;
                        r.T();
                    } else {
                        r.l = 1;
                        e = t;
                    }
                }
            }
        }
    };
    t.prototype.G = function(e) {
        if (this._ === 1) {
            this.clear();
            return;
        }
        var t = e;
        while (t.t || t.i) {
            if (t.i) {
                t = t.i;
                while (t.t) t = t.t;
            } else {
                t = t.t;
            }
            var r = e.u;
            e.u = t.u;
            t.u = r;
            var n = e.o;
            e.o = t.o;
            t.o = n;
            e = t;
        }
        if (this.A.t === t) {
            this.A.t = t.h;
        } else if (this.A.i === t) {
            this.A.i = t.h;
        }
        this.R(t);
        var s = t.h;
        if (t === s.t) {
            s.t = undefined;
        } else s.i = undefined;
        this._ -= 1;
        this.N.l = 0;
        if (this.enableIndex) {
            while (s !== this.A) {
                s.O -= 1;
                s = s.h;
            }
        }
    };
    t.prototype.P = function(e) {
        var t = typeof e === "number" ? e : undefined;
        var r = typeof e === "function" ? e : undefined;
        var n = typeof e === "undefined" ? [] : undefined;
        var s = 0;
        var o = this.N;
        var a = [];
        while (a.length || o) {
            if (o) {
                a.push(o);
                o = o.t;
            } else {
                o = a.pop();
                if (s === t) return o;
                n && n.push(o);
                r && r(o, s, this);
                s += 1;
                o = o.i;
            }
        }
        return n;
    };
    t.prototype.q = function(e) {
        while (true) {
            var t = e.h;
            if (t.l === 0) return;
            var r = t.h;
            if (t === r.t) {
                var n = r.i;
                if (n && n.l === 1) {
                    n.l = t.l = 0;
                    if (r === this.N) return;
                    r.l = 1;
                    e = r;
                    continue;
                } else if (e === t.i) {
                    e.l = 0;
                    if (e.t) {
                        e.t.h = t;
                    }
                    if (e.i) {
                        e.i.h = r;
                    }
                    t.i = e.t;
                    r.t = e.i;
                    e.t = t;
                    e.i = r;
                    if (r === this.N) {
                        this.N = e;
                        this.A.h = e;
                    } else {
                        var s = r.h;
                        if (s.t === r) {
                            s.t = e;
                        } else s.i = e;
                    }
                    e.h = r.h;
                    t.h = e;
                    r.h = e;
                    r.l = 1;
                } else {
                    t.l = 0;
                    if (r === this.N) {
                        this.N = r.I();
                    } else r.I();
                    r.l = 1;
                    return;
                }
            } else {
                var n = r.t;
                if (n && n.l === 1) {
                    n.l = t.l = 0;
                    if (r === this.N) return;
                    r.l = 1;
                    e = r;
                    continue;
                } else if (e === t.t) {
                    e.l = 0;
                    if (e.t) {
                        e.t.h = r;
                    }
                    if (e.i) {
                        e.i.h = t;
                    }
                    r.i = e.t;
                    t.t = e.i;
                    e.t = r;
                    e.i = t;
                    if (r === this.N) {
                        this.N = e;
                        this.A.h = e;
                    } else {
                        var s = r.h;
                        if (s.t === r) {
                            s.t = e;
                        } else s.i = e;
                    }
                    e.h = r.h;
                    t.h = e;
                    r.h = e;
                    r.l = 1;
                } else {
                    t.l = 0;
                    if (r === this.N) {
                        this.N = r.T();
                    } else r.T();
                    r.l = 1;
                    return;
                }
            }
            if (this.enableIndex) {
                t.M();
                r.M();
                e.M();
            }
            return;
        }
    };
    t.prototype.D = function(e, t, r) {
        if (this.N === undefined) {
            this._ += 1;
            this.N = new this.S(e, t, 0);
            this.N.h = this.A;
            this.A.h = this.A.t = this.A.i = this.N;
            return this._;
        }
        var n;
        var s = this.A.t;
        var o = this.g(s.u, e);
        if (o === 0) {
            s.o = t;
            return this._;
        } else if (o > 0) {
            s.t = new this.S(e, t);
            s.t.h = s;
            n = s.t;
            this.A.t = n;
        } else {
            var a = this.A.i;
            var l = this.g(a.u, e);
            if (l === 0) {
                a.o = t;
                return this._;
            } else if (l < 0) {
                a.i = new this.S(e, t);
                a.i.h = a;
                n = a.i;
                this.A.i = n;
            } else {
                if (r !== undefined) {
                    var c = r.C;
                    if (c !== this.A) {
                        var u = this.g(c.u, e);
                        if (u === 0) {
                            c.o = t;
                            return this._;
                        } else if (u > 0) {
                            var d = c.v();
                            var h = this.g(d.u, e);
                            if (h === 0) {
                                d.o = t;
                                return this._;
                            } else if (h < 0) {
                                n = new this.S(e, t);
                                if (d.i === undefined) {
                                    d.i = n;
                                    n.h = d;
                                } else {
                                    c.t = n;
                                    n.h = c;
                                }
                            }
                        }
                    }
                }
                if (n === undefined) {
                    n = this.N;
                    while (true) {
                        var p = this.g(n.u, e);
                        if (p > 0) {
                            if (n.t === undefined) {
                                n.t = new this.S(e, t);
                                n.t.h = n;
                                n = n.t;
                                break;
                            }
                            n = n.t;
                        } else if (p < 0) {
                            if (n.i === undefined) {
                                n.i = new this.S(e, t);
                                n.i.h = n;
                                n = n.i;
                                break;
                            }
                            n = n.i;
                        } else {
                            n.o = t;
                            return this._;
                        }
                    }
                }
            }
        }
        if (this.enableIndex) {
            var g = n.h;
            while (g !== this.A) {
                g.O += 1;
                g = g.h;
            }
        }
        this.q(n);
        this._ += 1;
        return this._;
    };
    t.prototype.F = function(e, t) {
        while (e) {
            var r = this.g(e.u, t);
            if (r < 0) {
                e = e.i;
            } else if (r > 0) {
                e = e.t;
            } else return e;
        }
        return e || this.A;
    };
    t.prototype.clear = function() {
        this._ = 0;
        this.N = undefined;
        this.A.h = undefined;
        this.A.t = this.A.i = undefined;
    };
    t.prototype.updateKeyByIterator = function(e, t) {
        var r = e.C;
        if (r === this.A) {
            throwIteratorAccessError();
        }
        if (this._ === 1) {
            r.u = t;
            return true;
        }
        var n = r.p().u;
        if (r === this.A.t) {
            if (this.g(n, t) > 0) {
                r.u = t;
                return true;
            }
            return false;
        }
        var s = r.v().u;
        if (r === this.A.i) {
            if (this.g(s, t) < 0) {
                r.u = t;
                return true;
            }
            return false;
        }
        if (this.g(s, t) >= 0 || this.g(n, t) <= 0) return false;
        r.u = t;
        return true;
    };
    t.prototype.eraseElementByPos = function(e) {
        if (e < 0 || e > this._ - 1) {
            throw new RangeError;
        }
        var t = this.P(e);
        this.G(t);
        return this._;
    };
    t.prototype.eraseElementByKey = function(e) {
        if (this._ === 0) return false;
        var t = this.F(this.N, e);
        if (t === this.A) return false;
        this.G(t);
        return true;
    };
    t.prototype.eraseElementByIterator = function(e) {
        var t = e.C;
        if (t === this.A) {
            throwIteratorAccessError();
        }
        var r = t.i === undefined;
        var n = e.iteratorType === 0;
        if (n) {
            if (r) e.next();
        } else {
            if (!r || t.t === undefined) e.next();
        }
        this.G(t);
        return e;
    };
    t.prototype.getHeight = function() {
        if (this._ === 0) return 0;
        function e(t) {
            if (!t) return 0;
            return Math.max(e(t.t), e(t.i)) + 1;
        }
        return e(this.N);
    };
    return t;
}(Container$1);

var TreeIterator = function(e) {
    __extends(t, e);
    function t(t, r, n) {
        var s = e.call(this, n) || this;
        s.C = t;
        s.A = r;
        if (s.iteratorType === 0) {
            s.pre = function() {
                if (this.C === this.A.t) {
                    throwIteratorAccessError();
                }
                this.C = this.C.v();
                return this;
            };
            s.next = function() {
                if (this.C === this.A) {
                    throwIteratorAccessError();
                }
                this.C = this.C.p();
                return this;
            };
        } else {
            s.pre = function() {
                if (this.C === this.A.i) {
                    throwIteratorAccessError();
                }
                this.C = this.C.p();
                return this;
            };
            s.next = function() {
                if (this.C === this.A) {
                    throwIteratorAccessError();
                }
                this.C = this.C.v();
                return this;
            };
        }
        return s;
    }
    Object.defineProperty(t.prototype, "index", {
        get: function() {
            var e = this.C;
            var t = this.A.h;
            if (e === this.A) {
                if (t) {
                    return t.O - 1;
                }
                return 0;
            }
            var r = 0;
            if (e.t) {
                r += e.t.O;
            }
            while (e !== t) {
                var n = e.h;
                if (e === n.i) {
                    r += 1;
                    if (n.t) {
                        r += n.t.O;
                    }
                }
                e = n;
            }
            return r;
        },
        enumerable: false,
        configurable: true
    });
    t.prototype.isAccessible = function() {
        return this.C !== this.A;
    };
    return t;
}(ContainerIterator);

var OrderedMapIterator = function(e) {
    __extends(t, e);
    function t(t, r, n, s) {
        var o = e.call(this, t, r, s) || this;
        o.container = n;
        return o;
    }
    Object.defineProperty(t.prototype, "pointer", {
        get: function() {
            if (this.C === this.A) {
                throwIteratorAccessError();
            }
            var e = this;
            return new Proxy([], {
                get: function(t, r) {
                    if (r === "0") return e.C.u; else if (r === "1") return e.C.o;
                    t[0] = e.C.u;
                    t[1] = e.C.o;
                    return t[r];
                },
                set: function(t, r, n) {
                    if (r !== "1") {
                        throw new TypeError("prop must be 1");
                    }
                    e.C.o = n;
                    return true;
                }
            });
        },
        enumerable: false,
        configurable: true
    });
    t.prototype.copy = function() {
        return new t(this.C, this.A, this.container, this.iteratorType);
    };
    return t;
}(TreeIterator);

var OrderedMap = function(e) {
    __extends(t, e);
    function t(t, r, n) {
        if (t === void 0) {
            t = [];
        }
        var s = e.call(this, r, n) || this;
        var o = s;
        t.forEach(function(e) {
            o.setElement(e[0], e[1]);
        });
        return s;
    }
    t.prototype.begin = function() {
        return new OrderedMapIterator(this.A.t || this.A, this.A, this);
    };
    t.prototype.end = function() {
        return new OrderedMapIterator(this.A, this.A, this);
    };
    t.prototype.rBegin = function() {
        return new OrderedMapIterator(this.A.i || this.A, this.A, this, 1);
    };
    t.prototype.rEnd = function() {
        return new OrderedMapIterator(this.A, this.A, this, 1);
    };
    t.prototype.front = function() {
        if (this._ === 0) return;
        var e = this.A.t;
        return [ e.u, e.o ];
    };
    t.prototype.back = function() {
        if (this._ === 0) return;
        var e = this.A.i;
        return [ e.u, e.o ];
    };
    t.prototype.lowerBound = function(e) {
        var t = this.m(this.N, e);
        return new OrderedMapIterator(t, this.A, this);
    };
    t.prototype.upperBound = function(e) {
        var t = this.B(this.N, e);
        return new OrderedMapIterator(t, this.A, this);
    };
    t.prototype.reverseLowerBound = function(e) {
        var t = this.j(this.N, e);
        return new OrderedMapIterator(t, this.A, this);
    };
    t.prototype.reverseUpperBound = function(e) {
        var t = this.k(this.N, e);
        return new OrderedMapIterator(t, this.A, this);
    };
    t.prototype.forEach = function(e) {
        this.P(function(t, r, n) {
            e([ t.u, t.o ], r, n);
        });
    };
    t.prototype.setElement = function(e, t, r) {
        return this.D(e, t, r);
    };
    t.prototype.getElementByPos = function(e) {
        if (e < 0 || e > this._ - 1) {
            throw new RangeError;
        }
        var t = this.P(e);
        return [ t.u, t.o ];
    };
    t.prototype.find = function(e) {
        var t = this.F(this.N, e);
        return new OrderedMapIterator(t, this.A, this);
    };
    t.prototype.getElementByKey = function(e) {
        var t = this.F(this.N, e);
        return t.o;
    };
    t.prototype.union = function(e) {
        var t = this;
        e.forEach(function(e) {
            t.setElement(e[0], e[1]);
        });
        return this._;
    };
    t.prototype[Symbol.iterator] = function() {
        var e, t, r, n;
        return __generator(this, function(s) {
            switch (s.label) {
              case 0:
                e = this._;
                t = this.P();
                r = 0;
                s.label = 1;

              case 1:
                if (!(r < e)) return [ 3, 4 ];
                n = t[r];
                return [ 4, [ n.u, n.o ] ];

              case 2:
                s.sent();
                s.label = 3;

              case 3:
                ++r;
                return [ 3, 1 ];

              case 4:
                return [ 2 ];
            }
        });
    };
    return t;
}(TreeContainer);

const esm = Object.freeze(Object.defineProperty({
    __proto__: null,
    get OrderedMap() {
        return OrderedMap;
    }
}, Symbol.toStringTag, {
    value: "Module"
}));

const require$$1 = _commonjsHelpers.getAugmentedNamespace(esm);

var admin = {};

var hasRequiredAdmin;

function requireAdmin() {
    if (hasRequiredAdmin) return admin;
    hasRequiredAdmin = 1;
    Object.defineProperty(admin, "__esModule", {
        value: true
    });
    admin.registerAdminService = t;
    admin.addAdminServicesToServer = r;
    const e = [];
    function t(t, r) {
        e.push({
            getServiceDefinition: t,
            getHandlers: r
        });
    }
    function r(t) {
        for (const {getServiceDefinition: r, getHandlers: n} of e) {
            t.addService(r(), n());
        }
    }
    return admin;
}

var makeClient = {};

var client = {};

var call = {};

Object.defineProperty(call, "__esModule", {
    value: true
});

call.ClientDuplexStreamImpl = call.ClientWritableStreamImpl = call.ClientReadableStreamImpl = call.ClientUnaryCallImpl = void 0;

call.callErrorFromStatus = callErrorFromStatus;

const events_1$1 = require$$0__default$8.default;

const stream_1$1 = require$$0__default$7.default;

const constants_1$9 = constants;

function callErrorFromStatus(e, t) {
    const r = `${e.code} ${constants_1$9.Status[e.code]}: ${e.details}`;
    const n = new Error(r);
    const s = `${n.stack}\nfor call at\n${t}`;
    return Object.assign(new Error(r), e, {
        stack: s
    });
}

class ClientUnaryCallImpl extends events_1$1.EventEmitter {
    constructor() {
        super();
    }
    cancel() {
        var e;
        (e = this.call) === null || e === void 0 ? void 0 : e.cancelWithStatus(constants_1$9.Status.CANCELLED, "Cancelled on client");
    }
    getPeer() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : "unknown";
    }
    getAuthContext() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getAuthContext()) !== null && t !== void 0 ? t : null;
    }
}

call.ClientUnaryCallImpl = ClientUnaryCallImpl;

class ClientReadableStreamImpl extends stream_1$1.Readable {
    constructor(e) {
        super({
            objectMode: true
        });
        this.deserialize = e;
    }
    cancel() {
        var e;
        (e = this.call) === null || e === void 0 ? void 0 : e.cancelWithStatus(constants_1$9.Status.CANCELLED, "Cancelled on client");
    }
    getPeer() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : "unknown";
    }
    getAuthContext() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getAuthContext()) !== null && t !== void 0 ? t : null;
    }
    _read(e) {
        var t;
        (t = this.call) === null || t === void 0 ? void 0 : t.startRead();
    }
}

call.ClientReadableStreamImpl = ClientReadableStreamImpl;

class ClientWritableStreamImpl extends stream_1$1.Writable {
    constructor(e) {
        super({
            objectMode: true
        });
        this.serialize = e;
    }
    cancel() {
        var e;
        (e = this.call) === null || e === void 0 ? void 0 : e.cancelWithStatus(constants_1$9.Status.CANCELLED, "Cancelled on client");
    }
    getPeer() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : "unknown";
    }
    getAuthContext() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getAuthContext()) !== null && t !== void 0 ? t : null;
    }
    _write(e, t, r) {
        var n;
        const s = {
            callback: r
        };
        const o = Number(t);
        if (!Number.isNaN(o)) {
            s.flags = o;
        }
        (n = this.call) === null || n === void 0 ? void 0 : n.sendMessageWithContext(s, e);
    }
    _final(e) {
        var t;
        (t = this.call) === null || t === void 0 ? void 0 : t.halfClose();
        e();
    }
}

call.ClientWritableStreamImpl = ClientWritableStreamImpl;

class ClientDuplexStreamImpl extends stream_1$1.Duplex {
    constructor(e, t) {
        super({
            objectMode: true
        });
        this.serialize = e;
        this.deserialize = t;
    }
    cancel() {
        var e;
        (e = this.call) === null || e === void 0 ? void 0 : e.cancelWithStatus(constants_1$9.Status.CANCELLED, "Cancelled on client");
    }
    getPeer() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : "unknown";
    }
    getAuthContext() {
        var e, t;
        return (t = (e = this.call) === null || e === void 0 ? void 0 : e.getAuthContext()) !== null && t !== void 0 ? t : null;
    }
    _read(e) {
        var t;
        (t = this.call) === null || t === void 0 ? void 0 : t.startRead();
    }
    _write(e, t, r) {
        var n;
        const s = {
            callback: r
        };
        const o = Number(t);
        if (!Number.isNaN(o)) {
            s.flags = o;
        }
        (n = this.call) === null || n === void 0 ? void 0 : n.sendMessageWithContext(s, e);
    }
    _final(e) {
        var t;
        (t = this.call) === null || t === void 0 ? void 0 : t.halfClose();
        e();
    }
}

call.ClientDuplexStreamImpl = ClientDuplexStreamImpl;

var clientInterceptors = {};

var callInterface = {};

var hasRequiredCallInterface;

function requireCallInterface() {
    if (hasRequiredCallInterface) return callInterface;
    hasRequiredCallInterface = 1;
    Object.defineProperty(callInterface, "__esModule", {
        value: true
    });
    callInterface.InterceptingListenerImpl = void 0;
    callInterface.statusOrFromValue = t;
    callInterface.statusOrFromError = r;
    callInterface.isInterceptingListener = n;
    const e = metadata;
    function t(e) {
        return {
            ok: true,
            value: e
        };
    }
    function r(t) {
        var r;
        return {
            ok: false,
            error: Object.assign(Object.assign({}, t), {
                metadata: (r = t.metadata) !== null && r !== void 0 ? r : new e.Metadata
            })
        };
    }
    function n(e) {
        return e.onReceiveMetadata !== undefined && e.onReceiveMetadata.length === 1;
    }
    class InterceptingListenerImpl {
        constructor(e, t) {
            this.listener = e;
            this.nextListener = t;
            this.processingMetadata = false;
            this.hasPendingMessage = false;
            this.processingMessage = false;
            this.pendingStatus = null;
        }
        processPendingMessage() {
            if (this.hasPendingMessage) {
                this.nextListener.onReceiveMessage(this.pendingMessage);
                this.pendingMessage = null;
                this.hasPendingMessage = false;
            }
        }
        processPendingStatus() {
            if (this.pendingStatus) {
                this.nextListener.onReceiveStatus(this.pendingStatus);
            }
        }
        onReceiveMetadata(e) {
            this.processingMetadata = true;
            this.listener.onReceiveMetadata(e, e => {
                this.processingMetadata = false;
                this.nextListener.onReceiveMetadata(e);
                this.processPendingMessage();
                this.processPendingStatus();
            });
        }
        onReceiveMessage(e) {
            this.processingMessage = true;
            this.listener.onReceiveMessage(e, e => {
                this.processingMessage = false;
                if (this.processingMetadata) {
                    this.pendingMessage = e;
                    this.hasPendingMessage = true;
                } else {
                    this.nextListener.onReceiveMessage(e);
                    this.processPendingStatus();
                }
            });
        }
        onReceiveStatus(e) {
            this.listener.onReceiveStatus(e, e => {
                if (this.processingMetadata || this.processingMessage) {
                    this.pendingStatus = e;
                } else {
                    this.nextListener.onReceiveStatus(e);
                }
            });
        }
    }
    callInterface.InterceptingListenerImpl = InterceptingListenerImpl;
    return callInterface;
}

var hasRequiredClientInterceptors;

function requireClientInterceptors() {
    if (hasRequiredClientInterceptors) return clientInterceptors;
    hasRequiredClientInterceptors = 1;
    Object.defineProperty(clientInterceptors, "__esModule", {
        value: true
    });
    clientInterceptors.InterceptingCall = clientInterceptors.RequesterBuilder = clientInterceptors.ListenerBuilder = clientInterceptors.InterceptorConfigurationError = void 0;
    clientInterceptors.getInterceptingCall = c;
    const e = metadata;
    const t = requireCallInterface();
    const r = constants;
    const n = error;
    class InterceptorConfigurationError extends Error {
        constructor(e) {
            super(e);
            this.name = "InterceptorConfigurationError";
            Error.captureStackTrace(this, InterceptorConfigurationError);
        }
    }
    clientInterceptors.InterceptorConfigurationError = InterceptorConfigurationError;
    class ListenerBuilder {
        constructor() {
            this.metadata = undefined;
            this.message = undefined;
            this.status = undefined;
        }
        withOnReceiveMetadata(e) {
            this.metadata = e;
            return this;
        }
        withOnReceiveMessage(e) {
            this.message = e;
            return this;
        }
        withOnReceiveStatus(e) {
            this.status = e;
            return this;
        }
        build() {
            return {
                onReceiveMetadata: this.metadata,
                onReceiveMessage: this.message,
                onReceiveStatus: this.status
            };
        }
    }
    clientInterceptors.ListenerBuilder = ListenerBuilder;
    class RequesterBuilder {
        constructor() {
            this.start = undefined;
            this.message = undefined;
            this.halfClose = undefined;
            this.cancel = undefined;
        }
        withStart(e) {
            this.start = e;
            return this;
        }
        withSendMessage(e) {
            this.message = e;
            return this;
        }
        withHalfClose(e) {
            this.halfClose = e;
            return this;
        }
        withCancel(e) {
            this.cancel = e;
            return this;
        }
        build() {
            return {
                start: this.start,
                sendMessage: this.message,
                halfClose: this.halfClose,
                cancel: this.cancel
            };
        }
    }
    clientInterceptors.RequesterBuilder = RequesterBuilder;
    const s = {
        onReceiveMetadata: (e, t) => {
            t(e);
        },
        onReceiveMessage: (e, t) => {
            t(e);
        },
        onReceiveStatus: (e, t) => {
            t(e);
        }
    };
    const o = {
        start: (e, t, r) => {
            r(e, t);
        },
        sendMessage: (e, t) => {
            t(e);
        },
        halfClose: e => {
            e();
        },
        cancel: e => {
            e();
        }
    };
    class InterceptingCall {
        constructor(e, t) {
            var r, n, s, a;
            this.nextCall = e;
            this.processingMetadata = false;
            this.pendingMessageContext = null;
            this.processingMessage = false;
            this.pendingHalfClose = false;
            if (t) {
                this.requester = {
                    start: (r = t.start) !== null && r !== void 0 ? r : o.start,
                    sendMessage: (n = t.sendMessage) !== null && n !== void 0 ? n : o.sendMessage,
                    halfClose: (s = t.halfClose) !== null && s !== void 0 ? s : o.halfClose,
                    cancel: (a = t.cancel) !== null && a !== void 0 ? a : o.cancel
                };
            } else {
                this.requester = o;
            }
        }
        cancelWithStatus(e, t) {
            this.requester.cancel(() => {
                this.nextCall.cancelWithStatus(e, t);
            });
        }
        getPeer() {
            return this.nextCall.getPeer();
        }
        processPendingMessage() {
            if (this.pendingMessageContext) {
                this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage);
                this.pendingMessageContext = null;
                this.pendingMessage = null;
            }
        }
        processPendingHalfClose() {
            if (this.pendingHalfClose) {
                this.nextCall.halfClose();
            }
        }
        start(e, r) {
            var n, o, a, l, c, u;
            const d = {
                onReceiveMetadata: (o = (n = r === null || r === void 0 ? void 0 : r.onReceiveMetadata) === null || n === void 0 ? void 0 : n.bind(r)) !== null && o !== void 0 ? o : e => {},
                onReceiveMessage: (l = (a = r === null || r === void 0 ? void 0 : r.onReceiveMessage) === null || a === void 0 ? void 0 : a.bind(r)) !== null && l !== void 0 ? l : e => {},
                onReceiveStatus: (u = (c = r === null || r === void 0 ? void 0 : r.onReceiveStatus) === null || c === void 0 ? void 0 : c.bind(r)) !== null && u !== void 0 ? u : e => {}
            };
            this.processingMetadata = true;
            this.requester.start(e, d, (e, r) => {
                var n, o, a;
                this.processingMetadata = false;
                let l;
                if ((0, t.isInterceptingListener)(r)) {
                    l = r;
                } else {
                    const e = {
                        onReceiveMetadata: (n = r.onReceiveMetadata) !== null && n !== void 0 ? n : s.onReceiveMetadata,
                        onReceiveMessage: (o = r.onReceiveMessage) !== null && o !== void 0 ? o : s.onReceiveMessage,
                        onReceiveStatus: (a = r.onReceiveStatus) !== null && a !== void 0 ? a : s.onReceiveStatus
                    };
                    l = new t.InterceptingListenerImpl(e, d);
                }
                this.nextCall.start(e, l);
                this.processPendingMessage();
                this.processPendingHalfClose();
            });
        }
        sendMessageWithContext(e, t) {
            this.processingMessage = true;
            this.requester.sendMessage(t, r => {
                this.processingMessage = false;
                if (this.processingMetadata) {
                    this.pendingMessageContext = e;
                    this.pendingMessage = t;
                } else {
                    this.nextCall.sendMessageWithContext(e, r);
                    this.processPendingHalfClose();
                }
            });
        }
        sendMessage(e) {
            this.sendMessageWithContext({}, e);
        }
        startRead() {
            this.nextCall.startRead();
        }
        halfClose() {
            this.requester.halfClose(() => {
                if (this.processingMetadata || this.processingMessage) {
                    this.pendingHalfClose = true;
                } else {
                    this.nextCall.halfClose();
                }
            });
        }
        getAuthContext() {
            return this.nextCall.getAuthContext();
        }
    }
    clientInterceptors.InterceptingCall = InterceptingCall;
    function a(e, t, r) {
        var n, s;
        const o = (n = r.deadline) !== null && n !== void 0 ? n : Infinity;
        const a = r.host;
        const l = (s = r.parent) !== null && s !== void 0 ? s : null;
        const c = r.propagate_flags;
        const u = r.credentials;
        const d = e.createCall(t, o, a, l, c);
        if (u) {
            d.setCredentials(u);
        }
        return d;
    }
    class BaseInterceptingCall {
        constructor(e, t) {
            this.call = e;
            this.methodDefinition = t;
        }
        cancelWithStatus(e, t) {
            this.call.cancelWithStatus(e, t);
        }
        getPeer() {
            return this.call.getPeer();
        }
        sendMessageWithContext(e, t) {
            let s;
            try {
                s = this.methodDefinition.requestSerialize(t);
            } catch (e) {
                this.call.cancelWithStatus(r.Status.INTERNAL, `Request message serialization failure: ${(0, 
                n.getErrorMessage)(e)}`);
                return;
            }
            this.call.sendMessageWithContext(e, s);
        }
        sendMessage(e) {
            this.sendMessageWithContext({}, e);
        }
        start(t, s) {
            let o = null;
            this.call.start(t, {
                onReceiveMetadata: e => {
                    var t;
                    (t = s === null || s === void 0 ? void 0 : s.onReceiveMetadata) === null || t === void 0 ? void 0 : t.call(s, e);
                },
                onReceiveMessage: t => {
                    var a;
                    let l;
                    try {
                        l = this.methodDefinition.responseDeserialize(t);
                    } catch (t) {
                        o = {
                            code: r.Status.INTERNAL,
                            details: `Response message parsing error: ${(0, n.getErrorMessage)(t)}`,
                            metadata: new e.Metadata
                        };
                        this.call.cancelWithStatus(o.code, o.details);
                        return;
                    }
                    (a = s === null || s === void 0 ? void 0 : s.onReceiveMessage) === null || a === void 0 ? void 0 : a.call(s, l);
                },
                onReceiveStatus: e => {
                    var t, r;
                    if (o) {
                        (t = s === null || s === void 0 ? void 0 : s.onReceiveStatus) === null || t === void 0 ? void 0 : t.call(s, o);
                    } else {
                        (r = s === null || s === void 0 ? void 0 : s.onReceiveStatus) === null || r === void 0 ? void 0 : r.call(s, e);
                    }
                }
            });
        }
        startRead() {
            this.call.startRead();
        }
        halfClose() {
            this.call.halfClose();
        }
        getAuthContext() {
            return this.call.getAuthContext();
        }
    }
    class BaseUnaryInterceptingCall extends BaseInterceptingCall {
        constructor(e, t) {
            super(e, t);
        }
        start(e, t) {
            var r, n;
            let s = false;
            const o = {
                onReceiveMetadata: (n = (r = t === null || t === void 0 ? void 0 : t.onReceiveMetadata) === null || r === void 0 ? void 0 : r.bind(t)) !== null && n !== void 0 ? n : e => {},
                onReceiveMessage: e => {
                    var r;
                    s = true;
                    (r = t === null || t === void 0 ? void 0 : t.onReceiveMessage) === null || r === void 0 ? void 0 : r.call(t, e);
                },
                onReceiveStatus: e => {
                    var r, n;
                    if (!s) {
                        (r = t === null || t === void 0 ? void 0 : t.onReceiveMessage) === null || r === void 0 ? void 0 : r.call(t, null);
                    }
                    (n = t === null || t === void 0 ? void 0 : t.onReceiveStatus) === null || n === void 0 ? void 0 : n.call(t, e);
                }
            };
            super.start(e, o);
            this.call.startRead();
        }
    }
    class BaseStreamingInterceptingCall extends BaseInterceptingCall {}
    function l(e, t, r) {
        const n = a(e, r.path, t);
        if (r.responseStream) {
            return new BaseStreamingInterceptingCall(n, r);
        } else {
            return new BaseUnaryInterceptingCall(n, r);
        }
    }
    function c(e, t, r, n) {
        if (e.clientInterceptors.length > 0 && e.clientInterceptorProviders.length > 0) {
            throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options " + "to the client constructor. Only one of these is allowed.");
        }
        if (e.callInterceptors.length > 0 && e.callInterceptorProviders.length > 0) {
            throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call " + "options. Only one of these is allowed.");
        }
        let s = [];
        if (e.callInterceptors.length > 0 || e.callInterceptorProviders.length > 0) {
            s = [].concat(e.callInterceptors, e.callInterceptorProviders.map(e => e(t))).filter(e => e);
        } else {
            s = [].concat(e.clientInterceptors, e.clientInterceptorProviders.map(e => e(t))).filter(e => e);
        }
        const o = Object.assign({}, r, {
            method_definition: t
        });
        const a = s.reduceRight((e, t) => r => t(r, e), e => l(n, e, t));
        return a(o);
    }
    return clientInterceptors;
}

var hasRequiredClient;

function requireClient() {
    if (hasRequiredClient) return client;
    hasRequiredClient = 1;
    Object.defineProperty(client, "__esModule", {
        value: true
    });
    client.Client = void 0;
    const e = call;
    const t = requireChannel();
    const r = connectivityState;
    const n = constants;
    const s = metadata;
    const o = requireClientInterceptors();
    const a = Symbol();
    const l = Symbol();
    const c = Symbol();
    const u = Symbol();
    function d(e) {
        return typeof e === "function";
    }
    function h(e) {
        var t;
        return ((t = e.stack) === null || t === void 0 ? void 0 : t.split("\n").slice(1).join("\n")) || "no stack trace available";
    }
    class Client {
        constructor(e, r, n = {}) {
            var s, o;
            n = Object.assign({}, n);
            this[l] = (s = n.interceptors) !== null && s !== void 0 ? s : [];
            delete n.interceptors;
            this[c] = (o = n.interceptor_providers) !== null && o !== void 0 ? o : [];
            delete n.interceptor_providers;
            if (this[l].length > 0 && this[c].length > 0) {
                throw new Error("Both interceptors and interceptor_providers were passed as options " + "to the client constructor. Only one of these is allowed.");
            }
            this[u] = n.callInvocationTransformer;
            delete n.callInvocationTransformer;
            if (n.channelOverride) {
                this[a] = n.channelOverride;
            } else if (n.channelFactoryOverride) {
                const t = n.channelFactoryOverride;
                delete n.channelFactoryOverride;
                this[a] = t(e, r, n);
            } else {
                this[a] = new t.ChannelImplementation(e, r, n);
            }
        }
        close() {
            this[a].close();
        }
        getChannel() {
            return this[a];
        }
        waitForReady(e, t) {
            const n = s => {
                if (s) {
                    t(new Error("Failed to connect before the deadline"));
                    return;
                }
                let o;
                try {
                    o = this[a].getConnectivityState(true);
                } catch (e) {
                    t(new Error("The channel has been closed"));
                    return;
                }
                if (o === r.ConnectivityState.READY) {
                    t();
                } else {
                    try {
                        this[a].watchConnectivityState(o, e, n);
                    } catch (e) {
                        t(new Error("The channel has been closed"));
                    }
                }
            };
            setImmediate(n);
        }
        checkOptionalUnaryResponseArguments(e, t, r) {
            if (d(e)) {
                return {
                    metadata: new s.Metadata,
                    options: {},
                    callback: e
                };
            } else if (d(t)) {
                if (e instanceof s.Metadata) {
                    return {
                        metadata: e,
                        options: {},
                        callback: t
                    };
                } else {
                    return {
                        metadata: new s.Metadata,
                        options: e,
                        callback: t
                    };
                }
            } else {
                if (!(e instanceof s.Metadata && t instanceof Object && d(r))) {
                    throw new Error("Incorrect arguments passed");
                }
                return {
                    metadata: e,
                    options: t,
                    callback: r
                };
            }
        }
        makeUnaryRequest(t, r, s, d, p, g, m) {
            var _, E;
            const v = this.checkOptionalUnaryResponseArguments(p, g, m);
            const y = {
                path: t,
                requestStream: false,
                responseStream: false,
                requestSerialize: r,
                responseDeserialize: s
            };
            let S = {
                argument: d,
                metadata: v.metadata,
                call: new e.ClientUnaryCallImpl,
                channel: this[a],
                methodDefinition: y,
                callOptions: v.options,
                callback: v.callback
            };
            if (this[u]) {
                S = this[u](S);
            }
            const A = S.call;
            const b = {
                clientInterceptors: this[l],
                clientInterceptorProviders: this[c],
                callInterceptors: (_ = S.callOptions.interceptors) !== null && _ !== void 0 ? _ : [],
                callInterceptorProviders: (E = S.callOptions.interceptor_providers) !== null && E !== void 0 ? E : []
            };
            const C = (0, o.getInterceptingCall)(b, S.methodDefinition, S.callOptions, S.channel);
            A.call = C;
            let w = null;
            let I = false;
            let T = new Error;
            C.start(S.metadata, {
                onReceiveMetadata: e => {
                    A.emit("metadata", e);
                },
                onReceiveMessage(e) {
                    if (w !== null) {
                        C.cancelWithStatus(n.Status.UNIMPLEMENTED, "Too many responses received");
                    }
                    w = e;
                },
                onReceiveStatus(t) {
                    if (I) {
                        return;
                    }
                    I = true;
                    if (t.code === n.Status.OK) {
                        if (w === null) {
                            const r = h(T);
                            S.callback((0, e.callErrorFromStatus)({
                                code: n.Status.UNIMPLEMENTED,
                                details: "No message received",
                                metadata: t.metadata
                            }, r));
                        } else {
                            S.callback(null, w);
                        }
                    } else {
                        const r = h(T);
                        S.callback((0, e.callErrorFromStatus)(t, r));
                    }
                    T = null;
                    A.emit("status", t);
                }
            });
            C.sendMessage(d);
            C.halfClose();
            return A;
        }
        makeClientStreamRequest(t, r, s, d, p, g) {
            var m, _;
            const E = this.checkOptionalUnaryResponseArguments(d, p, g);
            const v = {
                path: t,
                requestStream: true,
                responseStream: false,
                requestSerialize: r,
                responseDeserialize: s
            };
            let y = {
                metadata: E.metadata,
                call: new e.ClientWritableStreamImpl(r),
                channel: this[a],
                methodDefinition: v,
                callOptions: E.options,
                callback: E.callback
            };
            if (this[u]) {
                y = this[u](y);
            }
            const S = y.call;
            const A = {
                clientInterceptors: this[l],
                clientInterceptorProviders: this[c],
                callInterceptors: (m = y.callOptions.interceptors) !== null && m !== void 0 ? m : [],
                callInterceptorProviders: (_ = y.callOptions.interceptor_providers) !== null && _ !== void 0 ? _ : []
            };
            const b = (0, o.getInterceptingCall)(A, y.methodDefinition, y.callOptions, y.channel);
            S.call = b;
            let C = null;
            let w = false;
            let I = new Error;
            b.start(y.metadata, {
                onReceiveMetadata: e => {
                    S.emit("metadata", e);
                },
                onReceiveMessage(e) {
                    if (C !== null) {
                        b.cancelWithStatus(n.Status.UNIMPLEMENTED, "Too many responses received");
                    }
                    C = e;
                    b.startRead();
                },
                onReceiveStatus(t) {
                    if (w) {
                        return;
                    }
                    w = true;
                    if (t.code === n.Status.OK) {
                        if (C === null) {
                            const r = h(I);
                            y.callback((0, e.callErrorFromStatus)({
                                code: n.Status.UNIMPLEMENTED,
                                details: "No message received",
                                metadata: t.metadata
                            }, r));
                        } else {
                            y.callback(null, C);
                        }
                    } else {
                        const r = h(I);
                        y.callback((0, e.callErrorFromStatus)(t, r));
                    }
                    I = null;
                    S.emit("status", t);
                }
            });
            return S;
        }
        checkMetadataAndOptions(e, t) {
            let r;
            let n;
            if (e instanceof s.Metadata) {
                r = e;
                if (t) {
                    n = t;
                } else {
                    n = {};
                }
            } else {
                if (e) {
                    n = e;
                } else {
                    n = {};
                }
                r = new s.Metadata;
            }
            return {
                metadata: r,
                options: n
            };
        }
        makeServerStreamRequest(t, r, s, d, p, g) {
            var m, _;
            const E = this.checkMetadataAndOptions(p, g);
            const v = {
                path: t,
                requestStream: false,
                responseStream: true,
                requestSerialize: r,
                responseDeserialize: s
            };
            let y = {
                argument: d,
                metadata: E.metadata,
                call: new e.ClientReadableStreamImpl(s),
                channel: this[a],
                methodDefinition: v,
                callOptions: E.options
            };
            if (this[u]) {
                y = this[u](y);
            }
            const S = y.call;
            const A = {
                clientInterceptors: this[l],
                clientInterceptorProviders: this[c],
                callInterceptors: (m = y.callOptions.interceptors) !== null && m !== void 0 ? m : [],
                callInterceptorProviders: (_ = y.callOptions.interceptor_providers) !== null && _ !== void 0 ? _ : []
            };
            const b = (0, o.getInterceptingCall)(A, y.methodDefinition, y.callOptions, y.channel);
            S.call = b;
            let C = false;
            let w = new Error;
            b.start(y.metadata, {
                onReceiveMetadata(e) {
                    S.emit("metadata", e);
                },
                onReceiveMessage(e) {
                    S.push(e);
                },
                onReceiveStatus(t) {
                    if (C) {
                        return;
                    }
                    C = true;
                    S.push(null);
                    if (t.code !== n.Status.OK) {
                        const r = h(w);
                        S.emit("error", (0, e.callErrorFromStatus)(t, r));
                    }
                    w = null;
                    S.emit("status", t);
                }
            });
            b.sendMessage(d);
            b.halfClose();
            return S;
        }
        makeBidiStreamRequest(t, r, s, d, p) {
            var g, m;
            const _ = this.checkMetadataAndOptions(d, p);
            const E = {
                path: t,
                requestStream: true,
                responseStream: true,
                requestSerialize: r,
                responseDeserialize: s
            };
            let v = {
                metadata: _.metadata,
                call: new e.ClientDuplexStreamImpl(r, s),
                channel: this[a],
                methodDefinition: E,
                callOptions: _.options
            };
            if (this[u]) {
                v = this[u](v);
            }
            const y = v.call;
            const S = {
                clientInterceptors: this[l],
                clientInterceptorProviders: this[c],
                callInterceptors: (g = v.callOptions.interceptors) !== null && g !== void 0 ? g : [],
                callInterceptorProviders: (m = v.callOptions.interceptor_providers) !== null && m !== void 0 ? m : []
            };
            const A = (0, o.getInterceptingCall)(S, v.methodDefinition, v.callOptions, v.channel);
            y.call = A;
            let b = false;
            let C = new Error;
            A.start(v.metadata, {
                onReceiveMetadata(e) {
                    y.emit("metadata", e);
                },
                onReceiveMessage(e) {
                    y.push(e);
                },
                onReceiveStatus(t) {
                    if (b) {
                        return;
                    }
                    b = true;
                    y.push(null);
                    if (t.code !== n.Status.OK) {
                        const r = h(C);
                        y.emit("error", (0, e.callErrorFromStatus)(t, r));
                    }
                    C = null;
                    y.emit("status", t);
                }
            });
            return y;
        }
    }
    client.Client = Client;
    return client;
}

var hasRequiredMakeClient;

function requireMakeClient() {
    if (hasRequiredMakeClient) return makeClient;
    hasRequiredMakeClient = 1;
    Object.defineProperty(makeClient, "__esModule", {
        value: true
    });
    makeClient.makeClientConstructor = n;
    makeClient.loadPackageDefinition = a;
    const e = requireClient();
    const t = {
        unary: e.Client.prototype.makeUnaryRequest,
        server_stream: e.Client.prototype.makeServerStreamRequest,
        client_stream: e.Client.prototype.makeClientStreamRequest,
        bidi: e.Client.prototype.makeBidiStreamRequest
    };
    function r(e) {
        return [ "__proto__", "prototype", "constructor" ].includes(e);
    }
    function n(n, o, a) {
        class ServiceClientImpl extends e.Client {}
        Object.keys(n).forEach(e => {
            if (r(e)) {
                return;
            }
            const o = n[e];
            let a;
            if (typeof e === "string" && e.charAt(0) === "$") {
                throw new Error("Method names cannot start with $");
            }
            if (o.requestStream) {
                if (o.responseStream) {
                    a = "bidi";
                } else {
                    a = "client_stream";
                }
            } else {
                if (o.responseStream) {
                    a = "server_stream";
                } else {
                    a = "unary";
                }
            }
            const l = o.requestSerialize;
            const c = o.responseDeserialize;
            const u = s(t[a], o.path, l, c);
            ServiceClientImpl.prototype[e] = u;
            Object.assign(ServiceClientImpl.prototype[e], o);
            if (o.originalName && !r(o.originalName)) {
                ServiceClientImpl.prototype[o.originalName] = ServiceClientImpl.prototype[e];
            }
        });
        ServiceClientImpl.service = n;
        ServiceClientImpl.serviceName = o;
        return ServiceClientImpl;
    }
    function s(e, t, r, n) {
        return function(...s) {
            return e.call(this, t, r, n, ...s);
        };
    }
    function o(e) {
        return "format" in e;
    }
    function a(e) {
        const t = {};
        for (const s in e) {
            if (Object.prototype.hasOwnProperty.call(e, s)) {
                const a = e[s];
                const l = s.split(".");
                if (l.some(e => r(e))) {
                    continue;
                }
                const c = l[l.length - 1];
                let u = t;
                for (const e of l.slice(0, -1)) {
                    if (!u[e]) {
                        u[e] = {};
                    }
                    u = u[e];
                }
                if (o(a)) {
                    u[c] = a;
                } else {
                    u[c] = n(a, c);
                }
            }
        }
        return t;
    }
    return makeClient;
}

var src$2 = {};

var INFINITY = 1 / 0;

var symbolTag = "[object Symbol]";

var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;

var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;

var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23", rsComboSymbolsRange = "\\u20d0-\\u20f0", rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;

var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d";

var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")", rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [ rsNonAstral, rsRegional, rsSurrPair ].join("|") + ")" + rsOptVar + reOptMod + ")*", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [ rsDingbat, rsRegional, rsSurrPair ].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [ rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral ].join("|") + ")";

var reApos = RegExp(rsApos, "g");

var reComboMark = RegExp(rsCombo, "g");

var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");

var reUnicodeWord = RegExp([ rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [ rsBreak, rsUpper, "$" ].join("|") + ")", rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [ rsBreak, rsUpper + rsLowerMisc, "$" ].join("|") + ")", rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, rsUpper + "+" + rsOptUpperContr, rsDigits, rsEmoji ].join("|"), "g");

var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");

var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;

var deburredLetters = {
    "À": "A",
    "Á": "A",
    "Â": "A",
    "Ã": "A",
    "Ä": "A",
    "Å": "A",
    "à": "a",
    "á": "a",
    "â": "a",
    "ã": "a",
    "ä": "a",
    "å": "a",
    "Ç": "C",
    "ç": "c",
    "Ð": "D",
    "ð": "d",
    "È": "E",
    "É": "E",
    "Ê": "E",
    "Ë": "E",
    "è": "e",
    "é": "e",
    "ê": "e",
    "ë": "e",
    "Ì": "I",
    "Í": "I",
    "Î": "I",
    "Ï": "I",
    "ì": "i",
    "í": "i",
    "î": "i",
    "ï": "i",
    "Ñ": "N",
    "ñ": "n",
    "Ò": "O",
    "Ó": "O",
    "Ô": "O",
    "Õ": "O",
    "Ö": "O",
    "Ø": "O",
    "ò": "o",
    "ó": "o",
    "ô": "o",
    "õ": "o",
    "ö": "o",
    "ø": "o",
    "Ù": "U",
    "Ú": "U",
    "Û": "U",
    "Ü": "U",
    "ù": "u",
    "ú": "u",
    "û": "u",
    "ü": "u",
    "Ý": "Y",
    "ý": "y",
    "ÿ": "y",
    "Æ": "Ae",
    "æ": "ae",
    "Þ": "Th",
    "þ": "th",
    "ß": "ss",
    "Ā": "A",
    "Ă": "A",
    "Ą": "A",
    "ā": "a",
    "ă": "a",
    "ą": "a",
    "Ć": "C",
    "Ĉ": "C",
    "Ċ": "C",
    "Č": "C",
    "ć": "c",
    "ĉ": "c",
    "ċ": "c",
    "č": "c",
    "Ď": "D",
    "Đ": "D",
    "ď": "d",
    "đ": "d",
    "Ē": "E",
    "Ĕ": "E",
    "Ė": "E",
    "Ę": "E",
    "Ě": "E",
    "ē": "e",
    "ĕ": "e",
    "ė": "e",
    "ę": "e",
    "ě": "e",
    "Ĝ": "G",
    "Ğ": "G",
    "Ġ": "G",
    "Ģ": "G",
    "ĝ": "g",
    "ğ": "g",
    "ġ": "g",
    "ģ": "g",
    "Ĥ": "H",
    "Ħ": "H",
    "ĥ": "h",
    "ħ": "h",
    "Ĩ": "I",
    "Ī": "I",
    "Ĭ": "I",
    "Į": "I",
    "İ": "I",
    "ĩ": "i",
    "ī": "i",
    "ĭ": "i",
    "į": "i",
    "ı": "i",
    "Ĵ": "J",
    "ĵ": "j",
    "Ķ": "K",
    "ķ": "k",
    "ĸ": "k",
    "Ĺ": "L",
    "Ļ": "L",
    "Ľ": "L",
    "Ŀ": "L",
    "Ł": "L",
    "ĺ": "l",
    "ļ": "l",
    "ľ": "l",
    "ŀ": "l",
    "ł": "l",
    "Ń": "N",
    "Ņ": "N",
    "Ň": "N",
    "Ŋ": "N",
    "ń": "n",
    "ņ": "n",
    "ň": "n",
    "ŋ": "n",
    "Ō": "O",
    "Ŏ": "O",
    "Ő": "O",
    "ō": "o",
    "ŏ": "o",
    "ő": "o",
    "Ŕ": "R",
    "Ŗ": "R",
    "Ř": "R",
    "ŕ": "r",
    "ŗ": "r",
    "ř": "r",
    "Ś": "S",
    "Ŝ": "S",
    "Ş": "S",
    "Š": "S",
    "ś": "s",
    "ŝ": "s",
    "ş": "s",
    "š": "s",
    "Ţ": "T",
    "Ť": "T",
    "Ŧ": "T",
    "ţ": "t",
    "ť": "t",
    "ŧ": "t",
    "Ũ": "U",
    "Ū": "U",
    "Ŭ": "U",
    "Ů": "U",
    "Ű": "U",
    "Ų": "U",
    "ũ": "u",
    "ū": "u",
    "ŭ": "u",
    "ů": "u",
    "ű": "u",
    "ų": "u",
    "Ŵ": "W",
    "ŵ": "w",
    "Ŷ": "Y",
    "ŷ": "y",
    "Ÿ": "Y",
    "Ź": "Z",
    "Ż": "Z",
    "Ž": "Z",
    "ź": "z",
    "ż": "z",
    "ž": "z",
    "IJ": "IJ",
    "ij": "ij",
    "Œ": "Oe",
    "œ": "oe",
    "ʼn": "'n",
    "ſ": "ss"
};

var freeGlobal = typeof _commonjsHelpers.commonjsGlobal == "object" && _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.Object === Object && _commonjsHelpers.commonjsGlobal;

var freeSelf = typeof self == "object" && self && self.Object === Object && self;

var root$1 = freeGlobal || freeSelf || Function("return this")();

function arrayReduce(e, t, r, n) {
    var s = -1, o = e ? e.length : 0;
    while (++s < o) {
        r = t(r, e[s], s, e);
    }
    return r;
}

function asciiToArray(e) {
    return e.split("");
}

function asciiWords(e) {
    return e.match(reAsciiWord) || [];
}

function basePropertyOf(e) {
    return function(t) {
        return e == null ? undefined : e[t];
    };
}

var deburrLetter = basePropertyOf(deburredLetters);

function hasUnicode(e) {
    return reHasUnicode.test(e);
}

function hasUnicodeWord(e) {
    return reHasUnicodeWord.test(e);
}

function stringToArray(e) {
    return hasUnicode(e) ? unicodeToArray(e) : asciiToArray(e);
}

function unicodeToArray(e) {
    return e.match(reUnicode) || [];
}

function unicodeWords(e) {
    return e.match(reUnicodeWord) || [];
}

var objectProto = Object.prototype;

var objectToString = objectProto.toString;

var Symbol$1 = root$1.Symbol;

var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined;

function baseSlice(e, t, r) {
    var n = -1, s = e.length;
    if (t < 0) {
        t = -t > s ? 0 : s + t;
    }
    r = r > s ? s : r;
    if (r < 0) {
        r += s;
    }
    s = t > r ? 0 : r - t >>> 0;
    t >>>= 0;
    var o = Array(s);
    while (++n < s) {
        o[n] = e[n + t];
    }
    return o;
}

function baseToString(e) {
    if (typeof e == "string") {
        return e;
    }
    if (isSymbol(e)) {
        return symbolToString ? symbolToString.call(e) : "";
    }
    var t = e + "";
    return t == "0" && 1 / e == -INFINITY ? "-0" : t;
}

function castSlice(e, t, r) {
    var n = e.length;
    r = r === undefined ? n : r;
    return !t && r >= n ? e : baseSlice(e, t, r);
}

function createCaseFirst(e) {
    return function(t) {
        t = toString(t);
        var r = hasUnicode(t) ? stringToArray(t) : undefined;
        var n = r ? r[0] : t.charAt(0);
        var s = r ? castSlice(r, 1).join("") : t.slice(1);
        return n[e]() + s;
    };
}

function createCompounder(e) {
    return function(t) {
        return arrayReduce(words(deburr(t).replace(reApos, "")), e, "");
    };
}

function isObjectLike(e) {
    return !!e && typeof e == "object";
}

function isSymbol(e) {
    return typeof e == "symbol" || isObjectLike(e) && objectToString.call(e) == symbolTag;
}

function toString(e) {
    return e == null ? "" : baseToString(e);
}

var camelCase = createCompounder(function(e, t, r) {
    t = t.toLowerCase();
    return e + (r ? capitalize(t) : t);
});

function capitalize(e) {
    return upperFirst(toString(e).toLowerCase());
}

function deburr(e) {
    e = toString(e);
    return e && e.replace(reLatin, deburrLetter).replace(reComboMark, "");
}

var upperFirst = createCaseFirst("toUpperCase");

function words(e, t, r) {
    e = toString(e);
    t = t;
    if (t === undefined) {
        return hasUnicodeWord(e) ? unicodeWords(e) : asciiWords(e);
    }
    return e.match(t) || [];
}

var lodash_camelcase = camelCase;

var src$1 = {
    exports: {}
};

var indexLight = {
    exports: {}
};

var indexMinimal = {};

var minimal = {};

var aspromise = asPromise;

function asPromise(e, t) {
    var r = new Array(arguments.length - 1), n = 0, s = 2, o = true;
    while (s < arguments.length) r[n++] = arguments[s++];
    return new Promise(function s(a, l) {
        r[n] = function e(t) {
            if (o) {
                o = false;
                if (t) l(t); else {
                    var r = new Array(arguments.length - 1), n = 0;
                    while (n < r.length) r[n++] = arguments[n];
                    a.apply(null, r);
                }
            }
        };
        try {
            e.apply(t || null, r);
        } catch (e) {
            if (o) {
                o = false;
                l(e);
            }
        }
    });
}

var base64$1 = {};

(function(e) {
    var t = e;
    t.length = function e(t) {
        var r = t.length;
        if (!r) return 0;
        var n = 0;
        while (--r % 4 > 1 && t.charAt(r) === "=") ++n;
        return Math.ceil(t.length * 3) / 4 - n;
    };
    var r = new Array(64);
    var n = new Array(123);
    for (var s = 0; s < 64; ) n[r[s] = s < 26 ? s + 65 : s < 52 ? s + 71 : s < 62 ? s - 4 : s - 59 | 43] = s++;
    t.encode = function e(t, n, s) {
        var o = null, a = [];
        var l = 0, c = 0, u;
        while (n < s) {
            var d = t[n++];
            switch (c) {
              case 0:
                a[l++] = r[d >> 2];
                u = (d & 3) << 4;
                c = 1;
                break;

              case 1:
                a[l++] = r[u | d >> 4];
                u = (d & 15) << 2;
                c = 2;
                break;

              case 2:
                a[l++] = r[u | d >> 6];
                a[l++] = r[d & 63];
                c = 0;
                break;
            }
            if (l > 8191) {
                (o || (o = [])).push(String.fromCharCode.apply(String, a));
                l = 0;
            }
        }
        if (c) {
            a[l++] = r[u];
            a[l++] = 61;
            if (c === 1) a[l++] = 61;
        }
        if (o) {
            if (l) o.push(String.fromCharCode.apply(String, a.slice(0, l)));
            return o.join("");
        }
        return String.fromCharCode.apply(String, a.slice(0, l));
    };
    var o = "invalid encoding";
    t.decode = function e(t, r, s) {
        var a = s;
        var l = 0, c;
        for (var u = 0; u < t.length; ) {
            var d = t.charCodeAt(u++);
            if (d === 61 && l > 1) break;
            if ((d = n[d]) === undefined) throw Error(o);
            switch (l) {
              case 0:
                c = d;
                l = 1;
                break;

              case 1:
                r[s++] = c << 2 | (d & 48) >> 4;
                c = d;
                l = 2;
                break;

              case 2:
                r[s++] = (c & 15) << 4 | (d & 60) >> 2;
                c = d;
                l = 3;
                break;

              case 3:
                r[s++] = (c & 3) << 6 | d;
                l = 0;
                break;
            }
        }
        if (l === 1) throw Error(o);
        return s - a;
    };
    t.test = function e(t) {
        return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t);
    };
})(base64$1);

var eventemitter = EventEmitter$1;

function EventEmitter$1() {
    this._listeners = {};
}

EventEmitter$1.prototype.on = function e(t, r, n) {
    (this._listeners[t] || (this._listeners[t] = [])).push({
        fn: r,
        ctx: n || this
    });
    return this;
};

EventEmitter$1.prototype.off = function e(t, r) {
    if (t === undefined) this._listeners = {}; else {
        if (r === undefined) this._listeners[t] = []; else {
            var n = this._listeners[t];
            for (var s = 0; s < n.length; ) if (n[s].fn === r) n.splice(s, 1); else ++s;
        }
    }
    return this;
};

EventEmitter$1.prototype.emit = function e(t) {
    var r = this._listeners[t];
    if (r) {
        var n = [], s = 1;
        for (;s < arguments.length; ) n.push(arguments[s++]);
        for (s = 0; s < r.length; ) r[s].fn.apply(r[s++].ctx, n);
    }
    return this;
};

var float = factory(factory);

function factory(e) {
    if (typeof Float32Array !== "undefined") (function() {
        var t = new Float32Array([ -0 ]), r = new Uint8Array(t.buffer), n = r[3] === 128;
        function s(e, n, s) {
            t[0] = e;
            n[s] = r[0];
            n[s + 1] = r[1];
            n[s + 2] = r[2];
            n[s + 3] = r[3];
        }
        function o(e, n, s) {
            t[0] = e;
            n[s] = r[3];
            n[s + 1] = r[2];
            n[s + 2] = r[1];
            n[s + 3] = r[0];
        }
        e.writeFloatLE = n ? s : o;
        e.writeFloatBE = n ? o : s;
        function a(e, n) {
            r[0] = e[n];
            r[1] = e[n + 1];
            r[2] = e[n + 2];
            r[3] = e[n + 3];
            return t[0];
        }
        function l(e, n) {
            r[3] = e[n];
            r[2] = e[n + 1];
            r[1] = e[n + 2];
            r[0] = e[n + 3];
            return t[0];
        }
        e.readFloatLE = n ? a : l;
        e.readFloatBE = n ? l : a;
    })(); else (function() {
        function t(e, t, r, n) {
            var s = t < 0 ? 1 : 0;
            if (s) t = -t;
            if (t === 0) e(1 / t > 0 ? 0 : 2147483648, r, n); else if (isNaN(t)) e(2143289344, r, n); else if (t > 34028234663852886e22) e((s << 31 | 2139095040) >>> 0, r, n); else if (t < 11754943508222875e-54) e((s << 31 | Math.round(t / 1401298464324817e-60)) >>> 0, r, n); else {
                var o = Math.floor(Math.log(t) / Math.LN2), a = Math.round(t * Math.pow(2, -o) * 8388608) & 8388607;
                e((s << 31 | o + 127 << 23 | a) >>> 0, r, n);
            }
        }
        e.writeFloatLE = t.bind(null, writeUintLE);
        e.writeFloatBE = t.bind(null, writeUintBE);
        function r(e, t, r) {
            var n = e(t, r), s = (n >> 31) * 2 + 1, o = n >>> 23 & 255, a = n & 8388607;
            return o === 255 ? a ? NaN : s * Infinity : o === 0 ? s * 1401298464324817e-60 * a : s * Math.pow(2, o - 150) * (a + 8388608);
        }
        e.readFloatLE = r.bind(null, readUintLE);
        e.readFloatBE = r.bind(null, readUintBE);
    })();
    if (typeof Float64Array !== "undefined") (function() {
        var t = new Float64Array([ -0 ]), r = new Uint8Array(t.buffer), n = r[7] === 128;
        function s(e, n, s) {
            t[0] = e;
            n[s] = r[0];
            n[s + 1] = r[1];
            n[s + 2] = r[2];
            n[s + 3] = r[3];
            n[s + 4] = r[4];
            n[s + 5] = r[5];
            n[s + 6] = r[6];
            n[s + 7] = r[7];
        }
        function o(e, n, s) {
            t[0] = e;
            n[s] = r[7];
            n[s + 1] = r[6];
            n[s + 2] = r[5];
            n[s + 3] = r[4];
            n[s + 4] = r[3];
            n[s + 5] = r[2];
            n[s + 6] = r[1];
            n[s + 7] = r[0];
        }
        e.writeDoubleLE = n ? s : o;
        e.writeDoubleBE = n ? o : s;
        function a(e, n) {
            r[0] = e[n];
            r[1] = e[n + 1];
            r[2] = e[n + 2];
            r[3] = e[n + 3];
            r[4] = e[n + 4];
            r[5] = e[n + 5];
            r[6] = e[n + 6];
            r[7] = e[n + 7];
            return t[0];
        }
        function l(e, n) {
            r[7] = e[n];
            r[6] = e[n + 1];
            r[5] = e[n + 2];
            r[4] = e[n + 3];
            r[3] = e[n + 4];
            r[2] = e[n + 5];
            r[1] = e[n + 6];
            r[0] = e[n + 7];
            return t[0];
        }
        e.readDoubleLE = n ? a : l;
        e.readDoubleBE = n ? l : a;
    })(); else (function() {
        function t(e, t, r, n, s, o) {
            var a = n < 0 ? 1 : 0;
            if (a) n = -n;
            if (n === 0) {
                e(0, s, o + t);
                e(1 / n > 0 ? 0 : 2147483648, s, o + r);
            } else if (isNaN(n)) {
                e(0, s, o + t);
                e(2146959360, s, o + r);
            } else if (n > 17976931348623157e292) {
                e(0, s, o + t);
                e((a << 31 | 2146435072) >>> 0, s, o + r);
            } else {
                var l;
                if (n < 22250738585072014e-324) {
                    l = n / 5e-324;
                    e(l >>> 0, s, o + t);
                    e((a << 31 | l / 4294967296) >>> 0, s, o + r);
                } else {
                    var c = Math.floor(Math.log(n) / Math.LN2);
                    if (c === 1024) c = 1023;
                    l = n * Math.pow(2, -c);
                    e(l * 4503599627370496 >>> 0, s, o + t);
                    e((a << 31 | c + 1023 << 20 | l * 1048576 & 1048575) >>> 0, s, o + r);
                }
            }
        }
        e.writeDoubleLE = t.bind(null, writeUintLE, 0, 4);
        e.writeDoubleBE = t.bind(null, writeUintBE, 4, 0);
        function r(e, t, r, n, s) {
            var o = e(n, s + t), a = e(n, s + r);
            var l = (a >> 31) * 2 + 1, c = a >>> 20 & 2047, u = 4294967296 * (a & 1048575) + o;
            return c === 2047 ? u ? NaN : l * Infinity : c === 0 ? l * 5e-324 * u : l * Math.pow(2, c - 1075) * (u + 4503599627370496);
        }
        e.readDoubleLE = r.bind(null, readUintLE, 0, 4);
        e.readDoubleBE = r.bind(null, readUintBE, 4, 0);
    })();
    return e;
}

function writeUintLE(e, t, r) {
    t[r] = e & 255;
    t[r + 1] = e >>> 8 & 255;
    t[r + 2] = e >>> 16 & 255;
    t[r + 3] = e >>> 24;
}

function writeUintBE(e, t, r) {
    t[r] = e >>> 24;
    t[r + 1] = e >>> 16 & 255;
    t[r + 2] = e >>> 8 & 255;
    t[r + 3] = e & 255;
}

function readUintLE(e, t) {
    return (e[t] | e[t + 1] << 8 | e[t + 2] << 16 | e[t + 3] << 24) >>> 0;
}

function readUintBE(e, t) {
    return (e[t] << 24 | e[t + 1] << 16 | e[t + 2] << 8 | e[t + 3]) >>> 0;
}

var inquire_1 = inquire;

function inquire(moduleName) {
    try {
        var mod = eval("quire".replace(/^/, "re"))(moduleName);
        if (mod && (mod.length || Object.keys(mod).length)) return mod;
    } catch (e) {}
    return null;
}

var utf8$2 = {};

(function(e) {
    var t = e;
    t.length = function e(t) {
        var r = 0, n = 0;
        for (var s = 0; s < t.length; ++s) {
            n = t.charCodeAt(s);
            if (n < 128) r += 1; else if (n < 2048) r += 2; else if ((n & 64512) === 55296 && (t.charCodeAt(s + 1) & 64512) === 56320) {
                ++s;
                r += 4;
            } else r += 3;
        }
        return r;
    };
    t.read = function e(t, r, n) {
        var s = n - r;
        if (s < 1) return "";
        var o = null, a = [], l = 0, c;
        while (r < n) {
            c = t[r++];
            if (c < 128) a[l++] = c; else if (c > 191 && c < 224) a[l++] = (c & 31) << 6 | t[r++] & 63; else if (c > 239 && c < 365) {
                c = ((c & 7) << 18 | (t[r++] & 63) << 12 | (t[r++] & 63) << 6 | t[r++] & 63) - 65536;
                a[l++] = 55296 + (c >> 10);
                a[l++] = 56320 + (c & 1023);
            } else a[l++] = (c & 15) << 12 | (t[r++] & 63) << 6 | t[r++] & 63;
            if (l > 8191) {
                (o || (o = [])).push(String.fromCharCode.apply(String, a));
                l = 0;
            }
        }
        if (o) {
            if (l) o.push(String.fromCharCode.apply(String, a.slice(0, l)));
            return o.join("");
        }
        return String.fromCharCode.apply(String, a.slice(0, l));
    };
    t.write = function e(t, r, n) {
        var s = n, o, a;
        for (var l = 0; l < t.length; ++l) {
            o = t.charCodeAt(l);
            if (o < 128) {
                r[n++] = o;
            } else if (o < 2048) {
                r[n++] = o >> 6 | 192;
                r[n++] = o & 63 | 128;
            } else if ((o & 64512) === 55296 && ((a = t.charCodeAt(l + 1)) & 64512) === 56320) {
                o = 65536 + ((o & 1023) << 10) + (a & 1023);
                ++l;
                r[n++] = o >> 18 | 240;
                r[n++] = o >> 12 & 63 | 128;
                r[n++] = o >> 6 & 63 | 128;
                r[n++] = o & 63 | 128;
            } else {
                r[n++] = o >> 12 | 224;
                r[n++] = o >> 6 & 63 | 128;
                r[n++] = o & 63 | 128;
            }
        }
        return n - s;
    };
})(utf8$2);

var pool_1 = pool;

function pool(e, t, r) {
    var n = r || 8192;
    var s = n >>> 1;
    var o = null;
    var a = n;
    return function r(l) {
        if (l < 1 || l > s) return e(l);
        if (a + l > n) {
            o = e(n);
            a = 0;
        }
        var c = t.call(o, a, a += l);
        if (a & 7) a = (a | 7) + 1;
        return c;
    };
}

var longbits;

var hasRequiredLongbits;

function requireLongbits() {
    if (hasRequiredLongbits) return longbits;
    hasRequiredLongbits = 1;
    longbits = t;
    var e = requireMinimal();
    function t(e, t) {
        this.lo = e >>> 0;
        this.hi = t >>> 0;
    }
    var r = t.zero = new t(0, 0);
    r.toNumber = function() {
        return 0;
    };
    r.zzEncode = r.zzDecode = function() {
        return this;
    };
    r.length = function() {
        return 1;
    };
    var n = t.zeroHash = "\0\0\0\0\0\0\0\0";
    t.fromNumber = function e(n) {
        if (n === 0) return r;
        var s = n < 0;
        if (s) n = -n;
        var o = n >>> 0, a = (n - o) / 4294967296 >>> 0;
        if (s) {
            a = ~a >>> 0;
            o = ~o >>> 0;
            if (++o > 4294967295) {
                o = 0;
                if (++a > 4294967295) a = 0;
            }
        }
        return new t(o, a);
    };
    t.from = function n(s) {
        if (typeof s === "number") return t.fromNumber(s);
        if (e.isString(s)) {
            if (e.Long) s = e.Long.fromString(s); else return t.fromNumber(parseInt(s, 10));
        }
        return s.low || s.high ? new t(s.low >>> 0, s.high >>> 0) : r;
    };
    t.prototype.toNumber = function e(t) {
        if (!t && this.hi >>> 31) {
            var r = ~this.lo + 1 >>> 0, n = ~this.hi >>> 0;
            if (!r) n = n + 1 >>> 0;
            return -(r + n * 4294967296);
        }
        return this.lo + this.hi * 4294967296;
    };
    t.prototype.toLong = function t(r) {
        return e.Long ? new e.Long(this.lo | 0, this.hi | 0, Boolean(r)) : {
            low: this.lo | 0,
            high: this.hi | 0,
            unsigned: Boolean(r)
        };
    };
    var s = String.prototype.charCodeAt;
    t.fromHash = function e(o) {
        if (o === n) return r;
        return new t((s.call(o, 0) | s.call(o, 1) << 8 | s.call(o, 2) << 16 | s.call(o, 3) << 24) >>> 0, (s.call(o, 4) | s.call(o, 5) << 8 | s.call(o, 6) << 16 | s.call(o, 7) << 24) >>> 0);
    };
    t.prototype.toHash = function e() {
        return String.fromCharCode(this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24);
    };
    t.prototype.zzEncode = function e() {
        var t = this.hi >> 31;
        this.hi = ((this.hi << 1 | this.lo >>> 31) ^ t) >>> 0;
        this.lo = (this.lo << 1 ^ t) >>> 0;
        return this;
    };
    t.prototype.zzDecode = function e() {
        var t = -(this.lo & 1);
        this.lo = ((this.lo >>> 1 | this.hi << 31) ^ t) >>> 0;
        this.hi = (this.hi >>> 1 ^ t) >>> 0;
        return this;
    };
    t.prototype.length = function e() {
        var t = this.lo, r = (this.lo >>> 28 | this.hi << 4) >>> 0, n = this.hi >>> 24;
        return n === 0 ? r === 0 ? t < 16384 ? t < 128 ? 1 : 2 : t < 2097152 ? 3 : 4 : r < 16384 ? r < 128 ? 5 : 6 : r < 2097152 ? 7 : 8 : n < 128 ? 9 : 10;
    };
    return longbits;
}

var hasRequiredMinimal;

function requireMinimal() {
    if (hasRequiredMinimal) return minimal;
    hasRequiredMinimal = 1;
    (function(e) {
        var t = e;
        t.asPromise = aspromise;
        t.base64 = base64$1;
        t.EventEmitter = eventemitter;
        t.float = float;
        t.inquire = inquire_1;
        t.utf8 = utf8$2;
        t.pool = pool_1;
        t.LongBits = requireLongbits();
        t.isNode = Boolean(typeof _commonjsHelpers.commonjsGlobal !== "undefined" && _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.process && _commonjsHelpers.commonjsGlobal.process.versions && _commonjsHelpers.commonjsGlobal.process.versions.node);
        t.global = t.isNode && _commonjsHelpers.commonjsGlobal || typeof window !== "undefined" && window || typeof self !== "undefined" && self || _commonjsHelpers.commonjsGlobal;
        t.emptyArray = Object.freeze ? Object.freeze([]) : [];
        t.emptyObject = Object.freeze ? Object.freeze({}) : {};
        t.isInteger = Number.isInteger || function e(t) {
            return typeof t === "number" && isFinite(t) && Math.floor(t) === t;
        };
        t.isString = function e(t) {
            return typeof t === "string" || t instanceof String;
        };
        t.isObject = function e(t) {
            return t && typeof t === "object";
        };
        t.isset = t.isSet = function e(t, r) {
            var n = t[r];
            if (n != null && t.hasOwnProperty(r)) return typeof n !== "object" || (Array.isArray(n) ? n.length : Object.keys(n).length) > 0;
            return false;
        };
        t.Buffer = function() {
            try {
                var e = t.inquire("buffer").Buffer;
                return e.prototype.utf8Write ? e : null;
            } catch (e) {
                return null;
            }
        }();
        t._Buffer_from = null;
        t._Buffer_allocUnsafe = null;
        t.newBuffer = function e(r) {
            return typeof r === "number" ? t.Buffer ? t._Buffer_allocUnsafe(r) : new t.Array(r) : t.Buffer ? t._Buffer_from(r) : typeof Uint8Array === "undefined" ? r : new Uint8Array(r);
        };
        t.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
        t.Long = t.global.dcodeIO && t.global.dcodeIO.Long || t.global.Long || t.inquire("long");
        t.key2Re = /^true|false|0|1$/;
        t.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
        t.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
        t.longToHash = function e(r) {
            return r ? t.LongBits.from(r).toHash() : t.LongBits.zeroHash;
        };
        t.longFromHash = function e(r, n) {
            var s = t.LongBits.fromHash(r);
            if (t.Long) return t.Long.fromBits(s.lo, s.hi, n);
            return s.toNumber(Boolean(n));
        };
        function r(e, t, r) {
            for (var n = Object.keys(t), s = 0; s < n.length; ++s) if (e[n[s]] === undefined || !r) e[n[s]] = t[n[s]];
            return e;
        }
        t.merge = r;
        t.lcFirst = function e(t) {
            return t.charAt(0).toLowerCase() + t.substring(1);
        };
        function n(e) {
            function t(e, n) {
                if (!(this instanceof t)) return new t(e, n);
                Object.defineProperty(this, "message", {
                    get: function() {
                        return e;
                    }
                });
                if (Error.captureStackTrace) Error.captureStackTrace(this, t); else Object.defineProperty(this, "stack", {
                    value: (new Error).stack || ""
                });
                if (n) r(this, n);
            }
            t.prototype = Object.create(Error.prototype, {
                constructor: {
                    value: t,
                    writable: true,
                    enumerable: false,
                    configurable: true
                },
                name: {
                    get: function t() {
                        return e;
                    },
                    set: undefined,
                    enumerable: false,
                    configurable: true
                },
                toString: {
                    value: function e() {
                        return this.name + ": " + this.message;
                    },
                    writable: true,
                    enumerable: false,
                    configurable: true
                }
            });
            return t;
        }
        t.newError = n;
        t.ProtocolError = n("ProtocolError");
        t.oneOfGetter = function e(t) {
            var r = {};
            for (var n = 0; n < t.length; ++n) r[t[n]] = 1;
            return function() {
                for (var e = Object.keys(this), t = e.length - 1; t > -1; --t) if (r[e[t]] === 1 && this[e[t]] !== undefined && this[e[t]] !== null) return e[t];
            };
        };
        t.oneOfSetter = function e(t) {
            return function(e) {
                for (var r = 0; r < t.length; ++r) if (t[r] !== e) delete this[t[r]];
            };
        };
        t.toJSONOptions = {
            longs: String,
            enums: String,
            bytes: String,
            json: true
        };
        t._configure = function() {
            var e = t.Buffer;
            if (!e) {
                t._Buffer_from = t._Buffer_allocUnsafe = null;
                return;
            }
            t._Buffer_from = e.from !== Uint8Array.from && e.from || function t(r, n) {
                return new e(r, n);
            };
            t._Buffer_allocUnsafe = e.allocUnsafe || function t(r) {
                return new e(r);
            };
        };
    })(minimal);
    return minimal;
}

var writer = Writer$1;

var util$b = requireMinimal();

var BufferWriter$1;

var LongBits$1 = util$b.LongBits, base64 = util$b.base64, utf8$1 = util$b.utf8;

function Op(e, t, r) {
    this.fn = e;
    this.len = t;
    this.next = undefined;
    this.val = r;
}

function noop$1() {}

function State(e) {
    this.head = e.head;
    this.tail = e.tail;
    this.len = e.len;
    this.next = e.states;
}

function Writer$1() {
    this.len = 0;
    this.head = new Op(noop$1, 0, 0);
    this.tail = this.head;
    this.states = null;
}

var create$1 = function e() {
    return util$b.Buffer ? function e() {
        return (Writer$1.create = function e() {
            return new BufferWriter$1;
        })();
    } : function e() {
        return new Writer$1;
    };
};

Writer$1.create = create$1();

Writer$1.alloc = function e(t) {
    return new util$b.Array(t);
};

if (util$b.Array !== Array) Writer$1.alloc = util$b.pool(Writer$1.alloc, util$b.Array.prototype.subarray);

Writer$1.prototype._push = function e(t, r, n) {
    this.tail = this.tail.next = new Op(t, r, n);
    this.len += r;
    return this;
};

function writeByte(e, t, r) {
    t[r] = e & 255;
}

function writeVarint32(e, t, r) {
    while (e > 127) {
        t[r++] = e & 127 | 128;
        e >>>= 7;
    }
    t[r] = e;
}

function VarintOp(e, t) {
    this.len = e;
    this.next = undefined;
    this.val = t;
}

VarintOp.prototype = Object.create(Op.prototype);

VarintOp.prototype.fn = writeVarint32;

Writer$1.prototype.uint32 = function e(t) {
    this.len += (this.tail = this.tail.next = new VarintOp((t = t >>> 0) < 128 ? 1 : t < 16384 ? 2 : t < 2097152 ? 3 : t < 268435456 ? 4 : 5, t)).len;
    return this;
};

Writer$1.prototype.int32 = function e(t) {
    return t < 0 ? this._push(writeVarint64, 10, LongBits$1.fromNumber(t)) : this.uint32(t);
};

Writer$1.prototype.sint32 = function e(t) {
    return this.uint32((t << 1 ^ t >> 31) >>> 0);
};

function writeVarint64(e, t, r) {
    while (e.hi) {
        t[r++] = e.lo & 127 | 128;
        e.lo = (e.lo >>> 7 | e.hi << 25) >>> 0;
        e.hi >>>= 7;
    }
    while (e.lo > 127) {
        t[r++] = e.lo & 127 | 128;
        e.lo = e.lo >>> 7;
    }
    t[r++] = e.lo;
}

Writer$1.prototype.uint64 = function e(t) {
    var r = LongBits$1.from(t);
    return this._push(writeVarint64, r.length(), r);
};

Writer$1.prototype.int64 = Writer$1.prototype.uint64;

Writer$1.prototype.sint64 = function e(t) {
    var r = LongBits$1.from(t).zzEncode();
    return this._push(writeVarint64, r.length(), r);
};

Writer$1.prototype.bool = function e(t) {
    return this._push(writeByte, 1, t ? 1 : 0);
};

function writeFixed32(e, t, r) {
    t[r] = e & 255;
    t[r + 1] = e >>> 8 & 255;
    t[r + 2] = e >>> 16 & 255;
    t[r + 3] = e >>> 24;
}

Writer$1.prototype.fixed32 = function e(t) {
    return this._push(writeFixed32, 4, t >>> 0);
};

Writer$1.prototype.sfixed32 = Writer$1.prototype.fixed32;

Writer$1.prototype.fixed64 = function e(t) {
    var r = LongBits$1.from(t);
    return this._push(writeFixed32, 4, r.lo)._push(writeFixed32, 4, r.hi);
};

Writer$1.prototype.sfixed64 = Writer$1.prototype.fixed64;

Writer$1.prototype.float = function e(t) {
    return this._push(util$b.float.writeFloatLE, 4, t);
};

Writer$1.prototype.double = function e(t) {
    return this._push(util$b.float.writeDoubleLE, 8, t);
};

var writeBytes = util$b.Array.prototype.set ? function e(t, r, n) {
    r.set(t, n);
} : function e(t, r, n) {
    for (var s = 0; s < t.length; ++s) r[n + s] = t[s];
};

Writer$1.prototype.bytes = function e(t) {
    var r = t.length >>> 0;
    if (!r) return this._push(writeByte, 1, 0);
    if (util$b.isString(t)) {
        var n = Writer$1.alloc(r = base64.length(t));
        base64.decode(t, n, 0);
        t = n;
    }
    return this.uint32(r)._push(writeBytes, r, t);
};

Writer$1.prototype.string = function e(t) {
    var r = utf8$1.length(t);
    return r ? this.uint32(r)._push(utf8$1.write, r, t) : this._push(writeByte, 1, 0);
};

Writer$1.prototype.fork = function e() {
    this.states = new State(this);
    this.head = this.tail = new Op(noop$1, 0, 0);
    this.len = 0;
    return this;
};

Writer$1.prototype.reset = function e() {
    if (this.states) {
        this.head = this.states.head;
        this.tail = this.states.tail;
        this.len = this.states.len;
        this.states = this.states.next;
    } else {
        this.head = this.tail = new Op(noop$1, 0, 0);
        this.len = 0;
    }
    return this;
};

Writer$1.prototype.ldelim = function e() {
    var t = this.head, r = this.tail, n = this.len;
    this.reset().uint32(n);
    if (n) {
        this.tail.next = t.next;
        this.tail = r;
        this.len += n;
    }
    return this;
};

Writer$1.prototype.finish = function e() {
    var t = this.head.next, r = this.constructor.alloc(this.len), n = 0;
    while (t) {
        t.fn(t.val, r, n);
        n += t.len;
        t = t.next;
    }
    return r;
};

Writer$1._configure = function(e) {
    BufferWriter$1 = e;
    Writer$1.create = create$1();
    BufferWriter$1._configure();
};

var writer_buffer = BufferWriter;

var Writer = writer;

(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;

var util$a = requireMinimal();

function BufferWriter() {
    Writer.call(this);
}

BufferWriter._configure = function() {
    BufferWriter.alloc = util$a._Buffer_allocUnsafe;
    BufferWriter.writeBytesBuffer = util$a.Buffer && util$a.Buffer.prototype instanceof Uint8Array && util$a.Buffer.prototype.set.name === "set" ? function e(t, r, n) {
        r.set(t, n);
    } : function e(t, r, n) {
        if (t.copy) t.copy(r, n, 0, t.length); else for (var s = 0; s < t.length; ) r[n++] = t[s++];
    };
};

BufferWriter.prototype.bytes = function e(t) {
    if (util$a.isString(t)) t = util$a._Buffer_from(t, "base64");
    var r = t.length >>> 0;
    this.uint32(r);
    if (r) this._push(BufferWriter.writeBytesBuffer, r, t);
    return this;
};

function writeStringBuffer(e, t, r) {
    if (e.length < 40) util$a.utf8.write(e, t, r); else if (t.utf8Write) t.utf8Write(e, r); else t.write(e, r);
}

BufferWriter.prototype.string = function e(t) {
    var r = util$a.Buffer.byteLength(t);
    this.uint32(r);
    if (r) this._push(writeStringBuffer, r, t);
    return this;
};

BufferWriter._configure();

var reader = Reader$1;

var util$9 = requireMinimal();

var BufferReader$1;

var LongBits = util$9.LongBits, utf8 = util$9.utf8;

function indexOutOfRange(e, t) {
    return RangeError("index out of range: " + e.pos + " + " + (t || 1) + " > " + e.len);
}

function Reader$1(e) {
    this.buf = e;
    this.pos = 0;
    this.len = e.length;
}

var create_array = typeof Uint8Array !== "undefined" ? function e(t) {
    if (t instanceof Uint8Array || Array.isArray(t)) return new Reader$1(t);
    throw Error("illegal buffer");
} : function e(t) {
    if (Array.isArray(t)) return new Reader$1(t);
    throw Error("illegal buffer");
};

var create = function e() {
    return util$9.Buffer ? function e(t) {
        return (Reader$1.create = function e(t) {
            return util$9.Buffer.isBuffer(t) ? new BufferReader$1(t) : create_array(t);
        })(t);
    } : create_array;
};

Reader$1.create = create();

Reader$1.prototype._slice = util$9.Array.prototype.subarray || util$9.Array.prototype.slice;

Reader$1.prototype.uint32 = function e() {
    var t = 4294967295;
    return function e() {
        t = (this.buf[this.pos] & 127) >>> 0;
        if (this.buf[this.pos++] < 128) return t;
        t = (t | (this.buf[this.pos] & 127) << 7) >>> 0;
        if (this.buf[this.pos++] < 128) return t;
        t = (t | (this.buf[this.pos] & 127) << 14) >>> 0;
        if (this.buf[this.pos++] < 128) return t;
        t = (t | (this.buf[this.pos] & 127) << 21) >>> 0;
        if (this.buf[this.pos++] < 128) return t;
        t = (t | (this.buf[this.pos] & 15) << 28) >>> 0;
        if (this.buf[this.pos++] < 128) return t;
        if ((this.pos += 5) > this.len) {
            this.pos = this.len;
            throw indexOutOfRange(this, 10);
        }
        return t;
    };
}();

Reader$1.prototype.int32 = function e() {
    return this.uint32() | 0;
};

Reader$1.prototype.sint32 = function e() {
    var t = this.uint32();
    return t >>> 1 ^ -(t & 1) | 0;
};

function readLongVarint() {
    var e = new LongBits(0, 0);
    var t = 0;
    if (this.len - this.pos > 4) {
        for (;t < 4; ++t) {
            e.lo = (e.lo | (this.buf[this.pos] & 127) << t * 7) >>> 0;
            if (this.buf[this.pos++] < 128) return e;
        }
        e.lo = (e.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
        e.hi = (e.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
        if (this.buf[this.pos++] < 128) return e;
        t = 0;
    } else {
        for (;t < 3; ++t) {
            if (this.pos >= this.len) throw indexOutOfRange(this);
            e.lo = (e.lo | (this.buf[this.pos] & 127) << t * 7) >>> 0;
            if (this.buf[this.pos++] < 128) return e;
        }
        e.lo = (e.lo | (this.buf[this.pos++] & 127) << t * 7) >>> 0;
        return e;
    }
    if (this.len - this.pos > 4) {
        for (;t < 5; ++t) {
            e.hi = (e.hi | (this.buf[this.pos] & 127) << t * 7 + 3) >>> 0;
            if (this.buf[this.pos++] < 128) return e;
        }
    } else {
        for (;t < 5; ++t) {
            if (this.pos >= this.len) throw indexOutOfRange(this);
            e.hi = (e.hi | (this.buf[this.pos] & 127) << t * 7 + 3) >>> 0;
            if (this.buf[this.pos++] < 128) return e;
        }
    }
    throw Error("invalid varint encoding");
}

Reader$1.prototype.bool = function e() {
    return this.uint32() !== 0;
};

function readFixed32_end(e, t) {
    return (e[t - 4] | e[t - 3] << 8 | e[t - 2] << 16 | e[t - 1] << 24) >>> 0;
}

Reader$1.prototype.fixed32 = function e() {
    if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4);
    return readFixed32_end(this.buf, this.pos += 4);
};

Reader$1.prototype.sfixed32 = function e() {
    if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4);
    return readFixed32_end(this.buf, this.pos += 4) | 0;
};

function readFixed64() {
    if (this.pos + 8 > this.len) throw indexOutOfRange(this, 8);
    return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
}

Reader$1.prototype.float = function e() {
    if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4);
    var t = util$9.float.readFloatLE(this.buf, this.pos);
    this.pos += 4;
    return t;
};

Reader$1.prototype.double = function e() {
    if (this.pos + 8 > this.len) throw indexOutOfRange(this, 4);
    var t = util$9.float.readDoubleLE(this.buf, this.pos);
    this.pos += 8;
    return t;
};

Reader$1.prototype.bytes = function e() {
    var t = this.uint32(), r = this.pos, n = this.pos + t;
    if (n > this.len) throw indexOutOfRange(this, t);
    this.pos += t;
    if (Array.isArray(this.buf)) return this.buf.slice(r, n);
    if (r === n) {
        var s = util$9.Buffer;
        return s ? s.alloc(0) : new this.buf.constructor(0);
    }
    return this._slice.call(this.buf, r, n);
};

Reader$1.prototype.string = function e() {
    var t = this.bytes();
    return utf8.read(t, 0, t.length);
};

Reader$1.prototype.skip = function e(t) {
    if (typeof t === "number") {
        if (this.pos + t > this.len) throw indexOutOfRange(this, t);
        this.pos += t;
    } else {
        do {
            if (this.pos >= this.len) throw indexOutOfRange(this);
        } while (this.buf[this.pos++] & 128);
    }
    return this;
};

Reader$1.prototype.skipType = function(e) {
    switch (e) {
      case 0:
        this.skip();
        break;

      case 1:
        this.skip(8);
        break;

      case 2:
        this.skip(this.uint32());
        break;

      case 3:
        while ((e = this.uint32() & 7) !== 4) {
            this.skipType(e);
        }
        break;

      case 5:
        this.skip(4);
        break;

      default:
        throw Error("invalid wire type " + e + " at offset " + this.pos);
    }
    return this;
};

Reader$1._configure = function(e) {
    BufferReader$1 = e;
    Reader$1.create = create();
    BufferReader$1._configure();
    var t = util$9.Long ? "toLong" : "toNumber";
    util$9.merge(Reader$1.prototype, {
        int64: function e() {
            return readLongVarint.call(this)[t](false);
        },
        uint64: function e() {
            return readLongVarint.call(this)[t](true);
        },
        sint64: function e() {
            return readLongVarint.call(this).zzDecode()[t](false);
        },
        fixed64: function e() {
            return readFixed64.call(this)[t](true);
        },
        sfixed64: function e() {
            return readFixed64.call(this)[t](false);
        }
    });
};

var reader_buffer = BufferReader;

var Reader = reader;

(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;

var util$8 = requireMinimal();

function BufferReader(e) {
    Reader.call(this, e);
}

BufferReader._configure = function() {
    if (util$8.Buffer) BufferReader.prototype._slice = util$8.Buffer.prototype.slice;
};

BufferReader.prototype.string = function e() {
    var t = this.uint32();
    return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + t, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + t, this.len));
};

BufferReader._configure();

var rpc = {};

var service$1 = Service$2;

var util$7 = requireMinimal();

(Service$2.prototype = Object.create(util$7.EventEmitter.prototype)).constructor = Service$2;

function Service$2(e, t, r) {
    if (typeof e !== "function") throw TypeError("rpcImpl must be a function");
    util$7.EventEmitter.call(this);
    this.rpcImpl = e;
    this.requestDelimited = Boolean(t);
    this.responseDelimited = Boolean(r);
}

Service$2.prototype.rpcCall = function e(t, r, n, s, o) {
    if (!s) throw TypeError("request must be specified");
    var a = this;
    if (!o) return util$7.asPromise(e, a, t, r, n, s);
    if (!a.rpcImpl) {
        setTimeout(function() {
            o(Error("already ended"));
        }, 0);
        return undefined;
    }
    try {
        return a.rpcImpl(t, r[a.requestDelimited ? "encodeDelimited" : "encode"](s).finish(), function e(r, s) {
            if (r) {
                a.emit("error", r, t);
                return o(r);
            }
            if (s === null) {
                a.end(true);
                return undefined;
            }
            if (!(s instanceof n)) {
                try {
                    s = n[a.responseDelimited ? "decodeDelimited" : "decode"](s);
                } catch (r) {
                    a.emit("error", r, t);
                    return o(r);
                }
            }
            a.emit("data", s, t);
            return o(null, s);
        });
    } catch (e) {
        a.emit("error", e, t);
        setTimeout(function() {
            o(e);
        }, 0);
        return undefined;
    }
};

Service$2.prototype.end = function e(t) {
    if (this.rpcImpl) {
        if (!t) this.rpcImpl(null, null, null);
        this.rpcImpl = null;
        this.emit("end").off();
    }
    return this;
};

(function(e) {
    var t = e;
    t.Service = service$1;
})(rpc);

var roots = {};

(function(e) {
    var t = e;
    t.build = "minimal";
    t.Writer = writer;
    t.BufferWriter = writer_buffer;
    t.Reader = reader;
    t.BufferReader = reader_buffer;
    t.util = requireMinimal();
    t.rpc = rpc;
    t.roots = roots;
    t.configure = r;
    function r() {
        t.util._configure();
        t.Writer._configure(t.BufferWriter);
        t.Reader._configure(t.BufferReader);
    }
    r();
})(indexMinimal);

var types$1 = {};

var util$6 = {
    exports: {}
};

var codegen_1;

var hasRequiredCodegen;

function requireCodegen() {
    if (hasRequiredCodegen) return codegen_1;
    hasRequiredCodegen = 1;
    codegen_1 = e;
    function e(t, r) {
        if (typeof t === "string") {
            r = t;
            t = undefined;
        }
        var n = [];
        function s(t) {
            if (typeof t !== "string") {
                var r = o();
                if (e.verbose) console.log("codegen: " + r);
                r = "return " + r;
                if (t) {
                    var a = Object.keys(t), l = new Array(a.length + 1), c = new Array(a.length), u = 0;
                    while (u < a.length) {
                        l[u] = a[u];
                        c[u] = t[a[u++]];
                    }
                    l[u] = r;
                    return Function.apply(null, l).apply(null, c);
                }
                return Function(r)();
            }
            var d = new Array(arguments.length - 1), h = 0;
            while (h < d.length) d[h] = arguments[++h];
            h = 0;
            t = t.replace(/%([%dfijs])/g, function e(t, r) {
                var n = d[h++];
                switch (r) {
                  case "d":
                  case "f":
                    return String(Number(n));

                  case "i":
                    return String(Math.floor(n));

                  case "j":
                    return JSON.stringify(n);

                  case "s":
                    return String(n);
                }
                return "%";
            });
            if (h !== d.length) throw Error("parameter count mismatch");
            n.push(t);
            return s;
        }
        function o(e) {
            return "function " + (e || r || "") + "(" + (t && t.join(",") || "") + "){\n  " + n.join("\n  ") + "\n}";
        }
        s.toString = o;
        return s;
    }
    e.verbose = false;
    return codegen_1;
}

var fetch_1;

var hasRequiredFetch;

function requireFetch() {
    if (hasRequiredFetch) return fetch_1;
    hasRequiredFetch = 1;
    fetch_1 = n;
    var e = aspromise, t = inquire_1;
    var r = t("fs");
    function n(t, s, o) {
        if (typeof s === "function") {
            o = s;
            s = {};
        } else if (!s) s = {};
        if (!o) return e(n, this, t, s);
        if (!s.xhr && r && r.readFile) return r.readFile(t, function e(r, a) {
            return r && typeof XMLHttpRequest !== "undefined" ? n.xhr(t, s, o) : r ? o(r) : o(null, s.binary ? a : a.toString("utf8"));
        });
        return n.xhr(t, s, o);
    }
    n.xhr = function e(t, r, n) {
        var s = new XMLHttpRequest;
        s.onreadystatechange = function e() {
            if (s.readyState !== 4) return undefined;
            if (s.status !== 0 && s.status !== 200) return n(Error("status " + s.status));
            if (r.binary) {
                var t = s.response;
                if (!t) {
                    t = [];
                    for (var o = 0; o < s.responseText.length; ++o) t.push(s.responseText.charCodeAt(o) & 255);
                }
                return n(null, typeof Uint8Array !== "undefined" ? new Uint8Array(t) : t);
            }
            return n(null, s.responseText);
        };
        if (r.binary) {
            if ("overrideMimeType" in s) s.overrideMimeType("text/plain; charset=x-user-defined");
            s.responseType = "arraybuffer";
        }
        s.open("GET", t);
        s.send();
    };
    return fetch_1;
}

var path$1 = {};

var hasRequiredPath;

function requirePath() {
    if (hasRequiredPath) return path$1;
    hasRequiredPath = 1;
    (function(e) {
        var t = e;
        var r = t.isAbsolute = function e(t) {
            return /^(?:\/|\w+:)/.test(t);
        };
        var n = t.normalize = function e(t) {
            t = t.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
            var n = t.split("/"), s = r(t), o = "";
            if (s) o = n.shift() + "/";
            for (var a = 0; a < n.length; ) {
                if (n[a] === "..") {
                    if (a > 0 && n[a - 1] !== "..") n.splice(--a, 2); else if (s) n.splice(a, 1); else ++a;
                } else if (n[a] === ".") n.splice(a, 1); else ++a;
            }
            return o + n.join("/");
        };
        t.resolve = function e(t, s, o) {
            if (!o) s = n(s);
            if (r(s)) return s;
            if (!o) t = n(t);
            return (t = t.replace(/(?:\/|^)[^/]+$/, "")).length ? n(t + "/" + s) : s;
        };
    })(path$1);
    return path$1;
}

var namespace;

var hasRequiredNamespace;

function requireNamespace() {
    if (hasRequiredNamespace) return namespace;
    hasRequiredNamespace = 1;
    namespace = c;
    var e = requireObject();
    ((c.prototype = Object.create(e.prototype)).constructor = c).className = "Namespace";
    var t = requireField(), r = requireUtil$1(), n = requireOneof();
    var s, o, a;
    c.fromJSON = function e(t, r) {
        return new c(t, r.options).addJSON(r.nested);
    };
    function l(e, t) {
        if (!(e && e.length)) return undefined;
        var r = {};
        for (var n = 0; n < e.length; ++n) r[e[n].name] = e[n].toJSON(t);
        return r;
    }
    c.arrayToJSON = l;
    c.isReservedId = function e(t, r) {
        if (t) for (var n = 0; n < t.length; ++n) if (typeof t[n] !== "string" && t[n][0] <= r && t[n][1] > r) return true;
        return false;
    };
    c.isReservedName = function e(t, r) {
        if (t) for (var n = 0; n < t.length; ++n) if (t[n] === r) return true;
        return false;
    };
    function c(t, r) {
        e.call(this, t, r);
        this.nested = undefined;
        this._nestedArray = null;
        this._lookupCache = {};
        this._needsRecursiveFeatureResolution = true;
        this._needsRecursiveResolve = true;
    }
    function u(e) {
        e._nestedArray = null;
        e._lookupCache = {};
        var t = e;
        while (t = t.parent) {
            t._lookupCache = {};
        }
        return e;
    }
    Object.defineProperty(c.prototype, "nestedArray", {
        get: function() {
            return this._nestedArray || (this._nestedArray = r.toArray(this.nested));
        }
    });
    c.prototype.toJSON = function e(t) {
        return r.toObject([ "options", this.options, "nested", l(this.nestedArray, t) ]);
    };
    c.prototype.addJSON = function e(r) {
        var n = this;
        if (r) {
            for (var l = Object.keys(r), u = 0, d; u < l.length; ++u) {
                d = r[l[u]];
                n.add((d.fields !== undefined ? s.fromJSON : d.values !== undefined ? a.fromJSON : d.methods !== undefined ? o.fromJSON : d.id !== undefined ? t.fromJSON : c.fromJSON)(l[u], d));
            }
        }
        return this;
    };
    c.prototype.get = function e(t) {
        return this.nested && this.nested[t] || null;
    };
    c.prototype.getEnum = function e(t) {
        if (this.nested && this.nested[t] instanceof a) return this.nested[t].values;
        throw Error("no such enum: " + t);
    };
    c.prototype.add = function e(r) {
        if (!(r instanceof t && r.extend !== undefined || r instanceof s || r instanceof n || r instanceof a || r instanceof o || r instanceof c)) throw TypeError("object must be a valid nested object");
        if (!this.nested) this.nested = {}; else {
            var l = this.get(r.name);
            if (l) {
                if (l instanceof c && r instanceof c && !(l instanceof s || l instanceof o)) {
                    var d = l.nestedArray;
                    for (var h = 0; h < d.length; ++h) r.add(d[h]);
                    this.remove(l);
                    if (!this.nested) this.nested = {};
                    r.setOptions(l.options, true);
                } else throw Error("duplicate name '" + r.name + "' in " + this);
            }
        }
        this.nested[r.name] = r;
        if (!(this instanceof s || this instanceof o || this instanceof a || this instanceof t)) {
            if (!r._edition) {
                r._edition = r._defaultEdition;
            }
        }
        this._needsRecursiveFeatureResolution = true;
        this._needsRecursiveResolve = true;
        var p = this;
        while (p = p.parent) {
            p._needsRecursiveFeatureResolution = true;
            p._needsRecursiveResolve = true;
        }
        r.onAdd(this);
        return u(this);
    };
    c.prototype.remove = function t(r) {
        if (!(r instanceof e)) throw TypeError("object must be a ReflectionObject");
        if (r.parent !== this) throw Error(r + " is not a member of " + this);
        delete this.nested[r.name];
        if (!Object.keys(this.nested).length) this.nested = undefined;
        r.onRemove(this);
        return u(this);
    };
    c.prototype.define = function e(t, n) {
        if (r.isString(t)) t = t.split("."); else if (!Array.isArray(t)) throw TypeError("illegal path");
        if (t && t.length && t[0] === "") throw Error("path must be relative");
        var s = this;
        while (t.length > 0) {
            var o = t.shift();
            if (s.nested && s.nested[o]) {
                s = s.nested[o];
                if (!(s instanceof c)) throw Error("path conflicts with non-namespace objects");
            } else s.add(s = new c(o));
        }
        if (n) s.addJSON(n);
        return s;
    };
    c.prototype.resolveAll = function e() {
        if (!this._needsRecursiveResolve) return this;
        this._resolveFeaturesRecursive(this._edition);
        var t = this.nestedArray, r = 0;
        this.resolve();
        while (r < t.length) if (t[r] instanceof c) t[r++].resolveAll(); else t[r++].resolve();
        this._needsRecursiveResolve = false;
        return this;
    };
    c.prototype._resolveFeaturesRecursive = function t(r) {
        if (!this._needsRecursiveFeatureResolution) return this;
        this._needsRecursiveFeatureResolution = false;
        r = this._edition || r;
        e.prototype._resolveFeaturesRecursive.call(this, r);
        this.nestedArray.forEach(e => {
            e._resolveFeaturesRecursive(r);
        });
        return this;
    };
    c.prototype.lookup = function e(t, n, s) {
        if (typeof n === "boolean") {
            s = n;
            n = undefined;
        } else if (n && !Array.isArray(n)) n = [ n ];
        if (r.isString(t) && t.length) {
            if (t === ".") return this.root;
            t = t.split(".");
        } else if (!t.length) return this;
        var o = t.join(".");
        if (t[0] === "") return this.root.lookup(t.slice(1), n);
        var a = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + o];
        if (a && (!n || n.indexOf(a.constructor) > -1)) {
            return a;
        }
        a = this._lookupImpl(t, o);
        if (a && (!n || n.indexOf(a.constructor) > -1)) {
            return a;
        }
        if (s) return null;
        var l = this;
        while (l.parent) {
            a = l.parent._lookupImpl(t, o);
            if (a && (!n || n.indexOf(a.constructor) > -1)) {
                return a;
            }
            l = l.parent;
        }
        return null;
    };
    c.prototype._lookupImpl = function e(t, r) {
        if (Object.prototype.hasOwnProperty.call(this._lookupCache, r)) {
            return this._lookupCache[r];
        }
        var n = this.get(t[0]);
        var s = null;
        if (n) {
            if (t.length === 1) {
                s = n;
            } else if (n instanceof c) {
                t = t.slice(1);
                s = n._lookupImpl(t, t.join("."));
            }
        } else {
            for (var o = 0; o < this.nestedArray.length; ++o) if (this._nestedArray[o] instanceof c && (n = this._nestedArray[o]._lookupImpl(t, r))) s = n;
        }
        this._lookupCache[r] = s;
        return s;
    };
    c.prototype.lookupType = function e(t) {
        var r = this.lookup(t, [ s ]);
        if (!r) throw Error("no such type: " + t);
        return r;
    };
    c.prototype.lookupEnum = function e(t) {
        var r = this.lookup(t, [ a ]);
        if (!r) throw Error("no such Enum '" + t + "' in " + this);
        return r;
    };
    c.prototype.lookupTypeOrEnum = function e(t) {
        var r = this.lookup(t, [ s, a ]);
        if (!r) throw Error("no such Type or Enum '" + t + "' in " + this);
        return r;
    };
    c.prototype.lookupService = function e(t) {
        var r = this.lookup(t, [ o ]);
        if (!r) throw Error("no such Service '" + t + "' in " + this);
        return r;
    };
    c._configure = function(e, t, r) {
        s = e;
        o = t;
        a = r;
    };
    return namespace;
}

var mapfield;

var hasRequiredMapfield;

function requireMapfield() {
    if (hasRequiredMapfield) return mapfield;
    hasRequiredMapfield = 1;
    mapfield = n;
    var e = requireField();
    ((n.prototype = Object.create(e.prototype)).constructor = n).className = "MapField";
    var t = types$1, r = requireUtil$1();
    function n(t, n, s, o, a, l) {
        e.call(this, t, n, o, undefined, undefined, a, l);
        if (!r.isString(s)) throw TypeError("keyType must be a string");
        this.keyType = s;
        this.resolvedKeyType = null;
        this.map = true;
    }
    n.fromJSON = function e(t, r) {
        return new n(t, r.id, r.keyType, r.type, r.options, r.comment);
    };
    n.prototype.toJSON = function e(t) {
        var n = t ? Boolean(t.keepComments) : false;
        return r.toObject([ "keyType", this.keyType, "type", this.type, "id", this.id, "extend", this.extend, "options", this.options, "comment", n ? this.comment : undefined ]);
    };
    n.prototype.resolve = function r() {
        if (this.resolved) return this;
        if (t.mapKey[this.keyType] === undefined) throw Error("invalid key type: " + this.keyType);
        return e.prototype.resolve.call(this);
    };
    n.d = function e(t, s, o) {
        if (typeof o === "function") o = r.decorateType(o).name; else if (o && typeof o === "object") o = r.decorateEnum(o).name;
        return function e(a, l) {
            r.decorateType(a.constructor).add(new n(l, t, s, o));
        };
    };
    return mapfield;
}

var method;

var hasRequiredMethod;

function requireMethod() {
    if (hasRequiredMethod) return method;
    hasRequiredMethod = 1;
    method = r;
    var e = requireObject();
    ((r.prototype = Object.create(e.prototype)).constructor = r).className = "Method";
    var t = requireUtil$1();
    function r(r, n, s, o, a, l, c, u, d) {
        if (t.isObject(a)) {
            c = a;
            a = l = undefined;
        } else if (t.isObject(l)) {
            c = l;
            l = undefined;
        }
        if (!(n === undefined || t.isString(n))) throw TypeError("type must be a string");
        if (!t.isString(s)) throw TypeError("requestType must be a string");
        if (!t.isString(o)) throw TypeError("responseType must be a string");
        e.call(this, r, c);
        this.type = n || "rpc";
        this.requestType = s;
        this.requestStream = a ? true : undefined;
        this.responseType = o;
        this.responseStream = l ? true : undefined;
        this.resolvedRequestType = null;
        this.resolvedResponseType = null;
        this.comment = u;
        this.parsedOptions = d;
    }
    r.fromJSON = function e(t, n) {
        return new r(t, n.type, n.requestType, n.responseType, n.requestStream, n.responseStream, n.options, n.comment, n.parsedOptions);
    };
    r.prototype.toJSON = function e(r) {
        var n = r ? Boolean(r.keepComments) : false;
        return t.toObject([ "type", this.type !== "rpc" && this.type || undefined, "requestType", this.requestType, "requestStream", this.requestStream, "responseType", this.responseType, "responseStream", this.responseStream, "options", this.options, "comment", n ? this.comment : undefined, "parsedOptions", this.parsedOptions ]);
    };
    r.prototype.resolve = function t() {
        if (this.resolved) return this;
        this.resolvedRequestType = this.parent.lookupType(this.requestType);
        this.resolvedResponseType = this.parent.lookupType(this.responseType);
        return e.prototype.resolve.call(this);
    };
    return method;
}

var service;

var hasRequiredService;

function requireService() {
    if (hasRequiredService) return service;
    hasRequiredService = 1;
    service = s;
    var e = requireNamespace();
    ((s.prototype = Object.create(e.prototype)).constructor = s).className = "Service";
    var t = requireMethod(), r = requireUtil$1(), n = rpc;
    function s(t, r) {
        e.call(this, t, r);
        this.methods = {};
        this._methodsArray = null;
    }
    s.fromJSON = function e(r, n) {
        var o = new s(r, n.options);
        if (n.methods) for (var a = Object.keys(n.methods), l = 0; l < a.length; ++l) o.add(t.fromJSON(a[l], n.methods[a[l]]));
        if (n.nested) o.addJSON(n.nested);
        if (n.edition) o._edition = n.edition;
        o.comment = n.comment;
        o._defaultEdition = "proto3";
        return o;
    };
    s.prototype.toJSON = function t(n) {
        var s = e.prototype.toJSON.call(this, n);
        var o = n ? Boolean(n.keepComments) : false;
        return r.toObject([ "edition", this._editionToJSON(), "options", s && s.options || undefined, "methods", e.arrayToJSON(this.methodsArray, n) || {}, "nested", s && s.nested || undefined, "comment", o ? this.comment : undefined ]);
    };
    Object.defineProperty(s.prototype, "methodsArray", {
        get: function() {
            return this._methodsArray || (this._methodsArray = r.toArray(this.methods));
        }
    });
    function o(e) {
        e._methodsArray = null;
        return e;
    }
    s.prototype.get = function t(r) {
        return this.methods[r] || e.prototype.get.call(this, r);
    };
    s.prototype.resolveAll = function t() {
        if (!this._needsRecursiveResolve) return this;
        e.prototype.resolve.call(this);
        var r = this.methodsArray;
        for (var n = 0; n < r.length; ++n) r[n].resolve();
        return this;
    };
    s.prototype._resolveFeaturesRecursive = function t(r) {
        if (!this._needsRecursiveFeatureResolution) return this;
        r = this._edition || r;
        e.prototype._resolveFeaturesRecursive.call(this, r);
        this.methodsArray.forEach(e => {
            e._resolveFeaturesRecursive(r);
        });
        return this;
    };
    s.prototype.add = function r(n) {
        if (this.get(n.name)) throw Error("duplicate name '" + n.name + "' in " + this);
        if (n instanceof t) {
            this.methods[n.name] = n;
            n.parent = this;
            return o(this);
        }
        return e.prototype.add.call(this, n);
    };
    s.prototype.remove = function r(n) {
        if (n instanceof t) {
            if (this.methods[n.name] !== n) throw Error(n + " is not a member of " + this);
            delete this.methods[n.name];
            n.parent = null;
            return o(this);
        }
        return e.prototype.remove.call(this, n);
    };
    s.prototype.create = function e(t, s, o) {
        var a = new n.Service(t, s, o);
        for (var l = 0, c; l < this.methodsArray.length; ++l) {
            var u = r.lcFirst((c = this._methodsArray[l]).resolve().name).replace(/[^$\w_]/g, "");
            a[u] = r.codegen([ "r", "c" ], r.isReserved(u) ? u + "_" : u)("return this.rpcCall(m,q,s,r,c)")({
                m: c,
                q: c.resolvedRequestType.ctor,
                s: c.resolvedResponseType.ctor
            });
        }
        return a;
    };
    return service;
}

var message = Message;

var util$5 = requireMinimal();

function Message(e) {
    if (e) for (var t = Object.keys(e), r = 0; r < t.length; ++r) this[t[r]] = e[t[r]];
}

Message.create = function e(t) {
    return this.$type.create(t);
};

Message.encode = function e(t, r) {
    return this.$type.encode(t, r);
};

Message.encodeDelimited = function e(t, r) {
    return this.$type.encodeDelimited(t, r);
};

Message.decode = function e(t) {
    return this.$type.decode(t);
};

Message.decodeDelimited = function e(t) {
    return this.$type.decodeDelimited(t);
};

Message.verify = function e(t) {
    return this.$type.verify(t);
};

Message.fromObject = function e(t) {
    return this.$type.fromObject(t);
};

Message.toObject = function e(t, r) {
    return this.$type.toObject(t, r);
};

Message.prototype.toJSON = function e() {
    return this.$type.toObject(this, util$5.toJSONOptions);
};

var decoder_1;

var hasRequiredDecoder;

function requireDecoder() {
    if (hasRequiredDecoder) return decoder_1;
    hasRequiredDecoder = 1;
    decoder_1 = s;
    var e = require_enum(), t = types$1, r = requireUtil$1();
    function n(e) {
        return "missing required '" + e.name + "'";
    }
    function s(s) {
        var o = r.codegen([ "r", "l", "e" ], s.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (s.fieldsArray.filter(function(e) {
            return e.map;
        }).length ? ",k,value" : ""))("while(r.pos<c){")("var t=r.uint32()")("if(t===e)")("break")("switch(t>>>3){");
        var a = 0;
        for (;a < s.fieldsArray.length; ++a) {
            var l = s._fieldsArray[a].resolve(), c = l.resolvedType instanceof e ? "int32" : l.type, u = "m" + r.safeProp(l.name);
            o("case %i: {", l.id);
            if (l.map) {
                o("if(%s===util.emptyObject)", u)("%s={}", u)("var c2 = r.uint32()+r.pos");
                if (t.defaults[l.keyType] !== undefined) o("k=%j", t.defaults[l.keyType]); else o("k=null");
                if (t.defaults[c] !== undefined) o("value=%j", t.defaults[c]); else o("value=null");
                o("while(r.pos<c2){")("var tag2=r.uint32()")("switch(tag2>>>3){")("case 1: k=r.%s(); break", l.keyType)("case 2:");
                if (t.basic[c] === undefined) o("value=types[%i].decode(r,r.uint32())", a); else o("value=r.%s()", c);
                o("break")("default:")("r.skipType(tag2&7)")("break")("}")("}");
                if (t.long[l.keyType] !== undefined) o('%s[typeof k==="object"?util.longToHash(k):k]=value', u); else o("%s[k]=value", u);
            } else if (l.repeated) {
                o("if(!(%s&&%s.length))", u, u)("%s=[]", u);
                if (t.packed[c] !== undefined) o("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())", u, c)("}else");
                if (t.basic[c] === undefined) o(l.delimited ? "%s.push(types[%i].decode(r,undefined,((t&~7)|4)))" : "%s.push(types[%i].decode(r,r.uint32()))", u, a); else o("%s.push(r.%s())", u, c);
            } else if (t.basic[c] === undefined) o(l.delimited ? "%s=types[%i].decode(r,undefined,((t&~7)|4))" : "%s=types[%i].decode(r,r.uint32())", u, a); else o("%s=r.%s()", u, c);
            o("break")("}");
        }
        o("default:")("r.skipType(t&7)")("break")("}")("}");
        for (a = 0; a < s._fieldsArray.length; ++a) {
            var d = s._fieldsArray[a];
            if (d.required) o("if(!m.hasOwnProperty(%j))", d.name)("throw util.ProtocolError(%j,{instance:m})", n(d));
        }
        return o("return m");
    }
    return decoder_1;
}

var verifier_1;

var hasRequiredVerifier;

function requireVerifier() {
    if (hasRequiredVerifier) return verifier_1;
    hasRequiredVerifier = 1;
    verifier_1 = o;
    var e = require_enum(), t = requireUtil$1();
    function r(e, t) {
        return e.name + ": " + t + (e.repeated && t !== "array" ? "[]" : e.map && t !== "object" ? "{k:" + e.keyType + "}" : "") + " expected";
    }
    function n(t, n, s, o) {
        if (n.resolvedType) {
            if (n.resolvedType instanceof e) {
                t("switch(%s){", o)("default:")("return%j", r(n, "enum value"));
                for (var a = Object.keys(n.resolvedType.values), l = 0; l < a.length; ++l) t("case %i:", n.resolvedType.values[a[l]]);
                t("break")("}");
            } else {
                t("{")("var e=types[%i].verify(%s);", s, o)("if(e)")("return%j+e", n.name + ".")("}");
            }
        } else {
            switch (n.type) {
              case "int32":
              case "uint32":
              case "sint32":
              case "fixed32":
              case "sfixed32":
                t("if(!util.isInteger(%s))", o)("return%j", r(n, "integer"));
                break;

              case "int64":
              case "uint64":
              case "sint64":
              case "fixed64":
              case "sfixed64":
                t("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", o, o, o, o)("return%j", r(n, "integer|Long"));
                break;

              case "float":
              case "double":
                t('if(typeof %s!=="number")', o)("return%j", r(n, "number"));
                break;

              case "bool":
                t('if(typeof %s!=="boolean")', o)("return%j", r(n, "boolean"));
                break;

              case "string":
                t("if(!util.isString(%s))", o)("return%j", r(n, "string"));
                break;

              case "bytes":
                t('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))', o, o, o)("return%j", r(n, "buffer"));
                break;
            }
        }
        return t;
    }
    function s(e, t, n) {
        switch (t.keyType) {
          case "int32":
          case "uint32":
          case "sint32":
          case "fixed32":
          case "sfixed32":
            e("if(!util.key32Re.test(%s))", n)("return%j", r(t, "integer key"));
            break;

          case "int64":
          case "uint64":
          case "sint64":
          case "fixed64":
          case "sfixed64":
            e("if(!util.key64Re.test(%s))", n)("return%j", r(t, "integer|Long key"));
            break;

          case "bool":
            e("if(!util.key2Re.test(%s))", n)("return%j", r(t, "boolean key"));
            break;
        }
        return e;
    }
    function o(e) {
        var o = t.codegen([ "m" ], e.name + "$verify")('if(typeof m!=="object"||m===null)')("return%j", "object expected");
        var a = e.oneofsArray, l = {};
        if (a.length) o("var p={}");
        for (var c = 0; c < e.fieldsArray.length; ++c) {
            var u = e._fieldsArray[c].resolve(), d = "m" + t.safeProp(u.name);
            if (u.optional) o("if(%s!=null&&m.hasOwnProperty(%j)){", d, u.name);
            if (u.map) {
                o("if(!util.isObject(%s))", d)("return%j", r(u, "object"))("var k=Object.keys(%s)", d)("for(var i=0;i<k.length;++i){");
                s(o, u, "k[i]");
                n(o, u, c, d + "[k[i]]")("}");
            } else if (u.repeated) {
                o("if(!Array.isArray(%s))", d)("return%j", r(u, "array"))("for(var i=0;i<%s.length;++i){", d);
                n(o, u, c, d + "[i]")("}");
            } else {
                if (u.partOf) {
                    var h = t.safeProp(u.partOf.name);
                    if (l[u.partOf.name] === 1) o("if(p%s===1)", h)("return%j", u.partOf.name + ": multiple values");
                    l[u.partOf.name] = 1;
                    o("p%s=1", h);
                }
                n(o, u, c, d);
            }
            if (u.optional) o("}");
        }
        return o("return null");
    }
    return verifier_1;
}

var converter = {};

var hasRequiredConverter;

function requireConverter() {
    if (hasRequiredConverter) return converter;
    hasRequiredConverter = 1;
    (function(e) {
        var t = e;
        var r = require_enum(), n = requireUtil$1();
        function s(e, t, n, s) {
            var o = false;
            if (t.resolvedType) {
                if (t.resolvedType instanceof r) {
                    e("switch(d%s){", s);
                    for (var a = t.resolvedType.values, l = Object.keys(a), c = 0; c < l.length; ++c) {
                        if (a[l[c]] === t.typeDefault && !o) {
                            e("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}', s, s, s);
                            if (!t.repeated) e("break");
                            o = true;
                        }
                        e("case%j:", l[c])("case %i:", a[l[c]])("m%s=%j", s, a[l[c]])("break");
                    }
                    e("}");
                } else e('if(typeof d%s!=="object")', s)("throw TypeError(%j)", t.fullName + ": object expected")("m%s=types[%i].fromObject(d%s)", s, n, s);
            } else {
                var u = false;
                switch (t.type) {
                  case "double":
                  case "float":
                    e("m%s=Number(d%s)", s, s);
                    break;

                  case "uint32":
                  case "fixed32":
                    e("m%s=d%s>>>0", s, s);
                    break;

                  case "int32":
                  case "sint32":
                  case "sfixed32":
                    e("m%s=d%s|0", s, s);
                    break;

                  case "uint64":
                    u = true;

                  case "int64":
                  case "sint64":
                  case "fixed64":
                  case "sfixed64":
                    e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j", s, s, u)('else if(typeof d%s==="string")', s)("m%s=parseInt(d%s,10)", s, s)('else if(typeof d%s==="number")', s)("m%s=d%s", s, s)('else if(typeof d%s==="object")', s)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", s, s, s, u ? "true" : "");
                    break;

                  case "bytes":
                    e('if(typeof d%s==="string")', s)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", s, s, s)("else if(d%s.length >= 0)", s)("m%s=d%s", s, s);
                    break;

                  case "string":
                    e("m%s=String(d%s)", s, s);
                    break;

                  case "bool":
                    e("m%s=Boolean(d%s)", s, s);
                    break;
                }
            }
            return e;
        }
        t.fromObject = function e(t) {
            var o = t.fieldsArray;
            var a = n.codegen([ "d" ], t.name + "$fromObject")("if(d instanceof this.ctor)")("return d");
            if (!o.length) return a("return new this.ctor");
            a("var m=new this.ctor");
            for (var l = 0; l < o.length; ++l) {
                var c = o[l].resolve(), u = n.safeProp(c.name);
                if (c.map) {
                    a("if(d%s){", u)('if(typeof d%s!=="object")', u)("throw TypeError(%j)", c.fullName + ": object expected")("m%s={}", u)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", u);
                    s(a, c, l, u + "[ks[i]]")("}")("}");
                } else if (c.repeated) {
                    a("if(d%s){", u)("if(!Array.isArray(d%s))", u)("throw TypeError(%j)", c.fullName + ": array expected")("m%s=[]", u)("for(var i=0;i<d%s.length;++i){", u);
                    s(a, c, l, u + "[i]")("}")("}");
                } else {
                    if (!(c.resolvedType instanceof r)) a("if(d%s!=null){", u);
                    s(a, c, l, u);
                    if (!(c.resolvedType instanceof r)) a("}");
                }
            }
            return a("return m");
        };
        function o(e, t, n, s) {
            if (t.resolvedType) {
                if (t.resolvedType instanceof r) e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s", s, n, s, s, n, s, s); else e("d%s=types[%i].toObject(m%s,o)", s, n, s);
            } else {
                var o = false;
                switch (t.type) {
                  case "double":
                  case "float":
                    e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", s, s, s, s);
                    break;

                  case "uint64":
                    o = true;

                  case "int64":
                  case "sint64":
                  case "fixed64":
                  case "sfixed64":
                    e('if(typeof m%s==="number")', s)("d%s=o.longs===String?String(m%s):m%s", s, s, s)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", s, s, s, s, o ? "true" : "", s);
                    break;

                  case "bytes":
                    e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", s, s, s, s, s);
                    break;

                  default:
                    e("d%s=m%s", s, s);
                    break;
                }
            }
            return e;
        }
        t.toObject = function e(t) {
            var s = t.fieldsArray.slice().sort(n.compareFieldsById);
            if (!s.length) return n.codegen()("return {}");
            var a = n.codegen([ "m", "o" ], t.name + "$toObject")("if(!o)")("o={}")("var d={}");
            var l = [], c = [], u = [], d = 0;
            for (;d < s.length; ++d) if (!s[d].partOf) (s[d].resolve().repeated ? l : s[d].map ? c : u).push(s[d]);
            if (l.length) {
                a("if(o.arrays||o.defaults){");
                for (d = 0; d < l.length; ++d) a("d%s=[]", n.safeProp(l[d].name));
                a("}");
            }
            if (c.length) {
                a("if(o.objects||o.defaults){");
                for (d = 0; d < c.length; ++d) a("d%s={}", n.safeProp(c[d].name));
                a("}");
            }
            if (u.length) {
                a("if(o.defaults){");
                for (d = 0; d < u.length; ++d) {
                    var h = u[d], p = n.safeProp(h.name);
                    if (h.resolvedType instanceof r) a("d%s=o.enums===String?%j:%j", p, h.resolvedType.valuesById[h.typeDefault], h.typeDefault); else if (h.long) a("if(util.Long){")("var n=new util.Long(%i,%i,%j)", h.typeDefault.low, h.typeDefault.high, h.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", p)("}else")("d%s=o.longs===String?%j:%i", p, h.typeDefault.toString(), h.typeDefault.toNumber()); else if (h.bytes) {
                        var g = "[" + Array.prototype.slice.call(h.typeDefault).join(",") + "]";
                        a("if(o.bytes===String)d%s=%j", p, String.fromCharCode.apply(String, h.typeDefault))("else{")("d%s=%s", p, g)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", p, p)("}");
                    } else a("d%s=%j", p, h.typeDefault);
                }
                a("}");
            }
            var m = false;
            for (d = 0; d < s.length; ++d) {
                var h = s[d], _ = t._fieldsArray.indexOf(h), p = n.safeProp(h.name);
                if (h.map) {
                    if (!m) {
                        m = true;
                        a("var ks2");
                    }
                    a("if(m%s&&(ks2=Object.keys(m%s)).length){", p, p)("d%s={}", p)("for(var j=0;j<ks2.length;++j){");
                    o(a, h, _, p + "[ks2[j]]")("}");
                } else if (h.repeated) {
                    a("if(m%s&&m%s.length){", p, p)("d%s=[]", p)("for(var j=0;j<m%s.length;++j){", p);
                    o(a, h, _, p + "[j]")("}");
                } else {
                    a("if(m%s!=null&&m.hasOwnProperty(%j)){", p, h.name);
                    o(a, h, _, p);
                    if (h.partOf) a("if(o.oneofs)")("d%s=%j", n.safeProp(h.partOf.name), h.name);
                }
                a("}");
            }
            return a("return d");
        };
    })(converter);
    return converter;
}

var wrappers = {};

(function(e) {
    var t = e;
    var r = message;
    t[".google.protobuf.Any"] = {
        fromObject: function(e) {
            if (e && e["@type"]) {
                var t = e["@type"].substring(e["@type"].lastIndexOf("/") + 1);
                var r = this.lookup(t);
                if (r) {
                    var n = e["@type"].charAt(0) === "." ? e["@type"].slice(1) : e["@type"];
                    if (n.indexOf("/") === -1) {
                        n = "/" + n;
                    }
                    return this.create({
                        type_url: n,
                        value: r.encode(r.fromObject(e)).finish()
                    });
                }
            }
            return this.fromObject(e);
        },
        toObject: function(e, t) {
            var n = "type.googleapis.com/";
            var s = "";
            var o = "";
            if (t && t.json && e.type_url && e.value) {
                o = e.type_url.substring(e.type_url.lastIndexOf("/") + 1);
                s = e.type_url.substring(0, e.type_url.lastIndexOf("/") + 1);
                var a = this.lookup(o);
                if (a) e = a.decode(e.value);
            }
            if (!(e instanceof this.ctor) && e instanceof r) {
                var l = e.$type.toObject(e, t);
                var c = e.$type.fullName[0] === "." ? e.$type.fullName.slice(1) : e.$type.fullName;
                if (s === "") {
                    s = n;
                }
                o = s + c;
                l["@type"] = o;
                return l;
            }
            return this.toObject(e, t);
        }
    };
})(wrappers);

var type;

var hasRequiredType;

function requireType() {
    if (hasRequiredType) return type;
    hasRequiredType = 1;
    type = _;
    var e = requireNamespace();
    ((_.prototype = Object.create(e.prototype)).constructor = _).className = "Type";
    var t = require_enum(), r = requireOneof(), n = requireField(), s = requireMapfield(), o = requireService(), a = message, l = reader, c = writer, u = requireUtil$1(), d = requireEncoder(), h = requireDecoder(), p = requireVerifier(), g = requireConverter(), m = wrappers;
    function _(t, r) {
        e.call(this, t, r);
        this.fields = {};
        this.oneofs = undefined;
        this.extensions = undefined;
        this.reserved = undefined;
        this.group = undefined;
        this._fieldsById = null;
        this._fieldsArray = null;
        this._oneofsArray = null;
        this._ctor = null;
    }
    Object.defineProperties(_.prototype, {
        fieldsById: {
            get: function() {
                if (this._fieldsById) return this._fieldsById;
                this._fieldsById = {};
                for (var e = Object.keys(this.fields), t = 0; t < e.length; ++t) {
                    var r = this.fields[e[t]], n = r.id;
                    if (this._fieldsById[n]) throw Error("duplicate id " + n + " in " + this);
                    this._fieldsById[n] = r;
                }
                return this._fieldsById;
            }
        },
        fieldsArray: {
            get: function() {
                return this._fieldsArray || (this._fieldsArray = u.toArray(this.fields));
            }
        },
        oneofsArray: {
            get: function() {
                return this._oneofsArray || (this._oneofsArray = u.toArray(this.oneofs));
            }
        },
        ctor: {
            get: function() {
                return this._ctor || (this.ctor = _.generateConstructor(this)());
            },
            set: function(e) {
                var t = e.prototype;
                if (!(t instanceof a)) {
                    (e.prototype = new a).constructor = e;
                    u.merge(e.prototype, t);
                }
                e.$type = e.prototype.$type = this;
                u.merge(e, a, true);
                this._ctor = e;
                var r = 0;
                for (;r < this.fieldsArray.length; ++r) this._fieldsArray[r].resolve();
                var n = {};
                for (r = 0; r < this.oneofsArray.length; ++r) n[this._oneofsArray[r].resolve().name] = {
                    get: u.oneOfGetter(this._oneofsArray[r].oneof),
                    set: u.oneOfSetter(this._oneofsArray[r].oneof)
                };
                if (r) Object.defineProperties(e.prototype, n);
            }
        }
    });
    _.generateConstructor = function e(t) {
        var r = u.codegen([ "p" ], t.name);
        for (var n = 0, s; n < t.fieldsArray.length; ++n) if ((s = t._fieldsArray[n]).map) r("this%s={}", u.safeProp(s.name)); else if (s.repeated) r("this%s=[]", u.safeProp(s.name));
        return r("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]");
    };
    function E(e) {
        e._fieldsById = e._fieldsArray = e._oneofsArray = null;
        delete e.encode;
        delete e.decode;
        delete e.verify;
        return e;
    }
    _.fromJSON = function a(l, c) {
        var u = new _(l, c.options);
        u.extensions = c.extensions;
        u.reserved = c.reserved;
        var d = Object.keys(c.fields), h = 0;
        for (;h < d.length; ++h) u.add((typeof c.fields[d[h]].keyType !== "undefined" ? s.fromJSON : n.fromJSON)(d[h], c.fields[d[h]]));
        if (c.oneofs) for (d = Object.keys(c.oneofs), h = 0; h < d.length; ++h) u.add(r.fromJSON(d[h], c.oneofs[d[h]]));
        if (c.nested) for (d = Object.keys(c.nested), h = 0; h < d.length; ++h) {
            var p = c.nested[d[h]];
            u.add((p.id !== undefined ? n.fromJSON : p.fields !== undefined ? _.fromJSON : p.values !== undefined ? t.fromJSON : p.methods !== undefined ? o.fromJSON : e.fromJSON)(d[h], p));
        }
        if (c.extensions && c.extensions.length) u.extensions = c.extensions;
        if (c.reserved && c.reserved.length) u.reserved = c.reserved;
        if (c.group) u.group = true;
        if (c.comment) u.comment = c.comment;
        if (c.edition) u._edition = c.edition;
        u._defaultEdition = "proto3";
        return u;
    };
    _.prototype.toJSON = function t(r) {
        var n = e.prototype.toJSON.call(this, r);
        var s = r ? Boolean(r.keepComments) : false;
        return u.toObject([ "edition", this._editionToJSON(), "options", n && n.options || undefined, "oneofs", e.arrayToJSON(this.oneofsArray, r), "fields", e.arrayToJSON(this.fieldsArray.filter(function(e) {
            return !e.declaringField;
        }), r) || {}, "extensions", this.extensions && this.extensions.length ? this.extensions : undefined, "reserved", this.reserved && this.reserved.length ? this.reserved : undefined, "group", this.group || undefined, "nested", n && n.nested || undefined, "comment", s ? this.comment : undefined ]);
    };
    _.prototype.resolveAll = function t() {
        if (!this._needsRecursiveResolve) return this;
        e.prototype.resolveAll.call(this);
        var r = this.oneofsArray;
        s = 0;
        while (s < r.length) r[s++].resolve();
        var n = this.fieldsArray, s = 0;
        while (s < n.length) n[s++].resolve();
        return this;
    };
    _.prototype._resolveFeaturesRecursive = function t(r) {
        if (!this._needsRecursiveFeatureResolution) return this;
        r = this._edition || r;
        e.prototype._resolveFeaturesRecursive.call(this, r);
        this.oneofsArray.forEach(e => {
            e._resolveFeatures(r);
        });
        this.fieldsArray.forEach(e => {
            e._resolveFeatures(r);
        });
        return this;
    };
    _.prototype.get = function e(t) {
        return this.fields[t] || this.oneofs && this.oneofs[t] || this.nested && this.nested[t] || null;
    };
    _.prototype.add = function t(s) {
        if (this.get(s.name)) throw Error("duplicate name '" + s.name + "' in " + this);
        if (s instanceof n && s.extend === undefined) {
            if (this._fieldsById ? this._fieldsById[s.id] : this.fieldsById[s.id]) throw Error("duplicate id " + s.id + " in " + this);
            if (this.isReservedId(s.id)) throw Error("id " + s.id + " is reserved in " + this);
            if (this.isReservedName(s.name)) throw Error("name '" + s.name + "' is reserved in " + this);
            if (s.parent) s.parent.remove(s);
            this.fields[s.name] = s;
            s.message = this;
            s.onAdd(this);
            return E(this);
        }
        if (s instanceof r) {
            if (!this.oneofs) this.oneofs = {};
            this.oneofs[s.name] = s;
            s.onAdd(this);
            return E(this);
        }
        return e.prototype.add.call(this, s);
    };
    _.prototype.remove = function t(s) {
        if (s instanceof n && s.extend === undefined) {
            if (!this.fields || this.fields[s.name] !== s) throw Error(s + " is not a member of " + this);
            delete this.fields[s.name];
            s.parent = null;
            s.onRemove(this);
            return E(this);
        }
        if (s instanceof r) {
            if (!this.oneofs || this.oneofs[s.name] !== s) throw Error(s + " is not a member of " + this);
            delete this.oneofs[s.name];
            s.parent = null;
            s.onRemove(this);
            return E(this);
        }
        return e.prototype.remove.call(this, s);
    };
    _.prototype.isReservedId = function t(r) {
        return e.isReservedId(this.reserved, r);
    };
    _.prototype.isReservedName = function t(r) {
        return e.isReservedName(this.reserved, r);
    };
    _.prototype.create = function e(t) {
        return new this.ctor(t);
    };
    _.prototype.setup = function e() {
        var t = this.fullName, r = [];
        for (var n = 0; n < this.fieldsArray.length; ++n) r.push(this._fieldsArray[n].resolve().resolvedType);
        this.encode = d(this)({
            Writer: c,
            types: r,
            util: u
        });
        this.decode = h(this)({
            Reader: l,
            types: r,
            util: u
        });
        this.verify = p(this)({
            types: r,
            util: u
        });
        this.fromObject = g.fromObject(this)({
            types: r,
            util: u
        });
        this.toObject = g.toObject(this)({
            types: r,
            util: u
        });
        var s = m[t];
        if (s) {
            var o = Object.create(this);
            o.fromObject = this.fromObject;
            this.fromObject = s.fromObject.bind(o);
            o.toObject = this.toObject;
            this.toObject = s.toObject.bind(o);
        }
        return this;
    };
    _.prototype.encode = function e(t, r) {
        return this.setup().encode(t, r);
    };
    _.prototype.encodeDelimited = function e(t, r) {
        return this.encode(t, r && r.len ? r.fork() : r).ldelim();
    };
    _.prototype.decode = function e(t, r) {
        return this.setup().decode(t, r);
    };
    _.prototype.decodeDelimited = function e(t) {
        if (!(t instanceof l)) t = l.create(t);
        return this.decode(t, t.uint32());
    };
    _.prototype.verify = function e(t) {
        return this.setup().verify(t);
    };
    _.prototype.fromObject = function e(t) {
        return this.setup().fromObject(t);
    };
    _.prototype.toObject = function e(t, r) {
        return this.setup().toObject(t, r);
    };
    _.d = function e(t) {
        return function e(r) {
            u.decorateType(r, t);
        };
    };
    return type;
}

var root;

var hasRequiredRoot;

function requireRoot() {
    if (hasRequiredRoot) return root;
    hasRequiredRoot = 1;
    root = c;
    var e = requireNamespace();
    ((c.prototype = Object.create(e.prototype)).constructor = c).className = "Root";
    var t = requireField(), r = require_enum(), n = requireOneof(), s = requireUtil$1();
    var o, a, l;
    function c(t) {
        e.call(this, "", t);
        this.deferred = [];
        this.files = [];
        this._edition = "proto2";
        this._fullyQualifiedObjects = {};
    }
    c.fromJSON = function e(t, r) {
        if (!r) r = new c;
        if (t.options) r.setOptions(t.options);
        return r.addJSON(t.nested).resolveAll();
    };
    c.prototype.resolvePath = s.path.resolve;
    c.prototype.fetch = s.fetch;
    function u() {}
    c.prototype.load = function e(t, r, n) {
        if (typeof r === "function") {
            n = r;
            r = undefined;
        }
        var o = this;
        if (!n) {
            return s.asPromise(e, o, t, r);
        }
        var c = n === u;
        function d(e, t) {
            if (!n) {
                return;
            }
            if (c) {
                throw e;
            }
            if (t) {
                t.resolveAll();
            }
            var r = n;
            n = null;
            r(e, t);
        }
        function h(e) {
            var t = e.lastIndexOf("google/protobuf/");
            if (t > -1) {
                var r = e.substring(t);
                if (r in l) return r;
            }
            return null;
        }
        function p(e, t) {
            try {
                if (s.isString(t) && t.charAt(0) === "{") t = JSON.parse(t);
                if (!s.isString(t)) o.setOptions(t.options).addJSON(t.nested); else {
                    a.filename = e;
                    var n = a(t, o, r), l, u = 0;
                    if (n.imports) for (;u < n.imports.length; ++u) if (l = h(n.imports[u]) || o.resolvePath(e, n.imports[u])) g(l);
                    if (n.weakImports) for (u = 0; u < n.weakImports.length; ++u) if (l = h(n.weakImports[u]) || o.resolvePath(e, n.weakImports[u])) g(l, true);
                }
            } catch (e) {
                d(e);
            }
            if (!c && !m) {
                d(null, o);
            }
        }
        function g(e, t) {
            e = h(e) || e;
            if (o.files.indexOf(e) > -1) {
                return;
            }
            o.files.push(e);
            if (e in l) {
                if (c) {
                    p(e, l[e]);
                } else {
                    ++m;
                    setTimeout(function() {
                        --m;
                        p(e, l[e]);
                    });
                }
                return;
            }
            if (c) {
                var r;
                try {
                    r = s.fs.readFileSync(e).toString("utf8");
                } catch (e) {
                    if (!t) d(e);
                    return;
                }
                p(e, r);
            } else {
                ++m;
                o.fetch(e, function(r, s) {
                    --m;
                    if (!n) {
                        return;
                    }
                    if (r) {
                        if (!t) d(r); else if (!m) d(null, o);
                        return;
                    }
                    p(e, s);
                });
            }
        }
        var m = 0;
        if (s.isString(t)) {
            t = [ t ];
        }
        for (var _ = 0, E; _ < t.length; ++_) if (E = o.resolvePath("", t[_])) g(E);
        if (c) {
            o.resolveAll();
            return o;
        }
        if (!m) {
            d(null, o);
        }
        return o;
    };
    c.prototype.loadSync = function e(t, r) {
        if (!s.isNode) throw Error("not supported");
        return this.load(t, r, u);
    };
    c.prototype.resolveAll = function t() {
        if (!this._needsRecursiveResolve) return this;
        if (this.deferred.length) throw Error("unresolvable extensions: " + this.deferred.map(function(e) {
            return "'extend " + e.extend + "' in " + e.parent.fullName;
        }).join(", "));
        return e.prototype.resolveAll.call(this);
    };
    var d = /^[A-Z]/;
    function h(e, r) {
        var n = r.parent.lookup(r.extend);
        if (n) {
            var s = new t(r.fullName, r.id, r.type, r.rule, undefined, r.options);
            if (n.get(s.name)) {
                return true;
            }
            s.declaringField = r;
            r.extensionField = s;
            n.add(s);
            return true;
        }
        return false;
    }
    c.prototype._handleAdd = function e(s) {
        if (s instanceof t) {
            if (s.extend !== undefined && !s.extensionField) if (!h(this, s)) this.deferred.push(s);
        } else if (s instanceof r) {
            if (d.test(s.name)) s.parent[s.name] = s.values;
        } else if (!(s instanceof n)) {
            if (s instanceof o) for (var a = 0; a < this.deferred.length; ) if (h(this, this.deferred[a])) this.deferred.splice(a, 1); else ++a;
            for (var l = 0; l < s.nestedArray.length; ++l) this._handleAdd(s._nestedArray[l]);
            if (d.test(s.name)) s.parent[s.name] = s;
        }
        if (s instanceof o || s instanceof r || s instanceof t) {
            this._fullyQualifiedObjects[s.fullName] = s;
        }
    };
    c.prototype._handleRemove = function n(s) {
        if (s instanceof t) {
            if (s.extend !== undefined) {
                if (s.extensionField) {
                    s.extensionField.parent.remove(s.extensionField);
                    s.extensionField = null;
                } else {
                    var o = this.deferred.indexOf(s);
                    if (o > -1) this.deferred.splice(o, 1);
                }
            }
        } else if (s instanceof r) {
            if (d.test(s.name)) delete s.parent[s.name];
        } else if (s instanceof e) {
            for (var a = 0; a < s.nestedArray.length; ++a) this._handleRemove(s._nestedArray[a]);
            if (d.test(s.name)) delete s.parent[s.name];
        }
        delete this._fullyQualifiedObjects[s.fullName];
    };
    c._configure = function(e, t, r) {
        o = e;
        a = t;
        l = r;
    };
    return root;
}

util$6.exports;

var hasRequiredUtil$1;

function requireUtil$1() {
    if (hasRequiredUtil$1) return util$6.exports;
    hasRequiredUtil$1 = 1;
    var e = util$6.exports = requireMinimal();
    var t = roots;
    var r, n;
    e.codegen = requireCodegen();
    e.fetch = requireFetch();
    e.path = requirePath();
    e.fs = e.inquire("fs");
    e.toArray = function e(t) {
        if (t) {
            var r = Object.keys(t), n = new Array(r.length), s = 0;
            while (s < r.length) n[s] = t[r[s++]];
            return n;
        }
        return [];
    };
    e.toObject = function e(t) {
        var r = {}, n = 0;
        while (n < t.length) {
            var s = t[n++], o = t[n++];
            if (o !== undefined) r[s] = o;
        }
        return r;
    };
    var s = /\\/g, o = /"/g;
    e.isReserved = function e(t) {
        return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(t);
    };
    e.safeProp = function t(r) {
        if (!/^[$\w_]+$/.test(r) || e.isReserved(r)) return '["' + r.replace(s, "\\\\").replace(o, '\\"') + '"]';
        return "." + r;
    };
    e.ucFirst = function e(t) {
        return t.charAt(0).toUpperCase() + t.substring(1);
    };
    var a = /_([a-z])/g;
    e.camelCase = function e(t) {
        return t.substring(0, 1) + t.substring(1).replace(a, function(e, t) {
            return t.toUpperCase();
        });
    };
    e.compareFieldsById = function e(t, r) {
        return t.id - r.id;
    };
    e.decorateType = function t(n, s) {
        if (n.$type) {
            if (s && n.$type.name !== s) {
                e.decorateRoot.remove(n.$type);
                n.$type.name = s;
                e.decorateRoot.add(n.$type);
            }
            return n.$type;
        }
        if (!r) r = requireType();
        var o = new r(s || n.name);
        e.decorateRoot.add(o);
        o.ctor = n;
        Object.defineProperty(n, "$type", {
            value: o,
            enumerable: false
        });
        Object.defineProperty(n.prototype, "$type", {
            value: o,
            enumerable: false
        });
        return o;
    };
    var l = 0;
    e.decorateEnum = function t(r) {
        if (r.$type) return r.$type;
        if (!n) n = require_enum();
        var s = new n("Enum" + l++, r);
        e.decorateRoot.add(s);
        Object.defineProperty(r, "$type", {
            value: s,
            enumerable: false
        });
        return s;
    };
    e.setProperty = function e(t, r, n, s) {
        function o(e, t, r) {
            var n = t.shift();
            if (n === "__proto__" || n === "prototype") {
                return e;
            }
            if (t.length > 0) {
                e[n] = o(e[n] || {}, t, r);
            } else {
                var a = e[n];
                if (a && s) return e;
                if (a) r = [].concat(a).concat(r);
                e[n] = r;
            }
            return e;
        }
        if (typeof t !== "object") throw TypeError("dst must be an object");
        if (!r) throw TypeError("path must be specified");
        r = r.split(".");
        return o(t, r, n);
    };
    Object.defineProperty(e, "decorateRoot", {
        get: function() {
            return t["decorated"] || (t["decorated"] = new (requireRoot()));
        }
    });
    return util$6.exports;
}

(function(e) {
    var t = e;
    var r = requireUtil$1();
    var n = [ "double", "float", "int32", "uint32", "sint32", "fixed32", "sfixed32", "int64", "uint64", "sint64", "fixed64", "sfixed64", "bool", "string", "bytes" ];
    function s(e, t) {
        var r = 0, s = {};
        t |= 0;
        while (r < e.length) s[n[r + t]] = e[r++];
        return s;
    }
    t.basic = s([ 1, 5, 0, 0, 0, 5, 5, 0, 0, 0, 1, 1, 0, 2, 2 ]);
    t.defaults = s([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false, "", r.emptyArray, null ]);
    t.long = s([ 0, 0, 0, 1, 1 ], 7);
    t.mapKey = s([ 0, 0, 0, 5, 5, 0, 0, 0, 1, 1, 0, 2 ], 2);
    t.packed = s([ 1, 5, 0, 0, 0, 5, 5, 0, 0, 0, 1, 1, 0 ]);
})(types$1);

var field;

var hasRequiredField;

function requireField() {
    if (hasRequiredField) return field;
    hasRequiredField = 1;
    field = a;
    var e = requireObject();
    ((a.prototype = Object.create(e.prototype)).constructor = a).className = "Field";
    var t = require_enum(), r = types$1, n = requireUtil$1();
    var s;
    var o = /^required|optional|repeated$/;
    a.fromJSON = function e(t, r) {
        var n = new a(t, r.id, r.type, r.rule, r.extend, r.options, r.comment);
        if (r.edition) n._edition = r.edition;
        n._defaultEdition = "proto3";
        return n;
    };
    function a(t, s, a, l, c, u, d) {
        if (n.isObject(l)) {
            d = c;
            u = l;
            l = c = undefined;
        } else if (n.isObject(c)) {
            d = u;
            u = c;
            c = undefined;
        }
        e.call(this, t, u);
        if (!n.isInteger(s) || s < 0) throw TypeError("id must be a non-negative integer");
        if (!n.isString(a)) throw TypeError("type must be a string");
        if (l !== undefined && !o.test(l = l.toString().toLowerCase())) throw TypeError("rule must be a string rule");
        if (c !== undefined && !n.isString(c)) throw TypeError("extend must be a string");
        if (l === "proto3_optional") {
            l = "optional";
        }
        this.rule = l && l !== "optional" ? l : undefined;
        this.type = a;
        this.id = s;
        this.extend = c || undefined;
        this.repeated = l === "repeated";
        this.map = false;
        this.message = null;
        this.partOf = null;
        this.typeDefault = null;
        this.defaultValue = null;
        this.long = n.Long ? r.long[a] !== undefined : false;
        this.bytes = a === "bytes";
        this.resolvedType = null;
        this.extensionField = null;
        this.declaringField = null;
        this.comment = d;
    }
    Object.defineProperty(a.prototype, "required", {
        get: function() {
            return this._features.field_presence === "LEGACY_REQUIRED";
        }
    });
    Object.defineProperty(a.prototype, "optional", {
        get: function() {
            return !this.required;
        }
    });
    Object.defineProperty(a.prototype, "delimited", {
        get: function() {
            return this.resolvedType instanceof s && this._features.message_encoding === "DELIMITED";
        }
    });
    Object.defineProperty(a.prototype, "packed", {
        get: function() {
            return this._features.repeated_field_encoding === "PACKED";
        }
    });
    Object.defineProperty(a.prototype, "hasPresence", {
        get: function() {
            if (this.repeated || this.map) {
                return false;
            }
            return this.partOf || this.declaringField || this.extensionField || this._features.field_presence !== "IMPLICIT";
        }
    });
    a.prototype.setOption = function t(r, n, s) {
        return e.prototype.setOption.call(this, r, n, s);
    };
    a.prototype.toJSON = function e(t) {
        var r = t ? Boolean(t.keepComments) : false;
        return n.toObject([ "edition", this._editionToJSON(), "rule", this.rule !== "optional" && this.rule || undefined, "type", this.type, "id", this.id, "extend", this.extend, "options", this.options, "comment", r ? this.comment : undefined ]);
    };
    a.prototype.resolve = function o() {
        if (this.resolved) return this;
        if ((this.typeDefault = r.defaults[this.type]) === undefined) {
            this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
            if (this.resolvedType instanceof s) this.typeDefault = null; else this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]];
        } else if (this.options && this.options.proto3_optional) {
            this.typeDefault = null;
        }
        if (this.options && this.options["default"] != null) {
            this.typeDefault = this.options["default"];
            if (this.resolvedType instanceof t && typeof this.typeDefault === "string") this.typeDefault = this.resolvedType.values[this.typeDefault];
        }
        if (this.options) {
            if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof t)) delete this.options.packed;
            if (!Object.keys(this.options).length) this.options = undefined;
        }
        if (this.long) {
            this.typeDefault = n.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");
            if (Object.freeze) Object.freeze(this.typeDefault);
        } else if (this.bytes && typeof this.typeDefault === "string") {
            var a;
            if (n.base64.test(this.typeDefault)) n.base64.decode(this.typeDefault, a = n.newBuffer(n.base64.length(this.typeDefault)), 0); else n.utf8.write(this.typeDefault, a = n.newBuffer(n.utf8.length(this.typeDefault)), 0);
            this.typeDefault = a;
        }
        if (this.map) this.defaultValue = n.emptyObject; else if (this.repeated) this.defaultValue = n.emptyArray; else this.defaultValue = this.typeDefault;
        if (this.parent instanceof s) this.parent.ctor.prototype[this.name] = this.defaultValue;
        return e.prototype.resolve.call(this);
    };
    a.prototype._inferLegacyProtoFeatures = function e(t) {
        if (t !== "proto2" && t !== "proto3") {
            return {};
        }
        var n = {};
        if (this.rule === "required") {
            n.field_presence = "LEGACY_REQUIRED";
        }
        if (this.parent && r.defaults[this.type] === undefined) {
            var o = this.parent.get(this.type.split(".").pop());
            if (o && o instanceof s && o.group) {
                n.message_encoding = "DELIMITED";
            }
        }
        if (this.getOption("packed") === true) {
            n.repeated_field_encoding = "PACKED";
        } else if (this.getOption("packed") === false) {
            n.repeated_field_encoding = "EXPANDED";
        }
        return n;
    };
    a.prototype._resolveFeatures = function t(r) {
        return e.prototype._resolveFeatures.call(this, this._edition || r);
    };
    a.d = function e(t, r, s, o) {
        if (typeof r === "function") r = n.decorateType(r).name; else if (r && typeof r === "object") r = n.decorateEnum(r).name;
        return function e(l, c) {
            n.decorateType(l.constructor).add(new a(c, t, r, s, {
                default: o
            }));
        };
    };
    a._configure = function e(t) {
        s = t;
    };
    return field;
}

var oneof;

var hasRequiredOneof;

function requireOneof() {
    if (hasRequiredOneof) return oneof;
    hasRequiredOneof = 1;
    oneof = n;
    var e = requireObject();
    ((n.prototype = Object.create(e.prototype)).constructor = n).className = "OneOf";
    var t = requireField(), r = requireUtil$1();
    function n(t, r, n, s) {
        if (!Array.isArray(r)) {
            n = r;
            r = undefined;
        }
        e.call(this, t, n);
        if (!(r === undefined || Array.isArray(r))) throw TypeError("fieldNames must be an Array");
        this.oneof = r || [];
        this.fieldsArray = [];
        this.comment = s;
    }
    n.fromJSON = function e(t, r) {
        return new n(t, r.oneof, r.options, r.comment);
    };
    n.prototype.toJSON = function e(t) {
        var n = t ? Boolean(t.keepComments) : false;
        return r.toObject([ "options", this.options, "oneof", this.oneof, "comment", n ? this.comment : undefined ]);
    };
    function s(e) {
        if (e.parent) for (var t = 0; t < e.fieldsArray.length; ++t) if (!e.fieldsArray[t].parent) e.parent.add(e.fieldsArray[t]);
    }
    n.prototype.add = function e(r) {
        if (!(r instanceof t)) throw TypeError("field must be a Field");
        if (r.parent && r.parent !== this.parent) r.parent.remove(r);
        this.oneof.push(r.name);
        this.fieldsArray.push(r);
        r.partOf = this;
        s(this);
        return this;
    };
    n.prototype.remove = function e(r) {
        if (!(r instanceof t)) throw TypeError("field must be a Field");
        var n = this.fieldsArray.indexOf(r);
        if (n < 0) throw Error(r + " is not a member of " + this);
        this.fieldsArray.splice(n, 1);
        n = this.oneof.indexOf(r.name);
        if (n > -1) this.oneof.splice(n, 1);
        r.partOf = null;
        return this;
    };
    n.prototype.onAdd = function t(r) {
        e.prototype.onAdd.call(this, r);
        var n = this;
        for (var o = 0; o < this.oneof.length; ++o) {
            var a = r.get(this.oneof[o]);
            if (a && !a.partOf) {
                a.partOf = n;
                n.fieldsArray.push(a);
            }
        }
        s(this);
    };
    n.prototype.onRemove = function t(r) {
        for (var n = 0, s; n < this.fieldsArray.length; ++n) if ((s = this.fieldsArray[n]).parent) s.parent.remove(s);
        e.prototype.onRemove.call(this, r);
    };
    Object.defineProperty(n.prototype, "isProto3Optional", {
        get: function() {
            if (this.fieldsArray == null || this.fieldsArray.length !== 1) {
                return false;
            }
            var e = this.fieldsArray[0];
            return e.options != null && e.options["proto3_optional"] === true;
        }
    });
    n.d = function e() {
        var t = new Array(arguments.length), s = 0;
        while (s < arguments.length) t[s] = arguments[s++];
        return function e(s, o) {
            r.decorateType(s.constructor).add(new n(o, t));
            Object.defineProperty(s, o, {
                get: r.oneOfGetter(t),
                set: r.oneOfSetter(t)
            });
        };
    };
    return oneof;
}

var object;

var hasRequiredObject;

function requireObject() {
    if (hasRequiredObject) return object;
    hasRequiredObject = 1;
    object = a;
    a.className = "ReflectionObject";
    const e = requireOneof();
    var t = requireUtil$1();
    var r;
    var n = {
        enum_type: "OPEN",
        field_presence: "EXPLICIT",
        json_format: "ALLOW",
        message_encoding: "LENGTH_PREFIXED",
        repeated_field_encoding: "PACKED",
        utf8_validation: "VERIFY"
    };
    var s = {
        enum_type: "CLOSED",
        field_presence: "EXPLICIT",
        json_format: "LEGACY_BEST_EFFORT",
        message_encoding: "LENGTH_PREFIXED",
        repeated_field_encoding: "EXPANDED",
        utf8_validation: "NONE"
    };
    var o = {
        enum_type: "OPEN",
        field_presence: "IMPLICIT",
        json_format: "ALLOW",
        message_encoding: "LENGTH_PREFIXED",
        repeated_field_encoding: "PACKED",
        utf8_validation: "VERIFY"
    };
    function a(e, r) {
        if (!t.isString(e)) throw TypeError("name must be a string");
        if (r && !t.isObject(r)) throw TypeError("options must be an object");
        this.options = r;
        this.parsedOptions = null;
        this.name = e;
        this._edition = null;
        this._defaultEdition = "proto2";
        this._features = {};
        this._featuresResolved = false;
        this.parent = null;
        this.resolved = false;
        this.comment = null;
        this.filename = null;
    }
    Object.defineProperties(a.prototype, {
        root: {
            get: function() {
                var e = this;
                while (e.parent !== null) e = e.parent;
                return e;
            }
        },
        fullName: {
            get: function() {
                var e = [ this.name ], t = this.parent;
                while (t) {
                    e.unshift(t.name);
                    t = t.parent;
                }
                return e.join(".");
            }
        }
    });
    a.prototype.toJSON = function e() {
        throw Error();
    };
    a.prototype.onAdd = function e(t) {
        if (this.parent && this.parent !== t) this.parent.remove(this);
        this.parent = t;
        this.resolved = false;
        var n = t.root;
        if (n instanceof r) n._handleAdd(this);
    };
    a.prototype.onRemove = function e(t) {
        var n = t.root;
        if (n instanceof r) n._handleRemove(this);
        this.parent = null;
        this.resolved = false;
    };
    a.prototype.resolve = function e() {
        if (this.resolved) return this;
        if (this.root instanceof r) this.resolved = true;
        return this;
    };
    a.prototype._resolveFeaturesRecursive = function e(t) {
        return this._resolveFeatures(this._edition || t);
    };
    a.prototype._resolveFeatures = function t(r) {
        if (this._featuresResolved) {
            return;
        }
        var a = {};
        if (!r) {
            throw new Error("Unknown edition for " + this.fullName);
        }
        var l = Object.assign(this.options ? Object.assign({}, this.options.features) : {}, this._inferLegacyProtoFeatures(r));
        if (this._edition) {
            if (r === "proto2") {
                a = Object.assign({}, s);
            } else if (r === "proto3") {
                a = Object.assign({}, o);
            } else if (r === "2023") {
                a = Object.assign({}, n);
            } else {
                throw new Error("Unknown edition: " + r);
            }
            this._features = Object.assign(a, l || {});
            this._featuresResolved = true;
            return;
        }
        if (this.partOf instanceof e) {
            var c = Object.assign({}, this.partOf._features);
            this._features = Object.assign(c, l || {});
        } else if (this.declaringField) ; else if (this.parent) {
            var u = Object.assign({}, this.parent._features);
            this._features = Object.assign(u, l || {});
        } else {
            throw new Error("Unable to find a parent for " + this.fullName);
        }
        if (this.extensionField) {
            this.extensionField._features = this._features;
        }
        this._featuresResolved = true;
    };
    a.prototype._inferLegacyProtoFeatures = function e() {
        return {};
    };
    a.prototype.getOption = function e(t) {
        if (this.options) return this.options[t];
        return undefined;
    };
    a.prototype.setOption = function e(r, n, s) {
        if (!this.options) this.options = {};
        if (/^features\./.test(r)) {
            t.setProperty(this.options, r, n, s);
        } else if (!s || this.options[r] === undefined) {
            if (this.getOption(r) !== n) this.resolved = false;
            this.options[r] = n;
        }
        return this;
    };
    a.prototype.setParsedOption = function e(r, n, s) {
        if (!this.parsedOptions) {
            this.parsedOptions = [];
        }
        var o = this.parsedOptions;
        if (s) {
            var a = o.find(function(e) {
                return Object.prototype.hasOwnProperty.call(e, r);
            });
            if (a) {
                var l = a[r];
                t.setProperty(l, s, n);
            } else {
                a = {};
                a[r] = t.setProperty({}, s, n);
                o.push(a);
            }
        } else {
            var c = {};
            c[r] = n;
            o.push(c);
        }
        return this;
    };
    a.prototype.setOptions = function e(t, r) {
        if (t) for (var n = Object.keys(t), s = 0; s < n.length; ++s) this.setOption(n[s], t[n[s]], r);
        return this;
    };
    a.prototype.toString = function e() {
        var t = this.constructor.className, r = this.fullName;
        if (r.length) return t + " " + r;
        return t;
    };
    a.prototype._editionToJSON = function e() {
        if (!this._edition || this._edition === "proto3") {
            return undefined;
        }
        return this._edition;
    };
    a._configure = function(e) {
        r = e;
    };
    return object;
}

var _enum;

var hasRequired_enum;

function require_enum() {
    if (hasRequired_enum) return _enum;
    hasRequired_enum = 1;
    _enum = n;
    var e = requireObject();
    ((n.prototype = Object.create(e.prototype)).constructor = n).className = "Enum";
    var t = requireNamespace(), r = requireUtil$1();
    function n(t, r, n, s, o, a) {
        e.call(this, t, n);
        if (r && typeof r !== "object") throw TypeError("values must be an object");
        this.valuesById = {};
        this.values = Object.create(this.valuesById);
        this.comment = s;
        this.comments = o || {};
        this.valuesOptions = a;
        this._valuesFeatures = {};
        this.reserved = undefined;
        if (r) for (var l = Object.keys(r), c = 0; c < l.length; ++c) if (typeof r[l[c]] === "number") this.valuesById[this.values[l[c]] = r[l[c]]] = l[c];
    }
    n.prototype._resolveFeatures = function t(r) {
        r = this._edition || r;
        e.prototype._resolveFeatures.call(this, r);
        Object.keys(this.values).forEach(e => {
            var t = Object.assign({}, this._features);
            this._valuesFeatures[e] = Object.assign(t, this.valuesOptions && this.valuesOptions[e] && this.valuesOptions[e].features);
        });
        return this;
    };
    n.fromJSON = function e(t, r) {
        var s = new n(t, r.values, r.options, r.comment, r.comments);
        s.reserved = r.reserved;
        if (r.edition) s._edition = r.edition;
        s._defaultEdition = "proto3";
        return s;
    };
    n.prototype.toJSON = function e(t) {
        var n = t ? Boolean(t.keepComments) : false;
        return r.toObject([ "edition", this._editionToJSON(), "options", this.options, "valuesOptions", this.valuesOptions, "values", this.values, "reserved", this.reserved && this.reserved.length ? this.reserved : undefined, "comment", n ? this.comment : undefined, "comments", n ? this.comments : undefined ]);
    };
    n.prototype.add = function e(t, n, s, o) {
        if (!r.isString(t)) throw TypeError("name must be a string");
        if (!r.isInteger(n)) throw TypeError("id must be an integer");
        if (this.values[t] !== undefined) throw Error("duplicate name '" + t + "' in " + this);
        if (this.isReservedId(n)) throw Error("id " + n + " is reserved in " + this);
        if (this.isReservedName(t)) throw Error("name '" + t + "' is reserved in " + this);
        if (this.valuesById[n] !== undefined) {
            if (!(this.options && this.options.allow_alias)) throw Error("duplicate id " + n + " in " + this);
            this.values[t] = n;
        } else this.valuesById[this.values[t] = n] = t;
        if (o) {
            if (this.valuesOptions === undefined) this.valuesOptions = {};
            this.valuesOptions[t] = o || null;
        }
        this.comments[t] = s || null;
        return this;
    };
    n.prototype.remove = function e(t) {
        if (!r.isString(t)) throw TypeError("name must be a string");
        var n = this.values[t];
        if (n == null) throw Error("name '" + t + "' does not exist in " + this);
        delete this.valuesById[n];
        delete this.values[t];
        delete this.comments[t];
        if (this.valuesOptions) delete this.valuesOptions[t];
        return this;
    };
    n.prototype.isReservedId = function e(r) {
        return t.isReservedId(this.reserved, r);
    };
    n.prototype.isReservedName = function e(r) {
        return t.isReservedName(this.reserved, r);
    };
    return _enum;
}

var encoder_1;

var hasRequiredEncoder;

function requireEncoder() {
    if (hasRequiredEncoder) return encoder_1;
    hasRequiredEncoder = 1;
    encoder_1 = s;
    var e = require_enum(), t = types$1, r = requireUtil$1();
    function n(e, t, r, n) {
        return t.delimited ? e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", r, n, (t.id << 3 | 3) >>> 0, (t.id << 3 | 4) >>> 0) : e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", r, n, (t.id << 3 | 2) >>> 0);
    }
    function s(s) {
        var o = r.codegen([ "m", "w" ], s.name + "$encode")("if(!w)")("w=Writer.create()");
        var a, l;
        var c = s.fieldsArray.slice().sort(r.compareFieldsById);
        for (var a = 0; a < c.length; ++a) {
            var u = c[a].resolve(), d = s._fieldsArray.indexOf(u), h = u.resolvedType instanceof e ? "int32" : u.type, p = t.basic[h];
            l = "m" + r.safeProp(u.name);
            if (u.map) {
                o("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", l, u.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", l)("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (u.id << 3 | 2) >>> 0, 8 | t.mapKey[u.keyType], u.keyType);
                if (p === undefined) o("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", d, l); else o(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | p, h, l);
                o("}")("}");
            } else if (u.repeated) {
                o("if(%s!=null&&%s.length){", l, l);
                if (u.packed && t.packed[h] !== undefined) {
                    o("w.uint32(%i).fork()", (u.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", l)("w.%s(%s[i])", h, l)("w.ldelim()");
                } else {
                    o("for(var i=0;i<%s.length;++i)", l);
                    if (p === undefined) n(o, u, d, l + "[i]"); else o("w.uint32(%i).%s(%s[i])", (u.id << 3 | p) >>> 0, h, l);
                }
                o("}");
            } else {
                if (u.optional) o("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", l, u.name);
                if (p === undefined) n(o, u, d, l); else o("w.uint32(%i).%s(%s)", (u.id << 3 | p) >>> 0, h, l);
            }
        }
        return o("return w");
    }
    return encoder_1;
}

indexLight.exports;

var protobuf$1 = indexLight.exports = indexMinimal;

protobuf$1.build = "light";

function load(e, t, r) {
    if (typeof t === "function") {
        r = t;
        t = new protobuf$1.Root;
    } else if (!t) t = new protobuf$1.Root;
    return t.load(e, r);
}

protobuf$1.load = load;

function loadSync(e, t) {
    if (!t) t = new protobuf$1.Root;
    return t.loadSync(e);
}

protobuf$1.loadSync = loadSync;

protobuf$1.encoder = requireEncoder();

protobuf$1.decoder = requireDecoder();

protobuf$1.verifier = requireVerifier();

protobuf$1.converter = requireConverter();

protobuf$1.ReflectionObject = requireObject();

protobuf$1.Namespace = requireNamespace();

protobuf$1.Root = requireRoot();

protobuf$1.Enum = require_enum();

protobuf$1.Type = requireType();

protobuf$1.Field = requireField();

protobuf$1.OneOf = requireOneof();

protobuf$1.MapField = requireMapfield();

protobuf$1.Service = requireService();

protobuf$1.Method = requireMethod();

protobuf$1.Message = message;

protobuf$1.wrappers = wrappers;

protobuf$1.types = types$1;

protobuf$1.util = requireUtil$1();

protobuf$1.ReflectionObject._configure(protobuf$1.Root);

protobuf$1.Namespace._configure(protobuf$1.Type, protobuf$1.Service, protobuf$1.Enum);

protobuf$1.Root._configure(protobuf$1.Type);

protobuf$1.Field._configure(protobuf$1.Type);

var indexLightExports = indexLight.exports;

var tokenize_1 = tokenize$1;

var delimRe = /[\s{}=;:[\],'"()<>]/g, stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;

var setCommentRe = /^ *[*/]+ */, setCommentAltRe = /^\s*\*?\/*/, setCommentSplitRe = /\n/g, whitespaceRe = /\s/, unescapeRe = /\\(.?)/g;

var unescapeMap = {
    0: "\0",
    r: "\r",
    n: "\n",
    t: "\t"
};

function unescape$1(e) {
    return e.replace(unescapeRe, function(e, t) {
        switch (t) {
          case "\\":
          case "":
            return t;

          default:
            return unescapeMap[t] || "";
        }
    });
}

tokenize$1.unescape = unescape$1;

function tokenize$1(e, t) {
    e = e.toString();
    var r = 0, n = e.length, s = 1, o = 0, a = {};
    var l = [];
    var c = null;
    function u(e) {
        return Error("illegal " + e + " (line " + s + ")");
    }
    function d() {
        var t = c === "'" ? stringSingleRe : stringDoubleRe;
        t.lastIndex = r - 1;
        var n = t.exec(e);
        if (!n) throw u("string");
        r = t.lastIndex;
        E(c);
        c = null;
        return unescape$1(n[1]);
    }
    function h(t) {
        return e.charAt(t);
    }
    function p(r, n, l) {
        var c = {
            type: e.charAt(r++),
            lineEmpty: false,
            leading: l
        };
        var u;
        if (t) {
            u = 2;
        } else {
            u = 3;
        }
        var d = r - u, h;
        do {
            if (--d < 0 || (h = e.charAt(d)) === "\n") {
                c.lineEmpty = true;
                break;
            }
        } while (h === " " || h === "\t");
        var p = e.substring(r, n).split(setCommentSplitRe);
        for (var g = 0; g < p.length; ++g) p[g] = p[g].replace(t ? setCommentAltRe : setCommentRe, "").trim();
        c.text = p.join("\n").trim();
        a[s] = c;
        o = s;
    }
    function g(t) {
        var r = m(t);
        var n = e.substring(t, r);
        var s = /^\s*\/\//.test(n);
        return s;
    }
    function m(e) {
        var t = e;
        while (t < n && h(t) !== "\n") {
            t++;
        }
        return t;
    }
    function _() {
        if (l.length > 0) return l.shift();
        if (c) return d();
        var o, a, _, E, v, y = r === 0;
        do {
            if (r === n) return null;
            o = false;
            while (whitespaceRe.test(_ = h(r))) {
                if (_ === "\n") {
                    y = true;
                    ++s;
                }
                if (++r === n) return null;
            }
            if (h(r) === "/") {
                if (++r === n) {
                    throw u("comment");
                }
                if (h(r) === "/") {
                    if (!t) {
                        v = h(E = r + 1) === "/";
                        while (h(++r) !== "\n") {
                            if (r === n) {
                                return null;
                            }
                        }
                        ++r;
                        if (v) {
                            p(E, r - 1, y);
                            y = true;
                        }
                        ++s;
                        o = true;
                    } else {
                        E = r;
                        v = false;
                        if (g(r - 1)) {
                            v = true;
                            do {
                                r = m(r);
                                if (r === n) {
                                    break;
                                }
                                r++;
                                if (!y) {
                                    break;
                                }
                            } while (g(r));
                        } else {
                            r = Math.min(n, m(r) + 1);
                        }
                        if (v) {
                            p(E, r, y);
                            y = true;
                        }
                        s++;
                        o = true;
                    }
                } else if ((_ = h(r)) === "*") {
                    E = r + 1;
                    v = t || h(E) === "*";
                    do {
                        if (_ === "\n") {
                            ++s;
                        }
                        if (++r === n) {
                            throw u("comment");
                        }
                        a = _;
                        _ = h(r);
                    } while (a !== "*" || _ !== "/");
                    ++r;
                    if (v) {
                        p(E, r - 2, y);
                        y = true;
                    }
                    o = true;
                } else {
                    return "/";
                }
            }
        } while (o);
        var S = r;
        delimRe.lastIndex = 0;
        var A = delimRe.test(h(S++));
        if (!A) while (S < n && !delimRe.test(h(S))) ++S;
        var b = e.substring(r, r = S);
        if (b === '"' || b === "'") c = b;
        return b;
    }
    function E(e) {
        l.push(e);
    }
    function v() {
        if (!l.length) {
            var e = _();
            if (e === null) return null;
            E(e);
        }
        return l[0];
    }
    function y(e, t) {
        var r = v(), n = r === e;
        if (n) {
            _();
            return true;
        }
        if (!t) throw u("token '" + r + "', '" + e + "' expected");
        return false;
    }
    function S(e) {
        var r = null;
        var n;
        if (e === undefined) {
            n = a[s - 1];
            delete a[s - 1];
            if (n && (t || n.type === "*" || n.lineEmpty)) {
                r = n.leading ? n.text : null;
            }
        } else {
            if (o < e) {
                v();
            }
            n = a[e];
            delete a[e];
            if (n && !n.lineEmpty && (t || n.type === "/")) {
                r = n.leading ? null : n.text;
            }
        }
        return r;
    }
    return Object.defineProperty({
        next: _,
        peek: v,
        push: E,
        skip: y,
        cmnt: S
    }, "line", {
        get: function() {
            return s;
        }
    });
}

var parse_1 = parse$1;

parse$1.filename = null;

parse$1.defaults = {
    keepCase: false
};

var tokenize = tokenize_1, Root = requireRoot(), Type = requireType(), Field = requireField(), MapField = requireMapfield(), OneOf = requireOneof(), Enum = require_enum(), Service$1 = requireService(), Method = requireMethod(), ReflectionObject = requireObject(), types = types$1, util$4 = requireUtil$1();

var base10Re = /^[1-9][0-9]*$/, base10NegRe = /^-?[1-9][0-9]*$/, base16Re = /^0[x][0-9a-fA-F]+$/, base16NegRe = /^-?0[x][0-9a-fA-F]+$/, base8Re = /^0[0-7]+$/, base8NegRe = /^-?0[0-7]+$/, numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/;

function parse$1(e, t, r) {
    if (!(t instanceof Root)) {
        r = t;
        t = new Root;
    }
    if (!r) r = parse$1.defaults;
    var n = r.preferTrailingComment || false;
    var s = tokenize(e, r.alternateCommentMode || false), o = s.next, a = s.push, l = s.peek, c = s.skip, u = s.cmnt;
    var d = true, h, p, g, m = "proto2";
    var _ = t;
    var E = [];
    var v = {};
    var y = r.keepCase ? function(e) {
        return e;
    } : util$4.camelCase;
    function S() {
        E.forEach(e => {
            e._edition = m;
            Object.keys(v).forEach(t => {
                if (e.getOption(t) !== undefined) return;
                e.setOption(t, v[t], true);
            });
        });
    }
    function A(e, t, r) {
        var n = parse$1.filename;
        if (!r) parse$1.filename = null;
        return Error("illegal " + (t || "token") + " '" + e + "' (" + (n ? n + ", " : "") + "line " + s.line + ")");
    }
    function b() {
        var e = [], t;
        do {
            if ((t = o()) !== '"' && t !== "'") throw A(t);
            e.push(o());
            c(t);
            t = l();
        } while (t === '"' || t === "'");
        return e.join("");
    }
    function C(e) {
        var t = o();
        switch (t) {
          case "'":
          case '"':
            a(t);
            return b();

          case "true":
          case "TRUE":
            return true;

          case "false":
          case "FALSE":
            return false;
        }
        try {
            return I(t, true);
        } catch (e) {
            if (typeRefRe.test(t)) return t;
            throw A(t, "value");
        }
    }
    function w(e, t) {
        var r, n;
        do {
            if (t && ((r = l()) === '"' || r === "'")) {
                var s = b();
                e.push(s);
                if (m >= 2023) {
                    throw A(s, "id");
                }
            } else {
                try {
                    e.push([ n = T(o()), c("to", true) ? T(o()) : n ]);
                } catch (n) {
                    if (t && typeRefRe.test(r) && m >= 2023) {
                        e.push(r);
                    } else {
                        throw n;
                    }
                }
            }
        } while (c(",", true));
        var a = {
            options: undefined
        };
        a.setOption = function(e, t) {
            if (this.options === undefined) this.options = {};
            this.options[e] = t;
        };
        B(a, function e(t) {
            if (t === "option") {
                H(a, t);
                c(";");
            } else throw A(t);
        }, function e() {
            G(a);
        });
    }
    function I(e, t) {
        var r = 1;
        if (e.charAt(0) === "-") {
            r = -1;
            e = e.substring(1);
        }
        switch (e) {
          case "inf":
          case "INF":
          case "Inf":
            return r * Infinity;

          case "nan":
          case "NAN":
          case "Nan":
          case "NaN":
            return NaN;

          case "0":
            return 0;
        }
        if (base10Re.test(e)) return r * parseInt(e, 10);
        if (base16Re.test(e)) return r * parseInt(e, 16);
        if (base8Re.test(e)) return r * parseInt(e, 8);
        if (numberRe.test(e)) return r * parseFloat(e);
        throw A(e, "number", t);
    }
    function T(e, t) {
        switch (e) {
          case "max":
          case "MAX":
          case "Max":
            return 536870911;

          case "0":
            return 0;
        }
        if (!t && e.charAt(0) === "-") throw A(e, "id");
        if (base10NegRe.test(e)) return parseInt(e, 10);
        if (base16NegRe.test(e)) return parseInt(e, 16);
        if (base8NegRe.test(e)) return parseInt(e, 8);
        throw A(e, "id");
    }
    function R() {
        if (h !== undefined) throw A("package");
        h = o();
        if (!typeRefRe.test(h)) throw A(h, "name");
        _ = _.define(h);
        c(";");
    }
    function k() {
        var e = l();
        var t;
        switch (e) {
          case "weak":
            t = g || (g = []);
            o();
            break;

          case "public":
            o();

          default:
            t = p || (p = []);
            break;
        }
        e = b();
        c(";");
        t.push(e);
    }
    function P() {
        c("=");
        m = b();
        if (m < 2023) throw A(m, "syntax");
        c(";");
    }
    function $() {
        c("=");
        m = b();
        const e = [ "2023" ];
        if (!e.includes(m)) throw A(m, "edition");
        c(";");
    }
    function O(e, t) {
        switch (t) {
          case "option":
            H(e, t);
            c(";");
            return true;

          case "message":
            N(e, t);
            return true;

          case "enum":
            x(e, t);
            return true;

          case "service":
            K(e, t);
            return true;

          case "extend":
            Y(e, t);
            return true;
        }
        return false;
    }
    function B(e, t, r) {
        var a = s.line;
        if (e) {
            if (typeof e.comment !== "string") {
                e.comment = u();
            }
            e.filename = parse$1.filename;
        }
        if (c("{", true)) {
            var l;
            while ((l = o()) !== "}") t(l);
            c(";", true);
        } else {
            if (r) r();
            c(";");
            if (e && (typeof e.comment !== "string" || n)) e.comment = u(a) || e.comment;
        }
    }
    function N(e, t) {
        if (!nameRe.test(t = o())) throw A(t, "type name");
        var r = new Type(t);
        B(r, function e(t) {
            if (O(r, t)) return;
            switch (t) {
              case "map":
                U(r);
                break;

              case "required":
                if (m !== "proto2") throw A(t);

              case "repeated":
                D(r, t);
                break;

              case "optional":
                if (m === "proto3") {
                    D(r, "proto3_optional");
                } else if (m !== "proto2") {
                    throw A(t);
                } else {
                    D(r, "optional");
                }
                break;

              case "oneof":
                M(r, t);
                break;

              case "extensions":
                w(r.extensions || (r.extensions = []));
                break;

              case "reserved":
                w(r.reserved || (r.reserved = []), true);
                break;

              default:
                if (m === "proto2" || !typeRefRe.test(t)) {
                    throw A(t);
                }
                a(t);
                D(r, "optional");
                break;
            }
        });
        e.add(r);
        if (e === _) {
            E.push(r);
        }
    }
    function D(e, t, r) {
        var n = o();
        if (n === "group") {
            L(e, t);
            return;
        }
        while (n.endsWith(".") || l().startsWith(".")) {
            n += o();
        }
        if (!typeRefRe.test(n)) throw A(n, "type");
        var s = o();
        if (!nameRe.test(s)) throw A(s, "name");
        s = y(s);
        c("=");
        var a = new Field(s, T(o()), n, t, r);
        B(a, function e(t) {
            if (t === "option") {
                H(a, t);
                c(";");
            } else throw A(t);
        }, function e() {
            G(a);
        });
        if (t === "proto3_optional") {
            var u = new OneOf("_" + s);
            a.setOption("proto3_optional", true);
            u.add(a);
            e.add(u);
        } else {
            e.add(a);
        }
        if (e === _) {
            E.push(a);
        }
    }
    function L(e, t) {
        if (m >= 2023) {
            throw A("group");
        }
        var r = o();
        if (!nameRe.test(r)) throw A(r, "name");
        var n = util$4.lcFirst(r);
        if (r === n) r = util$4.ucFirst(r);
        c("=");
        var s = T(o());
        var a = new Type(r);
        a.group = true;
        var l = new Field(n, s, r, t);
        l.filename = parse$1.filename;
        B(a, function e(t) {
            switch (t) {
              case "option":
                H(a, t);
                c(";");
                break;

              case "required":
              case "repeated":
                D(a, t);
                break;

              case "optional":
                if (m === "proto3") {
                    D(a, "proto3_optional");
                } else {
                    D(a, "optional");
                }
                break;

              case "message":
                N(a, t);
                break;

              case "enum":
                x(a, t);
                break;

              case "reserved":
                w(a.reserved || (a.reserved = []), true);
                break;

              default:
                throw A(t);
            }
        });
        e.add(a).add(l);
    }
    function U(e) {
        c("<");
        var t = o();
        if (types.mapKey[t] === undefined) throw A(t, "type");
        c(",");
        var r = o();
        if (!typeRefRe.test(r)) throw A(r, "type");
        c(">");
        var n = o();
        if (!nameRe.test(n)) throw A(n, "name");
        c("=");
        var s = new MapField(y(n), T(o()), t, r);
        B(s, function e(t) {
            if (t === "option") {
                H(s, t);
                c(";");
            } else throw A(t);
        }, function e() {
            G(s);
        });
        e.add(s);
    }
    function M(e, t) {
        if (!nameRe.test(t = o())) throw A(t, "name");
        var r = new OneOf(y(t));
        B(r, function e(t) {
            if (t === "option") {
                H(r, t);
                c(";");
            } else {
                a(t);
                D(r, "optional");
            }
        });
        e.add(r);
    }
    function x(e, t) {
        if (!nameRe.test(t = o())) throw A(t, "name");
        var r = new Enum(t);
        B(r, function e(t) {
            switch (t) {
              case "option":
                H(r, t);
                c(";");
                break;

              case "reserved":
                w(r.reserved || (r.reserved = []), true);
                if (r.reserved === undefined) r.reserved = [];
                break;

              default:
                q(r, t);
            }
        });
        e.add(r);
        if (e === _) {
            E.push(r);
        }
    }
    function q(e, t) {
        if (!nameRe.test(t)) throw A(t, "name");
        c("=");
        var r = T(o(), true), n = {
            options: undefined
        };
        n.getOption = function(e) {
            return this.options[e];
        };
        n.setOption = function(e, t) {
            ReflectionObject.prototype.setOption.call(n, e, t);
        };
        n.setParsedOption = function() {
            return undefined;
        };
        B(n, function e(t) {
            if (t === "option") {
                H(n, t);
                c(";");
            } else throw A(t);
        }, function e() {
            G(n);
        });
        e.add(t, r, n.comment, n.parsedOptions || n.options);
    }
    function H(e, t) {
        var r;
        var n;
        var s = true;
        if (t === "option") {
            t = o();
        }
        while (t !== "=") {
            if (t === "(") {
                var a = o();
                c(")");
                t = "(" + a + ")";
            }
            if (s) {
                s = false;
                if (t.includes(".") && !t.includes("(")) {
                    var l = t.split(".");
                    r = l[0] + ".";
                    t = l[1];
                    continue;
                }
                r = t;
            } else {
                n = n ? n += t : t;
            }
            t = o();
        }
        var u = n ? r.concat(n) : r;
        var d = W(e, u);
        n = n && n[0] === "." ? n.slice(1) : n;
        r = r && r[r.length - 1] === "." ? r.slice(0, -1) : r;
        Q(e, r, d, n);
    }
    function W(e, t) {
        if (c("{", true)) {
            var r = {};
            while (!c("}", true)) {
                if (!nameRe.test(V = o())) {
                    throw A(V, "name");
                }
                if (V === null) {
                    throw A(V, "end of input");
                }
                var n;
                var s = V;
                c(":", true);
                if (l() === "{") {
                    n = W(e, t + "." + V);
                } else if (l() === "[") {
                    n = [];
                    var a;
                    if (c("[", true)) {
                        do {
                            a = C();
                            n.push(a);
                        } while (c(",", true));
                        c("]");
                        if (typeof a !== "undefined") {
                            j(e, t + "." + V, a);
                        }
                    }
                } else {
                    n = C();
                    j(e, t + "." + V, n);
                }
                var u = r[s];
                if (u) n = [].concat(u).concat(n);
                r[s] = n;
                c(",", true);
                c(";", true);
            }
            return r;
        }
        var d = C();
        j(e, t, d);
        return d;
    }
    function j(e, t, r) {
        if (_ === e && /^features\./.test(t)) {
            v[t] = r;
            return;
        }
        if (e.setOption) e.setOption(t, r);
    }
    function Q(e, t, r, n) {
        if (e.setParsedOption) e.setParsedOption(t, r, n);
    }
    function G(e) {
        if (c("[", true)) {
            do {
                H(e, "option");
            } while (c(",", true));
            c("]");
        }
        return e;
    }
    function K(e, t) {
        if (!nameRe.test(t = o())) throw A(t, "service name");
        var r = new Service$1(t);
        B(r, function e(t) {
            if (O(r, t)) {
                return;
            }
            if (t === "rpc") z(r, t); else throw A(t);
        });
        e.add(r);
        if (e === _) {
            E.push(r);
        }
    }
    function z(e, t) {
        var r = u();
        var n = t;
        if (!nameRe.test(t = o())) throw A(t, "name");
        var s = t, a, l, d, h;
        c("(");
        if (c("stream", true)) l = true;
        if (!typeRefRe.test(t = o())) throw A(t);
        a = t;
        c(")");
        c("returns");
        c("(");
        if (c("stream", true)) h = true;
        if (!typeRefRe.test(t = o())) throw A(t);
        d = t;
        c(")");
        var p = new Method(s, n, a, d, l, h);
        p.comment = r;
        B(p, function e(t) {
            if (t === "option") {
                H(p, t);
                c(";");
            } else throw A(t);
        });
        e.add(p);
    }
    function Y(e, t) {
        if (!typeRefRe.test(t = o())) throw A(t, "reference");
        var r = t;
        B(null, function t(n) {
            switch (n) {
              case "required":
              case "repeated":
                D(e, n, r);
                break;

              case "optional":
                if (m === "proto3") {
                    D(e, "proto3_optional", r);
                } else {
                    D(e, "optional", r);
                }
                break;

              default:
                if (m === "proto2" || !typeRefRe.test(n)) throw A(n);
                a(n);
                D(e, "optional", r);
                break;
            }
        });
    }
    var V;
    while ((V = o()) !== null) {
        switch (V) {
          case "package":
            if (!d) throw A(V);
            R();
            break;

          case "import":
            if (!d) throw A(V);
            k();
            break;

          case "syntax":
            if (!d) throw A(V);
            P();
            break;

          case "edition":
            if (!d) throw A(V);
            $();
            break;

          case "option":
            H(_, V);
            c(";", true);
            break;

          default:
            if (O(_, V)) {
                d = false;
                continue;
            }
            throw A(V);
        }
    }
    S();
    parse$1.filename = null;
    return {
        package: h,
        imports: p,
        weakImports: g,
        root: t
    };
}

var common_1 = common;

var commonRe = /\/|\./;

function common(e, t) {
    if (!commonRe.test(e)) {
        e = "google/protobuf/" + e + ".proto";
        t = {
            nested: {
                google: {
                    nested: {
                        protobuf: {
                            nested: t
                        }
                    }
                }
            }
        };
    }
    common[e] = t;
}

common("any", {
    Any: {
        fields: {
            type_url: {
                type: "string",
                id: 1
            },
            value: {
                type: "bytes",
                id: 2
            }
        }
    }
});

var timeType;

common("duration", {
    Duration: timeType = {
        fields: {
            seconds: {
                type: "int64",
                id: 1
            },
            nanos: {
                type: "int32",
                id: 2
            }
        }
    }
});

common("timestamp", {
    Timestamp: timeType
});

common("empty", {
    Empty: {
        fields: {}
    }
});

common("struct", {
    Struct: {
        fields: {
            fields: {
                keyType: "string",
                type: "Value",
                id: 1
            }
        }
    },
    Value: {
        oneofs: {
            kind: {
                oneof: [ "nullValue", "numberValue", "stringValue", "boolValue", "structValue", "listValue" ]
            }
        },
        fields: {
            nullValue: {
                type: "NullValue",
                id: 1
            },
            numberValue: {
                type: "double",
                id: 2
            },
            stringValue: {
                type: "string",
                id: 3
            },
            boolValue: {
                type: "bool",
                id: 4
            },
            structValue: {
                type: "Struct",
                id: 5
            },
            listValue: {
                type: "ListValue",
                id: 6
            }
        }
    },
    NullValue: {
        values: {
            NULL_VALUE: 0
        }
    },
    ListValue: {
        fields: {
            values: {
                rule: "repeated",
                type: "Value",
                id: 1
            }
        }
    }
});

common("wrappers", {
    DoubleValue: {
        fields: {
            value: {
                type: "double",
                id: 1
            }
        }
    },
    FloatValue: {
        fields: {
            value: {
                type: "float",
                id: 1
            }
        }
    },
    Int64Value: {
        fields: {
            value: {
                type: "int64",
                id: 1
            }
        }
    },
    UInt64Value: {
        fields: {
            value: {
                type: "uint64",
                id: 1
            }
        }
    },
    Int32Value: {
        fields: {
            value: {
                type: "int32",
                id: 1
            }
        }
    },
    UInt32Value: {
        fields: {
            value: {
                type: "uint32",
                id: 1
            }
        }
    },
    BoolValue: {
        fields: {
            value: {
                type: "bool",
                id: 1
            }
        }
    },
    StringValue: {
        fields: {
            value: {
                type: "string",
                id: 1
            }
        }
    },
    BytesValue: {
        fields: {
            value: {
                type: "bytes",
                id: 1
            }
        }
    }
});

common("field_mask", {
    FieldMask: {
        fields: {
            paths: {
                rule: "repeated",
                type: "string",
                id: 1
            }
        }
    }
});

common.get = function e(t) {
    return common[t] || null;
};

src$1.exports;

var protobuf = src$1.exports = indexLightExports;

protobuf.build = "full";

protobuf.tokenize = tokenize_1;

protobuf.parse = parse_1;

protobuf.common = common_1;

protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);

var srcExports = src$1.exports;

var protobufjs = srcExports;

var descriptor = {
    exports: {}
};

var nested$3 = {
    google: {
        nested: {
            protobuf: {
                options: {
                    go_package: "google.golang.org/protobuf/types/descriptorpb",
                    java_package: "com.google.protobuf",
                    java_outer_classname: "DescriptorProtos",
                    csharp_namespace: "Google.Protobuf.Reflection",
                    objc_class_prefix: "GPB",
                    cc_enable_arenas: true,
                    optimize_for: "SPEED"
                },
                nested: {
                    FileDescriptorSet: {
                        edition: "proto2",
                        fields: {
                            file: {
                                rule: "repeated",
                                type: "FileDescriptorProto",
                                id: 1
                            }
                        },
                        extensions: [ [ 536e6, 536e6 ] ]
                    },
                    Edition: {
                        edition: "proto2",
                        values: {
                            EDITION_UNKNOWN: 0,
                            EDITION_LEGACY: 900,
                            EDITION_PROTO2: 998,
                            EDITION_PROTO3: 999,
                            EDITION_2023: 1e3,
                            EDITION_2024: 1001,
                            EDITION_1_TEST_ONLY: 1,
                            EDITION_2_TEST_ONLY: 2,
                            EDITION_99997_TEST_ONLY: 99997,
                            EDITION_99998_TEST_ONLY: 99998,
                            EDITION_99999_TEST_ONLY: 99999,
                            EDITION_MAX: 2147483647
                        }
                    },
                    FileDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            package: {
                                type: "string",
                                id: 2
                            },
                            dependency: {
                                rule: "repeated",
                                type: "string",
                                id: 3
                            },
                            publicDependency: {
                                rule: "repeated",
                                type: "int32",
                                id: 10
                            },
                            weakDependency: {
                                rule: "repeated",
                                type: "int32",
                                id: 11
                            },
                            optionDependency: {
                                rule: "repeated",
                                type: "string",
                                id: 15
                            },
                            messageType: {
                                rule: "repeated",
                                type: "DescriptorProto",
                                id: 4
                            },
                            enumType: {
                                rule: "repeated",
                                type: "EnumDescriptorProto",
                                id: 5
                            },
                            service: {
                                rule: "repeated",
                                type: "ServiceDescriptorProto",
                                id: 6
                            },
                            extension: {
                                rule: "repeated",
                                type: "FieldDescriptorProto",
                                id: 7
                            },
                            options: {
                                type: "FileOptions",
                                id: 8
                            },
                            sourceCodeInfo: {
                                type: "SourceCodeInfo",
                                id: 9
                            },
                            syntax: {
                                type: "string",
                                id: 12
                            },
                            edition: {
                                type: "Edition",
                                id: 14
                            }
                        }
                    },
                    DescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            field: {
                                rule: "repeated",
                                type: "FieldDescriptorProto",
                                id: 2
                            },
                            extension: {
                                rule: "repeated",
                                type: "FieldDescriptorProto",
                                id: 6
                            },
                            nestedType: {
                                rule: "repeated",
                                type: "DescriptorProto",
                                id: 3
                            },
                            enumType: {
                                rule: "repeated",
                                type: "EnumDescriptorProto",
                                id: 4
                            },
                            extensionRange: {
                                rule: "repeated",
                                type: "ExtensionRange",
                                id: 5
                            },
                            oneofDecl: {
                                rule: "repeated",
                                type: "OneofDescriptorProto",
                                id: 8
                            },
                            options: {
                                type: "MessageOptions",
                                id: 7
                            },
                            reservedRange: {
                                rule: "repeated",
                                type: "ReservedRange",
                                id: 9
                            },
                            reservedName: {
                                rule: "repeated",
                                type: "string",
                                id: 10
                            },
                            visibility: {
                                type: "SymbolVisibility",
                                id: 11
                            }
                        },
                        nested: {
                            ExtensionRange: {
                                fields: {
                                    start: {
                                        type: "int32",
                                        id: 1
                                    },
                                    end: {
                                        type: "int32",
                                        id: 2
                                    },
                                    options: {
                                        type: "ExtensionRangeOptions",
                                        id: 3
                                    }
                                }
                            },
                            ReservedRange: {
                                fields: {
                                    start: {
                                        type: "int32",
                                        id: 1
                                    },
                                    end: {
                                        type: "int32",
                                        id: 2
                                    }
                                }
                            }
                        }
                    },
                    ExtensionRangeOptions: {
                        edition: "proto2",
                        fields: {
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            },
                            declaration: {
                                rule: "repeated",
                                type: "Declaration",
                                id: 2,
                                options: {
                                    retention: "RETENTION_SOURCE"
                                }
                            },
                            features: {
                                type: "FeatureSet",
                                id: 50
                            },
                            verification: {
                                type: "VerificationState",
                                id: 3,
                                options: {
                                    default: "UNVERIFIED",
                                    retention: "RETENTION_SOURCE"
                                }
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        nested: {
                            Declaration: {
                                fields: {
                                    number: {
                                        type: "int32",
                                        id: 1
                                    },
                                    fullName: {
                                        type: "string",
                                        id: 2
                                    },
                                    type: {
                                        type: "string",
                                        id: 3
                                    },
                                    reserved: {
                                        type: "bool",
                                        id: 5
                                    },
                                    repeated: {
                                        type: "bool",
                                        id: 6
                                    }
                                },
                                reserved: [ [ 4, 4 ] ]
                            },
                            VerificationState: {
                                values: {
                                    DECLARATION: 0,
                                    UNVERIFIED: 1
                                }
                            }
                        }
                    },
                    FieldDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            number: {
                                type: "int32",
                                id: 3
                            },
                            label: {
                                type: "Label",
                                id: 4
                            },
                            type: {
                                type: "Type",
                                id: 5
                            },
                            typeName: {
                                type: "string",
                                id: 6
                            },
                            extendee: {
                                type: "string",
                                id: 2
                            },
                            defaultValue: {
                                type: "string",
                                id: 7
                            },
                            oneofIndex: {
                                type: "int32",
                                id: 9
                            },
                            jsonName: {
                                type: "string",
                                id: 10
                            },
                            options: {
                                type: "FieldOptions",
                                id: 8
                            },
                            proto3Optional: {
                                type: "bool",
                                id: 17
                            }
                        },
                        nested: {
                            Type: {
                                values: {
                                    TYPE_DOUBLE: 1,
                                    TYPE_FLOAT: 2,
                                    TYPE_INT64: 3,
                                    TYPE_UINT64: 4,
                                    TYPE_INT32: 5,
                                    TYPE_FIXED64: 6,
                                    TYPE_FIXED32: 7,
                                    TYPE_BOOL: 8,
                                    TYPE_STRING: 9,
                                    TYPE_GROUP: 10,
                                    TYPE_MESSAGE: 11,
                                    TYPE_BYTES: 12,
                                    TYPE_UINT32: 13,
                                    TYPE_ENUM: 14,
                                    TYPE_SFIXED32: 15,
                                    TYPE_SFIXED64: 16,
                                    TYPE_SINT32: 17,
                                    TYPE_SINT64: 18
                                }
                            },
                            Label: {
                                values: {
                                    LABEL_OPTIONAL: 1,
                                    LABEL_REPEATED: 3,
                                    LABEL_REQUIRED: 2
                                }
                            }
                        }
                    },
                    OneofDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            options: {
                                type: "OneofOptions",
                                id: 2
                            }
                        }
                    },
                    EnumDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            value: {
                                rule: "repeated",
                                type: "EnumValueDescriptorProto",
                                id: 2
                            },
                            options: {
                                type: "EnumOptions",
                                id: 3
                            },
                            reservedRange: {
                                rule: "repeated",
                                type: "EnumReservedRange",
                                id: 4
                            },
                            reservedName: {
                                rule: "repeated",
                                type: "string",
                                id: 5
                            },
                            visibility: {
                                type: "SymbolVisibility",
                                id: 6
                            }
                        },
                        nested: {
                            EnumReservedRange: {
                                fields: {
                                    start: {
                                        type: "int32",
                                        id: 1
                                    },
                                    end: {
                                        type: "int32",
                                        id: 2
                                    }
                                }
                            }
                        }
                    },
                    EnumValueDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            number: {
                                type: "int32",
                                id: 2
                            },
                            options: {
                                type: "EnumValueOptions",
                                id: 3
                            }
                        }
                    },
                    ServiceDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            method: {
                                rule: "repeated",
                                type: "MethodDescriptorProto",
                                id: 2
                            },
                            options: {
                                type: "ServiceOptions",
                                id: 3
                            }
                        }
                    },
                    MethodDescriptorProto: {
                        edition: "proto2",
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            inputType: {
                                type: "string",
                                id: 2
                            },
                            outputType: {
                                type: "string",
                                id: 3
                            },
                            options: {
                                type: "MethodOptions",
                                id: 4
                            },
                            clientStreaming: {
                                type: "bool",
                                id: 5
                            },
                            serverStreaming: {
                                type: "bool",
                                id: 6
                            }
                        }
                    },
                    FileOptions: {
                        edition: "proto2",
                        fields: {
                            javaPackage: {
                                type: "string",
                                id: 1
                            },
                            javaOuterClassname: {
                                type: "string",
                                id: 8
                            },
                            javaMultipleFiles: {
                                type: "bool",
                                id: 10
                            },
                            javaGenerateEqualsAndHash: {
                                type: "bool",
                                id: 20,
                                options: {
                                    deprecated: true
                                }
                            },
                            javaStringCheckUtf8: {
                                type: "bool",
                                id: 27
                            },
                            optimizeFor: {
                                type: "OptimizeMode",
                                id: 9,
                                options: {
                                    default: "SPEED"
                                }
                            },
                            goPackage: {
                                type: "string",
                                id: 11
                            },
                            ccGenericServices: {
                                type: "bool",
                                id: 16
                            },
                            javaGenericServices: {
                                type: "bool",
                                id: 17
                            },
                            pyGenericServices: {
                                type: "bool",
                                id: 18
                            },
                            deprecated: {
                                type: "bool",
                                id: 23
                            },
                            ccEnableArenas: {
                                type: "bool",
                                id: 31,
                                options: {
                                    default: true
                                }
                            },
                            objcClassPrefix: {
                                type: "string",
                                id: 36
                            },
                            csharpNamespace: {
                                type: "string",
                                id: 37
                            },
                            swiftPrefix: {
                                type: "string",
                                id: 39
                            },
                            phpClassPrefix: {
                                type: "string",
                                id: 40
                            },
                            phpNamespace: {
                                type: "string",
                                id: 41
                            },
                            phpMetadataNamespace: {
                                type: "string",
                                id: 44
                            },
                            rubyPackage: {
                                type: "string",
                                id: 45
                            },
                            features: {
                                type: "FeatureSet",
                                id: 50
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        reserved: [ [ 42, 42 ], [ 38, 38 ], "php_generic_services" ],
                        nested: {
                            OptimizeMode: {
                                values: {
                                    SPEED: 1,
                                    CODE_SIZE: 2,
                                    LITE_RUNTIME: 3
                                }
                            }
                        }
                    },
                    MessageOptions: {
                        edition: "proto2",
                        fields: {
                            messageSetWireFormat: {
                                type: "bool",
                                id: 1
                            },
                            noStandardDescriptorAccessor: {
                                type: "bool",
                                id: 2
                            },
                            deprecated: {
                                type: "bool",
                                id: 3
                            },
                            mapEntry: {
                                type: "bool",
                                id: 7
                            },
                            deprecatedLegacyJsonFieldConflicts: {
                                type: "bool",
                                id: 11,
                                options: {
                                    deprecated: true
                                }
                            },
                            features: {
                                type: "FeatureSet",
                                id: 12
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        reserved: [ [ 4, 4 ], [ 5, 5 ], [ 6, 6 ], [ 8, 8 ], [ 9, 9 ] ]
                    },
                    FieldOptions: {
                        edition: "proto2",
                        fields: {
                            ctype: {
                                type: "CType",
                                id: 1,
                                options: {
                                    default: "STRING"
                                }
                            },
                            packed: {
                                type: "bool",
                                id: 2
                            },
                            jstype: {
                                type: "JSType",
                                id: 6,
                                options: {
                                    default: "JS_NORMAL"
                                }
                            },
                            lazy: {
                                type: "bool",
                                id: 5
                            },
                            unverifiedLazy: {
                                type: "bool",
                                id: 15
                            },
                            deprecated: {
                                type: "bool",
                                id: 3
                            },
                            weak: {
                                type: "bool",
                                id: 10,
                                options: {
                                    deprecated: true
                                }
                            },
                            debugRedact: {
                                type: "bool",
                                id: 16
                            },
                            retention: {
                                type: "OptionRetention",
                                id: 17
                            },
                            targets: {
                                rule: "repeated",
                                type: "OptionTargetType",
                                id: 19
                            },
                            editionDefaults: {
                                rule: "repeated",
                                type: "EditionDefault",
                                id: 20
                            },
                            features: {
                                type: "FeatureSet",
                                id: 21
                            },
                            featureSupport: {
                                type: "FeatureSupport",
                                id: 22
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        reserved: [ [ 4, 4 ], [ 18, 18 ] ],
                        nested: {
                            CType: {
                                values: {
                                    STRING: 0,
                                    CORD: 1,
                                    STRING_PIECE: 2
                                }
                            },
                            JSType: {
                                values: {
                                    JS_NORMAL: 0,
                                    JS_STRING: 1,
                                    JS_NUMBER: 2
                                }
                            },
                            OptionRetention: {
                                values: {
                                    RETENTION_UNKNOWN: 0,
                                    RETENTION_RUNTIME: 1,
                                    RETENTION_SOURCE: 2
                                }
                            },
                            OptionTargetType: {
                                values: {
                                    TARGET_TYPE_UNKNOWN: 0,
                                    TARGET_TYPE_FILE: 1,
                                    TARGET_TYPE_EXTENSION_RANGE: 2,
                                    TARGET_TYPE_MESSAGE: 3,
                                    TARGET_TYPE_FIELD: 4,
                                    TARGET_TYPE_ONEOF: 5,
                                    TARGET_TYPE_ENUM: 6,
                                    TARGET_TYPE_ENUM_ENTRY: 7,
                                    TARGET_TYPE_SERVICE: 8,
                                    TARGET_TYPE_METHOD: 9
                                }
                            },
                            EditionDefault: {
                                fields: {
                                    edition: {
                                        type: "Edition",
                                        id: 3
                                    },
                                    value: {
                                        type: "string",
                                        id: 2
                                    }
                                }
                            },
                            FeatureSupport: {
                                fields: {
                                    editionIntroduced: {
                                        type: "Edition",
                                        id: 1
                                    },
                                    editionDeprecated: {
                                        type: "Edition",
                                        id: 2
                                    },
                                    deprecationWarning: {
                                        type: "string",
                                        id: 3
                                    },
                                    editionRemoved: {
                                        type: "Edition",
                                        id: 4
                                    }
                                }
                            }
                        }
                    },
                    OneofOptions: {
                        edition: "proto2",
                        fields: {
                            features: {
                                type: "FeatureSet",
                                id: 1
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ]
                    },
                    EnumOptions: {
                        edition: "proto2",
                        fields: {
                            allowAlias: {
                                type: "bool",
                                id: 2
                            },
                            deprecated: {
                                type: "bool",
                                id: 3
                            },
                            deprecatedLegacyJsonFieldConflicts: {
                                type: "bool",
                                id: 6,
                                options: {
                                    deprecated: true
                                }
                            },
                            features: {
                                type: "FeatureSet",
                                id: 7
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        reserved: [ [ 5, 5 ] ]
                    },
                    EnumValueOptions: {
                        edition: "proto2",
                        fields: {
                            deprecated: {
                                type: "bool",
                                id: 1
                            },
                            features: {
                                type: "FeatureSet",
                                id: 2
                            },
                            debugRedact: {
                                type: "bool",
                                id: 3
                            },
                            featureSupport: {
                                type: "FieldOptions.FeatureSupport",
                                id: 4
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ]
                    },
                    ServiceOptions: {
                        edition: "proto2",
                        fields: {
                            features: {
                                type: "FeatureSet",
                                id: 34
                            },
                            deprecated: {
                                type: "bool",
                                id: 33
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ]
                    },
                    MethodOptions: {
                        edition: "proto2",
                        fields: {
                            deprecated: {
                                type: "bool",
                                id: 33
                            },
                            idempotencyLevel: {
                                type: "IdempotencyLevel",
                                id: 34,
                                options: {
                                    default: "IDEMPOTENCY_UNKNOWN"
                                }
                            },
                            features: {
                                type: "FeatureSet",
                                id: 35
                            },
                            uninterpretedOption: {
                                rule: "repeated",
                                type: "UninterpretedOption",
                                id: 999
                            }
                        },
                        extensions: [ [ 1e3, 536870911 ] ],
                        nested: {
                            IdempotencyLevel: {
                                values: {
                                    IDEMPOTENCY_UNKNOWN: 0,
                                    NO_SIDE_EFFECTS: 1,
                                    IDEMPOTENT: 2
                                }
                            }
                        }
                    },
                    UninterpretedOption: {
                        edition: "proto2",
                        fields: {
                            name: {
                                rule: "repeated",
                                type: "NamePart",
                                id: 2
                            },
                            identifierValue: {
                                type: "string",
                                id: 3
                            },
                            positiveIntValue: {
                                type: "uint64",
                                id: 4
                            },
                            negativeIntValue: {
                                type: "int64",
                                id: 5
                            },
                            doubleValue: {
                                type: "double",
                                id: 6
                            },
                            stringValue: {
                                type: "bytes",
                                id: 7
                            },
                            aggregateValue: {
                                type: "string",
                                id: 8
                            }
                        },
                        nested: {
                            NamePart: {
                                fields: {
                                    namePart: {
                                        rule: "required",
                                        type: "string",
                                        id: 1
                                    },
                                    isExtension: {
                                        rule: "required",
                                        type: "bool",
                                        id: 2
                                    }
                                }
                            }
                        }
                    },
                    FeatureSet: {
                        edition: "proto2",
                        fields: {
                            fieldPresence: {
                                type: "FieldPresence",
                                id: 1,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_2023",
                                    "edition_defaults.value": "EXPLICIT"
                                }
                            },
                            enumType: {
                                type: "EnumType",
                                id: 2,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_PROTO3",
                                    "edition_defaults.value": "OPEN"
                                }
                            },
                            repeatedFieldEncoding: {
                                type: "RepeatedFieldEncoding",
                                id: 3,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_PROTO3",
                                    "edition_defaults.value": "PACKED"
                                }
                            },
                            utf8Validation: {
                                type: "Utf8Validation",
                                id: 4,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_PROTO3",
                                    "edition_defaults.value": "VERIFY"
                                }
                            },
                            messageEncoding: {
                                type: "MessageEncoding",
                                id: 5,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_LEGACY",
                                    "edition_defaults.value": "LENGTH_PREFIXED"
                                }
                            },
                            jsonFormat: {
                                type: "JsonFormat",
                                id: 6,
                                options: {
                                    retention: "RETENTION_RUNTIME",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2023",
                                    "edition_defaults.edition": "EDITION_PROTO3",
                                    "edition_defaults.value": "ALLOW"
                                }
                            },
                            enforceNamingStyle: {
                                type: "EnforceNamingStyle",
                                id: 7,
                                options: {
                                    retention: "RETENTION_SOURCE",
                                    targets: "TARGET_TYPE_METHOD",
                                    "feature_support.edition_introduced": "EDITION_2024",
                                    "edition_defaults.edition": "EDITION_2024",
                                    "edition_defaults.value": "STYLE2024"
                                }
                            },
                            defaultSymbolVisibility: {
                                type: "VisibilityFeature.DefaultSymbolVisibility",
                                id: 8,
                                options: {
                                    retention: "RETENTION_SOURCE",
                                    targets: "TARGET_TYPE_FILE",
                                    "feature_support.edition_introduced": "EDITION_2024",
                                    "edition_defaults.edition": "EDITION_2024",
                                    "edition_defaults.value": "EXPORT_TOP_LEVEL"
                                }
                            }
                        },
                        extensions: [ [ 1e3, 9994 ], [ 9995, 9999 ], [ 1e4, 1e4 ] ],
                        reserved: [ [ 999, 999 ] ],
                        nested: {
                            FieldPresence: {
                                values: {
                                    FIELD_PRESENCE_UNKNOWN: 0,
                                    EXPLICIT: 1,
                                    IMPLICIT: 2,
                                    LEGACY_REQUIRED: 3
                                }
                            },
                            EnumType: {
                                values: {
                                    ENUM_TYPE_UNKNOWN: 0,
                                    OPEN: 1,
                                    CLOSED: 2
                                }
                            },
                            RepeatedFieldEncoding: {
                                values: {
                                    REPEATED_FIELD_ENCODING_UNKNOWN: 0,
                                    PACKED: 1,
                                    EXPANDED: 2
                                }
                            },
                            Utf8Validation: {
                                values: {
                                    UTF8_VALIDATION_UNKNOWN: 0,
                                    VERIFY: 2,
                                    NONE: 3
                                }
                            },
                            MessageEncoding: {
                                values: {
                                    MESSAGE_ENCODING_UNKNOWN: 0,
                                    LENGTH_PREFIXED: 1,
                                    DELIMITED: 2
                                }
                            },
                            JsonFormat: {
                                values: {
                                    JSON_FORMAT_UNKNOWN: 0,
                                    ALLOW: 1,
                                    LEGACY_BEST_EFFORT: 2
                                }
                            },
                            EnforceNamingStyle: {
                                values: {
                                    ENFORCE_NAMING_STYLE_UNKNOWN: 0,
                                    STYLE2024: 1,
                                    STYLE_LEGACY: 2
                                }
                            },
                            VisibilityFeature: {
                                fields: {},
                                reserved: [ [ 1, 536870911 ] ],
                                nested: {
                                    DefaultSymbolVisibility: {
                                        values: {
                                            DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0,
                                            EXPORT_ALL: 1,
                                            EXPORT_TOP_LEVEL: 2,
                                            LOCAL_ALL: 3,
                                            STRICT: 4
                                        }
                                    }
                                }
                            }
                        }
                    },
                    FeatureSetDefaults: {
                        edition: "proto2",
                        fields: {
                            defaults: {
                                rule: "repeated",
                                type: "FeatureSetEditionDefault",
                                id: 1
                            },
                            minimumEdition: {
                                type: "Edition",
                                id: 4
                            },
                            maximumEdition: {
                                type: "Edition",
                                id: 5
                            }
                        },
                        nested: {
                            FeatureSetEditionDefault: {
                                fields: {
                                    edition: {
                                        type: "Edition",
                                        id: 3
                                    },
                                    overridableFeatures: {
                                        type: "FeatureSet",
                                        id: 4
                                    },
                                    fixedFeatures: {
                                        type: "FeatureSet",
                                        id: 5
                                    }
                                },
                                reserved: [ [ 1, 1 ], [ 2, 2 ], "features" ]
                            }
                        }
                    },
                    SourceCodeInfo: {
                        edition: "proto2",
                        fields: {
                            location: {
                                rule: "repeated",
                                type: "Location",
                                id: 1
                            }
                        },
                        extensions: [ [ 536e6, 536e6 ] ],
                        nested: {
                            Location: {
                                fields: {
                                    path: {
                                        rule: "repeated",
                                        type: "int32",
                                        id: 1,
                                        options: {
                                            packed: true
                                        }
                                    },
                                    span: {
                                        rule: "repeated",
                                        type: "int32",
                                        id: 2,
                                        options: {
                                            packed: true
                                        }
                                    },
                                    leadingComments: {
                                        type: "string",
                                        id: 3
                                    },
                                    trailingComments: {
                                        type: "string",
                                        id: 4
                                    },
                                    leadingDetachedComments: {
                                        rule: "repeated",
                                        type: "string",
                                        id: 6
                                    }
                                }
                            }
                        }
                    },
                    GeneratedCodeInfo: {
                        edition: "proto2",
                        fields: {
                            annotation: {
                                rule: "repeated",
                                type: "Annotation",
                                id: 1
                            }
                        },
                        nested: {
                            Annotation: {
                                fields: {
                                    path: {
                                        rule: "repeated",
                                        type: "int32",
                                        id: 1,
                                        options: {
                                            packed: true
                                        }
                                    },
                                    sourceFile: {
                                        type: "string",
                                        id: 2
                                    },
                                    begin: {
                                        type: "int32",
                                        id: 3
                                    },
                                    end: {
                                        type: "int32",
                                        id: 4
                                    },
                                    semantic: {
                                        type: "Semantic",
                                        id: 5
                                    }
                                },
                                nested: {
                                    Semantic: {
                                        values: {
                                            NONE: 0,
                                            SET: 1,
                                            ALIAS: 2
                                        }
                                    }
                                }
                            }
                        }
                    },
                    SymbolVisibility: {
                        edition: "proto2",
                        values: {
                            VISIBILITY_UNSET: 0,
                            VISIBILITY_LOCAL: 1,
                            VISIBILITY_EXPORT: 2
                        }
                    }
                }
            }
        }
    }
};

const require$$4 = {
    nested: nested$3
};

descriptor.exports;

(function(e, t) {
    var r = protobufjs;
    e.exports = t = r.descriptor = r.Root.fromJSON(require$$4).lookup(".google.protobuf");
    var n = r.Namespace, s = r.Root, o = r.Enum, a = r.Type, l = r.Field, c = r.MapField, u = r.OneOf, d = r.Service, h = r.Method;
    s.fromDescriptor = function e(r) {
        if (typeof r.length === "number") r = t.FileDescriptorSet.decode(r);
        var n = new s;
        if (r.file) {
            var c, u;
            for (var h = 0, p; h < r.file.length; ++h) {
                u = n;
                if ((c = r.file[h])["package"] && c["package"].length) u = n.define(c["package"]);
                var g = P(c);
                if (c.name && c.name.length) n.files.push(u.filename = c.name);
                if (c.messageType) for (p = 0; p < c.messageType.length; ++p) u.add(a.fromDescriptor(c.messageType[p], g));
                if (c.enumType) for (p = 0; p < c.enumType.length; ++p) u.add(o.fromDescriptor(c.enumType[p], g));
                if (c.extension) for (p = 0; p < c.extension.length; ++p) u.add(l.fromDescriptor(c.extension[p], g));
                if (c.service) for (p = 0; p < c.service.length; ++p) u.add(d.fromDescriptor(c.service[p], g));
                var m = w(c.options, t.FileOptions);
                if (m) {
                    var _ = Object.keys(m);
                    for (p = 0; p < _.length; ++p) u.setOption(_[p], m[_[p]]);
                }
            }
        }
        return n.resolveAll();
    };
    s.prototype.toDescriptor = function e(r) {
        var n = t.FileDescriptorSet.create();
        p(this, n.file, r);
        return n;
    };
    function p(e, r, c) {
        var u = t.FileDescriptorProto.create({
            name: e.filename || (e.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto"
        });
        $(c, u);
        if (!(e instanceof s)) u["package"] = e.fullName.substring(1);
        for (var h = 0, g; h < e.nestedArray.length; ++h) if ((g = e._nestedArray[h]) instanceof a) u.messageType.push(g.toDescriptor(c)); else if (g instanceof o) u.enumType.push(g.toDescriptor()); else if (g instanceof l) u.extension.push(g.toDescriptor(c)); else if (g instanceof d) u.service.push(g.toDescriptor()); else if (g instanceof n) p(g, r, c);
        u.options = T(e.options, t.FileOptions);
        if (u.messageType.length + u.enumType.length + u.extension.length + u.service.length) r.push(u);
    }
    var g = 0;
    a.fromDescriptor = function e(r, n, s) {
        if (typeof r.length === "number") r = t.DescriptorProto.decode(r);
        var c = new a(r.name.length ? r.name : "Type" + g++, w(r.options, t.MessageOptions)), d;
        if (!s) c._edition = n;
        if (r.oneofDecl) for (d = 0; d < r.oneofDecl.length; ++d) c.add(u.fromDescriptor(r.oneofDecl[d]));
        if (r.field) for (d = 0; d < r.field.length; ++d) {
            var h = l.fromDescriptor(r.field[d], n, true);
            c.add(h);
            if (r.field[d].hasOwnProperty("oneofIndex")) c.oneofsArray[r.field[d].oneofIndex].add(h);
        }
        if (r.extension) for (d = 0; d < r.extension.length; ++d) c.add(l.fromDescriptor(r.extension[d], n, true));
        if (r.nestedType) for (d = 0; d < r.nestedType.length; ++d) {
            c.add(a.fromDescriptor(r.nestedType[d], n, true));
            if (r.nestedType[d].options && r.nestedType[d].options.mapEntry) c.setOption("map_entry", true);
        }
        if (r.enumType) for (d = 0; d < r.enumType.length; ++d) c.add(o.fromDescriptor(r.enumType[d], n, true));
        if (r.extensionRange && r.extensionRange.length) {
            c.extensions = [];
            for (d = 0; d < r.extensionRange.length; ++d) c.extensions.push([ r.extensionRange[d].start, r.extensionRange[d].end ]);
        }
        if (r.reservedRange && r.reservedRange.length || r.reservedName && r.reservedName.length) {
            c.reserved = [];
            if (r.reservedRange) for (d = 0; d < r.reservedRange.length; ++d) c.reserved.push([ r.reservedRange[d].start, r.reservedRange[d].end ]);
            if (r.reservedName) for (d = 0; d < r.reservedName.length; ++d) c.reserved.push(r.reservedName[d]);
        }
        return c;
    };
    a.prototype.toDescriptor = function e(r) {
        var n = t.DescriptorProto.create({
            name: this.name
        }), s;
        for (s = 0; s < this.fieldsArray.length; ++s) {
            var u;
            n.field.push(u = this._fieldsArray[s].toDescriptor(r));
            if (this._fieldsArray[s] instanceof c) {
                var d = b(this._fieldsArray[s].keyType, this._fieldsArray[s].resolvedKeyType, false), h = b(this._fieldsArray[s].type, this._fieldsArray[s].resolvedType, false), p = h === 11 || h === 14 ? this._fieldsArray[s].resolvedType && R(this.parent, this._fieldsArray[s].resolvedType) || this._fieldsArray[s].type : undefined;
                n.nestedType.push(t.DescriptorProto.create({
                    name: u.typeName,
                    field: [ t.FieldDescriptorProto.create({
                        name: "key",
                        number: 1,
                        label: 1,
                        type: d
                    }), t.FieldDescriptorProto.create({
                        name: "value",
                        number: 2,
                        label: 1,
                        type: h,
                        typeName: p
                    }) ],
                    options: t.MessageOptions.create({
                        mapEntry: true
                    })
                }));
            }
        }
        for (s = 0; s < this.oneofsArray.length; ++s) n.oneofDecl.push(this._oneofsArray[s].toDescriptor());
        for (s = 0; s < this.nestedArray.length; ++s) {
            if (this._nestedArray[s] instanceof l) n.field.push(this._nestedArray[s].toDescriptor(r)); else if (this._nestedArray[s] instanceof a) n.nestedType.push(this._nestedArray[s].toDescriptor(r)); else if (this._nestedArray[s] instanceof o) n.enumType.push(this._nestedArray[s].toDescriptor());
        }
        if (this.extensions) for (s = 0; s < this.extensions.length; ++s) n.extensionRange.push(t.DescriptorProto.ExtensionRange.create({
            start: this.extensions[s][0],
            end: this.extensions[s][1]
        }));
        if (this.reserved) for (s = 0; s < this.reserved.length; ++s) if (typeof this.reserved[s] === "string") n.reservedName.push(this.reserved[s]); else n.reservedRange.push(t.DescriptorProto.ReservedRange.create({
            start: this.reserved[s][0],
            end: this.reserved[s][1]
        }));
        n.options = T(this.options, t.MessageOptions);
        return n;
    };
    var m = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/;
    l.fromDescriptor = function e(r, n, s) {
        if (typeof r.length === "number") r = t.DescriptorProto.decode(r);
        if (typeof r.number !== "number") throw Error("missing field id");
        var o;
        if (r.typeName && r.typeName.length) o = r.typeName; else o = S(r.type);
        var a;
        switch (r.label) {
          case 1:
            a = undefined;
            break;

          case 2:
            a = "required";
            break;

          case 3:
            a = "repeated";
            break;

          default:
            throw Error("illegal label: " + r.label);
        }
        var c = r.extendee;
        if (r.extendee !== undefined) {
            c = c.length ? c : undefined;
        }
        var u = new l(r.name.length ? r.name : "field" + r.number, r.number, o, a, c);
        if (!s) u._edition = n;
        u.options = w(r.options, t.FieldOptions);
        if (r.proto3_optional) u.options.proto3_optional = true;
        if (r.defaultValue && r.defaultValue.length) {
            var d = r.defaultValue;
            switch (d) {
              case "true":
              case "TRUE":
                d = true;
                break;

              case "false":
              case "FALSE":
                d = false;
                break;

              default:
                var h = m.exec(d);
                if (h) d = parseInt(d);
                break;
            }
            u.setOption("default", d);
        }
        if (A(r.type)) {
            if (n === "proto3") {
                if (r.options && !r.options.packed) u.setOption("packed", false);
            } else if ((!n || n === "proto2") && r.options && r.options.packed) u.setOption("packed", true);
        }
        return u;
    };
    l.prototype.toDescriptor = function e(n) {
        var s = t.FieldDescriptorProto.create({
            name: this.name,
            number: this.id
        });
        if (this.map) {
            s.type = 11;
            s.typeName = r.util.ucFirst(this.name);
            s.label = 3;
        } else {
            switch (s.type = b(this.type, this.resolve().resolvedType, this.delimited)) {
              case 10:
              case 11:
              case 14:
                s.typeName = this.resolvedType ? R(this.parent, this.resolvedType) : this.type;
                break;
            }
            if (this.rule === "repeated") {
                s.label = 3;
            } else if (this.required && n === "proto2") {
                s.label = 2;
            } else {
                s.label = 1;
            }
        }
        s.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend;
        if (this.partOf) if ((s.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) throw Error("missing oneof");
        if (this.options) {
            s.options = T(this.options, t.FieldOptions);
            if (this.options["default"] != null) s.defaultValue = String(this.options["default"]);
            if (this.options.proto3_optional) s.proto3_optional = true;
        }
        if (n === "proto3") {
            if (!this.packed) (s.options || (s.options = t.FieldOptions.create())).packed = false;
        } else if ((!n || n === "proto2") && this.packed) (s.options || (s.options = t.FieldOptions.create())).packed = true;
        return s;
    };
    var _ = 0;
    o.fromDescriptor = function e(r, n, s) {
        if (typeof r.length === "number") r = t.EnumDescriptorProto.decode(r);
        var a = {};
        if (r.value) for (var l = 0; l < r.value.length; ++l) {
            var c = r.value[l].name, u = r.value[l].number || 0;
            a[c && c.length ? c : "NAME" + u] = u;
        }
        var d = new o(r.name && r.name.length ? r.name : "Enum" + _++, a, w(r.options, t.EnumOptions));
        if (!s) d._edition = n;
        return d;
    };
    o.prototype.toDescriptor = function e() {
        var r = [];
        for (var n = 0, s = Object.keys(this.values); n < s.length; ++n) r.push(t.EnumValueDescriptorProto.create({
            name: s[n],
            number: this.values[s[n]]
        }));
        return t.EnumDescriptorProto.create({
            name: this.name,
            value: r,
            options: T(this.options, t.EnumOptions)
        });
    };
    var E = 0;
    u.fromDescriptor = function e(r) {
        if (typeof r.length === "number") r = t.OneofDescriptorProto.decode(r);
        return new u(r.name && r.name.length ? r.name : "oneof" + E++);
    };
    u.prototype.toDescriptor = function e() {
        return t.OneofDescriptorProto.create({
            name: this.name
        });
    };
    var v = 0;
    d.fromDescriptor = function e(r, n, s) {
        if (typeof r.length === "number") r = t.ServiceDescriptorProto.decode(r);
        var o = new d(r.name && r.name.length ? r.name : "Service" + v++, w(r.options, t.ServiceOptions));
        if (!s) o._edition = n;
        if (r.method) for (var a = 0; a < r.method.length; ++a) o.add(h.fromDescriptor(r.method[a]));
        return o;
    };
    d.prototype.toDescriptor = function e() {
        var r = [];
        for (var n = 0; n < this.methodsArray.length; ++n) r.push(this._methodsArray[n].toDescriptor());
        return t.ServiceDescriptorProto.create({
            name: this.name,
            method: r,
            options: T(this.options, t.ServiceOptions)
        });
    };
    var y = 0;
    h.fromDescriptor = function e(r) {
        if (typeof r.length === "number") r = t.MethodDescriptorProto.decode(r);
        return new h(r.name && r.name.length ? r.name : "Method" + y++, "rpc", r.inputType, r.outputType, Boolean(r.clientStreaming), Boolean(r.serverStreaming), w(r.options, t.MethodOptions));
    };
    h.prototype.toDescriptor = function e() {
        return t.MethodDescriptorProto.create({
            name: this.name,
            inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType,
            outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType,
            clientStreaming: this.requestStream,
            serverStreaming: this.responseStream,
            options: T(this.options, t.MethodOptions)
        });
    };
    function S(e) {
        switch (e) {
          case 1:
            return "double";

          case 2:
            return "float";

          case 3:
            return "int64";

          case 4:
            return "uint64";

          case 5:
            return "int32";

          case 6:
            return "fixed64";

          case 7:
            return "fixed32";

          case 8:
            return "bool";

          case 9:
            return "string";

          case 12:
            return "bytes";

          case 13:
            return "uint32";

          case 15:
            return "sfixed32";

          case 16:
            return "sfixed64";

          case 17:
            return "sint32";

          case 18:
            return "sint64";
        }
        throw Error("illegal type: " + e);
    }
    function A(e) {
        switch (e) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
          case 8:
          case 13:
          case 14:
          case 15:
          case 16:
          case 17:
          case 18:
            return true;
        }
        return false;
    }
    function b(e, t, r) {
        switch (e) {
          case "double":
            return 1;

          case "float":
            return 2;

          case "int64":
            return 3;

          case "uint64":
            return 4;

          case "int32":
            return 5;

          case "fixed64":
            return 6;

          case "fixed32":
            return 7;

          case "bool":
            return 8;

          case "string":
            return 9;

          case "bytes":
            return 12;

          case "uint32":
            return 13;

          case "sfixed32":
            return 15;

          case "sfixed64":
            return 16;

          case "sint32":
            return 17;

          case "sint64":
            return 18;
        }
        if (t instanceof o) return 14;
        if (t instanceof a) return r ? 10 : 11;
        throw Error("illegal type: " + e);
    }
    function C(e, t) {
        var r = {};
        for (var n = 0, s, l; n < t.fieldsArray.length; ++n) {
            if ((l = (s = t._fieldsArray[n]).name) === "uninterpretedOption") continue;
            if (!Object.prototype.hasOwnProperty.call(e, l)) continue;
            var c = k(l);
            if (s.resolvedType instanceof a) {
                r[c] = C(e[l], s.resolvedType);
            } else if (s.resolvedType instanceof o) {
                r[c] = s.resolvedType.valuesById[e[l]];
            } else {
                r[c] = e[l];
            }
        }
        return r;
    }
    function w(e, t) {
        if (!e) return undefined;
        return C(t.toObject(e), t);
    }
    function I(e, t) {
        var n = {};
        var s = Object.keys(e);
        for (var o = 0; o < s.length; ++o) {
            var l = s[o];
            var c = r.util.camelCase(l);
            if (!Object.prototype.hasOwnProperty.call(t.fields, c)) continue;
            var u = t.fields[c];
            if (u.resolvedType instanceof a) {
                n[c] = I(e[l], u.resolvedType);
            } else {
                n[c] = e[l];
            }
            if (u.repeated && !Array.isArray(n[c])) {
                n[c] = [ n[c] ];
            }
        }
        return n;
    }
    function T(e, t) {
        if (!e) return undefined;
        return t.fromObject(I(e, t));
    }
    function R(e, t) {
        var r = e.fullName.split("."), o = t.fullName.split("."), a = 0, l = 0, c = o.length - 1;
        if (!(e instanceof s) && t instanceof n) while (a < r.length && l < c && r[a] === o[l]) {
            var u = t.lookup(r[a++], true);
            if (u !== null && u !== t) break;
            ++l;
        } else for (;a < r.length && l < c && r[a] === o[l]; ++a, ++l) ;
        return o.slice(l).join(".");
    }
    function k(e) {
        return e.substring(0, 1) + e.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function(e, t) {
            return "_" + t.toLowerCase();
        });
    }
    function P(e) {
        if (e.syntax === "editions") {
            switch (e.edition) {
              case t.Edition.EDITION_2023:
                return "2023";

              default:
                throw new Error("Unsupported edition " + e.edition);
            }
        }
        if (e.syntax === "proto3") {
            return "proto3";
        }
        return "proto2";
    }
    function $(e, r) {
        if (!e) return;
        if (e === "proto2" || e === "proto3") {
            r.syntax = e;
        } else {
            r.syntax = "editions";
            switch (e) {
              case "2023":
                r.edition = t.Edition.EDITION_2023;
                break;

              default:
                throw new Error("Unsupported edition " + e);
            }
        }
    }
})(descriptor, descriptor.exports);

var descriptorExports = descriptor.exports;

var util$3 = {};

var nested$2 = {
    google: {
        nested: {
            protobuf: {
                nested: {
                    Api: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            methods: {
                                rule: "repeated",
                                type: "Method",
                                id: 2
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 3
                            },
                            version: {
                                type: "string",
                                id: 4
                            },
                            sourceContext: {
                                type: "SourceContext",
                                id: 5
                            },
                            mixins: {
                                rule: "repeated",
                                type: "Mixin",
                                id: 6
                            },
                            syntax: {
                                type: "Syntax",
                                id: 7
                            }
                        }
                    },
                    Method: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            requestTypeUrl: {
                                type: "string",
                                id: 2
                            },
                            requestStreaming: {
                                type: "bool",
                                id: 3
                            },
                            responseTypeUrl: {
                                type: "string",
                                id: 4
                            },
                            responseStreaming: {
                                type: "bool",
                                id: 5
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 6
                            },
                            syntax: {
                                type: "Syntax",
                                id: 7
                            }
                        }
                    },
                    Mixin: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            root: {
                                type: "string",
                                id: 2
                            }
                        }
                    },
                    SourceContext: {
                        fields: {
                            fileName: {
                                type: "string",
                                id: 1
                            }
                        }
                    },
                    Option: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            value: {
                                type: "Any",
                                id: 2
                            }
                        }
                    },
                    Syntax: {
                        values: {
                            SYNTAX_PROTO2: 0,
                            SYNTAX_PROTO3: 1
                        }
                    }
                }
            }
        }
    }
};

const require$$3$1 = {
    nested: nested$2
};

var nested$1 = {
    google: {
        nested: {
            protobuf: {
                nested: {
                    SourceContext: {
                        fields: {
                            fileName: {
                                type: "string",
                                id: 1
                            }
                        }
                    }
                }
            }
        }
    }
};

const require$$5 = {
    nested: nested$1
};

var nested = {
    google: {
        nested: {
            protobuf: {
                nested: {
                    Type: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            fields: {
                                rule: "repeated",
                                type: "Field",
                                id: 2
                            },
                            oneofs: {
                                rule: "repeated",
                                type: "string",
                                id: 3
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 4
                            },
                            sourceContext: {
                                type: "SourceContext",
                                id: 5
                            },
                            syntax: {
                                type: "Syntax",
                                id: 6
                            }
                        }
                    },
                    Field: {
                        fields: {
                            kind: {
                                type: "Kind",
                                id: 1
                            },
                            cardinality: {
                                type: "Cardinality",
                                id: 2
                            },
                            number: {
                                type: "int32",
                                id: 3
                            },
                            name: {
                                type: "string",
                                id: 4
                            },
                            typeUrl: {
                                type: "string",
                                id: 6
                            },
                            oneofIndex: {
                                type: "int32",
                                id: 7
                            },
                            packed: {
                                type: "bool",
                                id: 8
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 9
                            },
                            jsonName: {
                                type: "string",
                                id: 10
                            },
                            defaultValue: {
                                type: "string",
                                id: 11
                            }
                        },
                        nested: {
                            Kind: {
                                values: {
                                    TYPE_UNKNOWN: 0,
                                    TYPE_DOUBLE: 1,
                                    TYPE_FLOAT: 2,
                                    TYPE_INT64: 3,
                                    TYPE_UINT64: 4,
                                    TYPE_INT32: 5,
                                    TYPE_FIXED64: 6,
                                    TYPE_FIXED32: 7,
                                    TYPE_BOOL: 8,
                                    TYPE_STRING: 9,
                                    TYPE_GROUP: 10,
                                    TYPE_MESSAGE: 11,
                                    TYPE_BYTES: 12,
                                    TYPE_UINT32: 13,
                                    TYPE_ENUM: 14,
                                    TYPE_SFIXED32: 15,
                                    TYPE_SFIXED64: 16,
                                    TYPE_SINT32: 17,
                                    TYPE_SINT64: 18
                                }
                            },
                            Cardinality: {
                                values: {
                                    CARDINALITY_UNKNOWN: 0,
                                    CARDINALITY_OPTIONAL: 1,
                                    CARDINALITY_REQUIRED: 2,
                                    CARDINALITY_REPEATED: 3
                                }
                            }
                        }
                    },
                    Enum: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            enumvalue: {
                                rule: "repeated",
                                type: "EnumValue",
                                id: 2
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 3
                            },
                            sourceContext: {
                                type: "SourceContext",
                                id: 4
                            },
                            syntax: {
                                type: "Syntax",
                                id: 5
                            }
                        }
                    },
                    EnumValue: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            number: {
                                type: "int32",
                                id: 2
                            },
                            options: {
                                rule: "repeated",
                                type: "Option",
                                id: 3
                            }
                        }
                    },
                    Option: {
                        fields: {
                            name: {
                                type: "string",
                                id: 1
                            },
                            value: {
                                type: "Any",
                                id: 2
                            }
                        }
                    },
                    Syntax: {
                        values: {
                            SYNTAX_PROTO2: 0,
                            SYNTAX_PROTO3: 1
                        }
                    },
                    Any: {
                        fields: {
                            type_url: {
                                type: "string",
                                id: 1
                            },
                            value: {
                                type: "bytes",
                                id: 2
                            }
                        }
                    },
                    SourceContext: {
                        fields: {
                            fileName: {
                                type: "string",
                                id: 1
                            }
                        }
                    }
                }
            }
        }
    }
};

const require$$6 = {
    nested: nested
};

var hasRequiredUtil;

function requireUtil() {
    if (hasRequiredUtil) return util$3;
    hasRequiredUtil = 1;
    Object.defineProperty(util$3, "__esModule", {
        value: true
    });
    util$3.addCommonProtos = util$3.loadProtosWithOptionsSync = util$3.loadProtosWithOptions = void 0;
    const e = require$$0__default$5.default;
    const t = require$$0__default$4.default;
    const r = protobufjs;
    function n(r, n) {
        const s = r.resolvePath;
        r.resolvePath = (r, o) => {
            if (t.isAbsolute(o)) {
                return o;
            }
            for (const r of n) {
                const n = t.join(r, o);
                try {
                    e.accessSync(n, e.constants.R_OK);
                    return n;
                } catch (e) {
                    continue;
                }
            }
            process.emitWarning(`${o} not found in any of the include paths ${n}`);
            return s(r, o);
        };
    }
    async function s(e, t) {
        const s = new r.Root;
        t = t || {};
        if (!!t.includeDirs) {
            if (!Array.isArray(t.includeDirs)) {
                return Promise.reject(new Error("The includeDirs option must be an array"));
            }
            n(s, t.includeDirs);
        }
        const o = await s.load(e, t);
        o.resolveAll();
        return o;
    }
    util$3.loadProtosWithOptions = s;
    function o(e, t) {
        const s = new r.Root;
        t = t || {};
        if (!!t.includeDirs) {
            if (!Array.isArray(t.includeDirs)) {
                throw new Error("The includeDirs option must be an array");
            }
            n(s, t.includeDirs);
        }
        const o = s.loadSync(e, t);
        o.resolveAll();
        return o;
    }
    util$3.loadProtosWithOptionsSync = o;
    function a() {
        const e = require$$3$1;
        const t = require$$4;
        const n = require$$5;
        const s = require$$6;
        r.common("api", e.nested.google.nested.protobuf.nested);
        r.common("descriptor", t.nested.google.nested.protobuf.nested);
        r.common("source_context", n.nested.google.nested.protobuf.nested);
        r.common("type", s.nested.google.nested.protobuf.nested);
    }
    util$3.addCommonProtos = a;
    return util$3;
}

var umd = {
    exports: {}
};

umd.exports;

(function(e, t) {
    (function(r, n) {
        function s(e) {
            return e.default || e;
        }
        {
            n(t);
            e.exports = s(t);
        }
    })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : _commonjsHelpers.commonjsGlobal, function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.default = void 0;
        var t = null;
        try {
            t = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11 ])), {}).exports;
        } catch {}
        function r(e, t, r) {
            this.low = e | 0;
            this.high = t | 0;
            this.unsigned = !!r;
        }
        r.prototype.__isLong__;
        Object.defineProperty(r.prototype, "__isLong__", {
            value: true
        });
        function n(e) {
            return (e && e["__isLong__"]) === true;
        }
        function s(e) {
            var t = Math.clz32(e & -e);
            return e ? 31 - t : t;
        }
        r.isLong = n;
        var o = {};
        var a = {};
        function l(e, t) {
            var r, n, s;
            if (t) {
                e >>>= 0;
                if (s = 0 <= e && e < 256) {
                    n = a[e];
                    if (n) return n;
                }
                r = u(e, 0, true);
                if (s) a[e] = r;
                return r;
            } else {
                e |= 0;
                if (s = -128 <= e && e < 128) {
                    n = o[e];
                    if (n) return n;
                }
                r = u(e, e < 0 ? -1 : 0, false);
                if (s) o[e] = r;
                return r;
            }
        }
        r.fromInt = l;
        function c(e, t) {
            if (isNaN(e)) return t ? A : S;
            if (t) {
                if (e < 0) return A;
                if (e >= E) return T;
            } else {
                if (e <= -v) return R;
                if (e + 1 >= v) return I;
            }
            if (e < 0) return c(-e, t).neg();
            return u(e % _ | 0, e / _ | 0, t);
        }
        r.fromNumber = c;
        function u(e, t, n) {
            return new r(e, t, n);
        }
        r.fromBits = u;
        var d = Math.pow;
        function h(e, t, r) {
            if (e.length === 0) throw Error("empty string");
            if (typeof t === "number") {
                r = t;
                t = false;
            } else {
                t = !!t;
            }
            if (e === "NaN" || e === "Infinity" || e === "+Infinity" || e === "-Infinity") return t ? A : S;
            r = r || 10;
            if (r < 2 || 36 < r) throw RangeError("radix");
            var n;
            if ((n = e.indexOf("-")) > 0) throw Error("interior hyphen"); else if (n === 0) {
                return h(e.substring(1), t, r).neg();
            }
            var s = c(d(r, 8));
            var o = S;
            for (var a = 0; a < e.length; a += 8) {
                var l = Math.min(8, e.length - a), u = parseInt(e.substring(a, a + l), r);
                if (l < 8) {
                    var p = c(d(r, l));
                    o = o.mul(p).add(c(u));
                } else {
                    o = o.mul(s);
                    o = o.add(c(u));
                }
            }
            o.unsigned = t;
            return o;
        }
        r.fromString = h;
        function p(e, t) {
            if (typeof e === "number") return c(e, t);
            if (typeof e === "string") return h(e, t);
            return u(e.low, e.high, typeof t === "boolean" ? t : e.unsigned);
        }
        r.fromValue = p;
        var g = 1 << 16;
        var m = 1 << 24;
        var _ = g * g;
        var E = _ * _;
        var v = E / 2;
        var y = l(m);
        var S = l(0);
        r.ZERO = S;
        var A = l(0, true);
        r.UZERO = A;
        var b = l(1);
        r.ONE = b;
        var C = l(1, true);
        r.UONE = C;
        var w = l(-1);
        r.NEG_ONE = w;
        var I = u(4294967295 | 0, 2147483647 | 0, false);
        r.MAX_VALUE = I;
        var T = u(4294967295 | 0, 4294967295 | 0, true);
        r.MAX_UNSIGNED_VALUE = T;
        var R = u(0, 2147483648 | 0, false);
        r.MIN_VALUE = R;
        var k = r.prototype;
        k.toInt = function e() {
            return this.unsigned ? this.low >>> 0 : this.low;
        };
        k.toNumber = function e() {
            if (this.unsigned) return (this.high >>> 0) * _ + (this.low >>> 0);
            return this.high * _ + (this.low >>> 0);
        };
        k.toString = function e(t) {
            t = t || 10;
            if (t < 2 || 36 < t) throw RangeError("radix");
            if (this.isZero()) return "0";
            if (this.isNegative()) {
                if (this.eq(R)) {
                    var r = c(t), n = this.div(r), s = n.mul(r).sub(this);
                    return n.toString(t) + s.toInt().toString(t);
                } else return "-" + this.neg().toString(t);
            }
            var o = c(d(t, 6), this.unsigned), a = this;
            var l = "";
            while (true) {
                var u = a.div(o), h = a.sub(u.mul(o)).toInt() >>> 0, p = h.toString(t);
                a = u;
                if (a.isZero()) return p + l; else {
                    while (p.length < 6) p = "0" + p;
                    l = "" + p + l;
                }
            }
        };
        k.getHighBits = function e() {
            return this.high;
        };
        k.getHighBitsUnsigned = function e() {
            return this.high >>> 0;
        };
        k.getLowBits = function e() {
            return this.low;
        };
        k.getLowBitsUnsigned = function e() {
            return this.low >>> 0;
        };
        k.getNumBitsAbs = function e() {
            if (this.isNegative()) return this.eq(R) ? 64 : this.neg().getNumBitsAbs();
            var t = this.high != 0 ? this.high : this.low;
            for (var r = 31; r > 0; r--) if ((t & 1 << r) != 0) break;
            return this.high != 0 ? r + 33 : r + 1;
        };
        k.isSafeInteger = function e() {
            var t = this.high >> 21;
            if (!t) return true;
            if (this.unsigned) return false;
            return t === -1 && !(this.low === 0 && this.high === -2097152);
        };
        k.isZero = function e() {
            return this.high === 0 && this.low === 0;
        };
        k.eqz = k.isZero;
        k.isNegative = function e() {
            return !this.unsigned && this.high < 0;
        };
        k.isPositive = function e() {
            return this.unsigned || this.high >= 0;
        };
        k.isOdd = function e() {
            return (this.low & 1) === 1;
        };
        k.isEven = function e() {
            return (this.low & 1) === 0;
        };
        k.equals = function e(t) {
            if (!n(t)) t = p(t);
            if (this.unsigned !== t.unsigned && this.high >>> 31 === 1 && t.high >>> 31 === 1) return false;
            return this.high === t.high && this.low === t.low;
        };
        k.eq = k.equals;
        k.notEquals = function e(t) {
            return !this.eq(t);
        };
        k.neq = k.notEquals;
        k.ne = k.notEquals;
        k.lessThan = function e(t) {
            return this.comp(t) < 0;
        };
        k.lt = k.lessThan;
        k.lessThanOrEqual = function e(t) {
            return this.comp(t) <= 0;
        };
        k.lte = k.lessThanOrEqual;
        k.le = k.lessThanOrEqual;
        k.greaterThan = function e(t) {
            return this.comp(t) > 0;
        };
        k.gt = k.greaterThan;
        k.greaterThanOrEqual = function e(t) {
            return this.comp(t) >= 0;
        };
        k.gte = k.greaterThanOrEqual;
        k.ge = k.greaterThanOrEqual;
        k.compare = function e(t) {
            if (!n(t)) t = p(t);
            if (this.eq(t)) return 0;
            var r = this.isNegative(), s = t.isNegative();
            if (r && !s) return -1;
            if (!r && s) return 1;
            if (!this.unsigned) return this.sub(t).isNegative() ? -1 : 1;
            return t.high >>> 0 > this.high >>> 0 || t.high === this.high && t.low >>> 0 > this.low >>> 0 ? -1 : 1;
        };
        k.comp = k.compare;
        k.negate = function e() {
            if (!this.unsigned && this.eq(R)) return R;
            return this.not().add(b);
        };
        k.neg = k.negate;
        k.add = function e(t) {
            if (!n(t)) t = p(t);
            var r = this.high >>> 16;
            var s = this.high & 65535;
            var o = this.low >>> 16;
            var a = this.low & 65535;
            var l = t.high >>> 16;
            var c = t.high & 65535;
            var d = t.low >>> 16;
            var h = t.low & 65535;
            var g = 0, m = 0, _ = 0, E = 0;
            E += a + h;
            _ += E >>> 16;
            E &= 65535;
            _ += o + d;
            m += _ >>> 16;
            _ &= 65535;
            m += s + c;
            g += m >>> 16;
            m &= 65535;
            g += r + l;
            g &= 65535;
            return u(_ << 16 | E, g << 16 | m, this.unsigned);
        };
        k.subtract = function e(t) {
            if (!n(t)) t = p(t);
            return this.add(t.neg());
        };
        k.sub = k.subtract;
        k.multiply = function e(r) {
            if (this.isZero()) return this;
            if (!n(r)) r = p(r);
            if (t) {
                var s = t["mul"](this.low, this.high, r.low, r.high);
                return u(s, t["get_high"](), this.unsigned);
            }
            if (r.isZero()) return this.unsigned ? A : S;
            if (this.eq(R)) return r.isOdd() ? R : S;
            if (r.eq(R)) return this.isOdd() ? R : S;
            if (this.isNegative()) {
                if (r.isNegative()) return this.neg().mul(r.neg()); else return this.neg().mul(r).neg();
            } else if (r.isNegative()) return this.mul(r.neg()).neg();
            if (this.lt(y) && r.lt(y)) return c(this.toNumber() * r.toNumber(), this.unsigned);
            var o = this.high >>> 16;
            var a = this.high & 65535;
            var l = this.low >>> 16;
            var d = this.low & 65535;
            var h = r.high >>> 16;
            var g = r.high & 65535;
            var m = r.low >>> 16;
            var _ = r.low & 65535;
            var E = 0, v = 0, b = 0, C = 0;
            C += d * _;
            b += C >>> 16;
            C &= 65535;
            b += l * _;
            v += b >>> 16;
            b &= 65535;
            b += d * m;
            v += b >>> 16;
            b &= 65535;
            v += a * _;
            E += v >>> 16;
            v &= 65535;
            v += l * m;
            E += v >>> 16;
            v &= 65535;
            v += d * g;
            E += v >>> 16;
            v &= 65535;
            E += o * _ + a * m + l * g + d * h;
            E &= 65535;
            return u(b << 16 | C, E << 16 | v, this.unsigned);
        };
        k.mul = k.multiply;
        k.divide = function e(r) {
            if (!n(r)) r = p(r);
            if (r.isZero()) throw Error("division by zero");
            if (t) {
                if (!this.unsigned && this.high === -2147483648 && r.low === -1 && r.high === -1) {
                    return this;
                }
                var s = (this.unsigned ? t["div_u"] : t["div_s"])(this.low, this.high, r.low, r.high);
                return u(s, t["get_high"](), this.unsigned);
            }
            if (this.isZero()) return this.unsigned ? A : S;
            var o, a, l;
            if (!this.unsigned) {
                if (this.eq(R)) {
                    if (r.eq(b) || r.eq(w)) return R; else if (r.eq(R)) return b; else {
                        var h = this.shr(1);
                        o = h.div(r).shl(1);
                        if (o.eq(S)) {
                            return r.isNegative() ? b : w;
                        } else {
                            a = this.sub(r.mul(o));
                            l = o.add(a.div(r));
                            return l;
                        }
                    }
                } else if (r.eq(R)) return this.unsigned ? A : S;
                if (this.isNegative()) {
                    if (r.isNegative()) return this.neg().div(r.neg());
                    return this.neg().div(r).neg();
                } else if (r.isNegative()) return this.div(r.neg()).neg();
                l = S;
            } else {
                if (!r.unsigned) r = r.toUnsigned();
                if (r.gt(this)) return A;
                if (r.gt(this.shru(1))) return C;
                l = A;
            }
            a = this;
            while (a.gte(r)) {
                o = Math.max(1, Math.floor(a.toNumber() / r.toNumber()));
                var g = Math.ceil(Math.log(o) / Math.LN2), m = g <= 48 ? 1 : d(2, g - 48), _ = c(o), E = _.mul(r);
                while (E.isNegative() || E.gt(a)) {
                    o -= m;
                    _ = c(o, this.unsigned);
                    E = _.mul(r);
                }
                if (_.isZero()) _ = b;
                l = l.add(_);
                a = a.sub(E);
            }
            return l;
        };
        k.div = k.divide;
        k.modulo = function e(r) {
            if (!n(r)) r = p(r);
            if (t) {
                var s = (this.unsigned ? t["rem_u"] : t["rem_s"])(this.low, this.high, r.low, r.high);
                return u(s, t["get_high"](), this.unsigned);
            }
            return this.sub(this.div(r).mul(r));
        };
        k.mod = k.modulo;
        k.rem = k.modulo;
        k.not = function e() {
            return u(~this.low, ~this.high, this.unsigned);
        };
        k.countLeadingZeros = function e() {
            return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32;
        };
        k.clz = k.countLeadingZeros;
        k.countTrailingZeros = function e() {
            return this.low ? s(this.low) : s(this.high) + 32;
        };
        k.ctz = k.countTrailingZeros;
        k.and = function e(t) {
            if (!n(t)) t = p(t);
            return u(this.low & t.low, this.high & t.high, this.unsigned);
        };
        k.or = function e(t) {
            if (!n(t)) t = p(t);
            return u(this.low | t.low, this.high | t.high, this.unsigned);
        };
        k.xor = function e(t) {
            if (!n(t)) t = p(t);
            return u(this.low ^ t.low, this.high ^ t.high, this.unsigned);
        };
        k.shiftLeft = function e(t) {
            if (n(t)) t = t.toInt();
            if ((t &= 63) === 0) return this; else if (t < 32) return u(this.low << t, this.high << t | this.low >>> 32 - t, this.unsigned); else return u(0, this.low << t - 32, this.unsigned);
        };
        k.shl = k.shiftLeft;
        k.shiftRight = function e(t) {
            if (n(t)) t = t.toInt();
            if ((t &= 63) === 0) return this; else if (t < 32) return u(this.low >>> t | this.high << 32 - t, this.high >> t, this.unsigned); else return u(this.high >> t - 32, this.high >= 0 ? 0 : -1, this.unsigned);
        };
        k.shr = k.shiftRight;
        k.shiftRightUnsigned = function e(t) {
            if (n(t)) t = t.toInt();
            if ((t &= 63) === 0) return this;
            if (t < 32) return u(this.low >>> t | this.high << 32 - t, this.high >>> t, this.unsigned);
            if (t === 32) return u(this.high, 0, this.unsigned);
            return u(this.high >>> t - 32, 0, this.unsigned);
        };
        k.shru = k.shiftRightUnsigned;
        k.shr_u = k.shiftRightUnsigned;
        k.rotateLeft = function e(t) {
            var r;
            if (n(t)) t = t.toInt();
            if ((t &= 63) === 0) return this;
            if (t === 32) return u(this.high, this.low, this.unsigned);
            if (t < 32) {
                r = 32 - t;
                return u(this.low << t | this.high >>> r, this.high << t | this.low >>> r, this.unsigned);
            }
            t -= 32;
            r = 32 - t;
            return u(this.high << t | this.low >>> r, this.low << t | this.high >>> r, this.unsigned);
        };
        k.rotl = k.rotateLeft;
        k.rotateRight = function e(t) {
            var r;
            if (n(t)) t = t.toInt();
            if ((t &= 63) === 0) return this;
            if (t === 32) return u(this.high, this.low, this.unsigned);
            if (t < 32) {
                r = 32 - t;
                return u(this.high << r | this.low >>> t, this.low << r | this.high >>> t, this.unsigned);
            }
            t -= 32;
            r = 32 - t;
            return u(this.low << r | this.high >>> t, this.high << r | this.low >>> t, this.unsigned);
        };
        k.rotr = k.rotateRight;
        k.toSigned = function e() {
            if (!this.unsigned) return this;
            return u(this.low, this.high, false);
        };
        k.toUnsigned = function e() {
            if (this.unsigned) return this;
            return u(this.low, this.high, true);
        };
        k.toBytes = function e(t) {
            return t ? this.toBytesLE() : this.toBytesBE();
        };
        k.toBytesLE = function e() {
            var t = this.high, r = this.low;
            return [ r & 255, r >>> 8 & 255, r >>> 16 & 255, r >>> 24, t & 255, t >>> 8 & 255, t >>> 16 & 255, t >>> 24 ];
        };
        k.toBytesBE = function e() {
            var t = this.high, r = this.low;
            return [ t >>> 24, t >>> 16 & 255, t >>> 8 & 255, t & 255, r >>> 24, r >>> 16 & 255, r >>> 8 & 255, r & 255 ];
        };
        r.fromBytes = function e(t, n, s) {
            return s ? r.fromBytesLE(t, n) : r.fromBytesBE(t, n);
        };
        r.fromBytesLE = function e(t, n) {
            return new r(t[0] | t[1] << 8 | t[2] << 16 | t[3] << 24, t[4] | t[5] << 8 | t[6] << 16 | t[7] << 24, n);
        };
        r.fromBytesBE = function e(t, n) {
            return new r(t[4] << 24 | t[5] << 16 | t[6] << 8 | t[7], t[0] << 24 | t[1] << 16 | t[2] << 8 | t[3], n);
        };
        if (typeof BigInt === "function") {
            r.fromBigInt = function e(t, r) {
                var n = Number(BigInt.asIntN(32, t));
                var s = Number(BigInt.asIntN(32, t >> BigInt(32)));
                return u(n, s, r);
            };
            r.fromValue = function e(t, n) {
                if (typeof t === "bigint") return r.fromBigInt(t, n);
                return p(t, n);
            };
            k.toBigInt = function e() {
                var t = BigInt(this.low >>> 0);
                var r = BigInt(this.unsigned ? this.high >>> 0 : this.high);
                return r << BigInt(32) | t;
            };
        }
        e.default = r;
    });
})(umd, umd.exports);

var umdExports = umd.exports;

var hasRequiredSrc;

function requireSrc() {
    if (hasRequiredSrc) return src$2;
    hasRequiredSrc = 1;
    (function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.loadFileDescriptorSetFromObject = e.loadFileDescriptorSetFromBuffer = e.fromJSON = e.loadSync = e.load = e.IdempotencyLevel = e.isAnyExtension = e.Long = void 0;
        const t = lodash_camelcase;
        const r = protobufjs;
        const n = descriptorExports;
        const s = requireUtil();
        const o = umdExports;
        e.Long = o;
        function a(e) {
            return "@type" in e && typeof e["@type"] === "string";
        }
        e.isAnyExtension = a;
        var l;
        (function(e) {
            e["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN";
            e["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS";
            e["IDEMPOTENT"] = "IDEMPOTENT";
        })(l = e.IdempotencyLevel || (e.IdempotencyLevel = {}));
        const c = {
            longs: String,
            enums: String,
            bytes: String,
            defaults: true,
            oneofs: true,
            json: true
        };
        function u(e, t) {
            if (e === "") {
                return t;
            } else {
                return e + "." + t;
            }
        }
        function d(e) {
            return e instanceof r.Service || e instanceof r.Type || e instanceof r.Enum;
        }
        function h(e) {
            return e instanceof r.Namespace || e instanceof r.Root;
        }
        function p(e, t) {
            const r = u(t, e.name);
            if (d(e)) {
                return [ [ r, e ] ];
            } else {
                if (h(e) && typeof e.nested !== "undefined") {
                    return Object.keys(e.nested).map(t => p(e.nested[t], r)).reduce((e, t) => e.concat(t), []);
                }
            }
            return [];
        }
        function g(e, t) {
            return function r(n) {
                return e.toObject(e.decode(n), t);
            };
        }
        function m(e) {
            return function t(r) {
                if (Array.isArray(r)) {
                    throw new Error(`Failed to serialize message: expected object with ${e.name} structure, got array instead`);
                }
                const n = e.fromObject(r);
                return e.encode(n).finish();
            };
        }
        function _(e) {
            return (e || []).reduce((e, t) => {
                for (const [r, n] of Object.entries(t)) {
                    switch (r) {
                      case "uninterpreted_option":
                        e.uninterpreted_option.push(t.uninterpreted_option);
                        break;

                      default:
                        e[r] = n;
                    }
                }
                return e;
            }, {
                deprecated: false,
                idempotency_level: l.IDEMPOTENCY_UNKNOWN,
                uninterpreted_option: []
            });
        }
        function E(e, r, n, s) {
            const o = e.resolvedRequestType;
            const a = e.resolvedResponseType;
            return {
                path: "/" + r + "/" + e.name,
                requestStream: !!e.requestStream,
                responseStream: !!e.responseStream,
                requestSerialize: m(o),
                requestDeserialize: g(o, n),
                responseSerialize: m(a),
                responseDeserialize: g(a, n),
                originalName: t(e.name),
                requestType: y(o, n, s),
                responseType: y(a, n, s),
                options: _(e.parsedOptions)
            };
        }
        function v(e, t, r, n) {
            const s = {};
            for (const o of e.methodsArray) {
                s[o.name] = E(o, t, r, n);
            }
            return s;
        }
        function y(e, t, r) {
            const n = e.toDescriptor("proto3");
            return {
                format: "Protocol Buffer 3 DescriptorProto",
                type: n.$type.toObject(n, c),
                fileDescriptorProtos: r,
                serialize: m(e),
                deserialize: g(e, t)
            };
        }
        function S(e, t) {
            const r = e.toDescriptor("proto3");
            return {
                format: "Protocol Buffer 3 EnumDescriptorProto",
                type: r.$type.toObject(r, c),
                fileDescriptorProtos: t
            };
        }
        function A(e, t, n, s) {
            if (e instanceof r.Service) {
                return v(e, t, n, s);
            } else if (e instanceof r.Type) {
                return y(e, n, s);
            } else if (e instanceof r.Enum) {
                return S(e, s);
            } else {
                throw new Error("Type mismatch in reflection object handling");
            }
        }
        function b(e, t) {
            const r = {};
            e.resolveAll();
            const s = e.toDescriptor("proto3").file;
            const o = s.map(e => Buffer.from(n.FileDescriptorProto.encode(e).finish()));
            for (const [n, s] of p(e, "")) {
                r[n] = A(s, n, t, o);
            }
            return r;
        }
        function C(e, t) {
            t = t || {};
            const n = r.Root.fromDescriptor(e);
            n.resolveAll();
            return b(n, t);
        }
        function w(e, t) {
            return (0, s.loadProtosWithOptions)(e, t).then(e => b(e, t));
        }
        e.load = w;
        function I(e, t) {
            const r = (0, s.loadProtosWithOptionsSync)(e, t);
            return b(r, t);
        }
        e.loadSync = I;
        function T(e, t) {
            t = t || {};
            const n = r.Root.fromJSON(e);
            n.resolveAll();
            return b(n, t);
        }
        e.fromJSON = T;
        function R(e, t) {
            const r = n.FileDescriptorSet.decode(e);
            return C(r, t);
        }
        e.loadFileDescriptorSetFromBuffer = R;
        function k(e, t) {
            const r = n.FileDescriptorSet.fromObject(e);
            return C(r, t);
        }
        e.loadFileDescriptorSetFromObject = k;
        (0, s.addCommonProtos)();
    })(src$2);
    return src$2;
}

var hasRequiredChannelz;

function requireChannelz() {
    if (hasRequiredChannelz) return channelz;
    hasRequiredChannelz = 1;
    Object.defineProperty(channelz, "__esModule", {
        value: true
    });
    channelz.registerChannelzSocket = channelz.registerChannelzServer = channelz.registerChannelzSubchannel = channelz.registerChannelzChannel = channelz.ChannelzCallTrackerStub = channelz.ChannelzCallTracker = channelz.ChannelzChildrenTrackerStub = channelz.ChannelzChildrenTracker = channelz.ChannelzTrace = channelz.ChannelzTraceStub = void 0;
    channelz.unregisterChannelzRef = _;
    channelz.getChannelzHandlers = D;
    channelz.getChannelzServiceDefinition = U;
    channelz.setup = M;
    const e = require$$0__default$6.default;
    const t = require$$1;
    const r = connectivityState;
    const n = constants;
    const s = subchannelAddress;
    const o = requireAdmin();
    const a = requireMakeClient();
    function l(e) {
        return {
            channel_id: e.id,
            name: e.name
        };
    }
    function c(e) {
        return {
            subchannel_id: e.id,
            name: e.name
        };
    }
    function u(e) {
        return {
            server_id: e.id
        };
    }
    function d(e) {
        return {
            socket_id: e.id,
            name: e.name
        };
    }
    const h = 32;
    const p = 100;
    class ChannelzTraceStub {
        constructor() {
            this.events = [];
            this.creationTimestamp = new Date;
            this.eventsLogged = 0;
        }
        addTrace() {}
        getTraceMessage() {
            return {
                creation_timestamp: C(this.creationTimestamp),
                num_events_logged: this.eventsLogged,
                events: []
            };
        }
    }
    channelz.ChannelzTraceStub = ChannelzTraceStub;
    class ChannelzTrace {
        constructor() {
            this.events = [];
            this.eventsLogged = 0;
            this.creationTimestamp = new Date;
        }
        addTrace(e, t, r) {
            const n = new Date;
            this.events.push({
                description: t,
                severity: e,
                timestamp: n,
                childChannel: (r === null || r === void 0 ? void 0 : r.kind) === "channel" ? r : undefined,
                childSubchannel: (r === null || r === void 0 ? void 0 : r.kind) === "subchannel" ? r : undefined
            });
            if (this.events.length >= h * 2) {
                this.events = this.events.slice(h);
            }
            this.eventsLogged += 1;
        }
        getTraceMessage() {
            return {
                creation_timestamp: C(this.creationTimestamp),
                num_events_logged: this.eventsLogged,
                events: this.events.map(e => ({
                    description: e.description,
                    severity: e.severity,
                    timestamp: C(e.timestamp),
                    channel_ref: e.childChannel ? l(e.childChannel) : null,
                    subchannel_ref: e.childSubchannel ? c(e.childSubchannel) : null
                }))
            };
        }
    }
    channelz.ChannelzTrace = ChannelzTrace;
    class ChannelzChildrenTracker {
        constructor() {
            this.channelChildren = new t.OrderedMap;
            this.subchannelChildren = new t.OrderedMap;
            this.socketChildren = new t.OrderedMap;
            this.trackerMap = {
                ["channel"]: this.channelChildren,
                ["subchannel"]: this.subchannelChildren,
                ["socket"]: this.socketChildren
            };
        }
        refChild(e) {
            const t = this.trackerMap[e.kind];
            const r = t.find(e.id);
            if (r.equals(t.end())) {
                t.setElement(e.id, {
                    ref: e,
                    count: 1
                }, r);
            } else {
                r.pointer[1].count += 1;
            }
        }
        unrefChild(e) {
            const t = this.trackerMap[e.kind];
            const r = t.getElementByKey(e.id);
            if (r !== undefined) {
                r.count -= 1;
                if (r.count === 0) {
                    t.eraseElementByKey(e.id);
                }
            }
        }
        getChildLists() {
            return {
                channels: this.channelChildren,
                subchannels: this.subchannelChildren,
                sockets: this.socketChildren
            };
        }
    }
    channelz.ChannelzChildrenTracker = ChannelzChildrenTracker;
    class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker {
        refChild() {}
        unrefChild() {}
    }
    channelz.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub;
    class ChannelzCallTracker {
        constructor() {
            this.callsStarted = 0;
            this.callsSucceeded = 0;
            this.callsFailed = 0;
            this.lastCallStartedTimestamp = null;
        }
        addCallStarted() {
            this.callsStarted += 1;
            this.lastCallStartedTimestamp = new Date;
        }
        addCallSucceeded() {
            this.callsSucceeded += 1;
        }
        addCallFailed() {
            this.callsFailed += 1;
        }
    }
    channelz.ChannelzCallTracker = ChannelzCallTracker;
    class ChannelzCallTrackerStub extends ChannelzCallTracker {
        addCallStarted() {}
        addCallSucceeded() {}
        addCallFailed() {}
    }
    channelz.ChannelzCallTrackerStub = ChannelzCallTrackerStub;
    const g = {
        ["channel"]: new t.OrderedMap,
        ["subchannel"]: new t.OrderedMap,
        ["server"]: new t.OrderedMap,
        ["socket"]: new t.OrderedMap
    };
    const m = e => {
        let t = 1;
        function r() {
            return t++;
        }
        const n = g[e];
        return (t, s, o) => {
            const a = r();
            const l = {
                id: a,
                name: t,
                kind: e
            };
            if (o) {
                n.setElement(a, {
                    ref: l,
                    getInfo: s
                });
            }
            return l;
        };
    };
    channelz.registerChannelzChannel = m("channel");
    channelz.registerChannelzSubchannel = m("subchannel");
    channelz.registerChannelzServer = m("server");
    channelz.registerChannelzSocket = m("socket");
    function _(e) {
        g[e.kind].eraseElementByKey(e.id);
    }
    function E(e) {
        const t = Number.parseInt(e, 16);
        return [ t / 256 | 0, t % 256 ];
    }
    function v(e) {
        if (e === "") {
            return [];
        }
        const t = e.split(":").map(e => E(e));
        const r = [];
        return r.concat(...t);
    }
    function y(t) {
        return (0, e.isIPv6)(t) && t.toLowerCase().startsWith("::ffff:") && (0, e.isIPv4)(t.substring(7));
    }
    function S(e) {
        return Buffer.from(Uint8Array.from(e.split(".").map(e => Number.parseInt(e))));
    }
    function A(t) {
        if ((0, e.isIPv4)(t)) {
            return S(t);
        } else if (y(t)) {
            return S(t.substring(7));
        } else if ((0, e.isIPv6)(t)) {
            let e;
            let r;
            const n = t.indexOf("::");
            if (n === -1) {
                e = t;
                r = "";
            } else {
                e = t.substring(0, n);
                r = t.substring(n + 2);
            }
            const s = Buffer.from(v(e));
            const o = Buffer.from(v(r));
            const a = Buffer.alloc(16 - s.length - o.length, 0);
            return Buffer.concat([ s, a, o ]);
        } else {
            return null;
        }
    }
    function b(e) {
        switch (e) {
          case r.ConnectivityState.CONNECTING:
            return {
                state: "CONNECTING"
            };

          case r.ConnectivityState.IDLE:
            return {
                state: "IDLE"
            };

          case r.ConnectivityState.READY:
            return {
                state: "READY"
            };

          case r.ConnectivityState.SHUTDOWN:
            return {
                state: "SHUTDOWN"
            };

          case r.ConnectivityState.TRANSIENT_FAILURE:
            return {
                state: "TRANSIENT_FAILURE"
            };

          default:
            return {
                state: "UNKNOWN"
            };
        }
    }
    function C(e) {
        if (!e) {
            return null;
        }
        const t = e.getTime();
        return {
            seconds: t / 1e3 | 0,
            nanos: t % 1e3 * 1e6
        };
    }
    function w(e) {
        const t = e.getInfo();
        const r = [];
        const n = [];
        t.children.channels.forEach(e => {
            r.push(l(e[1].ref));
        });
        t.children.subchannels.forEach(e => {
            n.push(c(e[1].ref));
        });
        return {
            ref: l(e.ref),
            data: {
                target: t.target,
                state: b(t.state),
                calls_started: t.callTracker.callsStarted,
                calls_succeeded: t.callTracker.callsSucceeded,
                calls_failed: t.callTracker.callsFailed,
                last_call_started_timestamp: C(t.callTracker.lastCallStartedTimestamp),
                trace: t.trace.getTraceMessage()
            },
            channel_ref: r,
            subchannel_ref: n
        };
    }
    function I(e, t) {
        const r = parseInt(e.request.channel_id, 10);
        const s = g["channel"].getElementByKey(r);
        if (s === undefined) {
            t({
                code: n.Status.NOT_FOUND,
                details: "No channel data found for id " + r
            });
            return;
        }
        t(null, {
            channel: w(s)
        });
    }
    function T(e, t) {
        const r = parseInt(e.request.max_results, 10) || p;
        const n = [];
        const s = parseInt(e.request.start_channel_id, 10);
        const o = g["channel"];
        let a;
        for (a = o.lowerBound(s); !a.equals(o.end()) && n.length < r; a = a.next()) {
            n.push(w(a.pointer[1]));
        }
        t(null, {
            channel: n,
            end: a.equals(o.end())
        });
    }
    function R(e) {
        const t = e.getInfo();
        const r = [];
        t.listenerChildren.sockets.forEach(e => {
            r.push(d(e[1].ref));
        });
        return {
            ref: u(e.ref),
            data: {
                calls_started: t.callTracker.callsStarted,
                calls_succeeded: t.callTracker.callsSucceeded,
                calls_failed: t.callTracker.callsFailed,
                last_call_started_timestamp: C(t.callTracker.lastCallStartedTimestamp),
                trace: t.trace.getTraceMessage()
            },
            listen_socket: r
        };
    }
    function k(e, t) {
        const r = parseInt(e.request.server_id, 10);
        const s = g["server"];
        const o = s.getElementByKey(r);
        if (o === undefined) {
            t({
                code: n.Status.NOT_FOUND,
                details: "No server data found for id " + r
            });
            return;
        }
        t(null, {
            server: R(o)
        });
    }
    function P(e, t) {
        const r = parseInt(e.request.max_results, 10) || p;
        const n = parseInt(e.request.start_server_id, 10);
        const s = g["server"];
        const o = [];
        let a;
        for (a = s.lowerBound(n); !a.equals(s.end()) && o.length < r; a = a.next()) {
            o.push(R(a.pointer[1]));
        }
        t(null, {
            server: o,
            end: a.equals(s.end())
        });
    }
    function $(e, t) {
        const r = parseInt(e.request.subchannel_id, 10);
        const s = g["subchannel"].getElementByKey(r);
        if (s === undefined) {
            t({
                code: n.Status.NOT_FOUND,
                details: "No subchannel data found for id " + r
            });
            return;
        }
        const o = s.getInfo();
        const a = [];
        o.children.sockets.forEach(e => {
            a.push(d(e[1].ref));
        });
        const l = {
            ref: c(s.ref),
            data: {
                target: o.target,
                state: b(o.state),
                calls_started: o.callTracker.callsStarted,
                calls_succeeded: o.callTracker.callsSucceeded,
                calls_failed: o.callTracker.callsFailed,
                last_call_started_timestamp: C(o.callTracker.lastCallStartedTimestamp),
                trace: o.trace.getTraceMessage()
            },
            socket_ref: a
        };
        t(null, {
            subchannel: l
        });
    }
    function O(e) {
        var t;
        if ((0, s.isTcpSubchannelAddress)(e)) {
            return {
                address: "tcpip_address",
                tcpip_address: {
                    ip_address: (t = A(e.host)) !== null && t !== void 0 ? t : undefined,
                    port: e.port
                }
            };
        } else {
            return {
                address: "uds_address",
                uds_address: {
                    filename: e.path
                }
            };
        }
    }
    function B(e, t) {
        var r, s, o, a, l;
        const c = parseInt(e.request.socket_id, 10);
        const u = g["socket"].getElementByKey(c);
        if (u === undefined) {
            t({
                code: n.Status.NOT_FOUND,
                details: "No socket data found for id " + c
            });
            return;
        }
        const h = u.getInfo();
        const p = h.security ? {
            model: "tls",
            tls: {
                cipher_suite: h.security.cipherSuiteStandardName ? "standard_name" : "other_name",
                standard_name: (r = h.security.cipherSuiteStandardName) !== null && r !== void 0 ? r : undefined,
                other_name: (s = h.security.cipherSuiteOtherName) !== null && s !== void 0 ? s : undefined,
                local_certificate: (o = h.security.localCertificate) !== null && o !== void 0 ? o : undefined,
                remote_certificate: (a = h.security.remoteCertificate) !== null && a !== void 0 ? a : undefined
            }
        } : null;
        const m = {
            ref: d(u.ref),
            local: h.localAddress ? O(h.localAddress) : null,
            remote: h.remoteAddress ? O(h.remoteAddress) : null,
            remote_name: (l = h.remoteName) !== null && l !== void 0 ? l : undefined,
            security: p,
            data: {
                keep_alives_sent: h.keepAlivesSent,
                streams_started: h.streamsStarted,
                streams_succeeded: h.streamsSucceeded,
                streams_failed: h.streamsFailed,
                last_local_stream_created_timestamp: C(h.lastLocalStreamCreatedTimestamp),
                last_remote_stream_created_timestamp: C(h.lastRemoteStreamCreatedTimestamp),
                messages_received: h.messagesReceived,
                messages_sent: h.messagesSent,
                last_message_received_timestamp: C(h.lastMessageReceivedTimestamp),
                last_message_sent_timestamp: C(h.lastMessageSentTimestamp),
                local_flow_control_window: h.localFlowControlWindow ? {
                    value: h.localFlowControlWindow
                } : null,
                remote_flow_control_window: h.remoteFlowControlWindow ? {
                    value: h.remoteFlowControlWindow
                } : null
            }
        };
        t(null, {
            socket: m
        });
    }
    function N(e, t) {
        const r = parseInt(e.request.server_id, 10);
        const s = g["server"].getElementByKey(r);
        if (s === undefined) {
            t({
                code: n.Status.NOT_FOUND,
                details: "No server data found for id " + r
            });
            return;
        }
        const o = parseInt(e.request.start_socket_id, 10);
        const a = parseInt(e.request.max_results, 10) || p;
        const l = s.getInfo();
        const c = l.sessionChildren.sockets;
        const u = [];
        let h;
        for (h = c.lowerBound(o); !h.equals(c.end()) && u.length < a; h = h.next()) {
            u.push(d(h.pointer[1].ref));
        }
        t(null, {
            socket_ref: u,
            end: h.equals(c.end())
        });
    }
    function D() {
        return {
            GetChannel: I,
            GetTopChannels: T,
            GetServer: k,
            GetServers: P,
            GetSubchannel: $,
            GetSocket: B,
            GetServerSockets: N
        };
    }
    let L = null;
    function U() {
        if (L) {
            return L;
        }
        const e = requireSrc().loadSync;
        const t = e("channelz.proto", {
            keepCase: true,
            longs: String,
            enums: String,
            defaults: true,
            oneofs: true,
            includeDirs: [ `${__dirname}/../../proto` ]
        });
        const r = (0, a.loadPackageDefinition)(t);
        L = r.grpc.channelz.v1.Channelz.service;
        return L;
    }
    function M() {
        (0, o.registerAdminService)(U, D);
    }
    return channelz;
}

var singleSubchannelChannel = {};

var callNumber = {};

Object.defineProperty(callNumber, "__esModule", {
    value: true
});

callNumber.getNextCallNumber = getNextCallNumber;

let nextCallNumber = 0;

function getNextCallNumber() {
    return nextCallNumber++;
}

var compressionFilter = {};

var compressionAlgorithms = {};

Object.defineProperty(compressionAlgorithms, "__esModule", {
    value: true
});

compressionAlgorithms.CompressionAlgorithms = void 0;

var CompressionAlgorithms;

(function(e) {
    e[e["identity"] = 0] = "identity";
    e[e["deflate"] = 1] = "deflate";
    e[e["gzip"] = 2] = "gzip";
})(CompressionAlgorithms || (compressionAlgorithms.CompressionAlgorithms = CompressionAlgorithms = {}));

var filter = {};

var hasRequiredFilter;

function requireFilter() {
    if (hasRequiredFilter) return filter;
    hasRequiredFilter = 1;
    Object.defineProperty(filter, "__esModule", {
        value: true
    });
    filter.BaseFilter = void 0;
    class BaseFilter {
        async sendMetadata(e) {
            return e;
        }
        receiveMetadata(e) {
            return e;
        }
        async sendMessage(e) {
            return e;
        }
        async receiveMessage(e) {
            return e;
        }
        receiveTrailers(e) {
            return e;
        }
    }
    filter.BaseFilter = BaseFilter;
    return filter;
}

Object.defineProperty(compressionFilter, "__esModule", {
    value: true
});

compressionFilter.CompressionFilterFactory = compressionFilter.CompressionFilter = void 0;

const zlib = require$$4__default$2.default;

const compression_algorithms_1 = compressionAlgorithms;

const constants_1$8 = constants;

const filter_1 = requireFilter();

const logging$6 = logging$8;

const isCompressionAlgorithmKey = e => typeof e === "number" && typeof compression_algorithms_1.CompressionAlgorithms[e] === "string";

class CompressionHandler {
    async writeMessage(e, t) {
        let r = e;
        if (t) {
            r = await this.compressMessage(r);
        }
        const n = Buffer.allocUnsafe(r.length + 5);
        n.writeUInt8(t ? 1 : 0, 0);
        n.writeUInt32BE(r.length, 1);
        r.copy(n, 5);
        return n;
    }
    async readMessage(e) {
        const t = e.readUInt8(0) === 1;
        let r = e.slice(5);
        if (t) {
            r = await this.decompressMessage(r);
        }
        return r;
    }
}

class IdentityHandler extends CompressionHandler {
    async compressMessage(e) {
        return e;
    }
    async writeMessage(e, t) {
        const r = Buffer.allocUnsafe(e.length + 5);
        r.writeUInt8(0, 0);
        r.writeUInt32BE(e.length, 1);
        e.copy(r, 5);
        return r;
    }
    decompressMessage(e) {
        return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity'));
    }
}

class DeflateHandler extends CompressionHandler {
    constructor(e) {
        super();
        this.maxRecvMessageLength = e;
    }
    compressMessage(e) {
        return new Promise((t, r) => {
            zlib.deflate(e, (e, n) => {
                if (e) {
                    r(e);
                } else {
                    t(n);
                }
            });
        });
    }
    decompressMessage(e) {
        return new Promise((t, r) => {
            let n = 0;
            const s = [];
            const o = zlib.createInflate();
            o.on("data", e => {
                s.push(e);
                n += e.byteLength;
                if (this.maxRecvMessageLength !== -1 && n > this.maxRecvMessageLength) {
                    o.destroy();
                    r({
                        code: constants_1$8.Status.RESOURCE_EXHAUSTED,
                        details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
                    });
                }
            });
            o.on("end", () => {
                t(Buffer.concat(s));
            });
            o.write(e);
            o.end();
        });
    }
}

class GzipHandler extends CompressionHandler {
    constructor(e) {
        super();
        this.maxRecvMessageLength = e;
    }
    compressMessage(e) {
        return new Promise((t, r) => {
            zlib.gzip(e, (e, n) => {
                if (e) {
                    r(e);
                } else {
                    t(n);
                }
            });
        });
    }
    decompressMessage(e) {
        return new Promise((t, r) => {
            let n = 0;
            const s = [];
            const o = zlib.createGunzip();
            o.on("data", e => {
                s.push(e);
                n += e.byteLength;
                if (this.maxRecvMessageLength !== -1 && n > this.maxRecvMessageLength) {
                    o.destroy();
                    r({
                        code: constants_1$8.Status.RESOURCE_EXHAUSTED,
                        details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}`
                    });
                }
            });
            o.on("end", () => {
                t(Buffer.concat(s));
            });
            o.write(e);
            o.end();
        });
    }
}

class UnknownHandler extends CompressionHandler {
    constructor(e) {
        super();
        this.compressionName = e;
    }
    compressMessage(e) {
        return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`));
    }
    decompressMessage(e) {
        return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`));
    }
}

function getCompressionHandler(e, t) {
    switch (e) {
      case "identity":
        return new IdentityHandler;

      case "deflate":
        return new DeflateHandler(t);

      case "gzip":
        return new GzipHandler(t);

      default:
        return new UnknownHandler(e);
    }
}

class CompressionFilter extends filter_1.BaseFilter {
    constructor(e, t) {
        var r, n, s;
        super();
        this.sharedFilterConfig = t;
        this.sendCompression = new IdentityHandler;
        this.receiveCompression = new IdentityHandler;
        this.currentCompressionAlgorithm = "identity";
        const o = e["grpc.default_compression_algorithm"];
        this.maxReceiveMessageLength = (r = e["grpc.max_receive_message_length"]) !== null && r !== void 0 ? r : constants_1$8.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.maxSendMessageLength = (n = e["grpc.max_send_message_length"]) !== null && n !== void 0 ? n : constants_1$8.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
        if (o !== undefined) {
            if (isCompressionAlgorithmKey(o)) {
                const e = compression_algorithms_1.CompressionAlgorithms[o];
                const r = (s = t.serverSupportedEncodingHeader) === null || s === void 0 ? void 0 : s.split(",");
                if (!r || r.includes(e)) {
                    this.currentCompressionAlgorithm = e;
                    this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1);
                }
            } else {
                logging$6.log(constants_1$8.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${o}`);
            }
        }
    }
    async sendMetadata(e) {
        const t = await e;
        t.set("grpc-accept-encoding", "identity,deflate,gzip");
        t.set("accept-encoding", "identity");
        if (this.currentCompressionAlgorithm === "identity") {
            t.remove("grpc-encoding");
        } else {
            t.set("grpc-encoding", this.currentCompressionAlgorithm);
        }
        return t;
    }
    receiveMetadata(e) {
        const t = e.get("grpc-encoding");
        if (t.length > 0) {
            const e = t[0];
            if (typeof e === "string") {
                this.receiveCompression = getCompressionHandler(e, this.maxReceiveMessageLength);
            }
        }
        e.remove("grpc-encoding");
        const r = e.get("grpc-accept-encoding")[0];
        if (r) {
            this.sharedFilterConfig.serverSupportedEncodingHeader = r;
            const e = r.split(",");
            if (!e.includes(this.currentCompressionAlgorithm)) {
                this.sendCompression = new IdentityHandler;
                this.currentCompressionAlgorithm = "identity";
            }
        }
        e.remove("grpc-accept-encoding");
        return e;
    }
    async sendMessage(e) {
        var t;
        const r = await e;
        if (this.maxSendMessageLength !== -1 && r.message.length > this.maxSendMessageLength) {
            throw {
                code: constants_1$8.Status.RESOURCE_EXHAUSTED,
                details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}`
            };
        }
        let n;
        if (this.sendCompression instanceof IdentityHandler) {
            n = false;
        } else {
            n = (((t = r.flags) !== null && t !== void 0 ? t : 0) & 2) === 0;
        }
        return {
            message: await this.sendCompression.writeMessage(r.message, n),
            flags: r.flags
        };
    }
    async receiveMessage(e) {
        return this.receiveCompression.readMessage(await e);
    }
}

compressionFilter.CompressionFilter = CompressionFilter;

class CompressionFilterFactory {
    constructor(e, t) {
        this.options = t;
        this.sharedFilterConfig = {};
    }
    createFilter() {
        return new CompressionFilter(this.options, this.sharedFilterConfig);
    }
}

compressionFilter.CompressionFilterFactory = CompressionFilterFactory;

var controlPlaneStatus = {};

Object.defineProperty(controlPlaneStatus, "__esModule", {
    value: true
});

controlPlaneStatus.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode;

const constants_1$7 = constants;

const INAPPROPRIATE_CONTROL_PLANE_CODES = [ constants_1$7.Status.OK, constants_1$7.Status.INVALID_ARGUMENT, constants_1$7.Status.NOT_FOUND, constants_1$7.Status.ALREADY_EXISTS, constants_1$7.Status.FAILED_PRECONDITION, constants_1$7.Status.ABORTED, constants_1$7.Status.OUT_OF_RANGE, constants_1$7.Status.DATA_LOSS ];

function restrictControlPlaneStatusCode(e, t) {
    if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(e)) {
        return {
            code: constants_1$7.Status.INTERNAL,
            details: `Invalid status from control plane: ${e} ${constants_1$7.Status[e]} ${t}`
        };
    } else {
        return {
            code: e,
            details: t
        };
    }
}

var deadline = {};

Object.defineProperty(deadline, "__esModule", {
    value: true
});

deadline.minDeadline = minDeadline;

deadline.getDeadlineTimeoutString = getDeadlineTimeoutString;

deadline.getRelativeTimeout = getRelativeTimeout;

deadline.deadlineToString = deadlineToString;

deadline.formatDateDifference = formatDateDifference;

function minDeadline(...e) {
    let t = Infinity;
    for (const r of e) {
        const e = r instanceof Date ? r.getTime() : r;
        if (e < t) {
            t = e;
        }
    }
    return t;
}

const units = [ [ "m", 1 ], [ "S", 1e3 ], [ "M", 60 * 1e3 ], [ "H", 60 * 60 * 1e3 ] ];

function getDeadlineTimeoutString(e) {
    const t = (new Date).getTime();
    if (e instanceof Date) {
        e = e.getTime();
    }
    const r = Math.max(e - t, 0);
    for (const [e, t] of units) {
        const n = r / t;
        if (n < 1e8) {
            return String(Math.ceil(n)) + e;
        }
    }
    throw new Error("Deadline is too far in the future");
}

const MAX_TIMEOUT_TIME = 2147483647;

function getRelativeTimeout(e) {
    const t = e instanceof Date ? e.getTime() : e;
    const r = (new Date).getTime();
    const n = t - r;
    if (n < 0) {
        return 0;
    } else if (n > MAX_TIMEOUT_TIME) {
        return Infinity;
    } else {
        return n;
    }
}

function deadlineToString(e) {
    if (e instanceof Date) {
        return e.toISOString();
    } else {
        const t = new Date(e);
        if (Number.isNaN(t.getTime())) {
            return "" + e;
        } else {
            return t.toISOString();
        }
    }
}

function formatDateDifference(e, t) {
    return ((t.getTime() - e.getTime()) / 1e3).toFixed(3) + "s";
}

var filterStack = {};

var hasRequiredFilterStack;

function requireFilterStack() {
    if (hasRequiredFilterStack) return filterStack;
    hasRequiredFilterStack = 1;
    Object.defineProperty(filterStack, "__esModule", {
        value: true
    });
    filterStack.FilterStackFactory = filterStack.FilterStack = void 0;
    class FilterStack {
        constructor(e) {
            this.filters = e;
        }
        sendMetadata(e) {
            let t = e;
            for (let e = 0; e < this.filters.length; e++) {
                t = this.filters[e].sendMetadata(t);
            }
            return t;
        }
        receiveMetadata(e) {
            let t = e;
            for (let e = this.filters.length - 1; e >= 0; e--) {
                t = this.filters[e].receiveMetadata(t);
            }
            return t;
        }
        sendMessage(e) {
            let t = e;
            for (let e = 0; e < this.filters.length; e++) {
                t = this.filters[e].sendMessage(t);
            }
            return t;
        }
        receiveMessage(e) {
            let t = e;
            for (let e = this.filters.length - 1; e >= 0; e--) {
                t = this.filters[e].receiveMessage(t);
            }
            return t;
        }
        receiveTrailers(e) {
            let t = e;
            for (let e = this.filters.length - 1; e >= 0; e--) {
                t = this.filters[e].receiveTrailers(t);
            }
            return t;
        }
        push(e) {
            this.filters.unshift(...e);
        }
        getFilters() {
            return this.filters;
        }
    }
    filterStack.FilterStack = FilterStack;
    class FilterStackFactory {
        constructor(e) {
            this.factories = e;
        }
        push(e) {
            this.factories.unshift(...e);
        }
        clone() {
            return new FilterStackFactory([ ...this.factories ]);
        }
        createFilter() {
            return new FilterStack(this.factories.map(e => e.createFilter()));
        }
    }
    filterStack.FilterStackFactory = FilterStackFactory;
    return filterStack;
}

var hasRequiredSingleSubchannelChannel;

function requireSingleSubchannelChannel() {
    if (hasRequiredSingleSubchannelChannel) return singleSubchannelChannel;
    hasRequiredSingleSubchannelChannel = 1;
    Object.defineProperty(singleSubchannelChannel, "__esModule", {
        value: true
    });
    singleSubchannelChannel.SingleSubchannelChannel = void 0;
    const e = callNumber;
    const t = requireChannelz();
    const r = compressionFilter;
    const n = connectivityState;
    const s = constants;
    const o = controlPlaneStatus;
    const a = deadline;
    const l = requireFilterStack();
    const c = metadata;
    const u = resolver;
    const d = uriParser;
    class SubchannelCallWrapper {
        constructor(e, t, r, n, o) {
            var l, c;
            this.subchannel = e;
            this.method = t;
            this.options = n;
            this.callNumber = o;
            this.childCall = null;
            this.pendingMessage = null;
            this.readPending = false;
            this.halfClosePending = false;
            this.pendingStatus = null;
            this.readFilterPending = false;
            this.writeFilterPending = false;
            const u = this.method.split("/");
            let h = "";
            if (u.length >= 2) {
                h = u[1];
            }
            const p = (c = (l = (0, d.splitHostPort)(this.options.host)) === null || l === void 0 ? void 0 : l.host) !== null && c !== void 0 ? c : "localhost";
            this.serviceUrl = `https://${p}/${h}`;
            const g = (0, a.getRelativeTimeout)(n.deadline);
            if (g !== Infinity) {
                if (g <= 0) {
                    this.cancelWithStatus(s.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
                } else {
                    setTimeout(() => {
                        this.cancelWithStatus(s.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
                    }, g);
                }
            }
            this.filterStack = r.createFilter();
        }
        cancelWithStatus(e, t) {
            if (this.childCall) {
                this.childCall.cancelWithStatus(e, t);
            } else {
                this.pendingStatus = {
                    code: e,
                    details: t,
                    metadata: new c.Metadata
                };
            }
        }
        getPeer() {
            var e, t;
            return (t = (e = this.childCall) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : this.subchannel.getAddress();
        }
        async start(e, t) {
            if (this.pendingStatus) {
                t.onReceiveStatus(this.pendingStatus);
                return;
            }
            if (this.subchannel.getConnectivityState() !== n.ConnectivityState.READY) {
                t.onReceiveStatus({
                    code: s.Status.UNAVAILABLE,
                    details: "Subchannel not ready",
                    metadata: new c.Metadata
                });
                return;
            }
            const r = await this.filterStack.sendMetadata(Promise.resolve(e));
            let a;
            try {
                a = await this.subchannel.getCallCredentials().generateMetadata({
                    method_name: this.method,
                    service_url: this.serviceUrl
                });
            } catch (e) {
                const r = e;
                const {code: n, details: a} = (0, o.restrictControlPlaneStatusCode)(typeof r.code === "number" ? r.code : s.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${r.message}`);
                t.onReceiveStatus({
                    code: n,
                    details: a,
                    metadata: new c.Metadata
                });
                return;
            }
            a.merge(r);
            const l = {
                onReceiveMetadata: async e => {
                    t.onReceiveMetadata(await this.filterStack.receiveMetadata(e));
                },
                onReceiveMessage: async e => {
                    this.readFilterPending = true;
                    const r = await this.filterStack.receiveMessage(e);
                    this.readFilterPending = false;
                    t.onReceiveMessage(r);
                    if (this.pendingStatus) {
                        t.onReceiveStatus(this.pendingStatus);
                    }
                },
                onReceiveStatus: async e => {
                    const r = await this.filterStack.receiveTrailers(e);
                    if (this.readFilterPending) {
                        this.pendingStatus = r;
                    } else {
                        t.onReceiveStatus(r);
                    }
                }
            };
            this.childCall = this.subchannel.createCall(a, this.options.host, this.method, l);
            if (this.readPending) {
                this.childCall.startRead();
            }
            if (this.pendingMessage) {
                this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message);
            }
            if (this.halfClosePending && !this.writeFilterPending) {
                this.childCall.halfClose();
            }
        }
        async sendMessageWithContext(e, t) {
            this.writeFilterPending = true;
            const r = await this.filterStack.sendMessage(Promise.resolve({
                message: t,
                flags: e.flags
            }));
            this.writeFilterPending = false;
            if (this.childCall) {
                this.childCall.sendMessageWithContext(e, r.message);
                if (this.halfClosePending) {
                    this.childCall.halfClose();
                }
            } else {
                this.pendingMessage = {
                    context: e,
                    message: r.message
                };
            }
        }
        startRead() {
            if (this.childCall) {
                this.childCall.startRead();
            } else {
                this.readPending = true;
            }
        }
        halfClose() {
            if (this.childCall && !this.writeFilterPending) {
                this.childCall.halfClose();
            } else {
                this.halfClosePending = true;
            }
        }
        getCallNumber() {
            return this.callNumber;
        }
        setCredentials(e) {
            throw new Error("Method not implemented.");
        }
        getAuthContext() {
            if (this.childCall) {
                return this.childCall.getAuthContext();
            } else {
                return null;
            }
        }
    }
    class SingleSubchannelChannel {
        constructor(e, n, s) {
            this.subchannel = e;
            this.target = n;
            this.channelzEnabled = false;
            this.channelzTrace = new t.ChannelzTrace;
            this.callTracker = new t.ChannelzCallTracker;
            this.childrenTracker = new t.ChannelzChildrenTracker;
            this.channelzEnabled = s["grpc.enable_channelz"] !== 0;
            this.channelzRef = (0, t.registerChannelzChannel)((0, d.uriToString)(n), () => ({
                target: `${(0, d.uriToString)(n)} (${e.getAddress()})`,
                state: this.subchannel.getConnectivityState(),
                trace: this.channelzTrace,
                callTracker: this.callTracker,
                children: this.childrenTracker.getChildLists()
            }), this.channelzEnabled);
            if (this.channelzEnabled) {
                this.childrenTracker.refChild(e.getChannelzRef());
            }
            this.filterStackFactory = new l.FilterStackFactory([ new r.CompressionFilterFactory(this, s) ]);
        }
        close() {
            if (this.channelzEnabled) {
                this.childrenTracker.unrefChild(this.subchannel.getChannelzRef());
            }
            (0, t.unregisterChannelzRef)(this.channelzRef);
        }
        getTarget() {
            return (0, d.uriToString)(this.target);
        }
        getConnectivityState(e) {
            throw new Error("Method not implemented.");
        }
        watchConnectivityState(e, t, r) {
            throw new Error("Method not implemented.");
        }
        getChannelzRef() {
            return this.channelzRef;
        }
        createCall(t, r) {
            const n = {
                deadline: r,
                host: (0, u.getDefaultAuthority)(this.target),
                flags: s.Propagate.DEFAULTS,
                parentCall: null
            };
            return new SubchannelCallWrapper(this.subchannel, t, this.filterStackFactory, n, (0, 
            e.getNextCallNumber)());
        }
    }
    singleSubchannelChannel.SingleSubchannelChannel = SingleSubchannelChannel;
    return singleSubchannelChannel;
}

var hasRequiredSubchannel;

function requireSubchannel() {
    if (hasRequiredSubchannel) return subchannel;
    hasRequiredSubchannel = 1;
    Object.defineProperty(subchannel, "__esModule", {
        value: true
    });
    subchannel.Subchannel = void 0;
    const e = connectivityState;
    const t = requireBackoffTimeout();
    const r = logging$8;
    const n = constants;
    const s = uriParser;
    const o = subchannelAddress;
    const a = requireChannelz();
    const l = requireSingleSubchannelChannel();
    const c = "subchannel";
    const u = 2147483647;
    class Subchannel {
        constructor(r, n, s, l, c) {
            var u;
            this.channelTarget = r;
            this.subchannelAddress = n;
            this.options = s;
            this.connector = c;
            this.connectivityState = e.ConnectivityState.IDLE;
            this.transport = null;
            this.continueConnecting = false;
            this.stateListeners = new Set;
            this.refcount = 0;
            this.channelzEnabled = true;
            this.dataProducers = new Map;
            this.subchannelChannel = null;
            const d = {
                initialDelay: s["grpc.initial_reconnect_backoff_ms"],
                maxDelay: s["grpc.max_reconnect_backoff_ms"]
            };
            this.backoffTimeout = new t.BackoffTimeout(() => {
                this.handleBackoffTimer();
            }, d);
            this.backoffTimeout.unref();
            this.subchannelAddressString = (0, o.subchannelAddressToString)(n);
            this.keepaliveTime = (u = s["grpc.keepalive_time_ms"]) !== null && u !== void 0 ? u : -1;
            if (s["grpc.enable_channelz"] === 0) {
                this.channelzEnabled = false;
                this.channelzTrace = new a.ChannelzTraceStub;
                this.callTracker = new a.ChannelzCallTrackerStub;
                this.childrenTracker = new a.ChannelzChildrenTrackerStub;
                this.streamTracker = new a.ChannelzCallTrackerStub;
            } else {
                this.channelzTrace = new a.ChannelzTrace;
                this.callTracker = new a.ChannelzCallTracker;
                this.childrenTracker = new a.ChannelzChildrenTracker;
                this.streamTracker = new a.ChannelzCallTracker;
            }
            this.channelzRef = (0, a.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
            this.channelzTrace.addTrace("CT_INFO", "Subchannel created");
            this.trace("Subchannel constructed with options " + JSON.stringify(s, undefined, 2));
            this.secureConnector = l._createSecureConnector(r, s);
        }
        getChannelzInfo() {
            return {
                state: this.connectivityState,
                trace: this.channelzTrace,
                callTracker: this.callTracker,
                children: this.childrenTracker.getChildLists(),
                target: this.subchannelAddressString
            };
        }
        trace(e) {
            r.trace(n.LogVerbosity.DEBUG, c, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        refTrace(e) {
            r.trace(n.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        handleBackoffTimer() {
            if (this.continueConnecting) {
                this.transitionToState([ e.ConnectivityState.TRANSIENT_FAILURE ], e.ConnectivityState.CONNECTING);
            } else {
                this.transitionToState([ e.ConnectivityState.TRANSIENT_FAILURE ], e.ConnectivityState.IDLE);
            }
        }
        startBackoff() {
            this.backoffTimeout.runOnce();
        }
        stopBackoff() {
            this.backoffTimeout.stop();
            this.backoffTimeout.reset();
        }
        startConnectingInternal() {
            let t = this.options;
            if (t["grpc.keepalive_time_ms"]) {
                const e = Math.min(this.keepaliveTime, u);
                t = Object.assign(Object.assign({}, t), {
                    "grpc.keepalive_time_ms": e
                });
            }
            this.connector.connect(this.subchannelAddress, this.secureConnector, t).then(t => {
                if (this.transitionToState([ e.ConnectivityState.CONNECTING ], e.ConnectivityState.READY)) {
                    this.transport = t;
                    if (this.channelzEnabled) {
                        this.childrenTracker.refChild(t.getChannelzRef());
                    }
                    t.addDisconnectListener(t => {
                        this.transitionToState([ e.ConnectivityState.READY ], e.ConnectivityState.IDLE);
                        if (t && this.keepaliveTime > 0) {
                            this.keepaliveTime *= 2;
                            r.log(n.LogVerbosity.ERROR, `Connection to ${(0, s.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`);
                        }
                    });
                } else {
                    t.shutdown();
                }
            }, t => {
                this.transitionToState([ e.ConnectivityState.CONNECTING ], e.ConnectivityState.TRANSIENT_FAILURE, `${t}`);
            });
        }
        transitionToState(t, r, n) {
            var s, o;
            if (t.indexOf(this.connectivityState) === -1) {
                return false;
            }
            if (n) {
                this.trace(e.ConnectivityState[this.connectivityState] + " -> " + e.ConnectivityState[r] + ' with error "' + n + '"');
            } else {
                this.trace(e.ConnectivityState[this.connectivityState] + " -> " + e.ConnectivityState[r]);
            }
            if (this.channelzEnabled) {
                this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + e.ConnectivityState[r]);
            }
            const a = this.connectivityState;
            this.connectivityState = r;
            switch (r) {
              case e.ConnectivityState.READY:
                this.stopBackoff();
                break;

              case e.ConnectivityState.CONNECTING:
                this.startBackoff();
                this.startConnectingInternal();
                this.continueConnecting = false;
                break;

              case e.ConnectivityState.TRANSIENT_FAILURE:
                if (this.channelzEnabled && this.transport) {
                    this.childrenTracker.unrefChild(this.transport.getChannelzRef());
                }
                (s = this.transport) === null || s === void 0 ? void 0 : s.shutdown();
                this.transport = null;
                if (!this.backoffTimeout.isRunning()) {
                    process.nextTick(() => {
                        this.handleBackoffTimer();
                    });
                }
                break;

              case e.ConnectivityState.IDLE:
                if (this.channelzEnabled && this.transport) {
                    this.childrenTracker.unrefChild(this.transport.getChannelzRef());
                }
                (o = this.transport) === null || o === void 0 ? void 0 : o.shutdown();
                this.transport = null;
                break;

              default:
                throw new Error(`Invalid state: unknown ConnectivityState ${r}`);
            }
            for (const e of this.stateListeners) {
                e(this, a, r, this.keepaliveTime, n);
            }
            return true;
        }
        ref() {
            this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1));
            this.refcount += 1;
        }
        unref() {
            this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1));
            this.refcount -= 1;
            if (this.refcount === 0) {
                this.channelzTrace.addTrace("CT_INFO", "Shutting down");
                (0, a.unregisterChannelzRef)(this.channelzRef);
                this.secureConnector.destroy();
                process.nextTick(() => {
                    this.transitionToState([ e.ConnectivityState.CONNECTING, e.ConnectivityState.READY ], e.ConnectivityState.IDLE);
                });
            }
        }
        unrefIfOneRef() {
            if (this.refcount === 1) {
                this.unref();
                return true;
            }
            return false;
        }
        createCall(e, t, r, s) {
            if (!this.transport) {
                throw new Error("Cannot create call, subchannel not READY");
            }
            let o;
            if (this.channelzEnabled) {
                this.callTracker.addCallStarted();
                this.streamTracker.addCallStarted();
                o = {
                    onCallEnd: e => {
                        if (e.code === n.Status.OK) {
                            this.callTracker.addCallSucceeded();
                        } else {
                            this.callTracker.addCallFailed();
                        }
                    }
                };
            } else {
                o = {};
            }
            return this.transport.createCall(e, t, r, s, o);
        }
        startConnecting() {
            process.nextTick(() => {
                if (!this.transitionToState([ e.ConnectivityState.IDLE ], e.ConnectivityState.CONNECTING)) {
                    if (this.connectivityState === e.ConnectivityState.TRANSIENT_FAILURE) {
                        this.continueConnecting = true;
                    }
                }
            });
        }
        getConnectivityState() {
            return this.connectivityState;
        }
        addConnectivityStateListener(e) {
            this.stateListeners.add(e);
        }
        removeConnectivityStateListener(e) {
            this.stateListeners.delete(e);
        }
        resetBackoff() {
            process.nextTick(() => {
                this.backoffTimeout.reset();
                this.transitionToState([ e.ConnectivityState.TRANSIENT_FAILURE ], e.ConnectivityState.CONNECTING);
            });
        }
        getAddress() {
            return this.subchannelAddressString;
        }
        getChannelzRef() {
            return this.channelzRef;
        }
        isHealthy() {
            return true;
        }
        addHealthStateWatcher(e) {}
        removeHealthStateWatcher(e) {}
        getRealSubchannel() {
            return this;
        }
        realSubchannelEquals(e) {
            return e.getRealSubchannel() === this;
        }
        throttleKeepalive(e) {
            if (e > this.keepaliveTime) {
                this.keepaliveTime = e;
            }
        }
        getCallCredentials() {
            return this.secureConnector.getCallCredentials();
        }
        getChannel() {
            if (!this.subchannelChannel) {
                this.subchannelChannel = new l.SingleSubchannelChannel(this, this.channelTarget, this.options);
            }
            return this.subchannelChannel;
        }
        addDataWatcher(e) {
            throw new Error("Not implemented");
        }
        getOrCreateDataProducer(e, t) {
            const r = this.dataProducers.get(e);
            if (r) {
                return r;
            }
            const n = t(this);
            this.dataProducers.set(e, n);
            return n;
        }
        removeDataProducer(e) {
            this.dataProducers.delete(e);
        }
    }
    subchannel.Subchannel = Subchannel;
    return subchannel;
}

var transport = {};

var http_proxy = {};

var resolverDns = {};

var environment = {};

var hasRequiredEnvironment;

function requireEnvironment() {
    if (hasRequiredEnvironment) return environment;
    hasRequiredEnvironment = 1;
    var e;
    Object.defineProperty(environment, "__esModule", {
        value: true
    });
    environment.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0;
    environment.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((e = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && e !== void 0 ? e : "false") === "true";
    return environment;
}

var hasRequiredResolverDns;

function requireResolverDns() {
    if (hasRequiredResolverDns) return resolverDns;
    hasRequiredResolverDns = 1;
    (function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.DEFAULT_PORT = void 0;
        e.setup = E;
        const t = resolver;
        const r = require$$2__default.default;
        const n = requireServiceConfig();
        const s = constants;
        const o = requireCallInterface();
        const a = metadata;
        const l = logging$8;
        const c = constants;
        const u = uriParser;
        const d = require$$0__default$6.default;
        const h = requireBackoffTimeout();
        const p = requireEnvironment();
        const g = "dns_resolver";
        function m(e) {
            l.trace(c.LogVerbosity.DEBUG, g, e);
        }
        e.DEFAULT_PORT = 443;
        const _ = 3e4;
        class DnsResolver {
            constructor(t, n, o) {
                var l, c, p;
                this.target = t;
                this.listener = n;
                this.pendingLookupPromise = null;
                this.pendingTxtPromise = null;
                this.latestLookupResult = null;
                this.latestServiceConfigResult = null;
                this.continueResolving = false;
                this.isNextResolutionTimerRunning = false;
                this.isServiceConfigEnabled = true;
                this.returnedIpResult = false;
                this.alternativeResolver = new r.promises.Resolver;
                m("Resolver constructed for target " + (0, u.uriToString)(t));
                if (t.authority) {
                    this.alternativeResolver.setServers([ t.authority ]);
                }
                const g = (0, u.splitHostPort)(t.path);
                if (g === null) {
                    this.ipResult = null;
                    this.dnsHostname = null;
                    this.port = null;
                } else {
                    if ((0, d.isIPv4)(g.host) || (0, d.isIPv6)(g.host)) {
                        this.ipResult = [ {
                            addresses: [ {
                                host: g.host,
                                port: (l = g.port) !== null && l !== void 0 ? l : e.DEFAULT_PORT
                            } ]
                        } ];
                        this.dnsHostname = null;
                        this.port = null;
                    } else {
                        this.ipResult = null;
                        this.dnsHostname = g.host;
                        this.port = (c = g.port) !== null && c !== void 0 ? c : e.DEFAULT_PORT;
                    }
                }
                this.percentage = Math.random() * 100;
                if (o["grpc.service_config_disable_resolution"] === 1) {
                    this.isServiceConfigEnabled = false;
                }
                this.defaultResolutionError = {
                    code: s.Status.UNAVAILABLE,
                    details: `Name resolution failed for target ${(0, u.uriToString)(this.target)}`,
                    metadata: new a.Metadata
                };
                const E = {
                    initialDelay: o["grpc.initial_reconnect_backoff_ms"],
                    maxDelay: o["grpc.max_reconnect_backoff_ms"]
                };
                this.backoff = new h.BackoffTimeout(() => {
                    if (this.continueResolving) {
                        this.startResolutionWithBackoff();
                    }
                }, E);
                this.backoff.unref();
                this.minTimeBetweenResolutionsMs = (p = o["grpc.dns_min_time_between_resolutions_ms"]) !== null && p !== void 0 ? p : _;
                this.nextResolutionTimer = setTimeout(() => {}, 0);
                clearTimeout(this.nextResolutionTimer);
            }
            startResolution() {
                if (this.ipResult !== null) {
                    if (!this.returnedIpResult) {
                        m("Returning IP address for target " + (0, u.uriToString)(this.target));
                        setImmediate(() => {
                            this.listener((0, o.statusOrFromValue)(this.ipResult), {}, null, "");
                        });
                        this.returnedIpResult = true;
                    }
                    this.backoff.stop();
                    this.backoff.reset();
                    this.stopNextResolutionTimer();
                    return;
                }
                if (this.dnsHostname === null) {
                    m("Failed to parse DNS address " + (0, u.uriToString)(this.target));
                    setImmediate(() => {
                        this.listener((0, o.statusOrFromError)({
                            code: s.Status.UNAVAILABLE,
                            details: `Failed to parse DNS address ${(0, u.uriToString)(this.target)}`
                        }), {}, null, "");
                    });
                    this.stopNextResolutionTimer();
                } else {
                    if (this.pendingLookupPromise !== null) {
                        return;
                    }
                    m("Looking up DNS hostname " + this.dnsHostname);
                    this.latestLookupResult = null;
                    const e = this.dnsHostname;
                    this.pendingLookupPromise = this.lookup(e);
                    this.pendingLookupPromise.then(e => {
                        if (this.pendingLookupPromise === null) {
                            return;
                        }
                        this.pendingLookupPromise = null;
                        this.latestLookupResult = (0, o.statusOrFromValue)(e.map(e => ({
                            addresses: [ e ]
                        })));
                        const t = "[" + e.map(e => e.host + ":" + e.port).join(",") + "]";
                        m("Resolved addresses for target " + (0, u.uriToString)(this.target) + ": " + t);
                        const r = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, "");
                        this.handleHealthStatus(r);
                    }, e => {
                        if (this.pendingLookupPromise === null) {
                            return;
                        }
                        m("Resolution error for target " + (0, u.uriToString)(this.target) + ": " + e.message);
                        this.pendingLookupPromise = null;
                        this.stopNextResolutionTimer();
                        this.listener((0, o.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, "");
                    });
                    if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) {
                        this.pendingTxtPromise = this.resolveTxt(e);
                        this.pendingTxtPromise.then(e => {
                            if (this.pendingTxtPromise === null) {
                                return;
                            }
                            this.pendingTxtPromise = null;
                            let t;
                            try {
                                t = (0, n.extractAndSelectServiceConfig)(e, this.percentage);
                                if (t) {
                                    this.latestServiceConfigResult = (0, o.statusOrFromValue)(t);
                                } else {
                                    this.latestServiceConfigResult = null;
                                }
                            } catch (e) {
                                this.latestServiceConfigResult = (0, o.statusOrFromError)({
                                    code: s.Status.UNAVAILABLE,
                                    details: `Parsing service config failed with error ${e.message}`
                                });
                            }
                            if (this.latestLookupResult !== null) {
                                this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, "");
                            }
                        }, e => {});
                    }
                }
            }
            handleHealthStatus(e) {
                if (e) {
                    this.backoff.stop();
                    this.backoff.reset();
                } else {
                    this.continueResolving = true;
                }
            }
            async lookup(e) {
                if (p.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
                    m("Using alternative DNS resolver.");
                    const t = await Promise.allSettled([ this.alternativeResolver.resolve4(e), this.alternativeResolver.resolve6(e) ]);
                    if (t.every(e => e.status === "rejected")) {
                        throw new Error(t[0].reason);
                    }
                    return t.reduce((e, t) => t.status === "fulfilled" ? [ ...e, ...t.value ] : e, []).map(e => ({
                        host: e,
                        port: +this.port
                    }));
                }
                const t = await r.promises.lookup(e, {
                    all: true
                });
                return t.map(e => ({
                    host: e.address,
                    port: +this.port
                }));
            }
            async resolveTxt(e) {
                if (p.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) {
                    m("Using alternative DNS resolver.");
                    return this.alternativeResolver.resolveTxt(e);
                }
                return r.promises.resolveTxt(e);
            }
            startNextResolutionTimer() {
                var e, t;
                clearTimeout(this.nextResolutionTimer);
                this.nextResolutionTimer = setTimeout(() => {
                    this.stopNextResolutionTimer();
                    if (this.continueResolving) {
                        this.startResolutionWithBackoff();
                    }
                }, this.minTimeBetweenResolutionsMs);
                (t = (e = this.nextResolutionTimer).unref) === null || t === void 0 ? void 0 : t.call(e);
                this.isNextResolutionTimerRunning = true;
            }
            stopNextResolutionTimer() {
                clearTimeout(this.nextResolutionTimer);
                this.isNextResolutionTimerRunning = false;
            }
            startResolutionWithBackoff() {
                if (this.pendingLookupPromise === null) {
                    this.continueResolving = false;
                    this.backoff.runOnce();
                    this.startNextResolutionTimer();
                    this.startResolution();
                }
            }
            updateResolution() {
                if (this.pendingLookupPromise === null) {
                    if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) {
                        if (this.isNextResolutionTimerRunning) {
                            m('resolution update delayed by "min time between resolutions" rate limit');
                        } else {
                            m("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString());
                        }
                        this.continueResolving = true;
                    } else {
                        this.startResolutionWithBackoff();
                    }
                }
            }
            destroy() {
                this.continueResolving = false;
                this.backoff.reset();
                this.backoff.stop();
                this.stopNextResolutionTimer();
                this.pendingLookupPromise = null;
                this.pendingTxtPromise = null;
                this.latestLookupResult = null;
                this.latestServiceConfigResult = null;
                this.returnedIpResult = false;
            }
            static getDefaultAuthority(e) {
                return e.path;
            }
        }
        function E() {
            (0, t.registerResolver)("dns", DnsResolver);
            (0, t.registerDefaultScheme)("dns");
        }
    })(resolverDns);
    return resolverDns;
}

Object.defineProperty(http_proxy, "__esModule", {
    value: true
});

http_proxy.parseCIDR = parseCIDR;

http_proxy.mapProxyName = mapProxyName;

http_proxy.getProxiedConnection = getProxiedConnection;

const logging_1 = logging$8;

const constants_1$6 = constants;

const net_1 = require$$0__default$6.default;

const http = require$$1__default.default;

const logging$5 = logging$8;

const subchannel_address_1$1 = subchannelAddress;

const uri_parser_1$2 = uriParser;

const url_1 = require$$4__default.default;

const resolver_dns_1 = requireResolverDns();

const TRACER_NAME$5 = "proxy";

function trace(e) {
    logging$5.trace(constants_1$6.LogVerbosity.DEBUG, TRACER_NAME$5, e);
}

function getProxyInfo() {
    let e = "";
    let t = "";
    if (process.env.grpc_proxy) {
        t = "grpc_proxy";
        e = process.env.grpc_proxy;
    } else if (process.env.https_proxy) {
        t = "https_proxy";
        e = process.env.https_proxy;
    } else if (process.env.http_proxy) {
        t = "http_proxy";
        e = process.env.http_proxy;
    } else {
        return {};
    }
    let r;
    try {
        r = new url_1.URL(e);
    } catch (e) {
        (0, logging_1.log)(constants_1$6.LogVerbosity.ERROR, `cannot parse value of "${t}" env var`);
        return {};
    }
    if (r.protocol !== "http:") {
        (0, logging_1.log)(constants_1$6.LogVerbosity.ERROR, `"${r.protocol}" scheme not supported in proxy URI`);
        return {};
    }
    let n = null;
    if (r.username) {
        if (r.password) {
            (0, logging_1.log)(constants_1$6.LogVerbosity.INFO, "userinfo found in proxy URI");
            n = decodeURIComponent(`${r.username}:${r.password}`);
        } else {
            n = r.username;
        }
    }
    const s = r.hostname;
    let o = r.port;
    if (o === "") {
        o = "80";
    }
    const a = {
        address: `${s}:${o}`
    };
    if (n) {
        a.creds = n;
    }
    trace("Proxy server " + a.address + " set by environment variable " + t);
    return a;
}

function getNoProxyHostList() {
    let e = process.env.no_grpc_proxy;
    let t = "no_grpc_proxy";
    if (!e) {
        e = process.env.no_proxy;
        t = "no_proxy";
    }
    if (e) {
        trace("No proxy server list set by environment variable " + t);
        return e.split(",");
    } else {
        return [];
    }
}

function parseCIDR(e) {
    const t = e.split("/");
    if (t.length !== 2) {
        return null;
    }
    const r = parseInt(t[1], 10);
    if (!(0, net_1.isIPv4)(t[0]) || Number.isNaN(r) || r < 0 || r > 32) {
        return null;
    }
    return {
        ip: ipToInt(t[0]),
        prefixLength: r
    };
}

function ipToInt(e) {
    return e.split(".").reduce((e, t) => (e << 8) + parseInt(t, 10), 0);
}

function isIpInCIDR(e, t) {
    const r = e.ip;
    const n = -1 << 32 - e.prefixLength;
    const s = ipToInt(t);
    return (s & n) === (r & n);
}

function hostMatchesNoProxyList(e) {
    for (const t of getNoProxyHostList()) {
        const r = parseCIDR(t);
        if ((0, net_1.isIPv4)(e) && r && isIpInCIDR(r, e)) {
            return true;
        } else if (e.endsWith(t)) {
            return true;
        }
    }
    return false;
}

function mapProxyName(e, t) {
    var r;
    const n = {
        target: e,
        extraOptions: {}
    };
    if (((r = t["grpc.enable_http_proxy"]) !== null && r !== void 0 ? r : 1) === 0) {
        return n;
    }
    if (e.scheme === "unix") {
        return n;
    }
    const s = getProxyInfo();
    if (!s.address) {
        return n;
    }
    const o = (0, uri_parser_1$2.splitHostPort)(e.path);
    if (!o) {
        return n;
    }
    const a = o.host;
    if (hostMatchesNoProxyList(a)) {
        trace("Not using proxy for target in no_proxy list: " + (0, uri_parser_1$2.uriToString)(e));
        return n;
    }
    const l = {
        "grpc.http_connect_target": (0, uri_parser_1$2.uriToString)(e)
    };
    if (s.creds) {
        l["grpc.http_connect_creds"] = s.creds;
    }
    return {
        target: {
            scheme: "dns",
            path: s.address
        },
        extraOptions: l
    };
}

function getProxiedConnection(e, t) {
    var r;
    if (!("grpc.http_connect_target" in t)) {
        return Promise.resolve(null);
    }
    const n = t["grpc.http_connect_target"];
    const s = (0, uri_parser_1$2.parseUri)(n);
    if (s === null) {
        return Promise.resolve(null);
    }
    const o = (0, uri_parser_1$2.splitHostPort)(s.path);
    if (o === null) {
        return Promise.resolve(null);
    }
    const a = `${o.host}:${(r = o.port) !== null && r !== void 0 ? r : resolver_dns_1.DEFAULT_PORT}`;
    const l = {
        method: "CONNECT",
        path: a
    };
    const c = {
        Host: a
    };
    if ((0, subchannel_address_1$1.isTcpSubchannelAddress)(e)) {
        l.host = e.host;
        l.port = e.port;
    } else {
        l.socketPath = e.path;
    }
    if ("grpc.http_connect_creds" in t) {
        c["Proxy-Authorization"] = "Basic " + Buffer.from(t["grpc.http_connect_creds"]).toString("base64");
    }
    l.headers = c;
    const u = (0, subchannel_address_1$1.subchannelAddressToString)(e);
    trace("Using proxy " + u + " to connect to " + l.path);
    return new Promise((e, t) => {
        const r = http.request(l);
        r.once("connect", (n, s, o) => {
            r.removeAllListeners();
            s.removeAllListeners();
            if (n.statusCode === 200) {
                trace("Successfully connected to " + l.path + " through proxy " + u);
                if (o.length > 0) {
                    s.unshift(o);
                }
                trace("Successfully established a plaintext connection to " + l.path + " through proxy " + u);
                e(s);
            } else {
                (0, logging_1.log)(constants_1$6.LogVerbosity.ERROR, "Failed to connect to " + l.path + " through proxy " + u + " with status " + n.statusCode);
                t();
            }
        });
        r.once("error", e => {
            r.removeAllListeners();
            (0, logging_1.log)(constants_1$6.LogVerbosity.ERROR, "Failed to connect to proxy " + u + " with error " + e.message);
            t();
        });
        r.end();
    });
}

var subchannelCall = {};

var streamDecoder = {};

var hasRequiredStreamDecoder;

function requireStreamDecoder() {
    if (hasRequiredStreamDecoder) return streamDecoder;
    hasRequiredStreamDecoder = 1;
    Object.defineProperty(streamDecoder, "__esModule", {
        value: true
    });
    streamDecoder.StreamDecoder = void 0;
    var e;
    (function(e) {
        e[e["NO_DATA"] = 0] = "NO_DATA";
        e[e["READING_SIZE"] = 1] = "READING_SIZE";
        e[e["READING_MESSAGE"] = 2] = "READING_MESSAGE";
    })(e || (e = {}));
    class StreamDecoder {
        constructor(t) {
            this.maxReadMessageLength = t;
            this.readState = e.NO_DATA;
            this.readCompressFlag = Buffer.alloc(1);
            this.readPartialSize = Buffer.alloc(4);
            this.readSizeRemaining = 4;
            this.readMessageSize = 0;
            this.readPartialMessage = [];
            this.readMessageRemaining = 0;
        }
        write(t) {
            let r = 0;
            let n;
            const s = [];
            while (r < t.length) {
                switch (this.readState) {
                  case e.NO_DATA:
                    this.readCompressFlag = t.slice(r, r + 1);
                    r += 1;
                    this.readState = e.READING_SIZE;
                    this.readPartialSize.fill(0);
                    this.readSizeRemaining = 4;
                    this.readMessageSize = 0;
                    this.readMessageRemaining = 0;
                    this.readPartialMessage = [];
                    break;

                  case e.READING_SIZE:
                    n = Math.min(t.length - r, this.readSizeRemaining);
                    t.copy(this.readPartialSize, 4 - this.readSizeRemaining, r, r + n);
                    this.readSizeRemaining -= n;
                    r += n;
                    if (this.readSizeRemaining === 0) {
                        this.readMessageSize = this.readPartialSize.readUInt32BE(0);
                        if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) {
                            throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`);
                        }
                        this.readMessageRemaining = this.readMessageSize;
                        if (this.readMessageRemaining > 0) {
                            this.readState = e.READING_MESSAGE;
                        } else {
                            const t = Buffer.concat([ this.readCompressFlag, this.readPartialSize ], 5);
                            this.readState = e.NO_DATA;
                            s.push(t);
                        }
                    }
                    break;

                  case e.READING_MESSAGE:
                    n = Math.min(t.length - r, this.readMessageRemaining);
                    this.readPartialMessage.push(t.slice(r, r + n));
                    this.readMessageRemaining -= n;
                    r += n;
                    if (this.readMessageRemaining === 0) {
                        const t = [ this.readCompressFlag, this.readPartialSize ].concat(this.readPartialMessage);
                        const r = Buffer.concat(t, this.readMessageSize + 5);
                        this.readState = e.NO_DATA;
                        s.push(r);
                    }
                    break;

                  default:
                    throw new Error("Unexpected read state");
                }
            }
            return s;
        }
    }
    streamDecoder.StreamDecoder = StreamDecoder;
    return streamDecoder;
}

Object.defineProperty(subchannelCall, "__esModule", {
    value: true
});

subchannelCall.Http2SubchannelCall = void 0;

const http2$2 = require$$0__default$a.default;

const os = require$$1__default$2.default;

const constants_1$5 = constants;

const metadata_1$4 = metadata;

const stream_decoder_1 = requireStreamDecoder();

const logging$4 = logging$8;

const constants_2 = constants;

const TRACER_NAME$4 = "subchannel_call";

function getSystemErrorName(e) {
    for (const [t, r] of Object.entries(os.constants.errno)) {
        if (r === e) {
            return t;
        }
    }
    return "Unknown system error " + e;
}

function mapHttpStatusCode(e) {
    const t = `Received HTTP status code ${e}`;
    let r;
    switch (e) {
      case 400:
        r = constants_1$5.Status.INTERNAL;
        break;

      case 401:
        r = constants_1$5.Status.UNAUTHENTICATED;
        break;

      case 403:
        r = constants_1$5.Status.PERMISSION_DENIED;
        break;

      case 404:
        r = constants_1$5.Status.UNIMPLEMENTED;
        break;

      case 429:
      case 502:
      case 503:
      case 504:
        r = constants_1$5.Status.UNAVAILABLE;
        break;

      default:
        r = constants_1$5.Status.UNKNOWN;
    }
    return {
        code: r,
        details: t,
        metadata: new metadata_1$4.Metadata
    };
}

class Http2SubchannelCall {
    constructor(e, t, r, n, s) {
        var o;
        this.http2Stream = e;
        this.callEventTracker = t;
        this.listener = r;
        this.transport = n;
        this.callId = s;
        this.isReadFilterPending = false;
        this.isPushPending = false;
        this.canPush = false;
        this.readsClosed = false;
        this.statusOutput = false;
        this.unpushedReadMessages = [];
        this.finalStatus = null;
        this.internalError = null;
        this.serverEndedCall = false;
        this.connectionDropped = false;
        const a = (o = n.getOptions()["grpc.max_receive_message_length"]) !== null && o !== void 0 ? o : constants_1$5.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
        this.decoder = new stream_decoder_1.StreamDecoder(a);
        e.on("response", (e, t) => {
            let r = "";
            for (const t of Object.keys(e)) {
                r += "\t\t" + t + ": " + e[t] + "\n";
            }
            this.trace("Received server headers:\n" + r);
            this.httpStatusCode = e[":status"];
            if (t & http2$2.constants.NGHTTP2_FLAG_END_STREAM) {
                this.handleTrailers(e);
            } else {
                let t;
                try {
                    t = metadata_1$4.Metadata.fromHttp2Headers(e);
                } catch (e) {
                    this.endCall({
                        code: constants_1$5.Status.UNKNOWN,
                        details: e.message,
                        metadata: new metadata_1$4.Metadata
                    });
                    return;
                }
                this.listener.onReceiveMetadata(t);
            }
        });
        e.on("trailers", e => {
            this.handleTrailers(e);
        });
        e.on("data", e => {
            if (this.statusOutput) {
                return;
            }
            this.trace("receive HTTP/2 data frame of length " + e.length);
            let t;
            try {
                t = this.decoder.write(e);
            } catch (e) {
                if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) {
                    const e = mapHttpStatusCode(this.httpStatusCode);
                    this.cancelWithStatus(e.code, e.details);
                } else {
                    this.cancelWithStatus(constants_1$5.Status.RESOURCE_EXHAUSTED, e.message);
                }
                return;
            }
            for (const e of t) {
                this.trace("parsed message of length " + e.length);
                this.callEventTracker.addMessageReceived();
                this.tryPush(e);
            }
        });
        e.on("end", () => {
            this.readsClosed = true;
            this.maybeOutputStatus();
        });
        e.on("close", () => {
            this.serverEndedCall = true;
            process.nextTick(() => {
                var t;
                this.trace("HTTP/2 stream closed with code " + e.rstCode);
                if (((t = this.finalStatus) === null || t === void 0 ? void 0 : t.code) === constants_1$5.Status.OK) {
                    return;
                }
                let r;
                let n = "";
                switch (e.rstCode) {
                  case http2$2.constants.NGHTTP2_NO_ERROR:
                    if (this.finalStatus !== null) {
                        return;
                    }
                    if (this.httpStatusCode && this.httpStatusCode !== 200) {
                        const e = mapHttpStatusCode(this.httpStatusCode);
                        r = e.code;
                        n = e.details;
                    } else {
                        r = constants_1$5.Status.INTERNAL;
                        n = `Received RST_STREAM with code ${e.rstCode} (Call ended without gRPC status)`;
                    }
                    break;

                  case http2$2.constants.NGHTTP2_REFUSED_STREAM:
                    r = constants_1$5.Status.UNAVAILABLE;
                    n = "Stream refused by server";
                    break;

                  case http2$2.constants.NGHTTP2_CANCEL:
                    if (this.connectionDropped) {
                        r = constants_1$5.Status.UNAVAILABLE;
                        n = "Connection dropped";
                    } else {
                        r = constants_1$5.Status.CANCELLED;
                        n = "Call cancelled";
                    }
                    break;

                  case http2$2.constants.NGHTTP2_ENHANCE_YOUR_CALM:
                    r = constants_1$5.Status.RESOURCE_EXHAUSTED;
                    n = "Bandwidth exhausted or memory limit exceeded";
                    break;

                  case http2$2.constants.NGHTTP2_INADEQUATE_SECURITY:
                    r = constants_1$5.Status.PERMISSION_DENIED;
                    n = "Protocol not secure enough";
                    break;

                  case http2$2.constants.NGHTTP2_INTERNAL_ERROR:
                    r = constants_1$5.Status.INTERNAL;
                    if (this.internalError === null) {
                        n = `Received RST_STREAM with code ${e.rstCode} (Internal server error)`;
                    } else {
                        if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") {
                            r = constants_1$5.Status.UNAVAILABLE;
                            n = this.internalError.message;
                        } else {
                            n = `Received RST_STREAM with code ${e.rstCode} triggered by internal client error: ${this.internalError.message}`;
                        }
                    }
                    break;

                  default:
                    r = constants_1$5.Status.INTERNAL;
                    n = `Received RST_STREAM with code ${e.rstCode}`;
                }
                this.endCall({
                    code: r,
                    details: n,
                    metadata: new metadata_1$4.Metadata,
                    rstCode: e.rstCode
                });
            });
        });
        e.on("error", e => {
            if (e.code !== "ERR_HTTP2_STREAM_ERROR") {
                this.trace("Node error event: message=" + e.message + " code=" + e.code + " errno=" + getSystemErrorName(e.errno) + " syscall=" + e.syscall);
                this.internalError = e;
            }
            this.callEventTracker.onStreamEnd(false);
        });
    }
    getDeadlineInfo() {
        return [ `remote_addr=${this.getPeer()}` ];
    }
    onDisconnect() {
        this.connectionDropped = true;
        setImmediate(() => {
            this.endCall({
                code: constants_1$5.Status.UNAVAILABLE,
                details: "Connection dropped",
                metadata: new metadata_1$4.Metadata
            });
        });
    }
    outputStatus() {
        if (!this.statusOutput) {
            this.statusOutput = true;
            this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"');
            this.callEventTracker.onCallEnd(this.finalStatus);
            process.nextTick(() => {
                this.listener.onReceiveStatus(this.finalStatus);
            });
            this.http2Stream.resume();
        }
    }
    trace(e) {
        logging$4.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME$4, "[" + this.callId + "] " + e);
    }
    endCall(e) {
        if (this.finalStatus === null || this.finalStatus.code === constants_1$5.Status.OK) {
            this.finalStatus = e;
            this.maybeOutputStatus();
        }
        this.destroyHttp2Stream();
    }
    maybeOutputStatus() {
        if (this.finalStatus !== null) {
            if (this.finalStatus.code !== constants_1$5.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) {
                this.outputStatus();
            }
        }
    }
    push(e) {
        this.trace("pushing to reader message of length " + (e instanceof Buffer ? e.length : null));
        this.canPush = false;
        this.isPushPending = true;
        process.nextTick(() => {
            this.isPushPending = false;
            if (this.statusOutput) {
                return;
            }
            this.listener.onReceiveMessage(e);
            this.maybeOutputStatus();
        });
    }
    tryPush(e) {
        if (this.canPush) {
            this.http2Stream.pause();
            this.push(e);
        } else {
            this.trace("unpushedReadMessages.push message of length " + e.length);
            this.unpushedReadMessages.push(e);
        }
    }
    handleTrailers(e) {
        this.serverEndedCall = true;
        this.callEventTracker.onStreamEnd(true);
        let t = "";
        for (const r of Object.keys(e)) {
            t += "\t\t" + r + ": " + e[r] + "\n";
        }
        this.trace("Received server trailers:\n" + t);
        let r;
        try {
            r = metadata_1$4.Metadata.fromHttp2Headers(e);
        } catch (e) {
            r = new metadata_1$4.Metadata;
        }
        const n = r.getMap();
        let s;
        if (typeof n["grpc-status"] === "string") {
            const e = Number(n["grpc-status"]);
            this.trace("received status code " + e + " from server");
            r.remove("grpc-status");
            let t = "";
            if (typeof n["grpc-message"] === "string") {
                try {
                    t = decodeURI(n["grpc-message"]);
                } catch (e) {
                    t = n["grpc-message"];
                }
                r.remove("grpc-message");
                this.trace('received status details string "' + t + '" from server');
            }
            s = {
                code: e,
                details: t,
                metadata: r
            };
        } else if (this.httpStatusCode) {
            s = mapHttpStatusCode(this.httpStatusCode);
            s.metadata = r;
        } else {
            s = {
                code: constants_1$5.Status.UNKNOWN,
                details: "No status information received",
                metadata: r
            };
        }
        this.endCall(s);
    }
    destroyHttp2Stream() {
        var e;
        if (this.http2Stream.destroyed) {
            return;
        }
        if (this.serverEndedCall) {
            this.http2Stream.end();
        } else {
            let t;
            if (((e = this.finalStatus) === null || e === void 0 ? void 0 : e.code) === constants_1$5.Status.OK) {
                t = http2$2.constants.NGHTTP2_NO_ERROR;
            } else {
                t = http2$2.constants.NGHTTP2_CANCEL;
            }
            this.trace("close http2 stream with code " + t);
            this.http2Stream.close(t);
        }
    }
    cancelWithStatus(e, t) {
        this.trace("cancelWithStatus code: " + e + ' details: "' + t + '"');
        this.endCall({
            code: e,
            details: t,
            metadata: new metadata_1$4.Metadata
        });
    }
    getStatus() {
        return this.finalStatus;
    }
    getPeer() {
        return this.transport.getPeerName();
    }
    getCallNumber() {
        return this.callId;
    }
    getAuthContext() {
        return this.transport.getAuthContext();
    }
    startRead() {
        if (this.finalStatus !== null && this.finalStatus.code !== constants_1$5.Status.OK) {
            this.readsClosed = true;
            this.maybeOutputStatus();
            return;
        }
        this.canPush = true;
        if (this.unpushedReadMessages.length > 0) {
            const e = this.unpushedReadMessages.shift();
            this.push(e);
            return;
        }
        this.http2Stream.resume();
    }
    sendMessageWithContext(e, t) {
        this.trace("write() called with message of length " + t.length);
        const r = t => {
            process.nextTick(() => {
                var r;
                let n = constants_1$5.Status.UNAVAILABLE;
                if ((t === null || t === void 0 ? void 0 : t.code) === "ERR_STREAM_WRITE_AFTER_END") {
                    n = constants_1$5.Status.INTERNAL;
                }
                if (t) {
                    this.cancelWithStatus(n, `Write error: ${t.message}`);
                }
                (r = e.callback) === null || r === void 0 ? void 0 : r.call(e);
            });
        };
        this.trace("sending data chunk of length " + t.length);
        this.callEventTracker.addMessageSent();
        try {
            this.http2Stream.write(t, r);
        } catch (e) {
            this.endCall({
                code: constants_1$5.Status.UNAVAILABLE,
                details: `Write failed with error ${e.message}`,
                metadata: new metadata_1$4.Metadata
            });
        }
    }
    halfClose() {
        this.trace("end() called");
        this.trace("calling end() on HTTP/2 stream");
        this.http2Stream.end();
    }
}

subchannelCall.Http2SubchannelCall = Http2SubchannelCall;

var hasRequiredTransport;

function requireTransport() {
    if (hasRequiredTransport) return transport;
    hasRequiredTransport = 1;
    Object.defineProperty(transport, "__esModule", {
        value: true
    });
    transport.Http2SubchannelConnector = void 0;
    const e = require$$0__default$a.default;
    const t = require$$2__default$1.default;
    const r = requireChannelz();
    const n = constants;
    const s = http_proxy;
    const o = logging$8;
    const a = resolver;
    const l = subchannelAddress;
    const c = uriParser;
    const u = require$$0__default$6.default;
    const d = subchannelCall;
    const h = callNumber;
    const p = "transport";
    const g = "transport_flowctrl";
    const m = require$$12.version;
    const {HTTP2_HEADER_AUTHORITY: _, HTTP2_HEADER_CONTENT_TYPE: E, HTTP2_HEADER_METHOD: v, HTTP2_HEADER_PATH: y, HTTP2_HEADER_TE: S, HTTP2_HEADER_USER_AGENT: A} = e.constants;
    const b = 2e4;
    const C = Buffer.from("too_many_pings", "ascii");
    class Http2Transport {
        constructor(n, s, a, c) {
            this.session = n;
            this.options = a;
            this.remoteName = c;
            this.keepaliveTimer = null;
            this.pendingSendKeepalivePing = false;
            this.activeCalls = new Set;
            this.disconnectListeners = [];
            this.disconnectHandled = false;
            this.channelzEnabled = true;
            this.keepalivesSent = 0;
            this.messagesSent = 0;
            this.messagesReceived = 0;
            this.lastMessageSentTimestamp = null;
            this.lastMessageReceivedTimestamp = null;
            this.subchannelAddressString = (0, l.subchannelAddressToString)(s);
            if (a["grpc.enable_channelz"] === 0) {
                this.channelzEnabled = false;
                this.streamTracker = new r.ChannelzCallTrackerStub;
            } else {
                this.streamTracker = new r.ChannelzCallTracker;
            }
            this.channelzRef = (0, r.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled);
            this.userAgent = [ a["grpc.primary_user_agent"], `grpc-node-js/${m}`, a["grpc.secondary_user_agent"] ].filter(e => e).join(" ");
            if ("grpc.keepalive_time_ms" in a) {
                this.keepaliveTimeMs = a["grpc.keepalive_time_ms"];
            } else {
                this.keepaliveTimeMs = -1;
            }
            if ("grpc.keepalive_timeout_ms" in a) {
                this.keepaliveTimeoutMs = a["grpc.keepalive_timeout_ms"];
            } else {
                this.keepaliveTimeoutMs = b;
            }
            if ("grpc.keepalive_permit_without_calls" in a) {
                this.keepaliveWithoutCalls = a["grpc.keepalive_permit_without_calls"] === 1;
            } else {
                this.keepaliveWithoutCalls = false;
            }
            n.once("close", () => {
                this.trace("session closed");
                this.handleDisconnect();
            });
            n.once("goaway", (t, r, n) => {
                let s = false;
                if (t === e.constants.NGHTTP2_ENHANCE_YOUR_CALM && n && n.equals(C)) {
                    s = true;
                }
                this.trace("connection closed by GOAWAY with code " + t + " and data " + (n === null || n === void 0 ? void 0 : n.toString()));
                this.reportDisconnectToOwner(s);
            });
            n.once("error", e => {
                this.trace("connection closed with error " + e.message);
                this.handleDisconnect();
            });
            n.socket.once("close", e => {
                this.trace("connection closed. hadError=" + e);
                this.handleDisconnect();
            });
            if (o.isTracerEnabled(p)) {
                n.on("remoteSettings", e => {
                    this.trace("new settings received" + (this.session !== n ? " on the old connection" : "") + ": " + JSON.stringify(e));
                });
                n.on("localSettings", e => {
                    this.trace("local settings acknowledged by remote" + (this.session !== n ? " on the old connection" : "") + ": " + JSON.stringify(e));
                });
            }
            if (this.keepaliveWithoutCalls) {
                this.maybeStartKeepalivePingTimer();
            }
            if (n.socket instanceof t.TLSSocket) {
                this.authContext = {
                    transportSecurityType: "ssl",
                    sslPeerCertificate: n.socket.getPeerCertificate()
                };
            } else {
                this.authContext = {};
            }
        }
        getChannelzInfo() {
            var e, t, r;
            const n = this.session.socket;
            const s = n.remoteAddress ? (0, l.stringToSubchannelAddress)(n.remoteAddress, n.remotePort) : null;
            const o = n.localAddress ? (0, l.stringToSubchannelAddress)(n.localAddress, n.localPort) : null;
            let a;
            if (this.session.encrypted) {
                const t = n;
                const r = t.getCipher();
                const s = t.getCertificate();
                const o = t.getPeerCertificate();
                a = {
                    cipherSuiteStandardName: (e = r.standardName) !== null && e !== void 0 ? e : null,
                    cipherSuiteOtherName: r.standardName ? null : r.name,
                    localCertificate: s && "raw" in s ? s.raw : null,
                    remoteCertificate: o && "raw" in o ? o.raw : null
                };
            } else {
                a = null;
            }
            const c = {
                remoteAddress: s,
                localAddress: o,
                security: a,
                remoteName: this.remoteName,
                streamsStarted: this.streamTracker.callsStarted,
                streamsSucceeded: this.streamTracker.callsSucceeded,
                streamsFailed: this.streamTracker.callsFailed,
                messagesSent: this.messagesSent,
                messagesReceived: this.messagesReceived,
                keepAlivesSent: this.keepalivesSent,
                lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp,
                lastRemoteStreamCreatedTimestamp: null,
                lastMessageSentTimestamp: this.lastMessageSentTimestamp,
                lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp,
                localFlowControlWindow: (t = this.session.state.localWindowSize) !== null && t !== void 0 ? t : null,
                remoteFlowControlWindow: (r = this.session.state.remoteWindowSize) !== null && r !== void 0 ? r : null
            };
            return c;
        }
        trace(e) {
            o.trace(n.LogVerbosity.DEBUG, p, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        keepaliveTrace(e) {
            o.trace(n.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        flowControlTrace(e) {
            o.trace(n.LogVerbosity.DEBUG, g, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        internalsTrace(e) {
            o.trace(n.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + e);
        }
        reportDisconnectToOwner(e) {
            if (this.disconnectHandled) {
                return;
            }
            this.disconnectHandled = true;
            this.disconnectListeners.forEach(t => t(e));
        }
        handleDisconnect() {
            this.clearKeepaliveTimeout();
            this.reportDisconnectToOwner(false);
            for (const e of this.activeCalls) {
                e.onDisconnect();
            }
            setImmediate(() => {
                this.session.destroy();
            });
        }
        addDisconnectListener(e) {
            this.disconnectListeners.push(e);
        }
        canSendPing() {
            return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0);
        }
        maybeSendPing() {
            var e, t;
            if (!this.canSendPing()) {
                this.pendingSendKeepalivePing = true;
                return;
            }
            if (this.keepaliveTimer) {
                console.error("keepaliveTimeout is not null");
                return;
            }
            if (this.channelzEnabled) {
                this.keepalivesSent += 1;
            }
            this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
            this.keepaliveTimer = setTimeout(() => {
                this.keepaliveTimer = null;
                this.keepaliveTrace("Ping timeout passed without response");
                this.handleDisconnect();
            }, this.keepaliveTimeoutMs);
            (t = (e = this.keepaliveTimer).unref) === null || t === void 0 ? void 0 : t.call(e);
            let r = "";
            try {
                const e = this.session.ping((e, t, r) => {
                    this.clearKeepaliveTimeout();
                    if (e) {
                        this.keepaliveTrace("Ping failed with error " + e.message);
                        this.handleDisconnect();
                    } else {
                        this.keepaliveTrace("Received ping response");
                        this.maybeStartKeepalivePingTimer();
                    }
                });
                if (!e) {
                    r = "Ping returned false";
                }
            } catch (e) {
                r = (e instanceof Error ? e.message : "") || "Unknown error";
            }
            if (r) {
                this.keepaliveTrace("Ping send failed: " + r);
                this.handleDisconnect();
            }
        }
        maybeStartKeepalivePingTimer() {
            var e, t;
            if (!this.canSendPing()) {
                return;
            }
            if (this.pendingSendKeepalivePing) {
                this.pendingSendKeepalivePing = false;
                this.maybeSendPing();
            } else if (!this.keepaliveTimer) {
                this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
                this.keepaliveTimer = setTimeout(() => {
                    this.keepaliveTimer = null;
                    this.maybeSendPing();
                }, this.keepaliveTimeMs);
                (t = (e = this.keepaliveTimer).unref) === null || t === void 0 ? void 0 : t.call(e);
            }
        }
        clearKeepaliveTimeout() {
            if (this.keepaliveTimer) {
                clearTimeout(this.keepaliveTimer);
                this.keepaliveTimer = null;
            }
        }
        removeActiveCall(e) {
            this.activeCalls.delete(e);
            if (this.activeCalls.size === 0) {
                this.session.unref();
            }
        }
        addActiveCall(e) {
            this.activeCalls.add(e);
            if (this.activeCalls.size === 1) {
                this.session.ref();
                if (!this.keepaliveWithoutCalls) {
                    this.maybeStartKeepalivePingTimer();
                }
            }
        }
        createCall(e, t, r, n, s) {
            const o = e.toHttp2Headers();
            o[_] = t;
            o[A] = this.userAgent;
            o[E] = "application/grpc";
            o[v] = "POST";
            o[y] = r;
            o[S] = "trailers";
            let a;
            try {
                a = this.session.request(o);
            } catch (e) {
                this.handleDisconnect();
                throw e;
            }
            this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize);
            this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed);
            let l;
            let c;
            if (this.channelzEnabled) {
                this.streamTracker.addCallStarted();
                l = {
                    addMessageSent: () => {
                        var e;
                        this.messagesSent += 1;
                        this.lastMessageSentTimestamp = new Date;
                        (e = s.addMessageSent) === null || e === void 0 ? void 0 : e.call(s);
                    },
                    addMessageReceived: () => {
                        var e;
                        this.messagesReceived += 1;
                        this.lastMessageReceivedTimestamp = new Date;
                        (e = s.addMessageReceived) === null || e === void 0 ? void 0 : e.call(s);
                    },
                    onCallEnd: e => {
                        var t;
                        (t = s.onCallEnd) === null || t === void 0 ? void 0 : t.call(s, e);
                        this.removeActiveCall(c);
                    },
                    onStreamEnd: e => {
                        var t;
                        if (e) {
                            this.streamTracker.addCallSucceeded();
                        } else {
                            this.streamTracker.addCallFailed();
                        }
                        (t = s.onStreamEnd) === null || t === void 0 ? void 0 : t.call(s, e);
                    }
                };
            } else {
                l = {
                    addMessageSent: () => {
                        var e;
                        (e = s.addMessageSent) === null || e === void 0 ? void 0 : e.call(s);
                    },
                    addMessageReceived: () => {
                        var e;
                        (e = s.addMessageReceived) === null || e === void 0 ? void 0 : e.call(s);
                    },
                    onCallEnd: e => {
                        var t;
                        (t = s.onCallEnd) === null || t === void 0 ? void 0 : t.call(s, e);
                        this.removeActiveCall(c);
                    },
                    onStreamEnd: e => {
                        var t;
                        (t = s.onStreamEnd) === null || t === void 0 ? void 0 : t.call(s, e);
                    }
                };
            }
            c = new d.Http2SubchannelCall(a, l, n, this, (0, h.getNextCallNumber)());
            this.addActiveCall(c);
            return c;
        }
        getChannelzRef() {
            return this.channelzRef;
        }
        getPeerName() {
            return this.subchannelAddressString;
        }
        getOptions() {
            return this.options;
        }
        getAuthContext() {
            return this.authContext;
        }
        shutdown() {
            this.session.close();
            (0, r.unregisterChannelzRef)(this.channelzRef);
        }
    }
    class Http2SubchannelConnector {
        constructor(e) {
            this.channelTarget = e;
            this.session = null;
            this.isShutdown = false;
        }
        trace(e) {
            o.trace(n.LogVerbosity.DEBUG, p, (0, c.uriToString)(this.channelTarget) + " " + e);
        }
        createSession(t, r, n) {
            if (this.isShutdown) {
                return Promise.reject();
            }
            if (t.socket.closed) {
                return Promise.reject("Connection closed before starting HTTP/2 handshake");
            }
            return new Promise((s, o) => {
                var l, u, d, h, p, g, m, _;
                let E = null;
                let v = this.channelTarget;
                if ("grpc.http_connect_target" in n) {
                    const e = (0, c.parseUri)(n["grpc.http_connect_target"]);
                    if (e) {
                        v = e;
                        E = (0, c.uriToString)(e);
                    }
                }
                const y = t.secure ? "https" : "http";
                const S = (0, a.getDefaultAuthority)(v);
                const A = () => {
                    var e;
                    (e = this.session) === null || e === void 0 ? void 0 : e.destroy();
                    this.session = null;
                    setImmediate(() => {
                        if (!k) {
                            k = true;
                            o(`${R.trim()} (${(new Date).toISOString()})`);
                        }
                    });
                };
                const b = e => {
                    var t;
                    (t = this.session) === null || t === void 0 ? void 0 : t.destroy();
                    R = e.message;
                    this.trace("connection failed with error " + R);
                    if (!k) {
                        k = true;
                        o(`${R} (${(new Date).toISOString()})`);
                    }
                };
                const C = {
                    createConnection: (e, r) => t.socket,
                    settings: {
                        initialWindowSize: (h = (l = n["grpc-node.flow_control_window"]) !== null && l !== void 0 ? l : (d = (u = e.getDefaultSettings) === null || u === void 0 ? void 0 : u.call(e)) === null || d === void 0 ? void 0 : d.initialWindowSize) !== null && h !== void 0 ? h : 65535
                    },
                    maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER,
                    maxSessionMemory: (p = n["grpc-node.max_session_memory"]) !== null && p !== void 0 ? p : Number.MAX_SAFE_INTEGER
                };
                const w = e.connect(`${y}://${S}`, C);
                const I = (_ = (m = (g = e.getDefaultSettings) === null || g === void 0 ? void 0 : g.call(e)) === null || m === void 0 ? void 0 : m.initialWindowSize) !== null && _ !== void 0 ? _ : 65535;
                const T = n["grpc-node.flow_control_window"];
                this.session = w;
                let R = "Failed to connect";
                let k = false;
                w.unref();
                w.once("remoteSettings", () => {
                    var e;
                    if (T && T > I) {
                        try {
                            w.setLocalWindowSize(T);
                        } catch (t) {
                            const r = T - ((e = w.state.localWindowSize) !== null && e !== void 0 ? e : I);
                            if (r > 0) w.incrementWindowSize(r);
                        }
                    }
                    w.removeAllListeners();
                    t.socket.removeListener("close", A);
                    t.socket.removeListener("error", b);
                    s(new Http2Transport(w, r, n, E));
                    this.session = null;
                });
                w.once("close", A);
                w.once("error", b);
                t.socket.once("close", A);
                t.socket.once("error", b);
            });
        }
        tcpConnect(e, t) {
            return (0, s.getProxiedConnection)(e, t).then(t => {
                if (t) {
                    return t;
                } else {
                    return new Promise((t, r) => {
                        const n = () => {
                            r(new Error("Socket closed"));
                        };
                        const s = e => {
                            r(e);
                        };
                        const o = u.connect(e, () => {
                            o.removeListener("close", n);
                            o.removeListener("error", s);
                            t(o);
                        });
                        o.once("close", n);
                        o.once("error", s);
                    });
                }
            });
        }
        async connect(e, t, r) {
            if (this.isShutdown) {
                return Promise.reject();
            }
            let n = null;
            let s = null;
            const o = (0, l.subchannelAddressToString)(e);
            try {
                this.trace(o + " Waiting for secureConnector to be ready");
                await t.waitForReady();
                this.trace(o + " secureConnector is ready");
                n = await this.tcpConnect(e, r);
                n.setNoDelay();
                this.trace(o + " Established TCP connection");
                s = await t.connect(n);
                this.trace(o + " Established secure connection");
                return this.createSession(s, e, r);
            } catch (e) {
                n === null || n === void 0 ? void 0 : n.destroy();
                s === null || s === void 0 ? void 0 : s.socket.destroy();
                throw e;
            }
        }
        shutdown() {
            var e;
            this.isShutdown = true;
            (e = this.session) === null || e === void 0 ? void 0 : e.close();
            this.session = null;
        }
    }
    transport.Http2SubchannelConnector = Http2SubchannelConnector;
    return transport;
}

var hasRequiredSubchannelPool;

function requireSubchannelPool() {
    if (hasRequiredSubchannelPool) return subchannelPool;
    hasRequiredSubchannelPool = 1;
    Object.defineProperty(subchannelPool, "__esModule", {
        value: true
    });
    subchannelPool.SubchannelPool = void 0;
    subchannelPool.getSubchannelPool = l;
    const e = channelOptions;
    const t = requireSubchannel();
    const r = subchannelAddress;
    const n = uriParser;
    const s = requireTransport();
    const o = 1e4;
    class SubchannelPool {
        constructor() {
            this.pool = Object.create(null);
            this.cleanupTimer = null;
        }
        unrefUnusedSubchannels() {
            let e = true;
            for (const t in this.pool) {
                const r = this.pool[t];
                const n = r.filter(e => !e.subchannel.unrefIfOneRef());
                if (n.length > 0) {
                    e = false;
                }
                this.pool[t] = n;
            }
            if (e && this.cleanupTimer !== null) {
                clearInterval(this.cleanupTimer);
                this.cleanupTimer = null;
            }
        }
        ensureCleanupTask() {
            var e, t;
            if (this.cleanupTimer === null) {
                this.cleanupTimer = setInterval(() => {
                    this.unrefUnusedSubchannels();
                }, o);
                (t = (e = this.cleanupTimer).unref) === null || t === void 0 ? void 0 : t.call(e);
            }
        }
        getOrCreateSubchannel(o, a, l, c) {
            this.ensureCleanupTask();
            const u = (0, n.uriToString)(o);
            if (u in this.pool) {
                const t = this.pool[u];
                for (const n of t) {
                    if ((0, r.subchannelAddressEqual)(a, n.subchannelAddress) && (0, e.channelOptionsEqual)(l, n.channelArguments) && c._equals(n.channelCredentials)) {
                        return n.subchannel;
                    }
                }
            }
            const d = new t.Subchannel(o, a, l, c, new s.Http2SubchannelConnector(o));
            if (!(u in this.pool)) {
                this.pool[u] = [];
            }
            this.pool[u].push({
                subchannelAddress: a,
                channelArguments: l,
                channelCredentials: c,
                subchannel: d
            });
            d.ref();
            return d;
        }
    }
    subchannelPool.SubchannelPool = SubchannelPool;
    const a = new SubchannelPool;
    function l(e) {
        if (e) {
            return a;
        } else {
            return new SubchannelPool;
        }
    }
    return subchannelPool;
}

var loadBalancingCall = {};

Object.defineProperty(loadBalancingCall, "__esModule", {
    value: true
});

loadBalancingCall.LoadBalancingCall = void 0;

const connectivity_state_1 = connectivityState;

const constants_1$4 = constants;

const deadline_1$2 = deadline;

const metadata_1$3 = metadata;

const picker_1 = requirePicker();

const uri_parser_1$1 = uriParser;

const logging$3 = logging$8;

const control_plane_status_1$1 = controlPlaneStatus;

const http2$1 = require$$0__default$a.default;

const TRACER_NAME$3 = "load_balancing_call";

class LoadBalancingCall {
    constructor(e, t, r, n, s, o, a) {
        var l, c;
        this.channel = e;
        this.callConfig = t;
        this.methodName = r;
        this.host = n;
        this.credentials = s;
        this.deadline = o;
        this.callNumber = a;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.metadata = null;
        this.listener = null;
        this.onCallEnded = null;
        this.childStartTime = null;
        const u = this.methodName.split("/");
        let d = "";
        if (u.length >= 2) {
            d = u[1];
        }
        const h = (c = (l = (0, uri_parser_1$1.splitHostPort)(this.host)) === null || l === void 0 ? void 0 : l.host) !== null && c !== void 0 ? c : "localhost";
        this.serviceUrl = `https://${h}/${d}`;
        this.startTime = new Date;
    }
    getDeadlineInfo() {
        var e, t;
        const r = [];
        if (this.childStartTime) {
            if (this.childStartTime > this.startTime) {
                if ((e = this.metadata) === null || e === void 0 ? void 0 : e.getOptions().waitForReady) {
                    r.push("wait_for_ready");
                }
                r.push(`LB pick: ${(0, deadline_1$2.formatDateDifference)(this.startTime, this.childStartTime)}`);
            }
            r.push(...this.child.getDeadlineInfo());
            return r;
        } else {
            if ((t = this.metadata) === null || t === void 0 ? void 0 : t.getOptions().waitForReady) {
                r.push("wait_for_ready");
            }
            r.push("Waiting for LB pick");
        }
        return r;
    }
    trace(e) {
        logging$3.trace(constants_1$4.LogVerbosity.DEBUG, TRACER_NAME$3, "[" + this.callNumber + "] " + e);
    }
    outputStatus(e, t) {
        var r, n;
        if (!this.ended) {
            this.ended = true;
            this.trace("ended with status: code=" + e.code + ' details="' + e.details + '" start time=' + this.startTime.toISOString());
            const s = Object.assign(Object.assign({}, e), {
                progress: t
            });
            (r = this.listener) === null || r === void 0 ? void 0 : r.onReceiveStatus(s);
            (n = this.onCallEnded) === null || n === void 0 ? void 0 : n.call(this, s.code, s.details, s.metadata);
        }
    }
    doPick() {
        var e, t;
        if (this.ended) {
            return;
        }
        if (!this.metadata) {
            throw new Error("doPick called before start");
        }
        this.trace("Pick called");
        const r = this.metadata.clone();
        const n = this.channel.doPick(r, this.callConfig.pickInformation);
        const s = n.subchannel ? "(" + n.subchannel.getChannelzRef().id + ") " + n.subchannel.getAddress() : "" + n.subchannel;
        this.trace("Pick result: " + picker_1.PickResultType[n.pickResultType] + " subchannel: " + s + " status: " + ((e = n.status) === null || e === void 0 ? void 0 : e.code) + " " + ((t = n.status) === null || t === void 0 ? void 0 : t.details));
        switch (n.pickResultType) {
          case picker_1.PickResultType.COMPLETE:
            const e = this.credentials.compose(n.subchannel.getCallCredentials());
            e.generateMetadata({
                method_name: this.methodName,
                service_url: this.serviceUrl
            }).then(e => {
                var t;
                if (this.ended) {
                    this.trace("Credentials metadata generation finished after call ended");
                    return;
                }
                r.merge(e);
                if (r.get("authorization").length > 1) {
                    this.outputStatus({
                        code: constants_1$4.Status.INTERNAL,
                        details: '"authorization" metadata cannot have multiple values',
                        metadata: new metadata_1$3.Metadata
                    }, "PROCESSED");
                }
                if (n.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) {
                    this.trace("Picked subchannel " + s + " has state " + connectivity_state_1.ConnectivityState[n.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick");
                    this.doPick();
                    return;
                }
                if (this.deadline !== Infinity) {
                    r.set("grpc-timeout", (0, deadline_1$2.getDeadlineTimeoutString)(this.deadline));
                }
                try {
                    this.child = n.subchannel.getRealSubchannel().createCall(r, this.host, this.methodName, {
                        onReceiveMetadata: e => {
                            this.trace("Received metadata");
                            this.listener.onReceiveMetadata(e);
                        },
                        onReceiveMessage: e => {
                            this.trace("Received message");
                            this.listener.onReceiveMessage(e);
                        },
                        onReceiveStatus: e => {
                            this.trace("Received status");
                            if (e.rstCode === http2$1.constants.NGHTTP2_REFUSED_STREAM) {
                                this.outputStatus(e, "REFUSED");
                            } else {
                                this.outputStatus(e, "PROCESSED");
                            }
                        }
                    });
                    this.childStartTime = new Date;
                } catch (e) {
                    this.trace("Failed to start call on picked subchannel " + s + " with error " + e.message);
                    this.outputStatus({
                        code: constants_1$4.Status.INTERNAL,
                        details: "Failed to start HTTP/2 stream with error " + e.message,
                        metadata: new metadata_1$3.Metadata
                    }, "NOT_STARTED");
                    return;
                }
                (t = n.onCallStarted) === null || t === void 0 ? void 0 : t.call(n);
                this.onCallEnded = n.onCallEnded;
                this.trace("Created child call [" + this.child.getCallNumber() + "]");
                if (this.readPending) {
                    this.child.startRead();
                }
                if (this.pendingMessage) {
                    this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message);
                }
                if (this.pendingHalfClose) {
                    this.child.halfClose();
                }
            }, e => {
                const {code: t, details: r} = (0, control_plane_status_1$1.restrictControlPlaneStatusCode)(typeof e.code === "number" ? e.code : constants_1$4.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${e.message}`);
                this.outputStatus({
                    code: t,
                    details: r,
                    metadata: new metadata_1$3.Metadata
                }, "PROCESSED");
            });
            break;

          case picker_1.PickResultType.DROP:
            const {code: t, details: o} = (0, control_plane_status_1$1.restrictControlPlaneStatusCode)(n.status.code, n.status.details);
            setImmediate(() => {
                this.outputStatus({
                    code: t,
                    details: o,
                    metadata: n.status.metadata
                }, "DROP");
            });
            break;

          case picker_1.PickResultType.TRANSIENT_FAILURE:
            if (this.metadata.getOptions().waitForReady) {
                this.channel.queueCallForPick(this);
            } else {
                const {code: e, details: t} = (0, control_plane_status_1$1.restrictControlPlaneStatusCode)(n.status.code, n.status.details);
                setImmediate(() => {
                    this.outputStatus({
                        code: e,
                        details: t,
                        metadata: n.status.metadata
                    }, "PROCESSED");
                });
            }
            break;

          case picker_1.PickResultType.QUEUE:
            this.channel.queueCallForPick(this);
        }
    }
    cancelWithStatus(e, t) {
        var r;
        this.trace("cancelWithStatus code: " + e + ' details: "' + t + '"');
        (r = this.child) === null || r === void 0 ? void 0 : r.cancelWithStatus(e, t);
        this.outputStatus({
            code: e,
            details: t,
            metadata: new metadata_1$3.Metadata
        }, "PROCESSED");
    }
    getPeer() {
        var e, t;
        return (t = (e = this.child) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : this.channel.getTarget();
    }
    start(e, t) {
        this.trace("start called");
        this.listener = t;
        this.metadata = e;
        this.doPick();
    }
    sendMessageWithContext(e, t) {
        this.trace("write() called with message of length " + t.length);
        if (this.child) {
            this.child.sendMessageWithContext(e, t);
        } else {
            this.pendingMessage = {
                context: e,
                message: t
            };
        }
    }
    startRead() {
        this.trace("startRead called");
        if (this.child) {
            this.child.startRead();
        } else {
            this.readPending = true;
        }
    }
    halfClose() {
        this.trace("halfClose called");
        if (this.child) {
            this.child.halfClose();
        } else {
            this.pendingHalfClose = true;
        }
    }
    setCredentials(e) {
        throw new Error("Method not implemented.");
    }
    getCallNumber() {
        return this.callNumber;
    }
    getAuthContext() {
        if (this.child) {
            return this.child.getAuthContext();
        } else {
            return null;
        }
    }
}

loadBalancingCall.LoadBalancingCall = LoadBalancingCall;

var resolvingCall = {};

Object.defineProperty(resolvingCall, "__esModule", {
    value: true
});

resolvingCall.ResolvingCall = void 0;

const call_credentials_1 = callCredentials;

const constants_1$3 = constants;

const deadline_1$1 = deadline;

const metadata_1$2 = metadata;

const logging$2 = logging$8;

const control_plane_status_1 = controlPlaneStatus;

const TRACER_NAME$2 = "resolving_call";

class ResolvingCall {
    constructor(e, t, r, n, s) {
        this.channel = e;
        this.method = t;
        this.filterStackFactory = n;
        this.callNumber = s;
        this.child = null;
        this.readPending = false;
        this.pendingMessage = null;
        this.pendingHalfClose = false;
        this.ended = false;
        this.readFilterPending = false;
        this.writeFilterPending = false;
        this.pendingChildStatus = null;
        this.metadata = null;
        this.listener = null;
        this.statusWatchers = [];
        this.deadlineTimer = setTimeout(() => {}, 0);
        this.filterStack = null;
        this.deadlineStartTime = null;
        this.configReceivedTime = null;
        this.childStartTime = null;
        this.credentials = call_credentials_1.CallCredentials.createEmpty();
        this.deadline = r.deadline;
        this.host = r.host;
        if (r.parentCall) {
            if (r.flags & constants_1$3.Propagate.CANCELLATION) {
                r.parentCall.on("cancelled", () => {
                    this.cancelWithStatus(constants_1$3.Status.CANCELLED, "Cancelled by parent call");
                });
            }
            if (r.flags & constants_1$3.Propagate.DEADLINE) {
                this.trace("Propagating deadline from parent: " + r.parentCall.getDeadline());
                this.deadline = (0, deadline_1$1.minDeadline)(this.deadline, r.parentCall.getDeadline());
            }
        }
        this.trace("Created");
        this.runDeadlineTimer();
    }
    trace(e) {
        logging$2.trace(constants_1$3.LogVerbosity.DEBUG, TRACER_NAME$2, "[" + this.callNumber + "] " + e);
    }
    runDeadlineTimer() {
        clearTimeout(this.deadlineTimer);
        this.deadlineStartTime = new Date;
        this.trace("Deadline: " + (0, deadline_1$1.deadlineToString)(this.deadline));
        const e = (0, deadline_1$1.getRelativeTimeout)(this.deadline);
        if (e !== Infinity) {
            this.trace("Deadline will be reached in " + e + "ms");
            const t = () => {
                if (!this.deadlineStartTime) {
                    this.cancelWithStatus(constants_1$3.Status.DEADLINE_EXCEEDED, "Deadline exceeded");
                    return;
                }
                const e = [];
                const t = new Date;
                e.push(`Deadline exceeded after ${(0, deadline_1$1.formatDateDifference)(this.deadlineStartTime, t)}`);
                if (this.configReceivedTime) {
                    if (this.configReceivedTime > this.deadlineStartTime) {
                        e.push(`name resolution: ${(0, deadline_1$1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`);
                    }
                    if (this.childStartTime) {
                        if (this.childStartTime > this.configReceivedTime) {
                            e.push(`metadata filters: ${(0, deadline_1$1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`);
                        }
                    } else {
                        e.push("waiting for metadata filters");
                    }
                } else {
                    e.push("waiting for name resolution");
                }
                if (this.child) {
                    e.push(...this.child.getDeadlineInfo());
                }
                this.cancelWithStatus(constants_1$3.Status.DEADLINE_EXCEEDED, e.join(","));
            };
            if (e <= 0) {
                process.nextTick(t);
            } else {
                this.deadlineTimer = setTimeout(t, e);
            }
        }
    }
    outputStatus(e) {
        if (!this.ended) {
            this.ended = true;
            if (!this.filterStack) {
                this.filterStack = this.filterStackFactory.createFilter();
            }
            clearTimeout(this.deadlineTimer);
            const t = this.filterStack.receiveTrailers(e);
            this.trace("ended with status: code=" + t.code + ' details="' + t.details + '"');
            this.statusWatchers.forEach(e => e(t));
            process.nextTick(() => {
                var e;
                (e = this.listener) === null || e === void 0 ? void 0 : e.onReceiveStatus(t);
            });
        }
    }
    sendMessageOnChild(e, t) {
        if (!this.child) {
            throw new Error("sendMessageonChild called with child not populated");
        }
        const r = this.child;
        this.writeFilterPending = true;
        this.filterStack.sendMessage(Promise.resolve({
            message: t,
            flags: e.flags
        })).then(t => {
            this.writeFilterPending = false;
            r.sendMessageWithContext(e, t.message);
            if (this.pendingHalfClose) {
                r.halfClose();
            }
        }, e => {
            this.cancelWithStatus(e.code, e.details);
        });
    }
    getConfig() {
        if (this.ended) {
            return;
        }
        if (!this.metadata || !this.listener) {
            throw new Error("getConfig called before start");
        }
        const e = this.channel.getConfig(this.method, this.metadata);
        if (e.type === "NONE") {
            this.channel.queueCallForConfig(this);
            return;
        } else if (e.type === "ERROR") {
            if (this.metadata.getOptions().waitForReady) {
                this.channel.queueCallForConfig(this);
            } else {
                this.outputStatus(e.error);
            }
            return;
        }
        this.configReceivedTime = new Date;
        const t = e.config;
        if (t.status !== constants_1$3.Status.OK) {
            const {code: e, details: r} = (0, control_plane_status_1.restrictControlPlaneStatusCode)(t.status, "Failed to route call to method " + this.method);
            this.outputStatus({
                code: e,
                details: r,
                metadata: new metadata_1$2.Metadata
            });
            return;
        }
        if (t.methodConfig.timeout) {
            const e = new Date;
            e.setSeconds(e.getSeconds() + t.methodConfig.timeout.seconds);
            e.setMilliseconds(e.getMilliseconds() + t.methodConfig.timeout.nanos / 1e6);
            this.deadline = (0, deadline_1$1.minDeadline)(this.deadline, e);
            this.runDeadlineTimer();
        }
        this.filterStackFactory.push(t.dynamicFilterFactories);
        this.filterStack = this.filterStackFactory.createFilter();
        this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(e => {
            this.child = this.channel.createRetryingCall(t, this.method, this.host, this.credentials, this.deadline);
            this.trace("Created child [" + this.child.getCallNumber() + "]");
            this.childStartTime = new Date;
            this.child.start(e, {
                onReceiveMetadata: e => {
                    this.trace("Received metadata");
                    this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(e));
                },
                onReceiveMessage: e => {
                    this.trace("Received message");
                    this.readFilterPending = true;
                    this.filterStack.receiveMessage(e).then(e => {
                        this.trace("Finished filtering received message");
                        this.readFilterPending = false;
                        this.listener.onReceiveMessage(e);
                        if (this.pendingChildStatus) {
                            this.outputStatus(this.pendingChildStatus);
                        }
                    }, e => {
                        this.cancelWithStatus(e.code, e.details);
                    });
                },
                onReceiveStatus: e => {
                    this.trace("Received status");
                    if (this.readFilterPending) {
                        this.pendingChildStatus = e;
                    } else {
                        this.outputStatus(e);
                    }
                }
            });
            if (this.readPending) {
                this.child.startRead();
            }
            if (this.pendingMessage) {
                this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message);
            } else if (this.pendingHalfClose) {
                this.child.halfClose();
            }
        }, e => {
            this.outputStatus(e);
        });
    }
    reportResolverError(e) {
        var t;
        if ((t = this.metadata) === null || t === void 0 ? void 0 : t.getOptions().waitForReady) {
            this.channel.queueCallForConfig(this);
        } else {
            this.outputStatus(e);
        }
    }
    cancelWithStatus(e, t) {
        var r;
        this.trace("cancelWithStatus code: " + e + ' details: "' + t + '"');
        (r = this.child) === null || r === void 0 ? void 0 : r.cancelWithStatus(e, t);
        this.outputStatus({
            code: e,
            details: t,
            metadata: new metadata_1$2.Metadata
        });
    }
    getPeer() {
        var e, t;
        return (t = (e = this.child) === null || e === void 0 ? void 0 : e.getPeer()) !== null && t !== void 0 ? t : this.channel.getTarget();
    }
    start(e, t) {
        this.trace("start called");
        this.metadata = e.clone();
        this.listener = t;
        this.getConfig();
    }
    sendMessageWithContext(e, t) {
        this.trace("write() called with message of length " + t.length);
        if (this.child) {
            this.sendMessageOnChild(e, t);
        } else {
            this.pendingMessage = {
                context: e,
                message: t
            };
        }
    }
    startRead() {
        this.trace("startRead called");
        if (this.child) {
            this.child.startRead();
        } else {
            this.readPending = true;
        }
    }
    halfClose() {
        this.trace("halfClose called");
        if (this.child && !this.writeFilterPending) {
            this.child.halfClose();
        } else {
            this.pendingHalfClose = true;
        }
    }
    setCredentials(e) {
        this.credentials = e;
    }
    addStatusWatcher(e) {
        this.statusWatchers.push(e);
    }
    getCallNumber() {
        return this.callNumber;
    }
    getAuthContext() {
        if (this.child) {
            return this.child.getAuthContext();
        } else {
            return null;
        }
    }
}

resolvingCall.ResolvingCall = ResolvingCall;

var retryingCall = {};

Object.defineProperty(retryingCall, "__esModule", {
    value: true
});

retryingCall.RetryingCall = retryingCall.MessageBufferTracker = retryingCall.RetryThrottler = void 0;

const constants_1$2 = constants;

const deadline_1 = deadline;

const metadata_1$1 = metadata;

const logging$1 = logging$8;

const TRACER_NAME$1 = "retrying_call";

class RetryThrottler {
    constructor(e, t, r) {
        this.maxTokens = e;
        this.tokenRatio = t;
        if (r) {
            this.tokens = r.tokens * (e / r.maxTokens);
        } else {
            this.tokens = e;
        }
    }
    addCallSucceeded() {
        this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens);
    }
    addCallFailed() {
        this.tokens = Math.max(this.tokens - 1, 0);
    }
    canRetryCall() {
        return this.tokens > this.maxTokens / 2;
    }
}

retryingCall.RetryThrottler = RetryThrottler;

class MessageBufferTracker {
    constructor(e, t) {
        this.totalLimit = e;
        this.limitPerCall = t;
        this.totalAllocated = 0;
        this.allocatedPerCall = new Map;
    }
    allocate(e, t) {
        var r;
        const n = (r = this.allocatedPerCall.get(t)) !== null && r !== void 0 ? r : 0;
        if (this.limitPerCall - n < e || this.totalLimit - this.totalAllocated < e) {
            return false;
        }
        this.allocatedPerCall.set(t, n + e);
        this.totalAllocated += e;
        return true;
    }
    free(e, t) {
        var r;
        if (this.totalAllocated < e) {
            throw new Error(`Invalid buffer allocation state: call ${t} freed ${e} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= e;
        const n = (r = this.allocatedPerCall.get(t)) !== null && r !== void 0 ? r : 0;
        if (n < e) {
            throw new Error(`Invalid buffer allocation state: call ${t} freed ${e} > allocated for call ${n}`);
        }
        this.allocatedPerCall.set(t, n - e);
    }
    freeAll(e) {
        var t;
        const r = (t = this.allocatedPerCall.get(e)) !== null && t !== void 0 ? t : 0;
        if (this.totalAllocated < r) {
            throw new Error(`Invalid buffer allocation state: call ${e} allocated ${r} > total allocated ${this.totalAllocated}`);
        }
        this.totalAllocated -= r;
        this.allocatedPerCall.delete(e);
    }
}

retryingCall.MessageBufferTracker = MessageBufferTracker;

const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts";

const DEFAULT_MAX_ATTEMPTS_LIMIT = 5;

class RetryingCall {
    constructor(e, t, r, n, s, o, a, l, c) {
        var u;
        this.channel = e;
        this.callConfig = t;
        this.methodName = r;
        this.host = n;
        this.credentials = s;
        this.deadline = o;
        this.callNumber = a;
        this.bufferTracker = l;
        this.retryThrottler = c;
        this.listener = null;
        this.initialMetadata = null;
        this.underlyingCalls = [];
        this.writeBuffer = [];
        this.writeBufferOffset = 0;
        this.readStarted = false;
        this.transparentRetryUsed = false;
        this.attempts = 0;
        this.hedgingTimer = null;
        this.committedCallIndex = null;
        this.initialRetryBackoffSec = 0;
        this.nextRetryBackoffSec = 0;
        const d = (u = e.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && u !== void 0 ? u : DEFAULT_MAX_ATTEMPTS_LIMIT;
        if (e.getOptions()["grpc.enable_retries"] === 0) {
            this.state = "NO_RETRY";
            this.maxAttempts = 1;
        } else if (t.methodConfig.retryPolicy) {
            this.state = "RETRY";
            const e = t.methodConfig.retryPolicy;
            this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(e.initialBackoff.substring(0, e.initialBackoff.length - 1));
            this.maxAttempts = Math.min(e.maxAttempts, d);
        } else if (t.methodConfig.hedgingPolicy) {
            this.state = "HEDGING";
            this.maxAttempts = Math.min(t.methodConfig.hedgingPolicy.maxAttempts, d);
        } else {
            this.state = "TRANSPARENT_ONLY";
            this.maxAttempts = 1;
        }
        this.startTime = new Date;
    }
    getDeadlineInfo() {
        if (this.underlyingCalls.length === 0) {
            return [];
        }
        const e = [];
        const t = this.underlyingCalls[this.underlyingCalls.length - 1];
        if (this.underlyingCalls.length > 1) {
            e.push(`previous attempts: ${this.underlyingCalls.length - 1}`);
        }
        if (t.startTime > this.startTime) {
            e.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, t.startTime)}`);
        }
        e.push(...t.call.getDeadlineInfo());
        return e;
    }
    getCallNumber() {
        return this.callNumber;
    }
    trace(e) {
        logging$1.trace(constants_1$2.LogVerbosity.DEBUG, TRACER_NAME$1, "[" + this.callNumber + "] " + e);
    }
    reportStatus(e) {
        this.trace("ended with status: code=" + e.code + ' details="' + e.details + '" start time=' + this.startTime.toISOString());
        this.bufferTracker.freeAll(this.callNumber);
        this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length;
        this.writeBuffer = [];
        process.nextTick(() => {
            var t;
            (t = this.listener) === null || t === void 0 ? void 0 : t.onReceiveStatus({
                code: e.code,
                details: e.details,
                metadata: e.metadata
            });
        });
    }
    cancelWithStatus(e, t) {
        this.trace("cancelWithStatus code: " + e + ' details: "' + t + '"');
        this.reportStatus({
            code: e,
            details: t,
            metadata: new metadata_1$1.Metadata
        });
        for (const {call: r} of this.underlyingCalls) {
            r.cancelWithStatus(e, t);
        }
    }
    getPeer() {
        if (this.committedCallIndex !== null) {
            return this.underlyingCalls[this.committedCallIndex].call.getPeer();
        } else {
            return "unknown";
        }
    }
    getBufferEntry(e) {
        var t;
        return (t = this.writeBuffer[e - this.writeBufferOffset]) !== null && t !== void 0 ? t : {
            entryType: "FREED",
            allocated: false
        };
    }
    getNextBufferIndex() {
        return this.writeBufferOffset + this.writeBuffer.length;
    }
    clearSentMessages() {
        if (this.state !== "COMMITTED") {
            return;
        }
        let e;
        if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") {
            e = this.getNextBufferIndex();
        } else {
            e = this.underlyingCalls[this.committedCallIndex].nextMessageToSend;
        }
        for (let t = this.writeBufferOffset; t < e; t++) {
            const e = this.getBufferEntry(t);
            if (e.allocated) {
                this.bufferTracker.free(e.message.message.length, this.callNumber);
            }
        }
        this.writeBuffer = this.writeBuffer.slice(e - this.writeBufferOffset);
        this.writeBufferOffset = e;
    }
    commitCall(e) {
        var t, r;
        if (this.state === "COMMITTED") {
            return;
        }
        this.trace("Committing call [" + this.underlyingCalls[e].call.getCallNumber() + "] at index " + e);
        this.state = "COMMITTED";
        (r = (t = this.callConfig).onCommitted) === null || r === void 0 ? void 0 : r.call(t);
        this.committedCallIndex = e;
        for (let t = 0; t < this.underlyingCalls.length; t++) {
            if (t === e) {
                continue;
            }
            if (this.underlyingCalls[t].state === "COMPLETED") {
                continue;
            }
            this.underlyingCalls[t].state = "COMPLETED";
            this.underlyingCalls[t].call.cancelWithStatus(constants_1$2.Status.CANCELLED, "Discarded in favor of other hedged attempt");
        }
        this.clearSentMessages();
    }
    commitCallWithMostMessages() {
        if (this.state === "COMMITTED") {
            return;
        }
        let e = -1;
        let t = -1;
        for (const [r, n] of this.underlyingCalls.entries()) {
            if (n.state === "ACTIVE" && n.nextMessageToSend > e) {
                e = n.nextMessageToSend;
                t = r;
            }
        }
        if (t === -1) {
            this.state = "TRANSPARENT_ONLY";
        } else {
            this.commitCall(t);
        }
    }
    isStatusCodeInList(e, t) {
        return e.some(e => {
            var r;
            return e === t || e.toString().toLowerCase() === ((r = constants_1$2.Status[t]) === null || r === void 0 ? void 0 : r.toLowerCase());
        });
    }
    getNextRetryJitter() {
        return Math.random() * (1.2 - .8) + .8;
    }
    getNextRetryBackoffMs() {
        var e;
        const t = (e = this.callConfig) === null || e === void 0 ? void 0 : e.methodConfig.retryPolicy;
        if (!t) {
            return 0;
        }
        const r = this.getNextRetryJitter();
        const n = r * this.nextRetryBackoffSec * 1e3;
        const s = Number(t.maxBackoff.substring(0, t.maxBackoff.length - 1));
        this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * t.backoffMultiplier, s);
        return n;
    }
    maybeRetryCall(e, t) {
        if (this.state !== "RETRY") {
            t(false);
            return;
        }
        if (this.attempts >= this.maxAttempts) {
            t(false);
            return;
        }
        let r;
        if (e === null) {
            r = this.getNextRetryBackoffMs();
        } else if (e < 0) {
            this.state = "TRANSPARENT_ONLY";
            t(false);
            return;
        } else {
            r = e;
            this.nextRetryBackoffSec = this.initialRetryBackoffSec;
        }
        setTimeout(() => {
            var e, r;
            if (this.state !== "RETRY") {
                t(false);
                return;
            }
            if ((r = (e = this.retryThrottler) === null || e === void 0 ? void 0 : e.canRetryCall()) !== null && r !== void 0 ? r : true) {
                t(true);
                this.attempts += 1;
                this.startNewAttempt();
            } else {
                this.trace("Retry attempt denied by throttling policy");
                t(false);
            }
        }, r);
    }
    countActiveCalls() {
        let e = 0;
        for (const t of this.underlyingCalls) {
            if ((t === null || t === void 0 ? void 0 : t.state) === "ACTIVE") {
                e += 1;
            }
        }
        return e;
    }
    handleProcessedStatus(e, t, r) {
        var n, s, o;
        switch (this.state) {
          case "COMMITTED":
          case "NO_RETRY":
          case "TRANSPARENT_ONLY":
            this.commitCall(t);
            this.reportStatus(e);
            break;

          case "HEDGING":
            if (this.isStatusCodeInList((n = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && n !== void 0 ? n : [], e.code)) {
                (s = this.retryThrottler) === null || s === void 0 ? void 0 : s.addCallFailed();
                let n;
                if (r === null) {
                    n = 0;
                } else if (r < 0) {
                    this.state = "TRANSPARENT_ONLY";
                    this.commitCall(t);
                    this.reportStatus(e);
                    return;
                } else {
                    n = r;
                }
                setTimeout(() => {
                    this.maybeStartHedgingAttempt();
                    if (this.countActiveCalls() === 0) {
                        this.commitCall(t);
                        this.reportStatus(e);
                    }
                }, n);
            } else {
                this.commitCall(t);
                this.reportStatus(e);
            }
            break;

          case "RETRY":
            if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, e.code)) {
                (o = this.retryThrottler) === null || o === void 0 ? void 0 : o.addCallFailed();
                this.maybeRetryCall(r, r => {
                    if (!r) {
                        this.commitCall(t);
                        this.reportStatus(e);
                    }
                });
            } else {
                this.commitCall(t);
                this.reportStatus(e);
            }
            break;
        }
    }
    getPushback(e) {
        const t = e.get("grpc-retry-pushback-ms");
        if (t.length === 0) {
            return null;
        }
        try {
            return parseInt(t[0]);
        } catch (e) {
            return -1;
        }
    }
    handleChildStatus(e, t) {
        var r;
        if (this.underlyingCalls[t].state === "COMPLETED") {
            return;
        }
        this.trace("state=" + this.state + " handling status with progress " + e.progress + " from child [" + this.underlyingCalls[t].call.getCallNumber() + "] in state " + this.underlyingCalls[t].state);
        this.underlyingCalls[t].state = "COMPLETED";
        if (e.code === constants_1$2.Status.OK) {
            (r = this.retryThrottler) === null || r === void 0 ? void 0 : r.addCallSucceeded();
            this.commitCall(t);
            this.reportStatus(e);
            return;
        }
        if (this.state === "NO_RETRY") {
            this.commitCall(t);
            this.reportStatus(e);
            return;
        }
        if (this.state === "COMMITTED") {
            this.reportStatus(e);
            return;
        }
        const n = this.getPushback(e.metadata);
        switch (e.progress) {
          case "NOT_STARTED":
            this.startNewAttempt();
            break;

          case "REFUSED":
            if (this.transparentRetryUsed) {
                this.handleProcessedStatus(e, t, n);
            } else {
                this.transparentRetryUsed = true;
                this.startNewAttempt();
            }
            break;

          case "DROP":
            this.commitCall(t);
            this.reportStatus(e);
            break;

          case "PROCESSED":
            this.handleProcessedStatus(e, t, n);
            break;
        }
    }
    maybeStartHedgingAttempt() {
        if (this.state !== "HEDGING") {
            return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
            return;
        }
        if (this.attempts >= this.maxAttempts) {
            return;
        }
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
    }
    maybeStartHedgingTimer() {
        var e, t, r;
        if (this.hedgingTimer) {
            clearTimeout(this.hedgingTimer);
        }
        if (this.state !== "HEDGING") {
            return;
        }
        if (!this.callConfig.methodConfig.hedgingPolicy) {
            return;
        }
        const n = this.callConfig.methodConfig.hedgingPolicy;
        if (this.attempts >= this.maxAttempts) {
            return;
        }
        const s = (e = n.hedgingDelay) !== null && e !== void 0 ? e : "0s";
        const o = Number(s.substring(0, s.length - 1));
        this.hedgingTimer = setTimeout(() => {
            this.maybeStartHedgingAttempt();
        }, o * 1e3);
        (r = (t = this.hedgingTimer).unref) === null || r === void 0 ? void 0 : r.call(t);
    }
    startNewAttempt() {
        const e = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline);
        this.trace("Created child call [" + e.getCallNumber() + "] for attempt " + this.attempts);
        const t = this.underlyingCalls.length;
        this.underlyingCalls.push({
            state: "ACTIVE",
            call: e,
            nextMessageToSend: 0,
            startTime: new Date
        });
        const r = this.attempts - 1;
        const n = this.initialMetadata.clone();
        if (r > 0) {
            n.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${r}`);
        }
        let s = false;
        e.start(n, {
            onReceiveMetadata: n => {
                this.trace("Received metadata from child [" + e.getCallNumber() + "]");
                this.commitCall(t);
                s = true;
                if (r > 0) {
                    n.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${r}`);
                }
                if (this.underlyingCalls[t].state === "ACTIVE") {
                    this.listener.onReceiveMetadata(n);
                }
            },
            onReceiveMessage: r => {
                this.trace("Received message from child [" + e.getCallNumber() + "]");
                this.commitCall(t);
                if (this.underlyingCalls[t].state === "ACTIVE") {
                    this.listener.onReceiveMessage(r);
                }
            },
            onReceiveStatus: n => {
                this.trace("Received status from child [" + e.getCallNumber() + "]");
                if (!s && r > 0) {
                    n.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${r}`);
                }
                this.handleChildStatus(n, t);
            }
        });
        this.sendNextChildMessage(t);
        if (this.readStarted) {
            e.startRead();
        }
    }
    start(e, t) {
        this.trace("start called");
        this.listener = t;
        this.initialMetadata = e;
        this.attempts += 1;
        this.startNewAttempt();
        this.maybeStartHedgingTimer();
    }
    handleChildWriteCompleted(e) {
        var t, r;
        const n = this.underlyingCalls[e];
        const s = n.nextMessageToSend;
        (r = (t = this.getBufferEntry(s)).callback) === null || r === void 0 ? void 0 : r.call(t);
        this.clearSentMessages();
        n.nextMessageToSend += 1;
        this.sendNextChildMessage(e);
    }
    sendNextChildMessage(e) {
        const t = this.underlyingCalls[e];
        if (t.state === "COMPLETED") {
            return;
        }
        if (this.getBufferEntry(t.nextMessageToSend)) {
            const r = this.getBufferEntry(t.nextMessageToSend);
            switch (r.entryType) {
              case "MESSAGE":
                t.call.sendMessageWithContext({
                    callback: t => {
                        this.handleChildWriteCompleted(e);
                    }
                }, r.message.message);
                break;

              case "HALF_CLOSE":
                t.nextMessageToSend += 1;
                t.call.halfClose();
                break;
            }
        }
    }
    sendMessageWithContext(e, t) {
        var r;
        this.trace("write() called with message of length " + t.length);
        const n = {
            message: t,
            flags: e.flags
        };
        const s = this.getNextBufferIndex();
        const o = {
            entryType: "MESSAGE",
            message: n,
            allocated: this.bufferTracker.allocate(t.length, this.callNumber)
        };
        this.writeBuffer.push(o);
        if (o.allocated) {
            (r = e.callback) === null || r === void 0 ? void 0 : r.call(e);
            for (const [e, r] of this.underlyingCalls.entries()) {
                if (r.state === "ACTIVE" && r.nextMessageToSend === s) {
                    r.call.sendMessageWithContext({
                        callback: t => {
                            this.handleChildWriteCompleted(e);
                        }
                    }, t);
                }
            }
        } else {
            this.commitCallWithMostMessages();
            if (this.committedCallIndex === null) {
                return;
            }
            const r = this.underlyingCalls[this.committedCallIndex];
            o.callback = e.callback;
            if (r.state === "ACTIVE" && r.nextMessageToSend === s) {
                r.call.sendMessageWithContext({
                    callback: e => {
                        this.handleChildWriteCompleted(this.committedCallIndex);
                    }
                }, t);
            }
        }
    }
    startRead() {
        this.trace("startRead called");
        this.readStarted = true;
        for (const e of this.underlyingCalls) {
            if ((e === null || e === void 0 ? void 0 : e.state) === "ACTIVE") {
                e.call.startRead();
            }
        }
    }
    halfClose() {
        this.trace("halfClose called");
        const e = this.getNextBufferIndex();
        this.writeBuffer.push({
            entryType: "HALF_CLOSE",
            allocated: false
        });
        for (const t of this.underlyingCalls) {
            if ((t === null || t === void 0 ? void 0 : t.state) === "ACTIVE" && t.nextMessageToSend === e) {
                t.nextMessageToSend += 1;
                t.call.halfClose();
            }
        }
    }
    setCredentials(e) {
        throw new Error("Method not implemented.");
    }
    getMethod() {
        return this.methodName;
    }
    getHost() {
        return this.host;
    }
    getAuthContext() {
        if (this.committedCallIndex !== null) {
            return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();
        } else {
            return null;
        }
    }
}

retryingCall.RetryingCall = RetryingCall;

var subchannelInterface = {};

var hasRequiredSubchannelInterface;

function requireSubchannelInterface() {
    if (hasRequiredSubchannelInterface) return subchannelInterface;
    hasRequiredSubchannelInterface = 1;
    Object.defineProperty(subchannelInterface, "__esModule", {
        value: true
    });
    subchannelInterface.BaseSubchannelWrapper = void 0;
    class BaseSubchannelWrapper {
        constructor(e) {
            this.child = e;
            this.healthy = true;
            this.healthListeners = new Set;
            this.refcount = 0;
            this.dataWatchers = new Set;
            e.addHealthStateWatcher(e => {
                if (this.healthy) {
                    this.updateHealthListeners();
                }
            });
        }
        updateHealthListeners() {
            for (const e of this.healthListeners) {
                e(this.isHealthy());
            }
        }
        getConnectivityState() {
            return this.child.getConnectivityState();
        }
        addConnectivityStateListener(e) {
            this.child.addConnectivityStateListener(e);
        }
        removeConnectivityStateListener(e) {
            this.child.removeConnectivityStateListener(e);
        }
        startConnecting() {
            this.child.startConnecting();
        }
        getAddress() {
            return this.child.getAddress();
        }
        throttleKeepalive(e) {
            this.child.throttleKeepalive(e);
        }
        ref() {
            this.child.ref();
            this.refcount += 1;
        }
        unref() {
            this.child.unref();
            this.refcount -= 1;
            if (this.refcount === 0) {
                this.destroy();
            }
        }
        destroy() {
            for (const e of this.dataWatchers) {
                e.destroy();
            }
        }
        getChannelzRef() {
            return this.child.getChannelzRef();
        }
        isHealthy() {
            return this.healthy && this.child.isHealthy();
        }
        addHealthStateWatcher(e) {
            this.healthListeners.add(e);
        }
        removeHealthStateWatcher(e) {
            this.healthListeners.delete(e);
        }
        addDataWatcher(e) {
            e.setSubchannel(this.getRealSubchannel());
            this.dataWatchers.add(e);
        }
        setHealthy(e) {
            if (e !== this.healthy) {
                this.healthy = e;
                if (this.child.isHealthy()) {
                    this.updateHealthListeners();
                }
            }
        }
        getRealSubchannel() {
            return this.child.getRealSubchannel();
        }
        realSubchannelEquals(e) {
            return this.getRealSubchannel() === e.getRealSubchannel();
        }
        getCallCredentials() {
            return this.child.getCallCredentials();
        }
        getChannel() {
            return this.child.getChannel();
        }
    }
    subchannelInterface.BaseSubchannelWrapper = BaseSubchannelWrapper;
    return subchannelInterface;
}

var hasRequiredInternalChannel;

function requireInternalChannel() {
    if (hasRequiredInternalChannel) return internalChannel;
    hasRequiredInternalChannel = 1;
    (function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.InternalChannel = e.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0;
        const t = channelCredentials;
        const r = resolvingLoadBalancer;
        const n = requireSubchannelPool();
        const s = requirePicker();
        const o = metadata;
        const a = constants;
        const l = requireFilterStack();
        const c = compressionFilter;
        const u = resolver;
        const d = logging$8;
        const h = http_proxy;
        const p = uriParser;
        const g = connectivityState;
        const m = requireChannelz();
        const _ = loadBalancingCall;
        const E = deadline;
        const v = resolvingCall;
        const y = callNumber;
        const S = controlPlaneStatus;
        const A = retryingCall;
        const b = requireSubchannelInterface();
        const C = 2147483647;
        const w = 1e3;
        const I = 30 * 60 * 1e3;
        const T = new Map;
        const R = 1 << 24;
        const k = 1 << 20;
        class ChannelSubchannelWrapper extends b.BaseSubchannelWrapper {
            constructor(e, t) {
                super(e);
                this.channel = t;
                this.refCount = 0;
                this.subchannelStateListener = (e, r, n, s) => {
                    t.throttleKeepalive(s);
                };
            }
            ref() {
                if (this.refCount === 0) {
                    this.child.addConnectivityStateListener(this.subchannelStateListener);
                    this.channel.addWrappedSubchannel(this);
                }
                this.child.ref();
                this.refCount += 1;
            }
            unref() {
                this.child.unref();
                this.refCount -= 1;
                if (this.refCount <= 0) {
                    this.child.removeConnectivityStateListener(this.subchannelStateListener);
                    this.channel.removeWrappedSubchannel(this);
                }
            }
        }
        class ShutdownPicker {
            pick(e) {
                return {
                    pickResultType: s.PickResultType.DROP,
                    status: {
                        code: a.Status.UNAVAILABLE,
                        details: "Channel closed before call started",
                        metadata: new o.Metadata
                    },
                    subchannel: null,
                    onCallStarted: null,
                    onCallEnded: null
                };
            }
        }
        e.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel";
        class ChannelzInfoTracker {
            constructor(e) {
                this.target = e;
                this.trace = new m.ChannelzTrace;
                this.callTracker = new m.ChannelzCallTracker;
                this.childrenTracker = new m.ChannelzChildrenTracker;
                this.state = g.ConnectivityState.IDLE;
            }
            getChannelzInfoCallback() {
                return () => ({
                    target: this.target,
                    state: this.state,
                    trace: this.trace,
                    callTracker: this.callTracker,
                    children: this.childrenTracker.getChildLists()
                });
            }
        }
        class InternalChannel {
            constructor(o, _, E) {
                var v, y, b, C, P, $;
                this.credentials = _;
                this.options = E;
                this.connectivityState = g.ConnectivityState.IDLE;
                this.currentPicker = new s.UnavailablePicker;
                this.configSelectionQueue = [];
                this.pickQueue = [];
                this.connectivityStateWatchers = [];
                this.callRefTimer = null;
                this.configSelector = null;
                this.currentResolutionError = null;
                this.wrappedSubchannels = new Set;
                this.callCount = 0;
                this.idleTimer = null;
                this.channelzEnabled = true;
                this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
                if (typeof o !== "string") {
                    throw new TypeError("Channel target must be a string");
                }
                if (!(_ instanceof t.ChannelCredentials)) {
                    throw new TypeError("Channel credentials must be a ChannelCredentials object");
                }
                if (E) {
                    if (typeof E !== "object") {
                        throw new TypeError("Channel options must be an object");
                    }
                }
                this.channelzInfoTracker = new ChannelzInfoTracker(o);
                const O = (0, p.parseUri)(o);
                if (O === null) {
                    throw new Error(`Could not parse target name "${o}"`);
                }
                const B = (0, u.mapUriDefaultScheme)(O);
                if (B === null) {
                    throw new Error(`Could not find a default scheme for target name "${o}"`);
                }
                if (this.options["grpc.enable_channelz"] === 0) {
                    this.channelzEnabled = false;
                }
                this.channelzRef = (0, m.registerChannelzChannel)(o, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled);
                if (this.channelzEnabled) {
                    this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created");
                }
                if (this.options["grpc.default_authority"]) {
                    this.defaultAuthority = this.options["grpc.default_authority"];
                } else {
                    this.defaultAuthority = (0, u.getDefaultAuthority)(B);
                }
                const N = (0, h.mapProxyName)(B, E);
                this.target = N.target;
                this.options = Object.assign({}, this.options, N.extraOptions);
                this.subchannelPool = (0, n.getSubchannelPool)(((v = this.options["grpc.use_local_subchannel_pool"]) !== null && v !== void 0 ? v : 0) === 0);
                this.retryBufferTracker = new A.MessageBufferTracker((y = this.options["grpc.retry_buffer_size"]) !== null && y !== void 0 ? y : R, (b = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && b !== void 0 ? b : k);
                this.keepaliveTime = (C = this.options["grpc.keepalive_time_ms"]) !== null && C !== void 0 ? C : -1;
                this.idleTimeoutMs = Math.max((P = this.options["grpc.client_idle_timeout_ms"]) !== null && P !== void 0 ? P : I, w);
                const D = {
                    createSubchannel: (t, r) => {
                        const n = {};
                        for (const [t, s] of Object.entries(r)) {
                            if (!t.startsWith(e.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) {
                                n[t] = s;
                            }
                        }
                        const s = this.subchannelPool.getOrCreateSubchannel(this.target, t, n, this.credentials);
                        s.throttleKeepalive(this.keepaliveTime);
                        if (this.channelzEnabled) {
                            this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", s.getChannelzRef());
                        }
                        const o = new ChannelSubchannelWrapper(s, this);
                        return o;
                    },
                    updateState: (e, t) => {
                        this.currentPicker = t;
                        const r = this.pickQueue.slice();
                        this.pickQueue = [];
                        if (r.length > 0) {
                            this.callRefTimerUnref();
                        }
                        for (const e of r) {
                            e.doPick();
                        }
                        this.updateState(e);
                    },
                    requestReresolution: () => {
                        throw new Error("Resolving load balancer should never call requestReresolution");
                    },
                    addChannelzChild: e => {
                        if (this.channelzEnabled) {
                            this.channelzInfoTracker.childrenTracker.refChild(e);
                        }
                    },
                    removeChannelzChild: e => {
                        if (this.channelzEnabled) {
                            this.channelzInfoTracker.childrenTracker.unrefChild(e);
                        }
                    }
                };
                this.resolvingLoadBalancer = new r.ResolvingLoadBalancer(this.target, D, this.options, (e, t) => {
                    var r;
                    if (e.retryThrottling) {
                        T.set(this.getTarget(), new A.RetryThrottler(e.retryThrottling.maxTokens, e.retryThrottling.tokenRatio, T.get(this.getTarget())));
                    } else {
                        T.delete(this.getTarget());
                    }
                    if (this.channelzEnabled) {
                        this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded");
                    }
                    (r = this.configSelector) === null || r === void 0 ? void 0 : r.unref();
                    this.configSelector = t;
                    this.currentResolutionError = null;
                    process.nextTick(() => {
                        const e = this.configSelectionQueue;
                        this.configSelectionQueue = [];
                        if (e.length > 0) {
                            this.callRefTimerUnref();
                        }
                        for (const t of e) {
                            t.getConfig();
                        }
                    });
                }, e => {
                    if (this.channelzEnabled) {
                        this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + e.code + ' and details "' + e.details + '"');
                    }
                    if (this.configSelectionQueue.length > 0) {
                        this.trace("Name resolution failed with calls queued for config selection");
                    }
                    if (this.configSelector === null) {
                        this.currentResolutionError = Object.assign(Object.assign({}, (0, S.restrictControlPlaneStatusCode)(e.code, e.details)), {
                            metadata: e.metadata
                        });
                    }
                    const t = this.configSelectionQueue;
                    this.configSelectionQueue = [];
                    if (t.length > 0) {
                        this.callRefTimerUnref();
                    }
                    for (const r of t) {
                        r.reportResolverError(e);
                    }
                });
                this.filterStackFactory = new l.FilterStackFactory([ new c.CompressionFilterFactory(this, this.options) ]);
                this.trace("Channel constructed with options " + JSON.stringify(E, undefined, 2));
                const L = new Error;
                if ((0, d.isTracerEnabled)("channel_stacktrace")) {
                    (0, d.trace)(a.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") " + "Channel constructed \n" + (($ = L.stack) === null || $ === void 0 ? void 0 : $.substring(L.stack.indexOf("\n") + 1)));
                }
                this.lastActivityTimestamp = new Date;
            }
            trace(e, t) {
                (0, d.trace)(t !== null && t !== void 0 ? t : a.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, 
                p.uriToString)(this.target) + " " + e);
            }
            callRefTimerRef() {
                var e, t, r, n;
                if (!this.callRefTimer) {
                    this.callRefTimer = setInterval(() => {}, C);
                }
                if (!((t = (e = this.callRefTimer).hasRef) === null || t === void 0 ? void 0 : t.call(e))) {
                    this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
                    (n = (r = this.callRefTimer).ref) === null || n === void 0 ? void 0 : n.call(r);
                }
            }
            callRefTimerUnref() {
                var e, t, r;
                if (!((e = this.callRefTimer) === null || e === void 0 ? void 0 : e.hasRef) || this.callRefTimer.hasRef()) {
                    this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length);
                    (r = (t = this.callRefTimer) === null || t === void 0 ? void 0 : t.unref) === null || r === void 0 ? void 0 : r.call(t);
                }
            }
            removeConnectivityStateWatcher(e) {
                const t = this.connectivityStateWatchers.findIndex(t => t === e);
                if (t >= 0) {
                    this.connectivityStateWatchers.splice(t, 1);
                }
            }
            updateState(e) {
                (0, d.trace)(a.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, 
                p.uriToString)(this.target) + " " + g.ConnectivityState[this.connectivityState] + " -> " + g.ConnectivityState[e]);
                if (this.channelzEnabled) {
                    this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + g.ConnectivityState[e]);
                }
                this.connectivityState = e;
                this.channelzInfoTracker.state = e;
                const t = this.connectivityStateWatchers.slice();
                for (const r of t) {
                    if (e !== r.currentState) {
                        if (r.timer) {
                            clearTimeout(r.timer);
                        }
                        this.removeConnectivityStateWatcher(r);
                        r.callback();
                    }
                }
                if (e !== g.ConnectivityState.TRANSIENT_FAILURE) {
                    this.currentResolutionError = null;
                }
            }
            throttleKeepalive(e) {
                if (e > this.keepaliveTime) {
                    this.keepaliveTime = e;
                    for (const t of this.wrappedSubchannels) {
                        t.throttleKeepalive(e);
                    }
                }
            }
            addWrappedSubchannel(e) {
                this.wrappedSubchannels.add(e);
            }
            removeWrappedSubchannel(e) {
                this.wrappedSubchannels.delete(e);
            }
            doPick(e, t) {
                return this.currentPicker.pick({
                    metadata: e,
                    extraPickInfo: t
                });
            }
            queueCallForPick(e) {
                this.pickQueue.push(e);
                this.callRefTimerRef();
            }
            getConfig(e, t) {
                if (this.connectivityState !== g.ConnectivityState.SHUTDOWN) {
                    this.resolvingLoadBalancer.exitIdle();
                }
                if (this.configSelector) {
                    return {
                        type: "SUCCESS",
                        config: this.configSelector.invoke(e, t, this.randomChannelId)
                    };
                } else {
                    if (this.currentResolutionError) {
                        return {
                            type: "ERROR",
                            error: this.currentResolutionError
                        };
                    } else {
                        return {
                            type: "NONE"
                        };
                    }
                }
            }
            queueCallForConfig(e) {
                this.configSelectionQueue.push(e);
                this.callRefTimerRef();
            }
            enterIdle() {
                this.resolvingLoadBalancer.destroy();
                this.updateState(g.ConnectivityState.IDLE);
                this.currentPicker = new s.QueuePicker(this.resolvingLoadBalancer);
                if (this.idleTimer) {
                    clearTimeout(this.idleTimer);
                    this.idleTimer = null;
                }
                if (this.callRefTimer) {
                    clearInterval(this.callRefTimer);
                    this.callRefTimer = null;
                }
            }
            startIdleTimeout(e) {
                var t, r;
                this.idleTimer = setTimeout(() => {
                    if (this.callCount > 0) {
                        this.startIdleTimeout(this.idleTimeoutMs);
                        return;
                    }
                    const e = new Date;
                    const t = e.valueOf() - this.lastActivityTimestamp.valueOf();
                    if (t >= this.idleTimeoutMs) {
                        this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity");
                        this.enterIdle();
                    } else {
                        this.startIdleTimeout(this.idleTimeoutMs - t);
                    }
                }, e);
                (r = (t = this.idleTimer).unref) === null || r === void 0 ? void 0 : r.call(t);
            }
            maybeStartIdleTimer() {
                if (this.connectivityState !== g.ConnectivityState.SHUTDOWN && !this.idleTimer) {
                    this.startIdleTimeout(this.idleTimeoutMs);
                }
            }
            onCallStart() {
                if (this.channelzEnabled) {
                    this.channelzInfoTracker.callTracker.addCallStarted();
                }
                this.callCount += 1;
            }
            onCallEnd(e) {
                if (this.channelzEnabled) {
                    if (e.code === a.Status.OK) {
                        this.channelzInfoTracker.callTracker.addCallSucceeded();
                    } else {
                        this.channelzInfoTracker.callTracker.addCallFailed();
                    }
                }
                this.callCount -= 1;
                this.lastActivityTimestamp = new Date;
                this.maybeStartIdleTimer();
            }
            createLoadBalancingCall(e, t, r, n, s) {
                const o = (0, y.getNextCallNumber)();
                this.trace("createLoadBalancingCall [" + o + '] method="' + t + '"');
                return new _.LoadBalancingCall(this, e, t, r, n, s, o);
            }
            createRetryingCall(e, t, r, n, s) {
                const o = (0, y.getNextCallNumber)();
                this.trace("createRetryingCall [" + o + '] method="' + t + '"');
                return new A.RetryingCall(this, e, t, r, n, s, o, this.retryBufferTracker, T.get(this.getTarget()));
            }
            createResolvingCall(e, t, r, n, s) {
                const o = (0, y.getNextCallNumber)();
                this.trace("createResolvingCall [" + o + '] method="' + e + '", deadline=' + (0, 
                E.deadlineToString)(t));
                const l = {
                    deadline: t,
                    flags: s !== null && s !== void 0 ? s : a.Propagate.DEFAULTS,
                    host: r !== null && r !== void 0 ? r : this.defaultAuthority,
                    parentCall: n
                };
                const c = new v.ResolvingCall(this, e, l, this.filterStackFactory.clone(), o);
                this.onCallStart();
                c.addStatusWatcher(e => {
                    this.onCallEnd(e);
                });
                return c;
            }
            close() {
                var e;
                this.resolvingLoadBalancer.destroy();
                this.updateState(g.ConnectivityState.SHUTDOWN);
                this.currentPicker = new ShutdownPicker;
                for (const e of this.configSelectionQueue) {
                    e.cancelWithStatus(a.Status.UNAVAILABLE, "Channel closed before call started");
                }
                this.configSelectionQueue = [];
                for (const e of this.pickQueue) {
                    e.cancelWithStatus(a.Status.UNAVAILABLE, "Channel closed before call started");
                }
                this.pickQueue = [];
                if (this.callRefTimer) {
                    clearInterval(this.callRefTimer);
                }
                if (this.idleTimer) {
                    clearTimeout(this.idleTimer);
                }
                if (this.channelzEnabled) {
                    (0, m.unregisterChannelzRef)(this.channelzRef);
                }
                this.subchannelPool.unrefUnusedSubchannels();
                (e = this.configSelector) === null || e === void 0 ? void 0 : e.unref();
                this.configSelector = null;
            }
            getTarget() {
                return (0, p.uriToString)(this.target);
            }
            getConnectivityState(e) {
                const t = this.connectivityState;
                if (e) {
                    this.resolvingLoadBalancer.exitIdle();
                    this.lastActivityTimestamp = new Date;
                    this.maybeStartIdleTimer();
                }
                return t;
            }
            watchConnectivityState(e, t, r) {
                if (this.connectivityState === g.ConnectivityState.SHUTDOWN) {
                    throw new Error("Channel has been shut down");
                }
                let n = null;
                if (t !== Infinity) {
                    const e = t instanceof Date ? t : new Date(t);
                    const o = new Date;
                    if (t === -Infinity || e <= o) {
                        process.nextTick(r, new Error("Deadline passed without connectivity state change"));
                        return;
                    }
                    n = setTimeout(() => {
                        this.removeConnectivityStateWatcher(s);
                        r(new Error("Deadline passed without connectivity state change"));
                    }, e.getTime() - o.getTime());
                }
                const s = {
                    currentState: e,
                    callback: r,
                    timer: n
                };
                this.connectivityStateWatchers.push(s);
            }
            getChannelzRef() {
                return this.channelzRef;
            }
            createCall(e, t, r, n, s) {
                if (typeof e !== "string") {
                    throw new TypeError("Channel#createCall: method must be a string");
                }
                if (!(typeof t === "number" || t instanceof Date)) {
                    throw new TypeError("Channel#createCall: deadline must be a number or Date");
                }
                if (this.connectivityState === g.ConnectivityState.SHUTDOWN) {
                    throw new Error("Channel has been shut down");
                }
                return this.createResolvingCall(e, t, r, n, s);
            }
            getOptions() {
                return this.options;
            }
        }
        e.InternalChannel = InternalChannel;
    })(internalChannel);
    return internalChannel;
}

var hasRequiredChannel;

function requireChannel() {
    if (hasRequiredChannel) return channel;
    hasRequiredChannel = 1;
    Object.defineProperty(channel, "__esModule", {
        value: true
    });
    channel.ChannelImplementation = void 0;
    const e = channelCredentials;
    const t = requireInternalChannel();
    class ChannelImplementation {
        constructor(r, n, s) {
            if (typeof r !== "string") {
                throw new TypeError("Channel target must be a string");
            }
            if (!(n instanceof e.ChannelCredentials)) {
                throw new TypeError("Channel credentials must be a ChannelCredentials object");
            }
            if (s) {
                if (typeof s !== "object") {
                    throw new TypeError("Channel options must be an object");
                }
            }
            this.internalChannel = new t.InternalChannel(r, n, s);
        }
        close() {
            this.internalChannel.close();
        }
        getTarget() {
            return this.internalChannel.getTarget();
        }
        getConnectivityState(e) {
            return this.internalChannel.getConnectivityState(e);
        }
        watchConnectivityState(e, t, r) {
            this.internalChannel.watchConnectivityState(e, t, r);
        }
        getChannelzRef() {
            return this.internalChannel.getChannelzRef();
        }
        createCall(e, t, r, n, s) {
            if (typeof e !== "string") {
                throw new TypeError("Channel#createCall: method must be a string");
            }
            if (!(typeof t === "number" || t instanceof Date)) {
                throw new TypeError("Channel#createCall: deadline must be a number or Date");
            }
            return this.internalChannel.createCall(e, t, r, n, s);
        }
    }
    channel.ChannelImplementation = ChannelImplementation;
    return channel;
}

var server = {};

var serverCall = {};

Object.defineProperty(serverCall, "__esModule", {
    value: true
});

serverCall.ServerDuplexStreamImpl = serverCall.ServerWritableStreamImpl = serverCall.ServerReadableStreamImpl = serverCall.ServerUnaryCallImpl = void 0;

serverCall.serverErrorToStatus = serverErrorToStatus;

const events_1 = require$$0__default$8.default;

const stream_1 = require$$0__default$7.default;

const constants_1$1 = constants;

const metadata_1 = metadata;

function serverErrorToStatus(e, t) {
    var r;
    const n = {
        code: constants_1$1.Status.UNKNOWN,
        details: "message" in e ? e.message : "Unknown Error",
        metadata: (r = t !== null && t !== void 0 ? t : e.metadata) !== null && r !== void 0 ? r : null
    };
    if ("code" in e && typeof e.code === "number" && Number.isInteger(e.code)) {
        n.code = e.code;
        if ("details" in e && typeof e.details === "string") {
            n.details = e.details;
        }
    }
    return n;
}

class ServerUnaryCallImpl extends events_1.EventEmitter {
    constructor(e, t, r, n) {
        super();
        this.path = e;
        this.call = t;
        this.metadata = r;
        this.request = n;
        this.cancelled = false;
    }
    getPeer() {
        return this.call.getPeer();
    }
    sendMetadata(e) {
        this.call.sendMetadata(e);
    }
    getDeadline() {
        return this.call.getDeadline();
    }
    getPath() {
        return this.path;
    }
    getHost() {
        return this.call.getHost();
    }
    getAuthContext() {
        return this.call.getAuthContext();
    }
    getMetricsRecorder() {
        return this.call.getMetricsRecorder();
    }
}

serverCall.ServerUnaryCallImpl = ServerUnaryCallImpl;

class ServerReadableStreamImpl extends stream_1.Readable {
    constructor(e, t, r) {
        super({
            objectMode: true
        });
        this.path = e;
        this.call = t;
        this.metadata = r;
        this.cancelled = false;
    }
    _read(e) {
        this.call.startRead();
    }
    getPeer() {
        return this.call.getPeer();
    }
    sendMetadata(e) {
        this.call.sendMetadata(e);
    }
    getDeadline() {
        return this.call.getDeadline();
    }
    getPath() {
        return this.path;
    }
    getHost() {
        return this.call.getHost();
    }
    getAuthContext() {
        return this.call.getAuthContext();
    }
    getMetricsRecorder() {
        return this.call.getMetricsRecorder();
    }
}

serverCall.ServerReadableStreamImpl = ServerReadableStreamImpl;

class ServerWritableStreamImpl extends stream_1.Writable {
    constructor(e, t, r, n) {
        super({
            objectMode: true
        });
        this.path = e;
        this.call = t;
        this.metadata = r;
        this.request = n;
        this.pendingStatus = {
            code: constants_1$1.Status.OK,
            details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata;
        this.on("error", e => {
            this.pendingStatus = serverErrorToStatus(e);
            this.end();
        });
    }
    getPeer() {
        return this.call.getPeer();
    }
    sendMetadata(e) {
        this.call.sendMetadata(e);
    }
    getDeadline() {
        return this.call.getDeadline();
    }
    getPath() {
        return this.path;
    }
    getHost() {
        return this.call.getHost();
    }
    getAuthContext() {
        return this.call.getAuthContext();
    }
    getMetricsRecorder() {
        return this.call.getMetricsRecorder();
    }
    _write(e, t, r) {
        this.call.sendMessage(e, r);
    }
    _final(e) {
        var t;
        e(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), {
            metadata: (t = this.pendingStatus.metadata) !== null && t !== void 0 ? t : this.trailingMetadata
        }));
    }
    end(e) {
        if (e) {
            this.trailingMetadata = e;
        }
        return super.end();
    }
}

serverCall.ServerWritableStreamImpl = ServerWritableStreamImpl;

class ServerDuplexStreamImpl extends stream_1.Duplex {
    constructor(e, t, r) {
        super({
            objectMode: true
        });
        this.path = e;
        this.call = t;
        this.metadata = r;
        this.pendingStatus = {
            code: constants_1$1.Status.OK,
            details: "OK"
        };
        this.cancelled = false;
        this.trailingMetadata = new metadata_1.Metadata;
        this.on("error", e => {
            this.pendingStatus = serverErrorToStatus(e);
            this.end();
        });
    }
    getPeer() {
        return this.call.getPeer();
    }
    sendMetadata(e) {
        this.call.sendMetadata(e);
    }
    getDeadline() {
        return this.call.getDeadline();
    }
    getPath() {
        return this.path;
    }
    getHost() {
        return this.call.getHost();
    }
    getAuthContext() {
        return this.call.getAuthContext();
    }
    getMetricsRecorder() {
        return this.call.getMetricsRecorder();
    }
    _read(e) {
        this.call.startRead();
    }
    _write(e, t, r) {
        this.call.sendMessage(e, r);
    }
    _final(e) {
        var t;
        e(null);
        this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), {
            metadata: (t = this.pendingStatus.metadata) !== null && t !== void 0 ? t : this.trailingMetadata
        }));
    }
    end(e) {
        if (e) {
            this.trailingMetadata = e;
        }
        return super.end();
    }
}

serverCall.ServerDuplexStreamImpl = ServerDuplexStreamImpl;

var serverCredentials = {};

Object.defineProperty(serverCredentials, "__esModule", {
    value: true
});

serverCredentials.ServerCredentials = void 0;

serverCredentials.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials;

serverCredentials.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors;

const tls_helpers_1 = tlsHelpers;

class ServerCredentials {
    constructor(e, t) {
        this.serverConstructorOptions = e;
        this.watchers = new Set;
        this.latestContextOptions = null;
        this.latestContextOptions = t !== null && t !== void 0 ? t : null;
    }
    _addWatcher(e) {
        this.watchers.add(e);
    }
    _removeWatcher(e) {
        this.watchers.delete(e);
    }
    getWatcherCount() {
        return this.watchers.size;
    }
    updateSecureContextOptions(e) {
        this.latestContextOptions = e;
        for (const e of this.watchers) {
            e(this.latestContextOptions);
        }
    }
    _isSecure() {
        return this.serverConstructorOptions !== null;
    }
    _getSecureContextOptions() {
        return this.latestContextOptions;
    }
    _getConstructorOptions() {
        return this.serverConstructorOptions;
    }
    _getInterceptors() {
        return [];
    }
    static createInsecure() {
        return new InsecureServerCredentials;
    }
    static createSsl(e, t, r = false) {
        var n;
        if (e !== null && !Buffer.isBuffer(e)) {
            throw new TypeError("rootCerts must be null or a Buffer");
        }
        if (!Array.isArray(t)) {
            throw new TypeError("keyCertPairs must be an array");
        }
        if (typeof r !== "boolean") {
            throw new TypeError("checkClientCertificate must be a boolean");
        }
        const s = [];
        const o = [];
        for (let e = 0; e < t.length; e++) {
            const r = t[e];
            if (r === null || typeof r !== "object") {
                throw new TypeError(`keyCertPair[${e}] must be an object`);
            }
            if (!Buffer.isBuffer(r.private_key)) {
                throw new TypeError(`keyCertPair[${e}].private_key must be a Buffer`);
            }
            if (!Buffer.isBuffer(r.cert_chain)) {
                throw new TypeError(`keyCertPair[${e}].cert_chain must be a Buffer`);
            }
            s.push(r.cert_chain);
            o.push(r.private_key);
        }
        return new SecureServerCredentials({
            requestCert: r,
            ciphers: tls_helpers_1.CIPHER_SUITES
        }, {
            ca: (n = e !== null && e !== void 0 ? e : (0, tls_helpers_1.getDefaultRootsData)()) !== null && n !== void 0 ? n : undefined,
            cert: s,
            key: o
        });
    }
}

serverCredentials.ServerCredentials = ServerCredentials;

class InsecureServerCredentials extends ServerCredentials {
    constructor() {
        super(null);
    }
    _getSettings() {
        return null;
    }
    _equals(e) {
        return e instanceof InsecureServerCredentials;
    }
}

class SecureServerCredentials extends ServerCredentials {
    constructor(e, t) {
        super(e, t);
        this.options = Object.assign(Object.assign({}, e), t);
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (!(e instanceof SecureServerCredentials)) {
            return false;
        }
        if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(e.options.ca)) {
            if (!this.options.ca.equals(e.options.ca)) {
                return false;
            }
        } else {
            if (this.options.ca !== e.options.ca) {
                return false;
            }
        }
        if (Array.isArray(this.options.cert) && Array.isArray(e.options.cert)) {
            if (this.options.cert.length !== e.options.cert.length) {
                return false;
            }
            for (let t = 0; t < this.options.cert.length; t++) {
                const r = this.options.cert[t];
                const n = e.options.cert[t];
                if (Buffer.isBuffer(r) && Buffer.isBuffer(n)) {
                    if (!r.equals(n)) {
                        return false;
                    }
                } else {
                    if (r !== n) {
                        return false;
                    }
                }
            }
        } else {
            if (this.options.cert !== e.options.cert) {
                return false;
            }
        }
        if (Array.isArray(this.options.key) && Array.isArray(e.options.key)) {
            if (this.options.key.length !== e.options.key.length) {
                return false;
            }
            for (let t = 0; t < this.options.key.length; t++) {
                const r = this.options.key[t];
                const n = e.options.key[t];
                if (Buffer.isBuffer(r) && Buffer.isBuffer(n)) {
                    if (!r.equals(n)) {
                        return false;
                    }
                } else {
                    if (r !== n) {
                        return false;
                    }
                }
            }
        } else {
            if (this.options.key !== e.options.key) {
                return false;
            }
        }
        if (this.options.requestCert !== e.options.requestCert) {
            return false;
        }
        return true;
    }
}

class CertificateProviderServerCredentials extends ServerCredentials {
    constructor(e, t, r) {
        super({
            requestCert: t !== null,
            rejectUnauthorized: r,
            ciphers: tls_helpers_1.CIPHER_SUITES
        });
        this.identityCertificateProvider = e;
        this.caCertificateProvider = t;
        this.requireClientCertificate = r;
        this.latestCaUpdate = null;
        this.latestIdentityUpdate = null;
        this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this);
        this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this);
    }
    _addWatcher(e) {
        var t;
        if (this.getWatcherCount() === 0) {
            (t = this.caCertificateProvider) === null || t === void 0 ? void 0 : t.addCaCertificateListener(this.caCertificateUpdateListener);
            this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
        super._addWatcher(e);
    }
    _removeWatcher(e) {
        var t;
        super._removeWatcher(e);
        if (this.getWatcherCount() === 0) {
            (t = this.caCertificateProvider) === null || t === void 0 ? void 0 : t.removeCaCertificateListener(this.caCertificateUpdateListener);
            this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener);
        }
    }
    _equals(e) {
        if (this === e) {
            return true;
        }
        if (!(e instanceof CertificateProviderServerCredentials)) {
            return false;
        }
        return this.caCertificateProvider === e.caCertificateProvider && this.identityCertificateProvider === e.identityCertificateProvider && this.requireClientCertificate === e.requireClientCertificate;
    }
    calculateSecureContextOptions() {
        var e;
        if (this.latestIdentityUpdate === null) {
            return null;
        }
        if (this.caCertificateProvider !== null && this.latestCaUpdate === null) {
            return null;
        }
        return {
            ca: (e = this.latestCaUpdate) === null || e === void 0 ? void 0 : e.caCertificate,
            cert: [ this.latestIdentityUpdate.certificate ],
            key: [ this.latestIdentityUpdate.privateKey ]
        };
    }
    finalizeUpdate() {
        const e = this.calculateSecureContextOptions();
        this.updateSecureContextOptions(e);
    }
    handleCaCertificateUpdate(e) {
        this.latestCaUpdate = e;
        this.finalizeUpdate();
    }
    handleIdentityCertitificateUpdate(e) {
        this.latestIdentityUpdate = e;
        this.finalizeUpdate();
    }
}

function createCertificateProviderServerCredentials(e, t, r) {
    return new CertificateProviderServerCredentials(e, t, r);
}

class InterceptorServerCredentials extends ServerCredentials {
    constructor(e, t) {
        super({});
        this.childCredentials = e;
        this.interceptors = t;
    }
    _isSecure() {
        return this.childCredentials._isSecure();
    }
    _equals(e) {
        if (!(e instanceof InterceptorServerCredentials)) {
            return false;
        }
        if (!this.childCredentials._equals(e.childCredentials)) {
            return false;
        }
        if (this.interceptors.length !== e.interceptors.length) {
            return false;
        }
        for (let t = 0; t < this.interceptors.length; t++) {
            if (this.interceptors[t] !== e.interceptors[t]) {
                return false;
            }
        }
        return true;
    }
    _getInterceptors() {
        return this.interceptors;
    }
    _addWatcher(e) {
        this.childCredentials._addWatcher(e);
    }
    _removeWatcher(e) {
        this.childCredentials._removeWatcher(e);
    }
    _getConstructorOptions() {
        return this.childCredentials._getConstructorOptions();
    }
    _getSecureContextOptions() {
        return this.childCredentials._getSecureContextOptions();
    }
}

function createServerCredentialsWithInterceptors(e, t) {
    return new InterceptorServerCredentials(e, t);
}

var serverInterceptors = {};

var orca = {};

var duration = {};

var hasRequiredDuration;

function requireDuration() {
    if (hasRequiredDuration) return duration;
    hasRequiredDuration = 1;
    Object.defineProperty(duration, "__esModule", {
        value: true
    });
    duration.durationMessageToDuration = e;
    duration.msToDuration = t;
    duration.durationToMs = r;
    duration.isDuration = n;
    duration.isDurationMessage = s;
    duration.parseDuration = a;
    duration.durationToString = l;
    function e(e) {
        return {
            seconds: Number.parseInt(e.seconds),
            nanos: e.nanos
        };
    }
    function t(e) {
        return {
            seconds: e / 1e3 | 0,
            nanos: e % 1e3 * 1e6 | 0
        };
    }
    function r(e) {
        return e.seconds * 1e3 + e.nanos / 1e6 | 0;
    }
    function n(e) {
        return typeof e.seconds === "number" && typeof e.nanos === "number";
    }
    function s(e) {
        return typeof e.seconds === "string" && typeof e.nanos === "number";
    }
    const o = /^(\d+)(?:\.(\d+))?s$/;
    function a(e) {
        const t = e.match(o);
        if (!t) {
            return null;
        }
        return {
            seconds: Number.parseInt(t[1], 10),
            nanos: t[2] ? Number.parseInt(t[2].padEnd(9, "0"), 10) : 0
        };
    }
    function l(e) {
        if (e.nanos === 0) {
            return `${e.seconds}s`;
        }
        let t;
        if (e.nanos % 1e6 === 0) {
            t = 1e6;
        } else if (e.nanos % 1e3 === 0) {
            t = 1e3;
        } else {
            t = 1;
        }
        return `${e.seconds}.${e.nanos / t}s`;
    }
    return duration;
}

var hasRequiredOrca;

function requireOrca() {
    if (hasRequiredOrca) return orca;
    hasRequiredOrca = 1;
    (function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.OrcaOobMetricsSubchannelWrapper = e.GRPC_METRICS_HEADER = e.ServerMetricRecorder = e.PerRequestMetricRecorder = void 0;
        e.createOrcaClient = d;
        e.createMetricsReader = p;
        const t = requireMakeClient();
        const r = requireDuration();
        const n = channelCredentials;
        const s = requireSubchannelInterface();
        const o = constants;
        const a = requireBackoffTimeout();
        const l = connectivityState;
        function c() {
            const e = requireSrc().loadSync;
            const r = e("xds/service/orca/v3/orca.proto", {
                keepCase: true,
                longs: String,
                enums: String,
                defaults: true,
                oneofs: true,
                includeDirs: [ `${__dirname}/../../proto/xds`, `${__dirname}/../../proto/protoc-gen-validate` ]
            });
            return (0, t.loadPackageDefinition)(r);
        }
        class PerRequestMetricRecorder {
            constructor() {
                this.message = {};
            }
            recordRequestCostMetric(e, t) {
                if (!this.message.request_cost) {
                    this.message.request_cost = {};
                }
                this.message.request_cost[e] = t;
            }
            recordUtilizationMetric(e, t) {
                if (!this.message.utilization) {
                    this.message.utilization = {};
                }
                this.message.utilization[e] = t;
            }
            recordNamedMetric(e, t) {
                if (!this.message.named_metrics) {
                    this.message.named_metrics = {};
                }
                this.message.named_metrics[e] = t;
            }
            recordCPUUtilizationMetric(e) {
                this.message.cpu_utilization = e;
            }
            recordMemoryUtilizationMetric(e) {
                this.message.mem_utilization = e;
            }
            recordApplicationUtilizationMetric(e) {
                this.message.application_utilization = e;
            }
            recordQpsMetric(e) {
                this.message.rps_fractional = e;
            }
            recordEpsMetric(e) {
                this.message.eps = e;
            }
            serialize() {
                const e = c();
                return e.xds.data.orca.v3.OrcaLoadReport.serialize(this.message);
            }
        }
        e.PerRequestMetricRecorder = PerRequestMetricRecorder;
        const u = 3e4;
        class ServerMetricRecorder {
            constructor() {
                this.message = {};
                this.serviceImplementation = {
                    StreamCoreMetrics: e => {
                        const t = e.request.report_interval ? (0, r.durationToMs)((0, r.durationMessageToDuration)(e.request.report_interval)) : u;
                        const n = setInterval(() => {
                            e.write(this.message);
                        }, t);
                        e.on("cancelled", () => {
                            clearInterval(n);
                        });
                    }
                };
            }
            putUtilizationMetric(e, t) {
                if (!this.message.utilization) {
                    this.message.utilization = {};
                }
                this.message.utilization[e] = t;
            }
            setAllUtilizationMetrics(e) {
                this.message.utilization = Object.assign({}, e);
            }
            deleteUtilizationMetric(e) {
                var t;
                (t = this.message.utilization) === null || t === void 0 ? true : delete t[e];
            }
            setCpuUtilizationMetric(e) {
                this.message.cpu_utilization = e;
            }
            deleteCpuUtilizationMetric() {
                delete this.message.cpu_utilization;
            }
            setApplicationUtilizationMetric(e) {
                this.message.application_utilization = e;
            }
            deleteApplicationUtilizationMetric() {
                delete this.message.application_utilization;
            }
            setQpsMetric(e) {
                this.message.rps_fractional = e;
            }
            deleteQpsMetric() {
                delete this.message.rps_fractional;
            }
            setEpsMetric(e) {
                this.message.eps = e;
            }
            deleteEpsMetric() {
                delete this.message.eps;
            }
            addToServer(e) {
                const t = c().xds.service.orca.v3.OpenRcaService.service;
                e.addService(t, this.serviceImplementation);
            }
        }
        e.ServerMetricRecorder = ServerMetricRecorder;
        function d(e) {
            const t = c().xds.service.orca.v3.OpenRcaService;
            return new t("unused", n.ChannelCredentials.createInsecure(), {
                channelOverride: e
            });
        }
        e.GRPC_METRICS_HEADER = "endpoint-load-metrics-bin";
        const h = "grpc_orca_load_report";
        function p(t, r) {
            return (n, s, o) => {
                let a = o.getOpaque(h);
                if (a) {
                    t(a);
                } else {
                    const r = o.get(e.GRPC_METRICS_HEADER);
                    if (r.length > 0) {
                        const e = c();
                        a = e.xds.data.orca.v3.OrcaLoadReport.deserialize(r[0]);
                        t(a);
                        o.setOpaque(h, a);
                    }
                }
                if (r) {
                    r(n, s, o);
                }
            };
        }
        const g = "orca_oob_metrics";
        class OobMetricsDataWatcher {
            constructor(e, t) {
                this.metricsListener = e;
                this.intervalMs = t;
                this.dataProducer = null;
            }
            setSubchannel(e) {
                const t = e.getOrCreateDataProducer(g, m);
                this.dataProducer = t;
                t.addDataWatcher(this);
            }
            destroy() {
                var e;
                (e = this.dataProducer) === null || e === void 0 ? void 0 : e.removeDataWatcher(this);
            }
            getInterval() {
                return this.intervalMs;
            }
            onMetricsUpdate(e) {
                this.metricsListener(e);
            }
        }
        class OobMetricsDataProducer {
            constructor(e) {
                this.subchannel = e;
                this.dataWatchers = new Set;
                this.orcaSupported = true;
                this.metricsCall = null;
                this.currentInterval = Infinity;
                this.backoffTimer = new a.BackoffTimeout(() => this.updateMetricsSubscription());
                this.subchannelStateListener = () => this.updateMetricsSubscription();
                const t = e.getChannel();
                this.client = d(t);
                e.addConnectivityStateListener(this.subchannelStateListener);
            }
            addDataWatcher(e) {
                this.dataWatchers.add(e);
                this.updateMetricsSubscription();
            }
            removeDataWatcher(e) {
                var t;
                this.dataWatchers.delete(e);
                if (this.dataWatchers.size === 0) {
                    this.subchannel.removeDataProducer(g);
                    (t = this.metricsCall) === null || t === void 0 ? void 0 : t.cancel();
                    this.metricsCall = null;
                    this.client.close();
                    this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);
                } else {
                    this.updateMetricsSubscription();
                }
            }
            updateMetricsSubscription() {
                var e;
                if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== l.ConnectivityState.READY) {
                    return;
                }
                const t = Math.min(...Array.from(this.dataWatchers).map(e => e.getInterval()));
                if (!this.metricsCall || t !== this.currentInterval) {
                    (e = this.metricsCall) === null || e === void 0 ? void 0 : e.cancel();
                    this.currentInterval = t;
                    const n = this.client.streamCoreMetrics({
                        report_interval: (0, r.msToDuration)(t)
                    });
                    this.metricsCall = n;
                    n.on("data", e => {
                        this.dataWatchers.forEach(t => {
                            t.onMetricsUpdate(e);
                        });
                    });
                    n.on("error", e => {
                        this.metricsCall = null;
                        if (e.code === o.Status.UNIMPLEMENTED) {
                            this.orcaSupported = false;
                            return;
                        }
                        if (e.code === o.Status.CANCELLED) {
                            return;
                        }
                        this.backoffTimer.runOnce();
                    });
                }
            }
        }
        class OrcaOobMetricsSubchannelWrapper extends s.BaseSubchannelWrapper {
            constructor(e, t, r) {
                super(e);
                this.addDataWatcher(new OobMetricsDataWatcher(t, r));
            }
            getWrappedSubchannel() {
                return this.child;
            }
        }
        e.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper;
        function m(e) {
            return new OobMetricsDataProducer(e);
        }
    })(orca);
    return orca;
}

var hasRequiredServerInterceptors;

function requireServerInterceptors() {
    if (hasRequiredServerInterceptors) return serverInterceptors;
    hasRequiredServerInterceptors = 1;
    Object.defineProperty(serverInterceptors, "__esModule", {
        value: true
    });
    serverInterceptors.BaseServerInterceptingCall = serverInterceptors.ServerInterceptingCall = serverInterceptors.ResponderBuilder = serverInterceptors.ServerListenerBuilder = void 0;
    serverInterceptors.isInterceptingServerListener = h;
    serverInterceptors.getServerInterceptingCall = I;
    const e = metadata;
    const t = constants;
    const r = require$$0__default$a.default;
    const n = error;
    const s = require$$4__default$2.default;
    const o = requireStreamDecoder();
    const a = logging$8;
    const l = require$$2__default$1.default;
    const c = requireOrca();
    const u = "server_call";
    function d(e) {
        a.trace(t.LogVerbosity.DEBUG, u, e);
    }
    class ServerListenerBuilder {
        constructor() {
            this.metadata = undefined;
            this.message = undefined;
            this.halfClose = undefined;
            this.cancel = undefined;
        }
        withOnReceiveMetadata(e) {
            this.metadata = e;
            return this;
        }
        withOnReceiveMessage(e) {
            this.message = e;
            return this;
        }
        withOnReceiveHalfClose(e) {
            this.halfClose = e;
            return this;
        }
        withOnCancel(e) {
            this.cancel = e;
            return this;
        }
        build() {
            return {
                onReceiveMetadata: this.metadata,
                onReceiveMessage: this.message,
                onReceiveHalfClose: this.halfClose,
                onCancel: this.cancel
            };
        }
    }
    serverInterceptors.ServerListenerBuilder = ServerListenerBuilder;
    function h(e) {
        return e.onReceiveMetadata !== undefined && e.onReceiveMetadata.length === 1;
    }
    class InterceptingServerListenerImpl {
        constructor(e, t) {
            this.listener = e;
            this.nextListener = t;
            this.cancelled = false;
            this.processingMetadata = false;
            this.hasPendingMessage = false;
            this.pendingMessage = null;
            this.processingMessage = false;
            this.hasPendingHalfClose = false;
        }
        processPendingMessage() {
            if (this.hasPendingMessage) {
                this.nextListener.onReceiveMessage(this.pendingMessage);
                this.pendingMessage = null;
                this.hasPendingMessage = false;
            }
        }
        processPendingHalfClose() {
            if (this.hasPendingHalfClose) {
                this.nextListener.onReceiveHalfClose();
                this.hasPendingHalfClose = false;
            }
        }
        onReceiveMetadata(e) {
            if (this.cancelled) {
                return;
            }
            this.processingMetadata = true;
            this.listener.onReceiveMetadata(e, e => {
                this.processingMetadata = false;
                if (this.cancelled) {
                    return;
                }
                this.nextListener.onReceiveMetadata(e);
                this.processPendingMessage();
                this.processPendingHalfClose();
            });
        }
        onReceiveMessage(e) {
            if (this.cancelled) {
                return;
            }
            this.processingMessage = true;
            this.listener.onReceiveMessage(e, e => {
                this.processingMessage = false;
                if (this.cancelled) {
                    return;
                }
                if (this.processingMetadata) {
                    this.pendingMessage = e;
                    this.hasPendingMessage = true;
                } else {
                    this.nextListener.onReceiveMessage(e);
                    this.processPendingHalfClose();
                }
            });
        }
        onReceiveHalfClose() {
            if (this.cancelled) {
                return;
            }
            this.listener.onReceiveHalfClose(() => {
                if (this.cancelled) {
                    return;
                }
                if (this.processingMetadata || this.processingMessage) {
                    this.hasPendingHalfClose = true;
                } else {
                    this.nextListener.onReceiveHalfClose();
                }
            });
        }
        onCancel() {
            this.cancelled = true;
            this.listener.onCancel();
            this.nextListener.onCancel();
        }
    }
    class ResponderBuilder {
        constructor() {
            this.start = undefined;
            this.metadata = undefined;
            this.message = undefined;
            this.status = undefined;
        }
        withStart(e) {
            this.start = e;
            return this;
        }
        withSendMetadata(e) {
            this.metadata = e;
            return this;
        }
        withSendMessage(e) {
            this.message = e;
            return this;
        }
        withSendStatus(e) {
            this.status = e;
            return this;
        }
        build() {
            return {
                start: this.start,
                sendMetadata: this.metadata,
                sendMessage: this.message,
                sendStatus: this.status
            };
        }
    }
    serverInterceptors.ResponderBuilder = ResponderBuilder;
    const p = {
        onReceiveMetadata: (e, t) => {
            t(e);
        },
        onReceiveMessage: (e, t) => {
            t(e);
        },
        onReceiveHalfClose: e => {
            e();
        },
        onCancel: () => {}
    };
    const g = {
        start: e => {
            e();
        },
        sendMetadata: (e, t) => {
            t(e);
        },
        sendMessage: (e, t) => {
            t(e);
        },
        sendStatus: (e, t) => {
            t(e);
        }
    };
    class ServerInterceptingCall {
        constructor(e, t) {
            var r, n, s, o;
            this.nextCall = e;
            this.processingMetadata = false;
            this.sentMetadata = false;
            this.processingMessage = false;
            this.pendingMessage = null;
            this.pendingMessageCallback = null;
            this.pendingStatus = null;
            this.responder = {
                start: (r = t === null || t === void 0 ? void 0 : t.start) !== null && r !== void 0 ? r : g.start,
                sendMetadata: (n = t === null || t === void 0 ? void 0 : t.sendMetadata) !== null && n !== void 0 ? n : g.sendMetadata,
                sendMessage: (s = t === null || t === void 0 ? void 0 : t.sendMessage) !== null && s !== void 0 ? s : g.sendMessage,
                sendStatus: (o = t === null || t === void 0 ? void 0 : t.sendStatus) !== null && o !== void 0 ? o : g.sendStatus
            };
        }
        processPendingMessage() {
            if (this.pendingMessageCallback) {
                this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback);
                this.pendingMessage = null;
                this.pendingMessageCallback = null;
            }
        }
        processPendingStatus() {
            if (this.pendingStatus) {
                this.nextCall.sendStatus(this.pendingStatus);
                this.pendingStatus = null;
            }
        }
        start(e) {
            this.responder.start(t => {
                var r, n, s, o;
                const a = {
                    onReceiveMetadata: (r = t === null || t === void 0 ? void 0 : t.onReceiveMetadata) !== null && r !== void 0 ? r : p.onReceiveMetadata,
                    onReceiveMessage: (n = t === null || t === void 0 ? void 0 : t.onReceiveMessage) !== null && n !== void 0 ? n : p.onReceiveMessage,
                    onReceiveHalfClose: (s = t === null || t === void 0 ? void 0 : t.onReceiveHalfClose) !== null && s !== void 0 ? s : p.onReceiveHalfClose,
                    onCancel: (o = t === null || t === void 0 ? void 0 : t.onCancel) !== null && o !== void 0 ? o : p.onCancel
                };
                const l = new InterceptingServerListenerImpl(a, e);
                this.nextCall.start(l);
            });
        }
        sendMetadata(e) {
            this.processingMetadata = true;
            this.sentMetadata = true;
            this.responder.sendMetadata(e, e => {
                this.processingMetadata = false;
                this.nextCall.sendMetadata(e);
                this.processPendingMessage();
                this.processPendingStatus();
            });
        }
        sendMessage(t, r) {
            this.processingMessage = true;
            if (!this.sentMetadata) {
                this.sendMetadata(new e.Metadata);
            }
            this.responder.sendMessage(t, e => {
                this.processingMessage = false;
                if (this.processingMetadata) {
                    this.pendingMessage = e;
                    this.pendingMessageCallback = r;
                } else {
                    this.nextCall.sendMessage(e, r);
                }
            });
        }
        sendStatus(e) {
            this.responder.sendStatus(e, e => {
                if (this.processingMetadata || this.processingMessage) {
                    this.pendingStatus = e;
                } else {
                    this.nextCall.sendStatus(e);
                }
            });
        }
        startRead() {
            this.nextCall.startRead();
        }
        getPeer() {
            return this.nextCall.getPeer();
        }
        getDeadline() {
            return this.nextCall.getDeadline();
        }
        getHost() {
            return this.nextCall.getHost();
        }
        getAuthContext() {
            return this.nextCall.getAuthContext();
        }
        getConnectionInfo() {
            return this.nextCall.getConnectionInfo();
        }
        getMetricsRecorder() {
            return this.nextCall.getMetricsRecorder();
        }
    }
    serverInterceptors.ServerInterceptingCall = ServerInterceptingCall;
    const m = "grpc-accept-encoding";
    const _ = "grpc-encoding";
    const E = "grpc-message";
    const v = "grpc-status";
    const y = "grpc-timeout";
    const S = /(\d{1,8})\s*([HMSmun])/;
    const A = {
        H: 36e5,
        M: 6e4,
        S: 1e3,
        m: 1,
        u: .001,
        n: 1e-6
    };
    const b = {
        [m]: "identity,deflate,gzip",
        [_]: "identity"
    };
    const C = {
        [r.constants.HTTP2_HEADER_STATUS]: r.constants.HTTP_STATUS_OK,
        [r.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto"
    };
    const w = {
        waitForTrailers: true
    };
    class BaseServerInterceptingCall {
        constructor(n, s, l, h, p) {
            var g, E;
            this.stream = n;
            this.callEventTracker = l;
            this.handler = h;
            this.listener = null;
            this.deadlineTimer = null;
            this.deadline = Infinity;
            this.maxSendMessageSize = t.DEFAULT_MAX_SEND_MESSAGE_LENGTH;
            this.maxReceiveMessageSize = t.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH;
            this.cancelled = false;
            this.metadataSent = false;
            this.wantTrailers = false;
            this.cancelNotified = false;
            this.incomingEncoding = "identity";
            this.readQueue = [];
            this.isReadPending = false;
            this.receivedHalfClose = false;
            this.streamEnded = false;
            this.metricsRecorder = new c.PerRequestMetricRecorder;
            this.stream.once("error", e => {});
            this.stream.once("close", () => {
                var e;
                d("Request to method " + ((e = this.handler) === null || e === void 0 ? void 0 : e.path) + " stream closed with rstCode " + this.stream.rstCode);
                if (this.callEventTracker && !this.streamEnded) {
                    this.streamEnded = true;
                    this.callEventTracker.onStreamEnd(false);
                    this.callEventTracker.onCallEnd({
                        code: t.Status.CANCELLED,
                        details: "Stream closed before sending status",
                        metadata: null
                    });
                }
                this.notifyOnCancel();
            });
            this.stream.on("data", e => {
                this.handleDataFrame(e);
            });
            this.stream.pause();
            this.stream.on("end", () => {
                this.handleEndEvent();
            });
            if ("grpc.max_send_message_length" in p) {
                this.maxSendMessageSize = p["grpc.max_send_message_length"];
            }
            if ("grpc.max_receive_message_length" in p) {
                this.maxReceiveMessageSize = p["grpc.max_receive_message_length"];
            }
            this.host = (g = s[":authority"]) !== null && g !== void 0 ? g : s.host;
            this.decoder = new o.StreamDecoder(this.maxReceiveMessageSize);
            const v = e.Metadata.fromHttp2Headers(s);
            if (a.isTracerEnabled(u)) {
                d("Request to " + this.handler.path + " received headers " + JSON.stringify(v.toJSON()));
            }
            const S = v.get(y);
            if (S.length > 0) {
                this.handleTimeoutHeader(S[0]);
            }
            const A = v.get(_);
            if (A.length > 0) {
                this.incomingEncoding = A[0];
            }
            v.remove(y);
            v.remove(_);
            v.remove(m);
            v.remove(r.constants.HTTP2_HEADER_ACCEPT_ENCODING);
            v.remove(r.constants.HTTP2_HEADER_TE);
            v.remove(r.constants.HTTP2_HEADER_CONTENT_TYPE);
            this.metadata = v;
            const b = (E = n.session) === null || E === void 0 ? void 0 : E.socket;
            this.connectionInfo = {
                localAddress: b === null || b === void 0 ? void 0 : b.localAddress,
                localPort: b === null || b === void 0 ? void 0 : b.localPort,
                remoteAddress: b === null || b === void 0 ? void 0 : b.remoteAddress,
                remotePort: b === null || b === void 0 ? void 0 : b.remotePort
            };
            this.shouldSendMetrics = !!p["grpc.server_call_metric_recording"];
        }
        handleTimeoutHeader(e) {
            const r = e.toString().match(S);
            if (r === null) {
                const r = {
                    code: t.Status.INTERNAL,
                    details: `Invalid ${y} value "${e}"`,
                    metadata: null
                };
                process.nextTick(() => {
                    this.sendStatus(r);
                });
                return;
            }
            const n = +r[1] * A[r[2]] | 0;
            const s = new Date;
            this.deadline = s.setMilliseconds(s.getMilliseconds() + n);
            this.deadlineTimer = setTimeout(() => {
                const e = {
                    code: t.Status.DEADLINE_EXCEEDED,
                    details: "Deadline exceeded",
                    metadata: null
                };
                this.sendStatus(e);
            }, n);
        }
        checkCancelled() {
            if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) {
                this.notifyOnCancel();
                this.cancelled = true;
            }
            return this.cancelled;
        }
        notifyOnCancel() {
            if (this.cancelNotified) {
                return;
            }
            this.cancelNotified = true;
            this.cancelled = true;
            process.nextTick(() => {
                var e;
                (e = this.listener) === null || e === void 0 ? void 0 : e.onCancel();
            });
            if (this.deadlineTimer) {
                clearTimeout(this.deadlineTimer);
            }
            this.stream.resume();
        }
        maybeSendMetadata() {
            if (!this.metadataSent) {
                this.sendMetadata(new e.Metadata);
            }
        }
        serializeMessage(e) {
            const t = this.handler.serialize(e);
            const r = t.byteLength;
            const n = Buffer.allocUnsafe(r + 5);
            n.writeUInt8(0, 0);
            n.writeUInt32BE(r, 1);
            t.copy(n, 5);
            return n;
        }
        decompressMessage(e, r) {
            const n = e.subarray(5);
            if (r === "identity") {
                return n;
            } else if (r === "deflate" || r === "gzip") {
                let e;
                if (r === "deflate") {
                    e = s.createInflate();
                } else {
                    e = s.createGunzip();
                }
                return new Promise((r, s) => {
                    let o = 0;
                    const a = [];
                    e.on("data", r => {
                        a.push(r);
                        o += r.byteLength;
                        if (this.maxReceiveMessageSize !== -1 && o > this.maxReceiveMessageSize) {
                            e.destroy();
                            s({
                                code: t.Status.RESOURCE_EXHAUSTED,
                                details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`
                            });
                        }
                    });
                    e.on("end", () => {
                        r(Buffer.concat(a));
                    });
                    e.write(n);
                    e.end();
                });
            } else {
                return Promise.reject({
                    code: t.Status.UNIMPLEMENTED,
                    details: `Received message compressed with unsupported encoding "${r}"`
                });
            }
        }
        async decompressAndMaybePush(e) {
            if (e.type !== "COMPRESSED") {
                throw new Error(`Invalid queue entry type: ${e.type}`);
            }
            const r = e.compressedMessage.readUInt8(0) === 1;
            const n = r ? this.incomingEncoding : "identity";
            let s;
            try {
                s = await this.decompressMessage(e.compressedMessage, n);
            } catch (e) {
                this.sendStatus(e);
                return;
            }
            try {
                e.parsedMessage = this.handler.deserialize(s);
            } catch (e) {
                this.sendStatus({
                    code: t.Status.INTERNAL,
                    details: `Error deserializing request: ${e.message}`
                });
                return;
            }
            e.type = "READABLE";
            this.maybePushNextMessage();
        }
        maybePushNextMessage() {
            if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") {
                this.isReadPending = false;
                const e = this.readQueue.shift();
                if (e.type === "READABLE") {
                    this.listener.onReceiveMessage(e.parsedMessage);
                } else {
                    this.listener.onReceiveHalfClose();
                }
            }
        }
        handleDataFrame(e) {
            var r;
            if (this.checkCancelled()) {
                return;
            }
            d("Request to " + this.handler.path + " received data frame of size " + e.length);
            let n;
            try {
                n = this.decoder.write(e);
            } catch (e) {
                this.sendStatus({
                    code: t.Status.RESOURCE_EXHAUSTED,
                    details: e.message
                });
                return;
            }
            for (const e of n) {
                this.stream.pause();
                const t = {
                    type: "COMPRESSED",
                    compressedMessage: e,
                    parsedMessage: null
                };
                this.readQueue.push(t);
                this.decompressAndMaybePush(t);
                (r = this.callEventTracker) === null || r === void 0 ? void 0 : r.addMessageReceived();
            }
        }
        handleEndEvent() {
            this.readQueue.push({
                type: "HALF_CLOSE",
                compressedMessage: null,
                parsedMessage: null
            });
            this.receivedHalfClose = true;
            this.maybePushNextMessage();
        }
        start(e) {
            d("Request to " + this.handler.path + " start called");
            if (this.checkCancelled()) {
                return;
            }
            this.listener = e;
            e.onReceiveMetadata(this.metadata);
        }
        sendMetadata(e) {
            if (this.checkCancelled()) {
                return;
            }
            if (this.metadataSent) {
                return;
            }
            this.metadataSent = true;
            const t = e ? e.toHttp2Headers() : null;
            const r = Object.assign(Object.assign(Object.assign({}, C), b), t);
            this.stream.respond(r, w);
        }
        sendMessage(e, r) {
            if (this.checkCancelled()) {
                return;
            }
            let s;
            try {
                s = this.serializeMessage(e);
            } catch (e) {
                this.sendStatus({
                    code: t.Status.INTERNAL,
                    details: `Error serializing response: ${(0, n.getErrorMessage)(e)}`,
                    metadata: null
                });
                return;
            }
            if (this.maxSendMessageSize !== -1 && s.length - 5 > this.maxSendMessageSize) {
                this.sendStatus({
                    code: t.Status.RESOURCE_EXHAUSTED,
                    details: `Sent message larger than max (${s.length} vs. ${this.maxSendMessageSize})`,
                    metadata: null
                });
                return;
            }
            this.maybeSendMetadata();
            d("Request to " + this.handler.path + " sent data frame of size " + s.length);
            this.stream.write(s, e => {
                var s;
                if (e) {
                    this.sendStatus({
                        code: t.Status.INTERNAL,
                        details: `Error writing message: ${(0, n.getErrorMessage)(e)}`,
                        metadata: null
                    });
                    return;
                }
                (s = this.callEventTracker) === null || s === void 0 ? void 0 : s.addMessageSent();
                r();
            });
        }
        sendStatus(r) {
            var n, s, o;
            if (this.checkCancelled()) {
                return;
            }
            d("Request to method " + ((n = this.handler) === null || n === void 0 ? void 0 : n.path) + " ended with status code: " + t.Status[r.code] + " details: " + r.details);
            const a = (o = (s = r.metadata) === null || s === void 0 ? void 0 : s.clone()) !== null && o !== void 0 ? o : new e.Metadata;
            if (this.shouldSendMetrics) {
                a.set(c.GRPC_METRICS_HEADER, this.metricsRecorder.serialize());
            }
            if (this.metadataSent) {
                if (!this.wantTrailers) {
                    this.wantTrailers = true;
                    this.stream.once("wantTrailers", () => {
                        if (this.callEventTracker && !this.streamEnded) {
                            this.streamEnded = true;
                            this.callEventTracker.onStreamEnd(true);
                            this.callEventTracker.onCallEnd(r);
                        }
                        const e = Object.assign({
                            [v]: r.code,
                            [E]: encodeURI(r.details)
                        }, a.toHttp2Headers());
                        this.stream.sendTrailers(e);
                        this.notifyOnCancel();
                    });
                    this.stream.end();
                } else {
                    this.notifyOnCancel();
                }
            } else {
                if (this.callEventTracker && !this.streamEnded) {
                    this.streamEnded = true;
                    this.callEventTracker.onStreamEnd(true);
                    this.callEventTracker.onCallEnd(r);
                }
                const e = Object.assign(Object.assign({
                    [v]: r.code,
                    [E]: encodeURI(r.details)
                }, C), a.toHttp2Headers());
                this.stream.respond(e, {
                    endStream: true
                });
                this.notifyOnCancel();
            }
        }
        startRead() {
            d("Request to " + this.handler.path + " startRead called");
            if (this.checkCancelled()) {
                return;
            }
            this.isReadPending = true;
            if (this.readQueue.length === 0) {
                if (!this.receivedHalfClose) {
                    this.stream.resume();
                }
            } else {
                this.maybePushNextMessage();
            }
        }
        getPeer() {
            var e;
            const t = (e = this.stream.session) === null || e === void 0 ? void 0 : e.socket;
            if (t === null || t === void 0 ? void 0 : t.remoteAddress) {
                if (t.remotePort) {
                    return `${t.remoteAddress}:${t.remotePort}`;
                } else {
                    return t.remoteAddress;
                }
            } else {
                return "unknown";
            }
        }
        getDeadline() {
            return this.deadline;
        }
        getHost() {
            return this.host;
        }
        getAuthContext() {
            var e;
            if (((e = this.stream.session) === null || e === void 0 ? void 0 : e.socket) instanceof l.TLSSocket) {
                const e = this.stream.session.socket.getPeerCertificate();
                return {
                    transportSecurityType: "ssl",
                    sslPeerCertificate: e.raw ? e : undefined
                };
            } else {
                return {};
            }
        }
        getConnectionInfo() {
            return this.connectionInfo;
        }
        getMetricsRecorder() {
            return this.metricsRecorder;
        }
    }
    serverInterceptors.BaseServerInterceptingCall = BaseServerInterceptingCall;
    function I(e, t, r, n, s, o) {
        const a = {
            path: s.path,
            requestStream: s.type === "clientStream" || s.type === "bidi",
            responseStream: s.type === "serverStream" || s.type === "bidi",
            requestDeserialize: s.deserialize,
            responseSerialize: s.serialize
        };
        const l = new BaseServerInterceptingCall(t, r, n, s, o);
        return e.reduce((e, t) => t(a, e), l);
    }
    return serverInterceptors;
}

var __runInitializers = _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__runInitializers || function(e, t, r) {
    var n = arguments.length > 2;
    for (var s = 0; s < t.length; s++) {
        r = n ? t[s].call(e, r) : t[s].call(e);
    }
    return n ? r : void 0;
};

var __esDecorate = _commonjsHelpers.commonjsGlobal && _commonjsHelpers.commonjsGlobal.__esDecorate || function(e, t, r, n, s, o) {
    function a(e) {
        if (e !== void 0 && typeof e !== "function") throw new TypeError("Function expected");
        return e;
    }
    var l = n.kind, c = l === "getter" ? "get" : l === "setter" ? "set" : "value";
    var u = !t && e ? n["static"] ? e : e.prototype : null;
    var d = t || (u ? Object.getOwnPropertyDescriptor(u, n.name) : {});
    var h, p = false;
    for (var g = r.length - 1; g >= 0; g--) {
        var m = {};
        for (var _ in n) m[_] = _ === "access" ? {} : n[_];
        for (var _ in n.access) m.access[_] = n.access[_];
        m.addInitializer = function(e) {
            if (p) throw new TypeError("Cannot add initializers after decoration has completed");
            o.push(a(e || null));
        };
        var E = (0, r[g])(l === "accessor" ? {
            get: d.get,
            set: d.set
        } : d[c], m);
        if (l === "accessor") {
            if (E === void 0) continue;
            if (E === null || typeof E !== "object") throw new TypeError("Object expected");
            if (h = a(E.get)) d.get = h;
            if (h = a(E.set)) d.set = h;
            if (h = a(E.init)) s.unshift(h);
        } else if (h = a(E)) {
            if (l === "field") s.unshift(h); else d[c] = h;
        }
    }
    if (u) Object.defineProperty(u, n.name, d);
    p = true;
};

Object.defineProperty(server, "__esModule", {
    value: true
});

server.Server = void 0;

const http2 = require$$0__default$a.default;

const util$2 = require$$1__default$1.default;

const constants_1 = constants;

const server_call_1 = serverCall;

const server_credentials_1 = serverCredentials;

const resolver_1 = resolver;

const logging = logging$8;

const subchannel_address_1 = subchannelAddress;

const uri_parser_1 = uriParser;

const channelz_1 = requireChannelz();

const server_interceptors_1 = requireServerInterceptors();

const UNLIMITED_CONNECTION_AGE_MS = 2147483647;

const KEEPALIVE_MAX_TIME_MS = 2147483647;

const KEEPALIVE_TIMEOUT_MS = 2e4;

const MAX_CONNECTION_IDLE_MS = 2147483647;

const {HTTP2_HEADER_PATH: HTTP2_HEADER_PATH} = http2.constants;

const TRACER_NAME = "server";

const kMaxAge = Buffer.from("max_age");

function serverCallTrace(e) {
    logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", e);
}

function noop() {}

function deprecate(e) {
    return function(t, r) {
        return util$2.deprecate(t, e);
    };
}

function getUnimplementedStatusResponse(e) {
    return {
        code: constants_1.Status.UNIMPLEMENTED,
        details: `The server does not implement the method ${e}`
    };
}

function getDefaultHandler(e, t) {
    const r = getUnimplementedStatusResponse(t);
    switch (e) {
      case "unary":
        return (e, t) => {
            t(r, null);
        };

      case "clientStream":
        return (e, t) => {
            t(r, null);
        };

      case "serverStream":
        return e => {
            e.emit("error", r);
        };

      case "bidi":
        return e => {
            e.emit("error", r);
        };

      default:
        throw new Error(`Invalid handlerType ${e}`);
    }
}

let Server = (() => {
    var e;
    let t = [];
    let r;
    return e = class Server {
        constructor(e) {
            var r, n, s, o, a, l;
            this.boundPorts = (__runInitializers(this, t), new Map);
            this.http2Servers = new Map;
            this.sessionIdleTimeouts = new Map;
            this.handlers = new Map;
            this.sessions = new Map;
            this.started = false;
            this.shutdown = false;
            this.serverAddressString = "null";
            this.channelzEnabled = true;
            this.options = e !== null && e !== void 0 ? e : {};
            if (this.options["grpc.enable_channelz"] === 0) {
                this.channelzEnabled = false;
                this.channelzTrace = new channelz_1.ChannelzTraceStub;
                this.callTracker = new channelz_1.ChannelzCallTrackerStub;
                this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub;
                this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub;
            } else {
                this.channelzTrace = new channelz_1.ChannelzTrace;
                this.callTracker = new channelz_1.ChannelzCallTracker;
                this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker;
                this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker;
            }
            this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled);
            this.channelzTrace.addTrace("CT_INFO", "Server created");
            this.maxConnectionAgeMs = (r = this.options["grpc.max_connection_age_ms"]) !== null && r !== void 0 ? r : UNLIMITED_CONNECTION_AGE_MS;
            this.maxConnectionAgeGraceMs = (n = this.options["grpc.max_connection_age_grace_ms"]) !== null && n !== void 0 ? n : UNLIMITED_CONNECTION_AGE_MS;
            this.keepaliveTimeMs = (s = this.options["grpc.keepalive_time_ms"]) !== null && s !== void 0 ? s : KEEPALIVE_MAX_TIME_MS;
            this.keepaliveTimeoutMs = (o = this.options["grpc.keepalive_timeout_ms"]) !== null && o !== void 0 ? o : KEEPALIVE_TIMEOUT_MS;
            this.sessionIdleTimeout = (a = this.options["grpc.max_connection_idle_ms"]) !== null && a !== void 0 ? a : MAX_CONNECTION_IDLE_MS;
            this.commonServerOptions = {
                maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER
            };
            if ("grpc-node.max_session_memory" in this.options) {
                this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"];
            } else {
                this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER;
            }
            if ("grpc.max_concurrent_streams" in this.options) {
                this.commonServerOptions.settings = {
                    maxConcurrentStreams: this.options["grpc.max_concurrent_streams"]
                };
            }
            this.interceptors = (l = this.options.interceptors) !== null && l !== void 0 ? l : [];
            this.trace("Server constructed");
        }
        getChannelzInfo() {
            return {
                trace: this.channelzTrace,
                callTracker: this.callTracker,
                listenerChildren: this.listenerChildrenTracker.getChildLists(),
                sessionChildren: this.sessionChildrenTracker.getChildLists()
            };
        }
        getChannelzSessionInfo(e) {
            var t, r, n;
            const s = this.sessions.get(e);
            const o = e.socket;
            const a = o.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(o.remoteAddress, o.remotePort) : null;
            const l = o.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(o.localAddress, o.localPort) : null;
            let c;
            if (e.encrypted) {
                const e = o;
                const r = e.getCipher();
                const n = e.getCertificate();
                const s = e.getPeerCertificate();
                c = {
                    cipherSuiteStandardName: (t = r.standardName) !== null && t !== void 0 ? t : null,
                    cipherSuiteOtherName: r.standardName ? null : r.name,
                    localCertificate: n && "raw" in n ? n.raw : null,
                    remoteCertificate: s && "raw" in s ? s.raw : null
                };
            } else {
                c = null;
            }
            const u = {
                remoteAddress: a,
                localAddress: l,
                security: c,
                remoteName: null,
                streamsStarted: s.streamTracker.callsStarted,
                streamsSucceeded: s.streamTracker.callsSucceeded,
                streamsFailed: s.streamTracker.callsFailed,
                messagesSent: s.messagesSent,
                messagesReceived: s.messagesReceived,
                keepAlivesSent: s.keepAlivesSent,
                lastLocalStreamCreatedTimestamp: null,
                lastRemoteStreamCreatedTimestamp: s.streamTracker.lastCallStartedTimestamp,
                lastMessageSentTimestamp: s.lastMessageSentTimestamp,
                lastMessageReceivedTimestamp: s.lastMessageReceivedTimestamp,
                localFlowControlWindow: (r = e.state.localWindowSize) !== null && r !== void 0 ? r : null,
                remoteFlowControlWindow: (n = e.state.remoteWindowSize) !== null && n !== void 0 ? n : null
            };
            return u;
        }
        trace(e) {
            logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + e);
        }
        keepaliveTrace(e) {
            logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + e);
        }
        addProtoService() {
            throw new Error("Not implemented. Use addService() instead");
        }
        addService(e, t) {
            if (e === null || typeof e !== "object" || t === null || typeof t !== "object") {
                throw new Error("addService() requires two objects as arguments");
            }
            const r = Object.keys(e);
            if (r.length === 0) {
                throw new Error("Cannot add an empty service to a server");
            }
            r.forEach(r => {
                const n = e[r];
                let s;
                if (n.requestStream) {
                    if (n.responseStream) {
                        s = "bidi";
                    } else {
                        s = "clientStream";
                    }
                } else {
                    if (n.responseStream) {
                        s = "serverStream";
                    } else {
                        s = "unary";
                    }
                }
                let o = t[r];
                let a;
                if (o === undefined && typeof n.originalName === "string") {
                    o = t[n.originalName];
                }
                if (o !== undefined) {
                    a = o.bind(t);
                } else {
                    a = getDefaultHandler(s, r);
                }
                const l = this.register(n.path, a, n.responseSerialize, n.requestDeserialize, s);
                if (l === false) {
                    throw new Error(`Method handler for ${n.path} already provided.`);
                }
            });
        }
        removeService(e) {
            if (e === null || typeof e !== "object") {
                throw new Error("removeService() requires object as argument");
            }
            const t = Object.keys(e);
            t.forEach(t => {
                const r = e[t];
                this.unregister(r.path);
            });
        }
        bind(e, t) {
            throw new Error("Not implemented. Use bindAsync() instead");
        }
        experimentalRegisterListenerToChannelz(e) {
            return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(e), () => ({
                localAddress: e,
                remoteAddress: null,
                security: null,
                remoteName: null,
                streamsStarted: 0,
                streamsSucceeded: 0,
                streamsFailed: 0,
                messagesSent: 0,
                messagesReceived: 0,
                keepAlivesSent: 0,
                lastLocalStreamCreatedTimestamp: null,
                lastRemoteStreamCreatedTimestamp: null,
                lastMessageSentTimestamp: null,
                lastMessageReceivedTimestamp: null,
                localFlowControlWindow: null,
                remoteFlowControlWindow: null
            }), this.channelzEnabled);
        }
        experimentalUnregisterListenerFromChannelz(e) {
            (0, channelz_1.unregisterChannelzRef)(e);
        }
        createHttp2Server(e) {
            let t;
            if (e._isSecure()) {
                const r = e._getConstructorOptions();
                const n = e._getSecureContextOptions();
                const s = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), r), n), {
                    enableTrace: this.options["grpc-node.tls_enable_trace"] === 1
                });
                let o = n !== null;
                this.trace("Initial credentials valid: " + o);
                t = http2.createSecureServer(s);
                t.prependListener("connection", e => {
                    if (!o) {
                        this.trace("Dropped connection from " + JSON.stringify(e.address()) + " due to unloaded credentials");
                        e.destroy();
                    }
                });
                t.on("secureConnection", e => {
                    e.on("error", e => {
                        this.trace("An incoming TLS connection closed with error: " + e.message);
                    });
                });
                const a = e => {
                    if (e) {
                        const r = t;
                        try {
                            r.setSecureContext(e);
                        } catch (t) {
                            logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + t.message);
                            e = null;
                        }
                    }
                    o = e !== null;
                    this.trace("Post-update credentials valid: " + o);
                };
                e._addWatcher(a);
                t.on("close", () => {
                    e._removeWatcher(a);
                });
            } else {
                t = http2.createServer(this.commonServerOptions);
            }
            t.setTimeout(0, noop);
            this._setupHandlers(t, e._getInterceptors());
            return t;
        }
        bindOneAddress(e, t) {
            this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(e));
            const r = this.createHttp2Server(t.credentials);
            return new Promise((n, s) => {
                const o = t => {
                    this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(e) + " with error " + t.message);
                    n({
                        port: "port" in e ? e.port : 1,
                        error: t.message
                    });
                };
                r.once("error", o);
                r.listen(e, () => {
                    const e = r.address();
                    let s;
                    if (typeof e === "string") {
                        s = {
                            path: e
                        };
                    } else {
                        s = {
                            host: e.address,
                            port: e.port
                        };
                    }
                    const a = this.experimentalRegisterListenerToChannelz(s);
                    this.listenerChildrenTracker.refChild(a);
                    this.http2Servers.set(r, {
                        channelzRef: a,
                        sessions: new Set,
                        ownsChannelzRef: true
                    });
                    t.listeningServers.add(r);
                    this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(s));
                    n({
                        port: "port" in s ? s.port : 1
                    });
                    r.removeListener("error", o);
                });
            });
        }
        async bindManyPorts(e, t) {
            if (e.length === 0) {
                return {
                    count: 0,
                    port: 0,
                    errors: []
                };
            }
            if ((0, subchannel_address_1.isTcpSubchannelAddress)(e[0]) && e[0].port === 0) {
                const r = await this.bindOneAddress(e[0], t);
                if (r.error) {
                    const n = await this.bindManyPorts(e.slice(1), t);
                    return Object.assign(Object.assign({}, n), {
                        errors: [ r.error, ...n.errors ]
                    });
                } else {
                    const n = e.slice(1).map(e => (0, subchannel_address_1.isTcpSubchannelAddress)(e) ? {
                        host: e.host,
                        port: r.port
                    } : e);
                    const s = await Promise.all(n.map(e => this.bindOneAddress(e, t)));
                    const o = [ r, ...s ];
                    return {
                        count: o.filter(e => e.error === undefined).length,
                        port: r.port,
                        errors: o.filter(e => e.error).map(e => e.error)
                    };
                }
            } else {
                const r = await Promise.all(e.map(e => this.bindOneAddress(e, t)));
                return {
                    count: r.filter(e => e.error === undefined).length,
                    port: r[0].port,
                    errors: r.filter(e => e.error).map(e => e.error)
                };
            }
        }
        async bindAddressList(e, t) {
            const r = await this.bindManyPorts(e, t);
            if (r.count > 0) {
                if (r.count < e.length) {
                    logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${r.count} addresses added out of total ${e.length} resolved`);
                }
                return r.port;
            } else {
                const t = `No address added out of total ${e.length} resolved`;
                logging.log(constants_1.LogVerbosity.ERROR, t);
                throw new Error(`${t} errors: [${r.errors.join(",")}]`);
            }
        }
        resolvePort(e) {
            return new Promise((t, r) => {
                let n = false;
                const s = (s, o, a, l) => {
                    if (n) {
                        return true;
                    }
                    n = true;
                    if (!s.ok) {
                        r(new Error(s.error.details));
                        return true;
                    }
                    const c = [].concat(...s.value.map(e => e.addresses));
                    if (c.length === 0) {
                        r(new Error(`No addresses resolved for port ${e}`));
                        return true;
                    }
                    t(c);
                    return true;
                };
                const o = (0, resolver_1.createResolver)(e, s, this.options);
                o.updateResolution();
            });
        }
        async bindPort(e, t) {
            const r = await this.resolvePort(e);
            if (t.cancelled) {
                this.completeUnbind(t);
                throw new Error("bindAsync operation cancelled by unbind call");
            }
            const n = await this.bindAddressList(r, t);
            if (t.cancelled) {
                this.completeUnbind(t);
                throw new Error("bindAsync operation cancelled by unbind call");
            }
            return n;
        }
        normalizePort(e) {
            const t = (0, uri_parser_1.parseUri)(e);
            if (t === null) {
                throw new Error(`Could not parse port "${e}"`);
            }
            const r = (0, resolver_1.mapUriDefaultScheme)(t);
            if (r === null) {
                throw new Error(`Could not get a default scheme for port "${e}"`);
            }
            return r;
        }
        bindAsync(e, t, r) {
            if (this.shutdown) {
                throw new Error("bindAsync called after shutdown");
            }
            if (typeof e !== "string") {
                throw new TypeError("port must be a string");
            }
            if (t === null || !(t instanceof server_credentials_1.ServerCredentials)) {
                throw new TypeError("creds must be a ServerCredentials object");
            }
            if (typeof r !== "function") {
                throw new TypeError("callback must be a function");
            }
            this.trace("bindAsync port=" + e);
            const n = this.normalizePort(e);
            const s = (e, t) => {
                process.nextTick(() => r(e, t));
            };
            let o = this.boundPorts.get((0, uri_parser_1.uriToString)(n));
            if (o) {
                if (!t._equals(o.credentials)) {
                    s(new Error(`${e} already bound with incompatible credentials`), 0);
                    return;
                }
                o.cancelled = false;
                if (o.completionPromise) {
                    o.completionPromise.then(e => r(null, e), e => r(e, 0));
                } else {
                    s(null, o.portNumber);
                }
                return;
            }
            o = {
                mapKey: (0, uri_parser_1.uriToString)(n),
                originalUri: n,
                completionPromise: null,
                cancelled: false,
                portNumber: 0,
                credentials: t,
                listeningServers: new Set
            };
            const a = (0, uri_parser_1.splitHostPort)(n.path);
            const l = this.bindPort(n, o);
            o.completionPromise = l;
            if ((a === null || a === void 0 ? void 0 : a.port) === 0) {
                l.then(e => {
                    const t = {
                        scheme: n.scheme,
                        authority: n.authority,
                        path: (0, uri_parser_1.combineHostPort)({
                            host: a.host,
                            port: e
                        })
                    };
                    o.mapKey = (0, uri_parser_1.uriToString)(t);
                    o.completionPromise = null;
                    o.portNumber = e;
                    this.boundPorts.set(o.mapKey, o);
                    r(null, e);
                }, e => {
                    r(e, 0);
                });
            } else {
                this.boundPorts.set(o.mapKey, o);
                l.then(e => {
                    o.completionPromise = null;
                    o.portNumber = e;
                    r(null, e);
                }, e => {
                    r(e, 0);
                });
            }
        }
        registerInjectorToChannelz() {
            return (0, channelz_1.registerChannelzSocket)("injector", () => ({
                localAddress: null,
                remoteAddress: null,
                security: null,
                remoteName: null,
                streamsStarted: 0,
                streamsSucceeded: 0,
                streamsFailed: 0,
                messagesSent: 0,
                messagesReceived: 0,
                keepAlivesSent: 0,
                lastLocalStreamCreatedTimestamp: null,
                lastRemoteStreamCreatedTimestamp: null,
                lastMessageSentTimestamp: null,
                lastMessageReceivedTimestamp: null,
                localFlowControlWindow: null,
                remoteFlowControlWindow: null
            }), this.channelzEnabled);
        }
        experimentalCreateConnectionInjectorWithChannelzRef(e, t, r = false) {
            if (e === null || !(e instanceof server_credentials_1.ServerCredentials)) {
                throw new TypeError("creds must be a ServerCredentials object");
            }
            if (this.channelzEnabled) {
                this.listenerChildrenTracker.refChild(t);
            }
            const n = this.createHttp2Server(e);
            const s = new Set;
            this.http2Servers.set(n, {
                channelzRef: t,
                sessions: s,
                ownsChannelzRef: r
            });
            return {
                injectConnection: e => {
                    n.emit("connection", e);
                },
                drain: e => {
                    var t, r;
                    for (const e of s) {
                        this.closeSession(e);
                    }
                    (r = (t = setTimeout(() => {
                        for (const e of s) {
                            e.destroy(http2.constants.NGHTTP2_CANCEL);
                        }
                    }, e)).unref) === null || r === void 0 ? void 0 : r.call(t);
                },
                destroy: () => {
                    this.closeServer(n);
                    for (const e of s) {
                        this.closeSession(e);
                    }
                }
            };
        }
        createConnectionInjector(e) {
            if (e === null || !(e instanceof server_credentials_1.ServerCredentials)) {
                throw new TypeError("creds must be a ServerCredentials object");
            }
            const t = this.registerInjectorToChannelz();
            return this.experimentalCreateConnectionInjectorWithChannelzRef(e, t, true);
        }
        closeServer(e, t) {
            this.trace("Closing server with address " + JSON.stringify(e.address()));
            const r = this.http2Servers.get(e);
            e.close(() => {
                if (r && r.ownsChannelzRef) {
                    this.listenerChildrenTracker.unrefChild(r.channelzRef);
                    (0, channelz_1.unregisterChannelzRef)(r.channelzRef);
                }
                this.http2Servers.delete(e);
                t === null || t === void 0 ? void 0 : t();
            });
        }
        closeSession(e, t) {
            var r;
            this.trace("Closing session initiated by " + ((r = e.socket) === null || r === void 0 ? void 0 : r.remoteAddress));
            const n = this.sessions.get(e);
            const s = () => {
                if (n) {
                    this.sessionChildrenTracker.unrefChild(n.ref);
                    (0, channelz_1.unregisterChannelzRef)(n.ref);
                }
                t === null || t === void 0 ? void 0 : t();
            };
            if (e.closed) {
                queueMicrotask(s);
            } else {
                e.close(s);
            }
        }
        completeUnbind(e) {
            for (const t of e.listeningServers) {
                const r = this.http2Servers.get(t);
                this.closeServer(t, () => {
                    e.listeningServers.delete(t);
                });
                if (r) {
                    for (const e of r.sessions) {
                        this.closeSession(e);
                    }
                }
            }
            this.boundPorts.delete(e.mapKey);
        }
        unbind(e) {
            this.trace("unbind port=" + e);
            const t = this.normalizePort(e);
            const r = (0, uri_parser_1.splitHostPort)(t.path);
            if ((r === null || r === void 0 ? void 0 : r.port) === 0) {
                throw new Error("Cannot unbind port 0");
            }
            const n = this.boundPorts.get((0, uri_parser_1.uriToString)(t));
            if (n) {
                this.trace("unbinding " + n.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(n.originalUri));
                if (n.completionPromise) {
                    n.cancelled = true;
                } else {
                    this.completeUnbind(n);
                }
            }
        }
        drain(e, t) {
            var r, n;
            this.trace("drain port=" + e + " graceTimeMs=" + t);
            const s = this.normalizePort(e);
            const o = (0, uri_parser_1.splitHostPort)(s.path);
            if ((o === null || o === void 0 ? void 0 : o.port) === 0) {
                throw new Error("Cannot drain port 0");
            }
            const a = this.boundPorts.get((0, uri_parser_1.uriToString)(s));
            if (!a) {
                return;
            }
            const l = new Set;
            for (const e of a.listeningServers) {
                const t = this.http2Servers.get(e);
                if (t) {
                    for (const e of t.sessions) {
                        l.add(e);
                        this.closeSession(e, () => {
                            l.delete(e);
                        });
                    }
                }
            }
            (n = (r = setTimeout(() => {
                for (const e of l) {
                    e.destroy(http2.constants.NGHTTP2_CANCEL);
                }
            }, t)).unref) === null || n === void 0 ? void 0 : n.call(r);
        }
        forceShutdown() {
            for (const e of this.boundPorts.values()) {
                e.cancelled = true;
            }
            this.boundPorts.clear();
            for (const e of this.http2Servers.keys()) {
                this.closeServer(e);
            }
            this.sessions.forEach((e, t) => {
                this.closeSession(t);
                t.destroy(http2.constants.NGHTTP2_CANCEL);
            });
            this.sessions.clear();
            (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
            this.shutdown = true;
        }
        register(e, t, r, n, s) {
            if (this.handlers.has(e)) {
                return false;
            }
            this.handlers.set(e, {
                func: t,
                serialize: r,
                deserialize: n,
                type: s,
                path: e
            });
            return true;
        }
        unregister(e) {
            return this.handlers.delete(e);
        }
        start() {
            if (this.http2Servers.size === 0 || [ ...this.http2Servers.keys() ].every(e => !e.listening)) {
                throw new Error("server must be bound in order to start");
            }
            if (this.started === true) {
                throw new Error("server is already started");
            }
            this.started = true;
        }
        tryShutdown(e) {
            var t;
            const r = t => {
                (0, channelz_1.unregisterChannelzRef)(this.channelzRef);
                e(t);
            };
            let n = 0;
            function s() {
                n--;
                if (n === 0) {
                    r();
                }
            }
            this.shutdown = true;
            for (const [e, r] of this.http2Servers.entries()) {
                n++;
                const o = r.channelzRef.name;
                this.trace("Waiting for server " + o + " to close");
                this.closeServer(e, () => {
                    this.trace("Server " + o + " finished closing");
                    s();
                });
                for (const e of r.sessions.keys()) {
                    n++;
                    const r = (t = e.socket) === null || t === void 0 ? void 0 : t.remoteAddress;
                    this.trace("Waiting for session " + r + " to close");
                    this.closeSession(e, () => {
                        this.trace("Session " + r + " finished closing");
                        s();
                    });
                }
            }
            if (n === 0) {
                r();
            }
        }
        addHttp2Port() {
            throw new Error("Not yet implemented");
        }
        getChannelzRef() {
            return this.channelzRef;
        }
        _verifyContentType(e, t) {
            const r = t[http2.constants.HTTP2_HEADER_CONTENT_TYPE];
            if (typeof r !== "string" || !r.startsWith("application/grpc")) {
                e.respond({
                    [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE
                }, {
                    endStream: true
                });
                return false;
            }
            return true;
        }
        _retrieveHandler(e) {
            serverCallTrace("Received call to method " + e + " at address " + this.serverAddressString);
            const t = this.handlers.get(e);
            if (t === undefined) {
                serverCallTrace("No handler registered for method " + e + ". Sending UNIMPLEMENTED status.");
                return null;
            }
            return t;
        }
        _respondWithError(e, t, r = null) {
            var n, s;
            const o = Object.assign({
                "grpc-status": (n = e.code) !== null && n !== void 0 ? n : constants_1.Status.INTERNAL,
                "grpc-message": e.details,
                [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK,
                [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto"
            }, (s = e.metadata) === null || s === void 0 ? void 0 : s.toHttp2Headers());
            t.respond(o, {
                endStream: true
            });
            this.callTracker.addCallFailed();
            r === null || r === void 0 ? void 0 : r.streamTracker.addCallFailed();
        }
        _channelzHandler(e, t, r) {
            this.onStreamOpened(t);
            const n = this.sessions.get(t.session);
            this.callTracker.addCallStarted();
            n === null || n === void 0 ? void 0 : n.streamTracker.addCallStarted();
            if (!this._verifyContentType(t, r)) {
                this.callTracker.addCallFailed();
                n === null || n === void 0 ? void 0 : n.streamTracker.addCallFailed();
                return;
            }
            const s = r[HTTP2_HEADER_PATH];
            const o = this._retrieveHandler(s);
            if (!o) {
                this._respondWithError(getUnimplementedStatusResponse(s), t, n);
                return;
            }
            const a = {
                addMessageSent: () => {
                    if (n) {
                        n.messagesSent += 1;
                        n.lastMessageSentTimestamp = new Date;
                    }
                },
                addMessageReceived: () => {
                    if (n) {
                        n.messagesReceived += 1;
                        n.lastMessageReceivedTimestamp = new Date;
                    }
                },
                onCallEnd: e => {
                    if (e.code === constants_1.Status.OK) {
                        this.callTracker.addCallSucceeded();
                    } else {
                        this.callTracker.addCallFailed();
                    }
                },
                onStreamEnd: e => {
                    if (n) {
                        if (e) {
                            n.streamTracker.addCallSucceeded();
                        } else {
                            n.streamTracker.addCallFailed();
                        }
                    }
                }
            };
            const l = (0, server_interceptors_1.getServerInterceptingCall)([ ...e, ...this.interceptors ], t, r, a, o, this.options);
            if (!this._runHandlerForCall(l, o)) {
                this.callTracker.addCallFailed();
                n === null || n === void 0 ? void 0 : n.streamTracker.addCallFailed();
                l.sendStatus({
                    code: constants_1.Status.INTERNAL,
                    details: `Unknown handler type: ${o.type}`
                });
            }
        }
        _streamHandler(e, t, r) {
            this.onStreamOpened(t);
            if (this._verifyContentType(t, r) !== true) {
                return;
            }
            const n = r[HTTP2_HEADER_PATH];
            const s = this._retrieveHandler(n);
            if (!s) {
                this._respondWithError(getUnimplementedStatusResponse(n), t, null);
                return;
            }
            const o = (0, server_interceptors_1.getServerInterceptingCall)([ ...e, ...this.interceptors ], t, r, null, s, this.options);
            if (!this._runHandlerForCall(o, s)) {
                o.sendStatus({
                    code: constants_1.Status.INTERNAL,
                    details: `Unknown handler type: ${s.type}`
                });
            }
        }
        _runHandlerForCall(e, t) {
            const {type: r} = t;
            if (r === "unary") {
                handleUnary(e, t);
            } else if (r === "clientStream") {
                handleClientStreaming(e, t);
            } else if (r === "serverStream") {
                handleServerStreaming(e, t);
            } else if (r === "bidi") {
                handleBidiStreaming(e, t);
            } else {
                return false;
            }
            return true;
        }
        _setupHandlers(e, t) {
            if (e === null) {
                return;
            }
            const r = e.address();
            let n = "null";
            if (r) {
                if (typeof r === "string") {
                    n = r;
                } else {
                    n = r.address + ":" + r.port;
                }
            }
            this.serverAddressString = n;
            const s = this.channelzEnabled ? this._channelzHandler : this._streamHandler;
            const o = this.channelzEnabled ? this._channelzSessionHandler(e) : this._sessionHandler(e);
            e.on("stream", s.bind(this, t));
            e.on("session", o);
        }
        _sessionHandler(e) {
            return t => {
                var r, n;
                (r = this.http2Servers.get(e)) === null || r === void 0 ? void 0 : r.sessions.add(t);
                let s = null;
                let o = null;
                let a = null;
                let l = false;
                const c = this.enableIdleTimeout(t);
                if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
                    const e = this.maxConnectionAgeMs / 10;
                    const r = Math.random() * e * 2 - e;
                    s = setTimeout(() => {
                        var e, r;
                        l = true;
                        this.trace("Connection dropped by max connection age: " + ((e = t.socket) === null || e === void 0 ? void 0 : e.remoteAddress));
                        try {
                            t.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                        } catch (e) {
                            t.destroy();
                            return;
                        }
                        t.close();
                        if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                            o = setTimeout(() => {
                                t.destroy();
                            }, this.maxConnectionAgeGraceMs);
                            (r = o.unref) === null || r === void 0 ? void 0 : r.call(o);
                        }
                    }, this.maxConnectionAgeMs + r);
                    (n = s.unref) === null || n === void 0 ? void 0 : n.call(s);
                }
                const u = () => {
                    if (a) {
                        clearTimeout(a);
                        a = null;
                    }
                };
                const d = () => !t.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
                let h;
                const p = () => {
                    var e;
                    if (!d()) {
                        return;
                    }
                    this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
                    a = setTimeout(() => {
                        u();
                        h();
                    }, this.keepaliveTimeMs);
                    (e = a.unref) === null || e === void 0 ? void 0 : e.call(a);
                };
                h = () => {
                    var e;
                    if (!d()) {
                        return;
                    }
                    this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
                    let r = "";
                    try {
                        const e = t.ping((e, r, n) => {
                            u();
                            if (e) {
                                this.keepaliveTrace("Ping failed with error: " + e.message);
                                l = true;
                                t.close();
                            } else {
                                this.keepaliveTrace("Received ping response");
                                p();
                            }
                        });
                        if (!e) {
                            r = "Ping returned false";
                        }
                    } catch (e) {
                        r = (e instanceof Error ? e.message : "") || "Unknown error";
                    }
                    if (r) {
                        this.keepaliveTrace("Ping send failed: " + r);
                        this.trace("Connection dropped due to ping send error: " + r);
                        l = true;
                        t.close();
                        return;
                    }
                    a = setTimeout(() => {
                        u();
                        this.keepaliveTrace("Ping timeout passed without response");
                        this.trace("Connection dropped by keepalive timeout");
                        l = true;
                        t.close();
                    }, this.keepaliveTimeoutMs);
                    (e = a.unref) === null || e === void 0 ? void 0 : e.call(a);
                };
                p();
                t.on("close", () => {
                    var r, n;
                    if (!l) {
                        this.trace(`Connection dropped by client ${(r = t.socket) === null || r === void 0 ? void 0 : r.remoteAddress}`);
                    }
                    if (s) {
                        clearTimeout(s);
                    }
                    if (o) {
                        clearTimeout(o);
                    }
                    u();
                    if (c !== null) {
                        clearTimeout(c.timeout);
                        this.sessionIdleTimeouts.delete(t);
                    }
                    (n = this.http2Servers.get(e)) === null || n === void 0 ? void 0 : n.sessions.delete(t);
                });
            };
        }
        _channelzSessionHandler(e) {
            return t => {
                var r, n, s, o;
                const a = (0, channelz_1.registerChannelzSocket)((n = (r = t.socket) === null || r === void 0 ? void 0 : r.remoteAddress) !== null && n !== void 0 ? n : "unknown", this.getChannelzSessionInfo.bind(this, t), this.channelzEnabled);
                const l = {
                    ref: a,
                    streamTracker: new channelz_1.ChannelzCallTracker,
                    messagesSent: 0,
                    messagesReceived: 0,
                    keepAlivesSent: 0,
                    lastMessageSentTimestamp: null,
                    lastMessageReceivedTimestamp: null
                };
                (s = this.http2Servers.get(e)) === null || s === void 0 ? void 0 : s.sessions.add(t);
                this.sessions.set(t, l);
                const c = `${t.socket.remoteAddress}:${t.socket.remotePort}`;
                this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + c);
                this.trace("Connection established by client " + c);
                this.sessionChildrenTracker.refChild(a);
                let u = null;
                let d = null;
                let h = null;
                let p = false;
                const g = this.enableIdleTimeout(t);
                if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) {
                    const e = this.maxConnectionAgeMs / 10;
                    const r = Math.random() * e * 2 - e;
                    u = setTimeout(() => {
                        var e;
                        p = true;
                        this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + c);
                        try {
                            t.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge);
                        } catch (e) {
                            t.destroy();
                            return;
                        }
                        t.close();
                        if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) {
                            d = setTimeout(() => {
                                t.destroy();
                            }, this.maxConnectionAgeGraceMs);
                            (e = d.unref) === null || e === void 0 ? void 0 : e.call(d);
                        }
                    }, this.maxConnectionAgeMs + r);
                    (o = u.unref) === null || o === void 0 ? void 0 : o.call(u);
                }
                const m = () => {
                    if (h) {
                        clearTimeout(h);
                        h = null;
                    }
                };
                const _ = () => !t.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0;
                let E;
                const v = () => {
                    var e;
                    if (!_()) {
                        return;
                    }
                    this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms");
                    h = setTimeout(() => {
                        m();
                        E();
                    }, this.keepaliveTimeMs);
                    (e = h.unref) === null || e === void 0 ? void 0 : e.call(h);
                };
                E = () => {
                    var e;
                    if (!_()) {
                        return;
                    }
                    this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms");
                    let r = "";
                    try {
                        const e = t.ping((e, r, n) => {
                            m();
                            if (e) {
                                this.keepaliveTrace("Ping failed with error: " + e.message);
                                this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + e.message + " return in " + r);
                                p = true;
                                t.close();
                            } else {
                                this.keepaliveTrace("Received ping response");
                                v();
                            }
                        });
                        if (!e) {
                            r = "Ping returned false";
                        }
                    } catch (e) {
                        r = (e instanceof Error ? e.message : "") || "Unknown error";
                    }
                    if (r) {
                        this.keepaliveTrace("Ping send failed: " + r);
                        this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + r);
                        p = true;
                        t.close();
                        return;
                    }
                    l.keepAlivesSent += 1;
                    h = setTimeout(() => {
                        m();
                        this.keepaliveTrace("Ping timeout passed without response");
                        this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + c);
                        p = true;
                        t.close();
                    }, this.keepaliveTimeoutMs);
                    (e = h.unref) === null || e === void 0 ? void 0 : e.call(h);
                };
                v();
                t.on("close", () => {
                    var r;
                    if (!p) {
                        this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + c);
                    }
                    this.sessionChildrenTracker.unrefChild(a);
                    (0, channelz_1.unregisterChannelzRef)(a);
                    if (u) {
                        clearTimeout(u);
                    }
                    if (d) {
                        clearTimeout(d);
                    }
                    m();
                    if (g !== null) {
                        clearTimeout(g.timeout);
                        this.sessionIdleTimeouts.delete(t);
                    }
                    (r = this.http2Servers.get(e)) === null || r === void 0 ? void 0 : r.sessions.delete(t);
                    this.sessions.delete(t);
                });
            };
        }
        enableIdleTimeout(e) {
            var t, r;
            if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) {
                return null;
            }
            const n = {
                activeStreams: 0,
                lastIdle: Date.now(),
                onClose: this.onStreamClose.bind(this, e),
                timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, e)
            };
            (r = (t = n.timeout).unref) === null || r === void 0 ? void 0 : r.call(t);
            this.sessionIdleTimeouts.set(e, n);
            const {socket: s} = e;
            this.trace("Enable idle timeout for " + s.remoteAddress + ":" + s.remotePort);
            return n;
        }
        onIdleTimeout(e, t) {
            const {socket: r} = t;
            const n = e.sessionIdleTimeouts.get(t);
            if (n !== undefined && n.activeStreams === 0) {
                if (Date.now() - n.lastIdle >= e.sessionIdleTimeout) {
                    e.trace("Session idle timeout triggered for " + (r === null || r === void 0 ? void 0 : r.remoteAddress) + ":" + (r === null || r === void 0 ? void 0 : r.remotePort) + " last idle at " + n.lastIdle);
                    e.closeSession(t);
                } else {
                    n.timeout.refresh();
                }
            }
        }
        onStreamOpened(e) {
            const t = e.session;
            const r = this.sessionIdleTimeouts.get(t);
            if (r) {
                r.activeStreams += 1;
                e.once("close", r.onClose);
            }
        }
        onStreamClose(e) {
            var t, r;
            const n = this.sessionIdleTimeouts.get(e);
            if (n) {
                n.activeStreams -= 1;
                if (n.activeStreams === 0) {
                    n.lastIdle = Date.now();
                    n.timeout.refresh();
                    this.trace("Session onStreamClose" + ((t = e.socket) === null || t === void 0 ? void 0 : t.remoteAddress) + ":" + ((r = e.socket) === null || r === void 0 ? void 0 : r.remotePort) + " at " + n.lastIdle);
                }
            }
        }
    }, (() => {
        const n = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
        r = [ deprecate("Calling start() is no longer necessary. It can be safely omitted.") ];
        __esDecorate(e, null, r, {
            kind: "method",
            name: "start",
            static: false,
            private: false,
            access: {
                has: e => "start" in e,
                get: e => e.start
            },
            metadata: n
        }, null, t);
        if (n) Object.defineProperty(e, Symbol.metadata, {
            enumerable: true,
            configurable: true,
            writable: true,
            value: n
        });
    })(), e;
})();

server.Server = Server;

async function handleUnary(e, t) {
    let r;
    function n(t, r, n, s) {
        if (t) {
            e.sendStatus((0, server_call_1.serverErrorToStatus)(t, n));
            return;
        }
        e.sendMessage(r, () => {
            e.sendStatus({
                code: constants_1.Status.OK,
                details: "OK",
                metadata: n !== null && n !== void 0 ? n : null
            });
        });
    }
    let s;
    let o = null;
    e.start({
        onReceiveMetadata(t) {
            s = t;
            e.startRead();
        },
        onReceiveMessage(r) {
            if (o) {
                e.sendStatus({
                    code: constants_1.Status.UNIMPLEMENTED,
                    details: `Received a second request message for server streaming method ${t.path}`,
                    metadata: null
                });
                return;
            }
            o = r;
            e.startRead();
        },
        onReceiveHalfClose() {
            if (!o) {
                e.sendStatus({
                    code: constants_1.Status.UNIMPLEMENTED,
                    details: `Received no request message for server streaming method ${t.path}`,
                    metadata: null
                });
                return;
            }
            r = new server_call_1.ServerWritableStreamImpl(t.path, e, s, o);
            try {
                t.func(r, n);
            } catch (t) {
                e.sendStatus({
                    code: constants_1.Status.UNKNOWN,
                    details: `Server method handler threw error ${t.message}`,
                    metadata: null
                });
            }
        },
        onCancel() {
            if (r) {
                r.cancelled = true;
                r.emit("cancelled", "cancelled");
            }
        }
    });
}

function handleClientStreaming(e, t) {
    let r;
    function n(t, r, n, s) {
        if (t) {
            e.sendStatus((0, server_call_1.serverErrorToStatus)(t, n));
            return;
        }
        e.sendMessage(r, () => {
            e.sendStatus({
                code: constants_1.Status.OK,
                details: "OK",
                metadata: n !== null && n !== void 0 ? n : null
            });
        });
    }
    e.start({
        onReceiveMetadata(s) {
            r = new server_call_1.ServerDuplexStreamImpl(t.path, e, s);
            try {
                t.func(r, n);
            } catch (t) {
                e.sendStatus({
                    code: constants_1.Status.UNKNOWN,
                    details: `Server method handler threw error ${t.message}`,
                    metadata: null
                });
            }
        },
        onReceiveMessage(e) {
            r.push(e);
        },
        onReceiveHalfClose() {
            r.push(null);
        },
        onCancel() {
            if (r) {
                r.cancelled = true;
                r.emit("cancelled", "cancelled");
                r.destroy();
            }
        }
    });
}

function handleServerStreaming(e, t) {
    let r;
    let n;
    let s = null;
    e.start({
        onReceiveMetadata(t) {
            n = t;
            e.startRead();
        },
        onReceiveMessage(r) {
            if (s) {
                e.sendStatus({
                    code: constants_1.Status.UNIMPLEMENTED,
                    details: `Received a second request message for server streaming method ${t.path}`,
                    metadata: null
                });
                return;
            }
            s = r;
            e.startRead();
        },
        onReceiveHalfClose() {
            if (!s) {
                e.sendStatus({
                    code: constants_1.Status.UNIMPLEMENTED,
                    details: `Received no request message for server streaming method ${t.path}`,
                    metadata: null
                });
                return;
            }
            r = new server_call_1.ServerWritableStreamImpl(t.path, e, n, s);
            try {
                t.func(r);
            } catch (t) {
                e.sendStatus({
                    code: constants_1.Status.UNKNOWN,
                    details: `Server method handler threw error ${t.message}`,
                    metadata: null
                });
            }
        },
        onCancel() {
            if (r) {
                r.cancelled = true;
                r.emit("cancelled", "cancelled");
                r.destroy();
            }
        }
    });
}

function handleBidiStreaming(e, t) {
    let r;
    e.start({
        onReceiveMetadata(n) {
            r = new server_call_1.ServerDuplexStreamImpl(t.path, e, n);
            try {
                t.func(r);
            } catch (t) {
                e.sendStatus({
                    code: constants_1.Status.UNKNOWN,
                    details: `Server method handler threw error ${t.message}`,
                    metadata: null
                });
            }
        },
        onReceiveMessage(e) {
            r.push(e);
        },
        onReceiveHalfClose() {
            r.push(null);
        },
        onCancel() {
            if (r) {
                r.cancelled = true;
                r.emit("cancelled", "cancelled");
                r.destroy();
            }
        }
    });
}

var statusBuilder = {};

Object.defineProperty(statusBuilder, "__esModule", {
    value: true
});

statusBuilder.StatusBuilder = void 0;

class StatusBuilder {
    constructor() {
        this.code = null;
        this.details = null;
        this.metadata = null;
    }
    withCode(e) {
        this.code = e;
        return this;
    }
    withDetails(e) {
        this.details = e;
        return this;
    }
    withMetadata(e) {
        this.metadata = e;
        return this;
    }
    build() {
        const e = {};
        if (this.code !== null) {
            e.code = this.code;
        }
        if (this.details !== null) {
            e.details = this.details;
        }
        if (this.metadata !== null) {
            e.metadata = this.metadata;
        }
        return e;
    }
}

statusBuilder.StatusBuilder = StatusBuilder;

var experimental = {};

var loadBalancerPickFirst = {};

var hasRequiredLoadBalancerPickFirst;

function requireLoadBalancerPickFirst() {
    if (hasRequiredLoadBalancerPickFirst) return loadBalancerPickFirst;
    hasRequiredLoadBalancerPickFirst = 1;
    Object.defineProperty(loadBalancerPickFirst, "__esModule", {
        value: true
    });
    loadBalancerPickFirst.LeafLoadBalancer = loadBalancerPickFirst.PickFirstLoadBalancer = loadBalancerPickFirst.PickFirstLoadBalancingConfig = void 0;
    loadBalancerPickFirst.shuffled = g;
    loadBalancerPickFirst.setup = v;
    const e = requireLoadBalancer();
    const t = connectivityState;
    const r = requirePicker();
    const n = subchannelAddress;
    const s = logging$8;
    const o = constants;
    const a = subchannelAddress;
    const l = require$$0__default$6.default;
    const c = requireCallInterface();
    const u = "pick_first";
    function d(e) {
        s.trace(o.LogVerbosity.DEBUG, u, e);
    }
    const h = "pick_first";
    const p = 250;
    class PickFirstLoadBalancingConfig {
        constructor(e) {
            this.shuffleAddressList = e;
        }
        getLoadBalancerName() {
            return h;
        }
        toJsonObject() {
            return {
                [h]: {
                    shuffleAddressList: this.shuffleAddressList
                }
            };
        }
        getShuffleAddressList() {
            return this.shuffleAddressList;
        }
        static createFromJson(e) {
            if ("shuffleAddressList" in e && !(typeof e.shuffleAddressList === "boolean")) {
                throw new Error("pick_first config field shuffleAddressList must be a boolean if provided");
            }
            return new PickFirstLoadBalancingConfig(e.shuffleAddressList === true);
        }
    }
    loadBalancerPickFirst.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig;
    class PickFirstPicker {
        constructor(e) {
            this.subchannel = e;
        }
        pick(e) {
            return {
                pickResultType: r.PickResultType.COMPLETE,
                subchannel: this.subchannel,
                status: null,
                onCallStarted: null,
                onCallEnded: null
            };
        }
    }
    function g(e) {
        const t = e.slice();
        for (let e = t.length - 1; e > 1; e--) {
            const r = Math.floor(Math.random() * (e + 1));
            const n = t[e];
            t[e] = t[r];
            t[r] = n;
        }
        return t;
    }
    function m(e) {
        if (e.length === 0) {
            return [];
        }
        const t = [];
        const r = [];
        const n = [];
        const s = (0, a.isTcpSubchannelAddress)(e[0]) && (0, l.isIPv6)(e[0].host);
        for (const t of e) {
            if ((0, a.isTcpSubchannelAddress)(t) && (0, l.isIPv6)(t.host)) {
                r.push(t);
            } else {
                n.push(t);
            }
        }
        const o = s ? r : n;
        const c = s ? n : r;
        for (let e = 0; e < Math.max(o.length, c.length); e++) {
            if (e < o.length) {
                t.push(o[e]);
            }
            if (e < c.length) {
                t.push(c[e]);
            }
        }
        return t;
    }
    const _ = "grpc-node.internal.pick-first.report_health_status";
    class PickFirstLoadBalancer {
        constructor(e) {
            this.channelControlHelper = e;
            this.children = [];
            this.currentState = t.ConnectivityState.IDLE;
            this.currentSubchannelIndex = 0;
            this.currentPick = null;
            this.subchannelStateListener = (e, t, r, n, s) => {
                this.onSubchannelStateUpdate(e, t, r, s);
            };
            this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState();
            this.stickyTransientFailureMode = false;
            this.reportHealthStatus = false;
            this.lastError = null;
            this.latestAddressList = null;
            this.latestOptions = {};
            this.latestResolutionNote = "";
            this.connectionDelayTimeout = setTimeout(() => {}, 0);
            clearTimeout(this.connectionDelayTimeout);
        }
        allChildrenHaveReportedTF() {
            return this.children.every(e => e.hasReportedTransientFailure);
        }
        resetChildrenReportedTF() {
            this.children.every(e => e.hasReportedTransientFailure = false);
        }
        calculateAndReportNewState() {
            var e;
            if (this.currentPick) {
                if (this.reportHealthStatus && !this.currentPick.isHealthy()) {
                    const e = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;
                    this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker({
                        details: e
                    }), e);
                } else {
                    this.updateState(t.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null);
                }
            } else if (((e = this.latestAddressList) === null || e === void 0 ? void 0 : e.length) === 0) {
                const e = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;
                this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker({
                    details: e
                }), e);
            } else if (this.children.length === 0) {
                this.updateState(t.ConnectivityState.IDLE, new r.QueuePicker(this), null);
            } else {
                if (this.stickyTransientFailureMode) {
                    const e = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;
                    this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker({
                        details: e
                    }), e);
                } else {
                    this.updateState(t.ConnectivityState.CONNECTING, new r.QueuePicker(this), null);
                }
            }
        }
        requestReresolution() {
            this.channelControlHelper.requestReresolution();
        }
        maybeEnterStickyTransientFailureMode() {
            if (!this.allChildrenHaveReportedTF()) {
                return;
            }
            this.requestReresolution();
            this.resetChildrenReportedTF();
            if (this.stickyTransientFailureMode) {
                this.calculateAndReportNewState();
                return;
            }
            this.stickyTransientFailureMode = true;
            for (const {subchannel: e} of this.children) {
                e.startConnecting();
            }
            this.calculateAndReportNewState();
        }
        removeCurrentPick() {
            if (this.currentPick !== null) {
                this.currentPick.removeConnectivityStateListener(this.subchannelStateListener);
                this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef());
                this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener);
                this.currentPick.unref();
                this.currentPick = null;
            }
        }
        onSubchannelStateUpdate(e, r, n, s) {
            var o;
            if ((o = this.currentPick) === null || o === void 0 ? void 0 : o.realSubchannelEquals(e)) {
                if (n !== t.ConnectivityState.READY) {
                    this.removeCurrentPick();
                    this.calculateAndReportNewState();
                }
                return;
            }
            for (const [r, o] of this.children.entries()) {
                if (e.realSubchannelEquals(o.subchannel)) {
                    if (n === t.ConnectivityState.READY) {
                        this.pickSubchannel(o.subchannel);
                    }
                    if (n === t.ConnectivityState.TRANSIENT_FAILURE) {
                        o.hasReportedTransientFailure = true;
                        if (s) {
                            this.lastError = s;
                        }
                        this.maybeEnterStickyTransientFailureMode();
                        if (r === this.currentSubchannelIndex) {
                            this.startNextSubchannelConnecting(r + 1);
                        }
                    }
                    o.subchannel.startConnecting();
                    return;
                }
            }
        }
        startNextSubchannelConnecting(e) {
            clearTimeout(this.connectionDelayTimeout);
            for (const [r, n] of this.children.entries()) {
                if (r >= e) {
                    const e = n.subchannel.getConnectivityState();
                    if (e === t.ConnectivityState.IDLE || e === t.ConnectivityState.CONNECTING) {
                        this.startConnecting(r);
                        return;
                    }
                }
            }
            this.maybeEnterStickyTransientFailureMode();
        }
        startConnecting(e) {
            var r, n;
            clearTimeout(this.connectionDelayTimeout);
            this.currentSubchannelIndex = e;
            if (this.children[e].subchannel.getConnectivityState() === t.ConnectivityState.IDLE) {
                d("Start connecting to subchannel with address " + this.children[e].subchannel.getAddress());
                process.nextTick(() => {
                    var t;
                    (t = this.children[e]) === null || t === void 0 ? void 0 : t.subchannel.startConnecting();
                });
            }
            this.connectionDelayTimeout = setTimeout(() => {
                this.startNextSubchannelConnecting(e + 1);
            }, p);
            (n = (r = this.connectionDelayTimeout).unref) === null || n === void 0 ? void 0 : n.call(r);
        }
        pickSubchannel(e) {
            d("Pick subchannel with address " + e.getAddress());
            this.stickyTransientFailureMode = false;
            e.ref();
            this.channelControlHelper.addChannelzChild(e.getChannelzRef());
            this.removeCurrentPick();
            this.resetSubchannelList();
            e.addConnectivityStateListener(this.subchannelStateListener);
            e.addHealthStateWatcher(this.pickedSubchannelHealthListener);
            this.currentPick = e;
            clearTimeout(this.connectionDelayTimeout);
            this.calculateAndReportNewState();
        }
        updateState(e, r, n) {
            d(t.ConnectivityState[this.currentState] + " -> " + t.ConnectivityState[e]);
            this.currentState = e;
            this.channelControlHelper.updateState(e, r, n);
        }
        resetSubchannelList() {
            for (const e of this.children) {
                e.subchannel.removeConnectivityStateListener(this.subchannelStateListener);
                e.subchannel.unref();
                this.channelControlHelper.removeChannelzChild(e.subchannel.getChannelzRef());
            }
            this.currentSubchannelIndex = 0;
            this.children = [];
        }
        connectToAddressList(e, r) {
            d("connectToAddressList([" + e.map(e => (0, n.subchannelAddressToString)(e)) + "])");
            const s = e.map(e => ({
                subchannel: this.channelControlHelper.createSubchannel(e, r),
                hasReportedTransientFailure: false
            }));
            for (const {subchannel: e} of s) {
                if (e.getConnectivityState() === t.ConnectivityState.READY) {
                    this.pickSubchannel(e);
                    return;
                }
            }
            for (const {subchannel: e} of s) {
                e.ref();
                this.channelControlHelper.addChannelzChild(e.getChannelzRef());
            }
            this.resetSubchannelList();
            this.children = s;
            for (const {subchannel: e} of this.children) {
                e.addConnectivityStateListener(this.subchannelStateListener);
            }
            for (const e of this.children) {
                if (e.subchannel.getConnectivityState() === t.ConnectivityState.TRANSIENT_FAILURE) {
                    e.hasReportedTransientFailure = true;
                }
            }
            this.startNextSubchannelConnecting(0);
            this.calculateAndReportNewState();
        }
        updateAddressList(e, s, o, a) {
            if (!(s instanceof PickFirstLoadBalancingConfig)) {
                return false;
            }
            if (!e.ok) {
                if (this.children.length === 0 && this.currentPick === null) {
                    this.channelControlHelper.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker(e.error), e.error.details);
                }
                return true;
            }
            let l = e.value;
            this.reportHealthStatus = o[_];
            if (s.getShuffleAddressList()) {
                l = g(l);
            }
            const c = [].concat(...l.map(e => e.addresses));
            d("updateAddressList([" + c.map(e => (0, n.subchannelAddressToString)(e)) + "])");
            const u = m(c);
            this.latestAddressList = u;
            this.latestOptions = o;
            this.connectToAddressList(u, o);
            this.latestResolutionNote = a;
            if (c.length > 0) {
                return true;
            } else {
                this.lastError = "No addresses resolved";
                return false;
            }
        }
        exitIdle() {
            if (this.currentState === t.ConnectivityState.IDLE && this.latestAddressList) {
                this.connectToAddressList(this.latestAddressList, this.latestOptions);
            }
        }
        resetBackoff() {}
        destroy() {
            this.resetSubchannelList();
            this.removeCurrentPick();
        }
        getTypeName() {
            return h;
        }
    }
    loadBalancerPickFirst.PickFirstLoadBalancer = PickFirstLoadBalancer;
    const E = new PickFirstLoadBalancingConfig(false);
    class LeafLoadBalancer {
        constructor(n, s, o, a) {
            this.endpoint = n;
            this.options = o;
            this.resolutionNote = a;
            this.latestState = t.ConnectivityState.IDLE;
            const l = (0, e.createChildChannelControlHelper)(s, {
                updateState: (e, t, r) => {
                    this.latestState = e;
                    this.latestPicker = t;
                    s.updateState(e, t, r);
                }
            });
            this.pickFirstBalancer = new PickFirstLoadBalancer(l);
            this.latestPicker = new r.QueuePicker(this.pickFirstBalancer);
        }
        startConnecting() {
            this.pickFirstBalancer.updateAddressList((0, c.statusOrFromValue)([ this.endpoint ]), E, Object.assign(Object.assign({}, this.options), {
                [_]: true
            }), this.resolutionNote);
        }
        updateEndpoint(e, r) {
            this.options = r;
            this.endpoint = e;
            if (this.latestState !== t.ConnectivityState.IDLE) {
                this.startConnecting();
            }
        }
        getConnectivityState() {
            return this.latestState;
        }
        getPicker() {
            return this.latestPicker;
        }
        getEndpoint() {
            return this.endpoint;
        }
        exitIdle() {
            this.pickFirstBalancer.exitIdle();
        }
        destroy() {
            this.pickFirstBalancer.destroy();
        }
    }
    loadBalancerPickFirst.LeafLoadBalancer = LeafLoadBalancer;
    function v() {
        (0, e.registerLoadBalancerType)(h, PickFirstLoadBalancer, PickFirstLoadBalancingConfig);
        (0, e.registerDefaultLoadBalancerType)(h);
    }
    return loadBalancerPickFirst;
}

var certificateProvider = {};

var hasRequiredCertificateProvider;

function requireCertificateProvider() {
    if (hasRequiredCertificateProvider) return certificateProvider;
    hasRequiredCertificateProvider = 1;
    Object.defineProperty(certificateProvider, "__esModule", {
        value: true
    });
    certificateProvider.FileWatcherCertificateProvider = void 0;
    const e = require$$0__default$5.default;
    const t = logging$8;
    const r = constants;
    const n = require$$1__default$1.default;
    const s = "certificate_provider";
    function o(e) {
        t.trace(r.LogVerbosity.DEBUG, s, e);
    }
    const a = (0, n.promisify)(e.readFile);
    class FileWatcherCertificateProvider {
        constructor(e) {
            this.config = e;
            this.refreshTimer = null;
            this.fileResultPromise = null;
            this.latestCaUpdate = undefined;
            this.caListeners = new Set;
            this.latestIdentityUpdate = undefined;
            this.identityListeners = new Set;
            this.lastUpdateTime = null;
            if (e.certificateFile === undefined !== (e.privateKeyFile === undefined)) {
                throw new Error("certificateFile and privateKeyFile must be set or unset together");
            }
            if (e.certificateFile === undefined && e.caCertificateFile === undefined) {
                throw new Error("At least one of certificateFile and caCertificateFile must be set");
            }
            o("File watcher constructed with config " + JSON.stringify(e));
        }
        updateCertificates() {
            if (this.fileResultPromise) {
                return;
            }
            this.fileResultPromise = Promise.allSettled([ this.config.certificateFile ? a(this.config.certificateFile) : Promise.reject(), this.config.privateKeyFile ? a(this.config.privateKeyFile) : Promise.reject(), this.config.caCertificateFile ? a(this.config.caCertificateFile) : Promise.reject() ]);
            this.fileResultPromise.then(([e, t, r]) => {
                if (!this.refreshTimer) {
                    return;
                }
                o("File watcher read certificates certificate " + e.status + ", privateKey " + t.status + ", CA certificate " + r.status);
                this.lastUpdateTime = new Date;
                this.fileResultPromise = null;
                if (e.status === "fulfilled" && t.status === "fulfilled") {
                    this.latestIdentityUpdate = {
                        certificate: e.value,
                        privateKey: t.value
                    };
                } else {
                    this.latestIdentityUpdate = null;
                }
                if (r.status === "fulfilled") {
                    this.latestCaUpdate = {
                        caCertificate: r.value
                    };
                } else {
                    this.latestCaUpdate = null;
                }
                for (const e of this.identityListeners) {
                    e(this.latestIdentityUpdate);
                }
                for (const e of this.caListeners) {
                    e(this.latestCaUpdate);
                }
            });
            o("File watcher initiated certificate update");
        }
        maybeStartWatchingFiles() {
            if (!this.refreshTimer) {
                const e = this.lastUpdateTime ? (new Date).getTime() - this.lastUpdateTime.getTime() : Infinity;
                if (e > this.config.refreshIntervalMs) {
                    this.updateCertificates();
                }
                if (e > this.config.refreshIntervalMs * 2) {
                    this.latestCaUpdate = undefined;
                    this.latestIdentityUpdate = undefined;
                }
                this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs);
                o("File watcher started watching");
            }
        }
        maybeStopWatchingFiles() {
            if (this.caListeners.size === 0 && this.identityListeners.size === 0) {
                this.fileResultPromise = null;
                if (this.refreshTimer) {
                    clearInterval(this.refreshTimer);
                    this.refreshTimer = null;
                }
            }
        }
        addCaCertificateListener(e) {
            this.caListeners.add(e);
            this.maybeStartWatchingFiles();
            if (this.latestCaUpdate !== undefined) {
                process.nextTick(e, this.latestCaUpdate);
            }
        }
        removeCaCertificateListener(e) {
            this.caListeners.delete(e);
            this.maybeStopWatchingFiles();
        }
        addIdentityCertificateListener(e) {
            this.identityListeners.add(e);
            this.maybeStartWatchingFiles();
            if (this.latestIdentityUpdate !== undefined) {
                process.nextTick(e, this.latestIdentityUpdate);
            }
        }
        removeIdentityCertificateListener(e) {
            this.identityListeners.delete(e);
            this.maybeStopWatchingFiles();
        }
    }
    certificateProvider.FileWatcherCertificateProvider = FileWatcherCertificateProvider;
    return certificateProvider;
}

var hasRequiredExperimental;

function requireExperimental() {
    if (hasRequiredExperimental) return experimental;
    hasRequiredExperimental = 1;
    (function(e) {
        Object.defineProperty(e, "__esModule", {
            value: true
        });
        e.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = e.createCertificateProviderChannelCredentials = e.FileWatcherCertificateProvider = e.createCertificateProviderServerCredentials = e.createServerCredentialsWithInterceptors = e.BaseSubchannelWrapper = e.registerAdminService = e.FilterStackFactory = e.BaseFilter = e.statusOrFromError = e.statusOrFromValue = e.PickResultType = e.QueuePicker = e.UnavailablePicker = e.ChildLoadBalancerHandler = e.EndpointMap = e.endpointHasAddress = e.endpointToString = e.subchannelAddressToString = e.LeafLoadBalancer = e.isLoadBalancerNameRegistered = e.parseLoadBalancingConfig = e.selectLbConfigFromList = e.registerLoadBalancerType = e.createChildChannelControlHelper = e.BackoffTimeout = e.parseDuration = e.durationToMs = e.splitHostPort = e.uriToString = e.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = e.createResolver = e.registerResolver = e.log = e.trace = void 0;
        var t = logging$8;
        Object.defineProperty(e, "trace", {
            enumerable: true,
            get: function() {
                return t.trace;
            }
        });
        Object.defineProperty(e, "log", {
            enumerable: true,
            get: function() {
                return t.log;
            }
        });
        var r = resolver;
        Object.defineProperty(e, "registerResolver", {
            enumerable: true,
            get: function() {
                return r.registerResolver;
            }
        });
        Object.defineProperty(e, "createResolver", {
            enumerable: true,
            get: function() {
                return r.createResolver;
            }
        });
        Object.defineProperty(e, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", {
            enumerable: true,
            get: function() {
                return r.CHANNEL_ARGS_CONFIG_SELECTOR_KEY;
            }
        });
        var n = uriParser;
        Object.defineProperty(e, "uriToString", {
            enumerable: true,
            get: function() {
                return n.uriToString;
            }
        });
        Object.defineProperty(e, "splitHostPort", {
            enumerable: true,
            get: function() {
                return n.splitHostPort;
            }
        });
        var s = requireDuration();
        Object.defineProperty(e, "durationToMs", {
            enumerable: true,
            get: function() {
                return s.durationToMs;
            }
        });
        Object.defineProperty(e, "parseDuration", {
            enumerable: true,
            get: function() {
                return s.parseDuration;
            }
        });
        var o = requireBackoffTimeout();
        Object.defineProperty(e, "BackoffTimeout", {
            enumerable: true,
            get: function() {
                return o.BackoffTimeout;
            }
        });
        var a = requireLoadBalancer();
        Object.defineProperty(e, "createChildChannelControlHelper", {
            enumerable: true,
            get: function() {
                return a.createChildChannelControlHelper;
            }
        });
        Object.defineProperty(e, "registerLoadBalancerType", {
            enumerable: true,
            get: function() {
                return a.registerLoadBalancerType;
            }
        });
        Object.defineProperty(e, "selectLbConfigFromList", {
            enumerable: true,
            get: function() {
                return a.selectLbConfigFromList;
            }
        });
        Object.defineProperty(e, "parseLoadBalancingConfig", {
            enumerable: true,
            get: function() {
                return a.parseLoadBalancingConfig;
            }
        });
        Object.defineProperty(e, "isLoadBalancerNameRegistered", {
            enumerable: true,
            get: function() {
                return a.isLoadBalancerNameRegistered;
            }
        });
        var l = requireLoadBalancerPickFirst();
        Object.defineProperty(e, "LeafLoadBalancer", {
            enumerable: true,
            get: function() {
                return l.LeafLoadBalancer;
            }
        });
        var c = subchannelAddress;
        Object.defineProperty(e, "subchannelAddressToString", {
            enumerable: true,
            get: function() {
                return c.subchannelAddressToString;
            }
        });
        Object.defineProperty(e, "endpointToString", {
            enumerable: true,
            get: function() {
                return c.endpointToString;
            }
        });
        Object.defineProperty(e, "endpointHasAddress", {
            enumerable: true,
            get: function() {
                return c.endpointHasAddress;
            }
        });
        Object.defineProperty(e, "EndpointMap", {
            enumerable: true,
            get: function() {
                return c.EndpointMap;
            }
        });
        var u = requireLoadBalancerChildHandler();
        Object.defineProperty(e, "ChildLoadBalancerHandler", {
            enumerable: true,
            get: function() {
                return u.ChildLoadBalancerHandler;
            }
        });
        var d = requirePicker();
        Object.defineProperty(e, "UnavailablePicker", {
            enumerable: true,
            get: function() {
                return d.UnavailablePicker;
            }
        });
        Object.defineProperty(e, "QueuePicker", {
            enumerable: true,
            get: function() {
                return d.QueuePicker;
            }
        });
        Object.defineProperty(e, "PickResultType", {
            enumerable: true,
            get: function() {
                return d.PickResultType;
            }
        });
        var h = requireCallInterface();
        Object.defineProperty(e, "statusOrFromValue", {
            enumerable: true,
            get: function() {
                return h.statusOrFromValue;
            }
        });
        Object.defineProperty(e, "statusOrFromError", {
            enumerable: true,
            get: function() {
                return h.statusOrFromError;
            }
        });
        var p = requireFilter();
        Object.defineProperty(e, "BaseFilter", {
            enumerable: true,
            get: function() {
                return p.BaseFilter;
            }
        });
        var g = requireFilterStack();
        Object.defineProperty(e, "FilterStackFactory", {
            enumerable: true,
            get: function() {
                return g.FilterStackFactory;
            }
        });
        var m = requireAdmin();
        Object.defineProperty(e, "registerAdminService", {
            enumerable: true,
            get: function() {
                return m.registerAdminService;
            }
        });
        var _ = requireSubchannelInterface();
        Object.defineProperty(e, "BaseSubchannelWrapper", {
            enumerable: true,
            get: function() {
                return _.BaseSubchannelWrapper;
            }
        });
        var E = serverCredentials;
        Object.defineProperty(e, "createServerCredentialsWithInterceptors", {
            enumerable: true,
            get: function() {
                return E.createServerCredentialsWithInterceptors;
            }
        });
        Object.defineProperty(e, "createCertificateProviderServerCredentials", {
            enumerable: true,
            get: function() {
                return E.createCertificateProviderServerCredentials;
            }
        });
        var v = requireCertificateProvider();
        Object.defineProperty(e, "FileWatcherCertificateProvider", {
            enumerable: true,
            get: function() {
                return v.FileWatcherCertificateProvider;
            }
        });
        var y = channelCredentials;
        Object.defineProperty(e, "createCertificateProviderChannelCredentials", {
            enumerable: true,
            get: function() {
                return y.createCertificateProviderChannelCredentials;
            }
        });
        var S = requireInternalChannel();
        Object.defineProperty(e, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", {
            enumerable: true,
            get: function() {
                return S.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX;
            }
        });
    })(experimental);
    return experimental;
}

var resolverUds = {};

var hasRequiredResolverUds;

function requireResolverUds() {
    if (hasRequiredResolverUds) return resolverUds;
    hasRequiredResolverUds = 1;
    Object.defineProperty(resolverUds, "__esModule", {
        value: true
    });
    resolverUds.setup = r;
    const e = resolver;
    const t = requireCallInterface();
    class UdsResolver {
        constructor(e, t, r) {
            this.listener = t;
            this.hasReturnedResult = false;
            this.endpoints = [];
            let n;
            if (e.authority === "") {
                n = "/" + e.path;
            } else {
                n = e.path;
            }
            this.endpoints = [ {
                addresses: [ {
                    path: n
                } ]
            } ];
        }
        updateResolution() {
            if (!this.hasReturnedResult) {
                this.hasReturnedResult = true;
                process.nextTick(this.listener, (0, t.statusOrFromValue)(this.endpoints), {}, null, "");
            }
        }
        destroy() {
            this.hasReturnedResult = false;
        }
        static getDefaultAuthority(e) {
            return "localhost";
        }
    }
    function r() {
        (0, e.registerResolver)("unix", UdsResolver);
    }
    return resolverUds;
}

var resolverIp = {};

var hasRequiredResolverIp;

function requireResolverIp() {
    if (hasRequiredResolverIp) return resolverIp;
    hasRequiredResolverIp = 1;
    Object.defineProperty(resolverIp, "__esModule", {
        value: true
    });
    resolverIp.setup = g;
    const e = require$$0__default$6.default;
    const t = requireCallInterface();
    const r = constants;
    const n = metadata;
    const s = resolver;
    const o = subchannelAddress;
    const a = uriParser;
    const l = logging$8;
    const c = "ip_resolver";
    function u(e) {
        l.trace(r.LogVerbosity.DEBUG, c, e);
    }
    const d = "ipv4";
    const h = "ipv6";
    const p = 443;
    class IpResolver {
        constructor(t, s, l) {
            var c;
            this.listener = s;
            this.endpoints = [];
            this.error = null;
            this.hasReturnedResult = false;
            u("Resolver constructed for target " + (0, a.uriToString)(t));
            const g = [];
            if (!(t.scheme === d || t.scheme === h)) {
                this.error = {
                    code: r.Status.UNAVAILABLE,
                    details: `Unrecognized scheme ${t.scheme} in IP resolver`,
                    metadata: new n.Metadata
                };
                return;
            }
            const m = t.path.split(",");
            for (const s of m) {
                const o = (0, a.splitHostPort)(s);
                if (o === null) {
                    this.error = {
                        code: r.Status.UNAVAILABLE,
                        details: `Failed to parse ${t.scheme} address ${s}`,
                        metadata: new n.Metadata
                    };
                    return;
                }
                if (t.scheme === d && !(0, e.isIPv4)(o.host) || t.scheme === h && !(0, e.isIPv6)(o.host)) {
                    this.error = {
                        code: r.Status.UNAVAILABLE,
                        details: `Failed to parse ${t.scheme} address ${s}`,
                        metadata: new n.Metadata
                    };
                    return;
                }
                g.push({
                    host: o.host,
                    port: (c = o.port) !== null && c !== void 0 ? c : p
                });
            }
            this.endpoints = g.map(e => ({
                addresses: [ e ]
            }));
            u("Parsed " + t.scheme + " address list " + g.map(o.subchannelAddressToString));
        }
        updateResolution() {
            if (!this.hasReturnedResult) {
                this.hasReturnedResult = true;
                process.nextTick(() => {
                    if (this.error) {
                        this.listener((0, t.statusOrFromError)(this.error), {}, null, "");
                    } else {
                        this.listener((0, t.statusOrFromValue)(this.endpoints), {}, null, "");
                    }
                });
            }
        }
        destroy() {
            this.hasReturnedResult = false;
        }
        static getDefaultAuthority(e) {
            return e.path.split(",")[0];
        }
    }
    function g() {
        (0, s.registerResolver)(d, IpResolver);
        (0, s.registerResolver)(h, IpResolver);
    }
    return resolverIp;
}

var loadBalancerRoundRobin = {};

var hasRequiredLoadBalancerRoundRobin;

function requireLoadBalancerRoundRobin() {
    if (hasRequiredLoadBalancerRoundRobin) return loadBalancerRoundRobin;
    hasRequiredLoadBalancerRoundRobin = 1;
    Object.defineProperty(loadBalancerRoundRobin, "__esModule", {
        value: true
    });
    loadBalancerRoundRobin.RoundRobinLoadBalancer = void 0;
    loadBalancerRoundRobin.setup = h;
    const e = requireLoadBalancer();
    const t = connectivityState;
    const r = requirePicker();
    const n = logging$8;
    const s = constants;
    const o = subchannelAddress;
    const a = requireLoadBalancerPickFirst();
    const l = "round_robin";
    function c(e) {
        n.trace(s.LogVerbosity.DEBUG, l, e);
    }
    const u = "round_robin";
    class RoundRobinLoadBalancingConfig {
        getLoadBalancerName() {
            return u;
        }
        constructor() {}
        toJsonObject() {
            return {
                [u]: {}
            };
        }
        static createFromJson(e) {
            return new RoundRobinLoadBalancingConfig;
        }
    }
    class RoundRobinPicker {
        constructor(e, t = 0) {
            this.children = e;
            this.nextIndex = t;
        }
        pick(e) {
            const t = this.children[this.nextIndex].picker;
            this.nextIndex = (this.nextIndex + 1) % this.children.length;
            return t.pick(e);
        }
        peekNextEndpoint() {
            return this.children[this.nextIndex].endpoint;
        }
    }
    function d(e, t) {
        return [ ...e.slice(t), ...e.slice(0, t) ];
    }
    class RoundRobinLoadBalancer {
        constructor(r) {
            this.channelControlHelper = r;
            this.children = [];
            this.currentState = t.ConnectivityState.IDLE;
            this.currentReadyPicker = null;
            this.updatesPaused = false;
            this.lastError = null;
            this.childChannelControlHelper = (0, e.createChildChannelControlHelper)(r, {
                updateState: (e, r, n) => {
                    if (this.currentState === t.ConnectivityState.READY && e !== t.ConnectivityState.READY) {
                        this.channelControlHelper.requestReresolution();
                    }
                    if (n) {
                        this.lastError = n;
                    }
                    this.calculateAndUpdateState();
                }
            });
        }
        countChildrenWithState(e) {
            return this.children.filter(t => t.getConnectivityState() === e).length;
        }
        calculateAndUpdateState() {
            if (this.updatesPaused) {
                return;
            }
            if (this.countChildrenWithState(t.ConnectivityState.READY) > 0) {
                const e = this.children.filter(e => e.getConnectivityState() === t.ConnectivityState.READY);
                let r = 0;
                if (this.currentReadyPicker !== null) {
                    const t = this.currentReadyPicker.peekNextEndpoint();
                    r = e.findIndex(e => (0, o.endpointEqual)(e.getEndpoint(), t));
                    if (r < 0) {
                        r = 0;
                    }
                }
                this.updateState(t.ConnectivityState.READY, new RoundRobinPicker(e.map(e => ({
                    endpoint: e.getEndpoint(),
                    picker: e.getPicker()
                })), r), null);
            } else if (this.countChildrenWithState(t.ConnectivityState.CONNECTING) > 0) {
                this.updateState(t.ConnectivityState.CONNECTING, new r.QueuePicker(this), null);
            } else if (this.countChildrenWithState(t.ConnectivityState.TRANSIENT_FAILURE) > 0) {
                const e = `round_robin: No connection established. Last error: ${this.lastError}`;
                this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker({
                    details: e
                }), e);
            } else {
                this.updateState(t.ConnectivityState.IDLE, new r.QueuePicker(this), null);
            }
            for (const e of this.children) {
                if (e.getConnectivityState() === t.ConnectivityState.IDLE) {
                    e.exitIdle();
                }
            }
        }
        updateState(e, r, n) {
            c(t.ConnectivityState[this.currentState] + " -> " + t.ConnectivityState[e]);
            if (e === t.ConnectivityState.READY) {
                this.currentReadyPicker = r;
            } else {
                this.currentReadyPicker = null;
            }
            this.currentState = e;
            this.channelControlHelper.updateState(e, r, n);
        }
        resetSubchannelList() {
            for (const e of this.children) {
                e.destroy();
            }
            this.children = [];
        }
        updateAddressList(e, n, s, l) {
            if (!(n instanceof RoundRobinLoadBalancingConfig)) {
                return false;
            }
            if (!e.ok) {
                if (this.children.length === 0) {
                    this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker(e.error), e.error.details);
                }
                return true;
            }
            const u = Math.random() * e.value.length | 0;
            const h = d(e.value, u);
            this.resetSubchannelList();
            if (h.length === 0) {
                const e = `No addresses resolved. Resolution note: ${l}`;
                this.updateState(t.ConnectivityState.TRANSIENT_FAILURE, new r.UnavailablePicker({
                    details: e
                }), e);
            }
            c("Connect to endpoint list " + h.map(o.endpointToString));
            this.updatesPaused = true;
            this.children = h.map(e => new a.LeafLoadBalancer(e, this.childChannelControlHelper, s, l));
            for (const e of this.children) {
                e.startConnecting();
            }
            this.updatesPaused = false;
            this.calculateAndUpdateState();
            return true;
        }
        exitIdle() {}
        resetBackoff() {}
        destroy() {
            this.resetSubchannelList();
        }
        getTypeName() {
            return u;
        }
    }
    loadBalancerRoundRobin.RoundRobinLoadBalancer = RoundRobinLoadBalancer;
    function h() {
        (0, e.registerLoadBalancerType)(u, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig);
    }
    return loadBalancerRoundRobin;
}

var loadBalancerOutlierDetection = {};

var hasRequiredLoadBalancerOutlierDetection;

function requireLoadBalancerOutlierDetection() {
    if (hasRequiredLoadBalancerOutlierDetection) return loadBalancerOutlierDetection;
    hasRequiredLoadBalancerOutlierDetection = 1;
    var e;
    Object.defineProperty(loadBalancerOutlierDetection, "__esModule", {
        value: true
    });
    loadBalancerOutlierDetection.OutlierDetectionLoadBalancer = loadBalancerOutlierDetection.OutlierDetectionLoadBalancingConfig = void 0;
    loadBalancerOutlierDetection.setup = b;
    const t = connectivityState;
    const r = constants;
    const n = requireDuration();
    const s = requireExperimental();
    const o = requireLoadBalancer();
    const a = requireLoadBalancerChildHandler();
    const l = requirePicker();
    const c = subchannelAddress;
    const u = requireSubchannelInterface();
    const d = logging$8;
    const h = "outlier_detection";
    function p(e) {
        d.trace(r.LogVerbosity.DEBUG, h, e);
    }
    const g = "outlier_detection";
    const m = ((e = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && e !== void 0 ? e : "true") === "true";
    const _ = {
        stdev_factor: 1900,
        enforcement_percentage: 100,
        minimum_hosts: 5,
        request_volume: 100
    };
    const E = {
        threshold: 85,
        enforcement_percentage: 100,
        minimum_hosts: 5,
        request_volume: 50
    };
    function v(e, t, r, n) {
        if (t in e && e[t] !== undefined && typeof e[t] !== r) {
            const s = n ? `${n}.${t}` : t;
            throw new Error(`outlier detection config ${s} parse error: expected ${r}, got ${typeof e[t]}`);
        }
    }
    function y(e, t, r) {
        const s = t;
        if (t in e && e[t] !== undefined) {
            if (!(0, n.isDuration)(e[t])) {
                throw new Error(`outlier detection config ${s} parse error: expected Duration, got ${typeof e[t]}`);
            }
            if (!(e[t].seconds >= 0 && e[t].seconds <= 315576e6 && e[t].nanos >= 0 && e[t].nanos <= 999999999)) {
                throw new Error(`outlier detection config ${s} parse error: values out of range for non-negative Duaration`);
            }
        }
    }
    function S(e, t, r) {
        const n = r ? `${r}.${t}` : t;
        v(e, t, "number", r);
        if (t in e && e[t] !== undefined && !(e[t] >= 0 && e[t] <= 100)) {
            throw new Error(`outlier detection config ${n} parse error: value out of range for percentage (0-100)`);
        }
    }
    class OutlierDetectionLoadBalancingConfig {
        constructor(e, t, r, n, s, o, a) {
            this.childPolicy = a;
            if (a.getLoadBalancerName() === "pick_first") {
                throw new Error("outlier_detection LB policy cannot have a pick_first child policy");
            }
            this.intervalMs = e !== null && e !== void 0 ? e : 1e4;
            this.baseEjectionTimeMs = t !== null && t !== void 0 ? t : 3e4;
            this.maxEjectionTimeMs = r !== null && r !== void 0 ? r : 3e5;
            this.maxEjectionPercent = n !== null && n !== void 0 ? n : 10;
            this.successRateEjection = s ? Object.assign(Object.assign({}, _), s) : null;
            this.failurePercentageEjection = o ? Object.assign(Object.assign({}, E), o) : null;
        }
        getLoadBalancerName() {
            return g;
        }
        toJsonObject() {
            var e, t;
            return {
                outlier_detection: {
                    interval: (0, n.msToDuration)(this.intervalMs),
                    base_ejection_time: (0, n.msToDuration)(this.baseEjectionTimeMs),
                    max_ejection_time: (0, n.msToDuration)(this.maxEjectionTimeMs),
                    max_ejection_percent: this.maxEjectionPercent,
                    success_rate_ejection: (e = this.successRateEjection) !== null && e !== void 0 ? e : undefined,
                    failure_percentage_ejection: (t = this.failurePercentageEjection) !== null && t !== void 0 ? t : undefined,
                    child_policy: [ this.childPolicy.toJsonObject() ]
                }
            };
        }
        getIntervalMs() {
            return this.intervalMs;
        }
        getBaseEjectionTimeMs() {
            return this.baseEjectionTimeMs;
        }
        getMaxEjectionTimeMs() {
            return this.maxEjectionTimeMs;
        }
        getMaxEjectionPercent() {
            return this.maxEjectionPercent;
        }
        getSuccessRateEjectionConfig() {
            return this.successRateEjection;
        }
        getFailurePercentageEjectionConfig() {
            return this.failurePercentageEjection;
        }
        getChildPolicy() {
            return this.childPolicy;
        }
        static createFromJson(e) {
            var t;
            y(e, "interval");
            y(e, "base_ejection_time");
            y(e, "max_ejection_time");
            S(e, "max_ejection_percent");
            if ("success_rate_ejection" in e && e.success_rate_ejection !== undefined) {
                if (typeof e.success_rate_ejection !== "object") {
                    throw new Error("outlier detection config success_rate_ejection must be an object");
                }
                v(e.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection");
                S(e.success_rate_ejection, "enforcement_percentage", "success_rate_ejection");
                v(e.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection");
                v(e.success_rate_ejection, "request_volume", "number", "success_rate_ejection");
            }
            if ("failure_percentage_ejection" in e && e.failure_percentage_ejection !== undefined) {
                if (typeof e.failure_percentage_ejection !== "object") {
                    throw new Error("outlier detection config failure_percentage_ejection must be an object");
                }
                S(e.failure_percentage_ejection, "threshold", "failure_percentage_ejection");
                S(e.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection");
                v(e.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection");
                v(e.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection");
            }
            if (!("child_policy" in e) || !Array.isArray(e.child_policy)) {
                throw new Error("outlier detection config child_policy must be an array");
            }
            const r = (0, o.selectLbConfigFromList)(e.child_policy);
            if (!r) {
                throw new Error("outlier detection config child_policy: no valid recognized policy found");
            }
            return new OutlierDetectionLoadBalancingConfig(e.interval ? (0, n.durationToMs)(e.interval) : null, e.base_ejection_time ? (0, 
            n.durationToMs)(e.base_ejection_time) : null, e.max_ejection_time ? (0, n.durationToMs)(e.max_ejection_time) : null, (t = e.max_ejection_percent) !== null && t !== void 0 ? t : null, e.success_rate_ejection, e.failure_percentage_ejection, r);
        }
    }
    loadBalancerOutlierDetection.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig;
    class OutlierDetectionSubchannelWrapper extends u.BaseSubchannelWrapper {
        constructor(e, t) {
            super(e);
            this.mapEntry = t;
            this.refCount = 0;
        }
        ref() {
            this.child.ref();
            this.refCount += 1;
        }
        unref() {
            this.child.unref();
            this.refCount -= 1;
            if (this.refCount <= 0) {
                if (this.mapEntry) {
                    const e = this.mapEntry.subchannelWrappers.indexOf(this);
                    if (e >= 0) {
                        this.mapEntry.subchannelWrappers.splice(e, 1);
                    }
                }
            }
        }
        eject() {
            this.setHealthy(false);
        }
        uneject() {
            this.setHealthy(true);
        }
        getMapEntry() {
            return this.mapEntry;
        }
        getWrappedSubchannel() {
            return this.child;
        }
    }
    function A() {
        return {
            success: 0,
            failure: 0
        };
    }
    class CallCounter {
        constructor() {
            this.activeBucket = A();
            this.inactiveBucket = A();
        }
        addSuccess() {
            this.activeBucket.success += 1;
        }
        addFailure() {
            this.activeBucket.failure += 1;
        }
        switchBuckets() {
            this.inactiveBucket = this.activeBucket;
            this.activeBucket = A();
        }
        getLastSuccesses() {
            return this.inactiveBucket.success;
        }
        getLastFailures() {
            return this.inactiveBucket.failure;
        }
    }
    class OutlierDetectionPicker {
        constructor(e, t) {
            this.wrappedPicker = e;
            this.countCalls = t;
        }
        pick(e) {
            const t = this.wrappedPicker.pick(e);
            if (t.pickResultType === l.PickResultType.COMPLETE) {
                const e = t.subchannel;
                const n = e.getMapEntry();
                if (n) {
                    let s = t.onCallEnded;
                    if (this.countCalls) {
                        s = (e, s, o) => {
                            var a;
                            if (e === r.Status.OK) {
                                n.counter.addSuccess();
                            } else {
                                n.counter.addFailure();
                            }
                            (a = t.onCallEnded) === null || a === void 0 ? void 0 : a.call(t, e, s, o);
                        };
                    }
                    return Object.assign(Object.assign({}, t), {
                        subchannel: e.getWrappedSubchannel(),
                        onCallEnded: s
                    });
                } else {
                    return Object.assign(Object.assign({}, t), {
                        subchannel: e.getWrappedSubchannel()
                    });
                }
            } else {
                return t;
            }
        }
    }
    class OutlierDetectionLoadBalancer {
        constructor(e) {
            this.entryMap = new c.EndpointMap;
            this.latestConfig = null;
            this.timerStartTime = null;
            this.childBalancer = new a.ChildLoadBalancerHandler((0, s.createChildChannelControlHelper)(e, {
                createSubchannel: (t, r) => {
                    const n = e.createSubchannel(t, r);
                    const s = this.entryMap.getForSubchannelAddress(t);
                    const o = new OutlierDetectionSubchannelWrapper(n, s);
                    if ((s === null || s === void 0 ? void 0 : s.currentEjectionTimestamp) !== null) {
                        o.eject();
                    }
                    s === null || s === void 0 ? void 0 : s.subchannelWrappers.push(o);
                    return o;
                },
                updateState: (r, n, s) => {
                    if (r === t.ConnectivityState.READY) {
                        e.updateState(r, new OutlierDetectionPicker(n, this.isCountingEnabled()), s);
                    } else {
                        e.updateState(r, n, s);
                    }
                }
            }));
            this.ejectionTimer = setInterval(() => {}, 0);
            clearInterval(this.ejectionTimer);
        }
        isCountingEnabled() {
            return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null);
        }
        getCurrentEjectionPercent() {
            let e = 0;
            for (const t of this.entryMap.values()) {
                if (t.currentEjectionTimestamp !== null) {
                    e += 1;
                }
            }
            return e * 100 / this.entryMap.size;
        }
        runSuccessRateCheck(e) {
            if (!this.latestConfig) {
                return;
            }
            const t = this.latestConfig.getSuccessRateEjectionConfig();
            if (!t) {
                return;
            }
            p("Running success rate check");
            const r = t.request_volume;
            let n = 0;
            const s = [];
            for (const [e, t] of this.entryMap.entries()) {
                const o = t.counter.getLastSuccesses();
                const a = t.counter.getLastFailures();
                p("Stats for " + (0, c.endpointToString)(e) + ": successes=" + o + " failures=" + a + " targetRequestVolume=" + r);
                if (o + a >= r) {
                    n += 1;
                    s.push(o / (o + a));
                }
            }
            p("Found " + n + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + s + "]");
            if (n < t.minimum_hosts) {
                return;
            }
            const o = s.reduce((e, t) => e + t) / s.length;
            let a = 0;
            for (const e of s) {
                const t = e - o;
                a += t * t;
            }
            const l = a / s.length;
            const u = Math.sqrt(l);
            const d = o - u * (t.stdev_factor / 1e3);
            p("stdev=" + u + " ejectionThreshold=" + d);
            for (const [n, s] of this.entryMap.entries()) {
                if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
                    break;
                }
                const o = s.counter.getLastSuccesses();
                const a = s.counter.getLastFailures();
                if (o + a < r) {
                    continue;
                }
                const l = o / (o + a);
                p("Checking candidate " + n + " successRate=" + l);
                if (l < d) {
                    const r = Math.random() * 100;
                    p("Candidate " + n + " randomNumber=" + r + " enforcement_percentage=" + t.enforcement_percentage);
                    if (r < t.enforcement_percentage) {
                        p("Ejecting candidate " + n);
                        this.eject(s, e);
                    }
                }
            }
        }
        runFailurePercentageCheck(e) {
            if (!this.latestConfig) {
                return;
            }
            const t = this.latestConfig.getFailurePercentageEjectionConfig();
            if (!t) {
                return;
            }
            p("Running failure percentage check. threshold=" + t.threshold + " request volume threshold=" + t.request_volume);
            let r = 0;
            for (const e of this.entryMap.values()) {
                const n = e.counter.getLastSuccesses();
                const s = e.counter.getLastFailures();
                if (n + s >= t.request_volume) {
                    r += 1;
                }
            }
            if (r < t.minimum_hosts) {
                return;
            }
            for (const [r, n] of this.entryMap.entries()) {
                if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) {
                    break;
                }
                const s = n.counter.getLastSuccesses();
                const o = n.counter.getLastFailures();
                p("Candidate successes=" + s + " failures=" + o);
                if (s + o < t.request_volume) {
                    continue;
                }
                const a = o * 100 / (o + s);
                if (a > t.threshold) {
                    const s = Math.random() * 100;
                    p("Candidate " + r + " randomNumber=" + s + " enforcement_percentage=" + t.enforcement_percentage);
                    if (s < t.enforcement_percentage) {
                        p("Ejecting candidate " + r);
                        this.eject(n, e);
                    }
                }
            }
        }
        eject(e, t) {
            e.currentEjectionTimestamp = new Date;
            e.ejectionTimeMultiplier += 1;
            for (const t of e.subchannelWrappers) {
                t.eject();
            }
        }
        uneject(e) {
            e.currentEjectionTimestamp = null;
            for (const t of e.subchannelWrappers) {
                t.uneject();
            }
        }
        switchAllBuckets() {
            for (const e of this.entryMap.values()) {
                e.counter.switchBuckets();
            }
        }
        startTimer(e) {
            var t, r;
            this.ejectionTimer = setTimeout(() => this.runChecks(), e);
            (r = (t = this.ejectionTimer).unref) === null || r === void 0 ? void 0 : r.call(t);
        }
        runChecks() {
            const e = new Date;
            p("Ejection timer running");
            this.switchAllBuckets();
            if (!this.latestConfig) {
                return;
            }
            this.timerStartTime = e;
            this.startTimer(this.latestConfig.getIntervalMs());
            this.runSuccessRateCheck(e);
            this.runFailurePercentageCheck(e);
            for (const [e, t] of this.entryMap.entries()) {
                if (t.currentEjectionTimestamp === null) {
                    if (t.ejectionTimeMultiplier > 0) {
                        t.ejectionTimeMultiplier -= 1;
                    }
                } else {
                    const r = this.latestConfig.getBaseEjectionTimeMs();
                    const n = this.latestConfig.getMaxEjectionTimeMs();
                    const s = new Date(t.currentEjectionTimestamp.getTime());
                    s.setMilliseconds(s.getMilliseconds() + Math.min(r * t.ejectionTimeMultiplier, Math.max(r, n)));
                    if (s < new Date) {
                        p("Unejecting " + e);
                        this.uneject(t);
                    }
                }
            }
        }
        updateAddressList(e, t, r, n) {
            if (!(t instanceof OutlierDetectionLoadBalancingConfig)) {
                return false;
            }
            p("Received update with config: " + JSON.stringify(t.toJsonObject(), undefined, 2));
            if (e.ok) {
                for (const t of e.value) {
                    if (!this.entryMap.has(t)) {
                        p("Adding map entry for " + (0, c.endpointToString)(t));
                        this.entryMap.set(t, {
                            counter: new CallCounter,
                            currentEjectionTimestamp: null,
                            ejectionTimeMultiplier: 0,
                            subchannelWrappers: []
                        });
                    }
                }
                this.entryMap.deleteMissing(e.value);
            }
            const s = t.getChildPolicy();
            this.childBalancer.updateAddressList(e, s, r, n);
            if (t.getSuccessRateEjectionConfig() || t.getFailurePercentageEjectionConfig()) {
                if (this.timerStartTime) {
                    p("Previous timer existed. Replacing timer");
                    clearTimeout(this.ejectionTimer);
                    const e = t.getIntervalMs() - ((new Date).getTime() - this.timerStartTime.getTime());
                    this.startTimer(e);
                } else {
                    p("Starting new timer");
                    this.timerStartTime = new Date;
                    this.startTimer(t.getIntervalMs());
                    this.switchAllBuckets();
                }
            } else {
                p("Counting disabled. Cancelling timer.");
                this.timerStartTime = null;
                clearTimeout(this.ejectionTimer);
                for (const e of this.entryMap.values()) {
                    this.uneject(e);
                    e.ejectionTimeMultiplier = 0;
                }
            }
            this.latestConfig = t;
            return true;
        }
        exitIdle() {
            this.childBalancer.exitIdle();
        }
        resetBackoff() {
            this.childBalancer.resetBackoff();
        }
        destroy() {
            clearTimeout(this.ejectionTimer);
            this.childBalancer.destroy();
        }
        getTypeName() {
            return g;
        }
    }
    loadBalancerOutlierDetection.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer;
    function b() {
        if (m) {
            (0, s.registerLoadBalancerType)(g, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig);
        }
    }
    return loadBalancerOutlierDetection;
}

var loadBalancerWeightedRoundRobin = {};

var priorityQueue = {};

var hasRequiredPriorityQueue;

function requirePriorityQueue() {
    if (hasRequiredPriorityQueue) return priorityQueue;
    hasRequiredPriorityQueue = 1;
    Object.defineProperty(priorityQueue, "__esModule", {
        value: true
    });
    priorityQueue.PriorityQueue = void 0;
    const e = 0;
    const t = e => Math.floor(e / 2);
    const r = e => e * 2 + 1;
    const n = e => e * 2 + 2;
    class PriorityQueue {
        constructor(e = (e, t) => e > t) {
            this.comparator = e;
            this.heap = [];
        }
        size() {
            return this.heap.length;
        }
        isEmpty() {
            return this.size() == 0;
        }
        peek() {
            return this.heap[e];
        }
        push(...e) {
            e.forEach(e => {
                this.heap.push(e);
                this.siftUp();
            });
            return this.size();
        }
        pop() {
            const t = this.peek();
            const r = this.size() - 1;
            if (r > e) {
                this.swap(e, r);
            }
            this.heap.pop();
            this.siftDown();
            return t;
        }
        replace(t) {
            const r = this.peek();
            this.heap[e] = t;
            this.siftDown();
            return r;
        }
        greater(e, t) {
            return this.comparator(this.heap[e], this.heap[t]);
        }
        swap(e, t) {
            [this.heap[e], this.heap[t]] = [ this.heap[t], this.heap[e] ];
        }
        siftUp() {
            let r = this.size() - 1;
            while (r > e && this.greater(r, t(r))) {
                this.swap(r, t(r));
                r = t(r);
            }
        }
        siftDown() {
            let t = e;
            while (r(t) < this.size() && this.greater(r(t), t) || n(t) < this.size() && this.greater(n(t), t)) {
                let e = n(t) < this.size() && this.greater(n(t), r(t)) ? n(t) : r(t);
                this.swap(t, e);
                t = e;
            }
        }
    }
    priorityQueue.PriorityQueue = PriorityQueue;
    return priorityQueue;
}

var hasRequiredLoadBalancerWeightedRoundRobin;

function requireLoadBalancerWeightedRoundRobin() {
    if (hasRequiredLoadBalancerWeightedRoundRobin) return loadBalancerWeightedRoundRobin;
    hasRequiredLoadBalancerWeightedRoundRobin = 1;
    Object.defineProperty(loadBalancerWeightedRoundRobin, "__esModule", {
        value: true
    });
    loadBalancerWeightedRoundRobin.WeightedRoundRobinLoadBalancingConfig = void 0;
    loadBalancerWeightedRoundRobin.setup = A;
    const e = connectivityState;
    const t = constants;
    const r = requireDuration();
    const n = requireLoadBalancer();
    const s = requireLoadBalancerPickFirst();
    const o = logging$8;
    const a = requireOrca();
    const l = requirePicker();
    const c = requirePriorityQueue();
    const u = subchannelAddress;
    const d = "weighted_round_robin";
    function h(e) {
        o.trace(t.LogVerbosity.DEBUG, d, e);
    }
    const p = "weighted_round_robin";
    const g = 1e4;
    const m = 1e4;
    const _ = 3 * 6e4;
    const E = 1e3;
    const v = 1;
    function y(e, t, r) {
        if (t in e && e[t] !== undefined && typeof e[t] !== r) {
            throw new Error(`weighted round robin config ${t} parse error: expected ${r}, got ${typeof e[t]}`);
        }
    }
    function S(e, t) {
        if (t in e && e[t] !== undefined && e[t] !== null) {
            let n;
            if ((0, r.isDuration)(e[t])) {
                n = e[t];
            } else if ((0, r.isDurationMessage)(e[t])) {
                n = (0, r.durationMessageToDuration)(e[t]);
            } else if (typeof e[t] === "string") {
                const s = (0, r.parseDuration)(e[t]);
                if (!s) {
                    throw new Error(`weighted round robin config ${t}: failed to parse duration string ${e[t]}`);
                }
                n = s;
            } else {
                throw new Error(`weighted round robin config ${t}: expected duration, got ${typeof e[t]}`);
            }
            return (0, r.durationToMs)(n);
        }
        return null;
    }
    class WeightedRoundRobinLoadBalancingConfig {
        constructor(e, t, r, n, s, o) {
            this.enableOobLoadReport = e !== null && e !== void 0 ? e : false;
            this.oobLoadReportingPeriodMs = t !== null && t !== void 0 ? t : g;
            this.blackoutPeriodMs = r !== null && r !== void 0 ? r : m;
            this.weightExpirationPeriodMs = n !== null && n !== void 0 ? n : _;
            this.weightUpdatePeriodMs = Math.max(s !== null && s !== void 0 ? s : E, 100);
            this.errorUtilizationPenalty = o !== null && o !== void 0 ? o : v;
        }
        getLoadBalancerName() {
            return p;
        }
        toJsonObject() {
            return {
                enable_oob_load_report: this.enableOobLoadReport,
                oob_load_reporting_period: (0, r.durationToString)((0, r.msToDuration)(this.oobLoadReportingPeriodMs)),
                blackout_period: (0, r.durationToString)((0, r.msToDuration)(this.blackoutPeriodMs)),
                weight_expiration_period: (0, r.durationToString)((0, r.msToDuration)(this.weightExpirationPeriodMs)),
                weight_update_period: (0, r.durationToString)((0, r.msToDuration)(this.weightUpdatePeriodMs)),
                error_utilization_penalty: this.errorUtilizationPenalty
            };
        }
        static createFromJson(e) {
            y(e, "enable_oob_load_report", "boolean");
            y(e, "error_utilization_penalty", "number");
            if (e.error_utilization_penalty < 0) {
                throw new Error("weighted round robin config error_utilization_penalty < 0");
            }
            return new WeightedRoundRobinLoadBalancingConfig(e.enable_oob_load_report, S(e, "oob_load_reporting_period"), S(e, "blackout_period"), S(e, "weight_expiration_period"), S(e, "weight_update_period"), e.error_utilization_penalty);
        }
        getEnableOobLoadReport() {
            return this.enableOobLoadReport;
        }
        getOobLoadReportingPeriodMs() {
            return this.oobLoadReportingPeriodMs;
        }
        getBlackoutPeriodMs() {
            return this.blackoutPeriodMs;
        }
        getWeightExpirationPeriodMs() {
            return this.weightExpirationPeriodMs;
        }
        getWeightUpdatePeriodMs() {
            return this.weightUpdatePeriodMs;
        }
        getErrorUtilizationPenalty() {
            return this.errorUtilizationPenalty;
        }
    }
    loadBalancerWeightedRoundRobin.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig;
    class WeightedRoundRobinPicker {
        constructor(e, t) {
            this.metricsHandler = t;
            this.queue = new c.PriorityQueue((e, t) => e.deadline < t.deadline);
            const r = e.filter(e => e.weight > 0);
            let n;
            if (r.length < 2) {
                n = 1;
            } else {
                let e = 0;
                for (const {weight: t} of r) {
                    e += t;
                }
                n = e / r.length;
            }
            for (const t of e) {
                const e = t.weight > 0 ? 1 / t.weight : n;
                this.queue.push({
                    endpointName: t.endpointName,
                    picker: t.picker,
                    period: e,
                    deadline: Math.random() * e
                });
            }
        }
        pick(e) {
            const t = this.queue.pop();
            this.queue.push(Object.assign(Object.assign({}, t), {
                deadline: t.deadline + t.period
            }));
            const r = t.picker.pick(e);
            if (r.pickResultType === l.PickResultType.COMPLETE) {
                if (this.metricsHandler) {
                    return Object.assign(Object.assign({}, r), {
                        onCallEnded: (0, a.createMetricsReader)(e => this.metricsHandler(e, t.endpointName), r.onCallEnded)
                    });
                } else {
                    const e = r.subchannel;
                    return Object.assign(Object.assign({}, r), {
                        subchannel: e.getWrappedSubchannel()
                    });
                }
            } else {
                return r;
            }
        }
    }
    class WeightedRoundRobinLoadBalancer {
        constructor(t) {
            this.channelControlHelper = t;
            this.latestConfig = null;
            this.children = new Map;
            this.currentState = e.ConnectivityState.IDLE;
            this.updatesPaused = false;
            this.lastError = null;
            this.weightUpdateTimer = null;
        }
        countChildrenWithState(e) {
            let t = 0;
            for (const r of this.children.values()) {
                if (r.child.getConnectivityState() === e) {
                    t += 1;
                }
            }
            return t;
        }
        updateWeight(e, t) {
            var r, n;
            const s = t.rps_fractional;
            let o = t.application_utilization;
            if (o > 0 && s > 0) {
                o += t.eps / s * ((n = (r = this.latestConfig) === null || r === void 0 ? void 0 : r.getErrorUtilizationPenalty()) !== null && n !== void 0 ? n : 0);
            }
            const a = o === 0 ? 0 : s / o;
            if (a === 0) {
                return;
            }
            const l = new Date;
            if (e.nonEmptySince === null) {
                e.nonEmptySince = l;
            }
            e.lastUpdated = l;
            e.weight = a;
        }
        getWeight(e) {
            if (!this.latestConfig) {
                return 0;
            }
            const t = (new Date).getTime();
            if (t - e.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) {
                e.nonEmptySince = null;
                return 0;
            }
            const r = this.latestConfig.getBlackoutPeriodMs();
            if (r > 0 && (e.nonEmptySince === null || t - e.nonEmptySince.getTime() < r)) {
                return 0;
            }
            return e.weight;
        }
        calculateAndUpdateState() {
            if (this.updatesPaused || !this.latestConfig) {
                return;
            }
            if (this.countChildrenWithState(e.ConnectivityState.READY) > 0) {
                const t = [];
                for (const [r, n] of this.children) {
                    if (n.child.getConnectivityState() !== e.ConnectivityState.READY) {
                        continue;
                    }
                    t.push({
                        endpointName: r,
                        picker: n.child.getPicker(),
                        weight: this.getWeight(n)
                    });
                }
                h("Created picker with weights: " + t.map(e => e.endpointName + ":" + e.weight).join(","));
                let r;
                if (!this.latestConfig.getEnableOobLoadReport()) {
                    r = (e, t) => {
                        const r = this.children.get(t);
                        if (r) {
                            this.updateWeight(r, e);
                        }
                    };
                } else {
                    r = null;
                }
                this.updateState(e.ConnectivityState.READY, new WeightedRoundRobinPicker(t, r), null);
            } else if (this.countChildrenWithState(e.ConnectivityState.CONNECTING) > 0) {
                this.updateState(e.ConnectivityState.CONNECTING, new l.QueuePicker(this), null);
            } else if (this.countChildrenWithState(e.ConnectivityState.TRANSIENT_FAILURE) > 0) {
                const t = `weighted_round_robin: No connection established. Last error: ${this.lastError}`;
                this.updateState(e.ConnectivityState.TRANSIENT_FAILURE, new l.UnavailablePicker({
                    details: t
                }), t);
            } else {
                this.updateState(e.ConnectivityState.IDLE, new l.QueuePicker(this), null);
            }
            for (const {child: t} of this.children.values()) {
                if (t.getConnectivityState() === e.ConnectivityState.IDLE) {
                    t.exitIdle();
                }
            }
        }
        updateState(t, r, n) {
            h(e.ConnectivityState[this.currentState] + " -> " + e.ConnectivityState[t]);
            this.currentState = t;
            this.channelControlHelper.updateState(t, r, n);
        }
        updateAddressList(t, r, o, c) {
            var d, p;
            if (!(r instanceof WeightedRoundRobinLoadBalancingConfig)) {
                return false;
            }
            if (!t.ok) {
                if (this.children.size === 0) {
                    this.updateState(e.ConnectivityState.TRANSIENT_FAILURE, new l.UnavailablePicker(t.error), t.error.details);
                }
                return true;
            }
            if (t.value.length === 0) {
                const t = `No addresses resolved. Resolution note: ${c}`;
                this.updateState(e.ConnectivityState.TRANSIENT_FAILURE, new l.UnavailablePicker({
                    details: t
                }), t);
                return false;
            }
            h("Connect to endpoint list " + t.value.map(u.endpointToString));
            const g = new Date;
            const m = new Set;
            this.updatesPaused = true;
            this.latestConfig = r;
            for (const l of t.value) {
                const t = (0, u.endpointToString)(l);
                m.add(t);
                let d = this.children.get(t);
                if (!d) {
                    d = {
                        child: new s.LeafLoadBalancer(l, (0, n.createChildChannelControlHelper)(this.channelControlHelper, {
                            updateState: (t, r, n) => {
                                if (this.currentState === e.ConnectivityState.READY && t !== e.ConnectivityState.READY) {
                                    this.channelControlHelper.requestReresolution();
                                }
                                if (t === e.ConnectivityState.READY) {
                                    d.nonEmptySince = null;
                                }
                                if (n) {
                                    this.lastError = n;
                                }
                                this.calculateAndUpdateState();
                            },
                            createSubchannel: (e, t) => {
                                const r = this.channelControlHelper.createSubchannel(e, t);
                                if (d === null || d === void 0 ? void 0 : d.oobMetricsListener) {
                                    return new a.OrcaOobMetricsSubchannelWrapper(r, d.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs());
                                } else {
                                    return r;
                                }
                            }
                        }), o, c),
                        lastUpdated: g,
                        nonEmptySince: null,
                        weight: 0,
                        oobMetricsListener: null
                    };
                    this.children.set(t, d);
                }
                if (r.getEnableOobLoadReport()) {
                    d.oobMetricsListener = e => {
                        this.updateWeight(d, e);
                    };
                } else {
                    d.oobMetricsListener = null;
                }
            }
            for (const [e, t] of this.children) {
                if (m.has(e)) {
                    t.child.startConnecting();
                } else {
                    t.child.destroy();
                    this.children.delete(e);
                }
            }
            this.updatesPaused = false;
            this.calculateAndUpdateState();
            if (this.weightUpdateTimer) {
                clearInterval(this.weightUpdateTimer);
            }
            this.weightUpdateTimer = (p = (d = setInterval(() => {
                if (this.currentState === e.ConnectivityState.READY) {
                    this.calculateAndUpdateState();
                }
            }, r.getWeightUpdatePeriodMs())).unref) === null || p === void 0 ? void 0 : p.call(d);
            return true;
        }
        exitIdle() {}
        resetBackoff() {}
        destroy() {
            for (const e of this.children.values()) {
                e.child.destroy();
            }
            this.children.clear();
            if (this.weightUpdateTimer) {
                clearInterval(this.weightUpdateTimer);
            }
        }
        getTypeName() {
            return p;
        }
    }
    function A() {
        (0, n.registerLoadBalancerType)(p, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig);
    }
    return loadBalancerWeightedRoundRobin;
}

(function(e) {
    Object.defineProperty(e, "__esModule", {
        value: true
    });
    e.experimental = e.ServerMetricRecorder = e.ServerInterceptingCall = e.ResponderBuilder = e.ServerListenerBuilder = e.addAdminServicesToServer = e.getChannelzHandlers = e.getChannelzServiceDefinition = e.InterceptorConfigurationError = e.InterceptingCall = e.RequesterBuilder = e.ListenerBuilder = e.StatusBuilder = e.getClientChannel = e.ServerCredentials = e.Server = e.setLogVerbosity = e.setLogger = e.load = e.loadObject = e.CallCredentials = e.ChannelCredentials = e.waitForClientReady = e.closeClient = e.Channel = e.makeGenericClientConstructor = e.makeClientConstructor = e.loadPackageDefinition = e.Client = e.compressionAlgorithms = e.propagate = e.connectivityState = e.status = e.logVerbosity = e.Metadata = e.credentials = void 0;
    const t = callCredentials;
    Object.defineProperty(e, "CallCredentials", {
        enumerable: true,
        get: function() {
            return t.CallCredentials;
        }
    });
    const r = requireChannel();
    Object.defineProperty(e, "Channel", {
        enumerable: true,
        get: function() {
            return r.ChannelImplementation;
        }
    });
    const n = compressionAlgorithms;
    Object.defineProperty(e, "compressionAlgorithms", {
        enumerable: true,
        get: function() {
            return n.CompressionAlgorithms;
        }
    });
    const s = connectivityState;
    Object.defineProperty(e, "connectivityState", {
        enumerable: true,
        get: function() {
            return s.ConnectivityState;
        }
    });
    const o = channelCredentials;
    Object.defineProperty(e, "ChannelCredentials", {
        enumerable: true,
        get: function() {
            return o.ChannelCredentials;
        }
    });
    const a = requireClient();
    Object.defineProperty(e, "Client", {
        enumerable: true,
        get: function() {
            return a.Client;
        }
    });
    const l = constants;
    Object.defineProperty(e, "logVerbosity", {
        enumerable: true,
        get: function() {
            return l.LogVerbosity;
        }
    });
    Object.defineProperty(e, "status", {
        enumerable: true,
        get: function() {
            return l.Status;
        }
    });
    Object.defineProperty(e, "propagate", {
        enumerable: true,
        get: function() {
            return l.Propagate;
        }
    });
    const c = logging$8;
    const u = requireMakeClient();
    Object.defineProperty(e, "loadPackageDefinition", {
        enumerable: true,
        get: function() {
            return u.loadPackageDefinition;
        }
    });
    Object.defineProperty(e, "makeClientConstructor", {
        enumerable: true,
        get: function() {
            return u.makeClientConstructor;
        }
    });
    Object.defineProperty(e, "makeGenericClientConstructor", {
        enumerable: true,
        get: function() {
            return u.makeClientConstructor;
        }
    });
    const d = metadata;
    Object.defineProperty(e, "Metadata", {
        enumerable: true,
        get: function() {
            return d.Metadata;
        }
    });
    const h = server;
    Object.defineProperty(e, "Server", {
        enumerable: true,
        get: function() {
            return h.Server;
        }
    });
    const p = serverCredentials;
    Object.defineProperty(e, "ServerCredentials", {
        enumerable: true,
        get: function() {
            return p.ServerCredentials;
        }
    });
    const g = statusBuilder;
    Object.defineProperty(e, "StatusBuilder", {
        enumerable: true,
        get: function() {
            return g.StatusBuilder;
        }
    });
    e.credentials = {
        combineChannelCredentials: (e, ...t) => t.reduce((e, t) => e.compose(t), e),
        combineCallCredentials: (e, ...t) => t.reduce((e, t) => e.compose(t), e),
        createInsecure: o.ChannelCredentials.createInsecure,
        createSsl: o.ChannelCredentials.createSsl,
        createFromSecureContext: o.ChannelCredentials.createFromSecureContext,
        createFromMetadataGenerator: t.CallCredentials.createFromMetadataGenerator,
        createFromGoogleCredential: t.CallCredentials.createFromGoogleCredential,
        createEmpty: t.CallCredentials.createEmpty
    };
    const m = e => e.close();
    e.closeClient = m;
    const _ = (e, t, r) => e.waitForReady(t, r);
    e.waitForClientReady = _;
    const E = (e, t) => {
        throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    };
    e.loadObject = E;
    const v = (e, t, r) => {
        throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead");
    };
    e.load = v;
    const y = e => {
        c.setLogger(e);
    };
    e.setLogger = y;
    const S = e => {
        c.setLoggerVerbosity(e);
    };
    e.setLogVerbosity = S;
    const A = e => a.Client.prototype.getChannel.call(e);
    e.getClientChannel = A;
    var b = requireClientInterceptors();
    Object.defineProperty(e, "ListenerBuilder", {
        enumerable: true,
        get: function() {
            return b.ListenerBuilder;
        }
    });
    Object.defineProperty(e, "RequesterBuilder", {
        enumerable: true,
        get: function() {
            return b.RequesterBuilder;
        }
    });
    Object.defineProperty(e, "InterceptingCall", {
        enumerable: true,
        get: function() {
            return b.InterceptingCall;
        }
    });
    Object.defineProperty(e, "InterceptorConfigurationError", {
        enumerable: true,
        get: function() {
            return b.InterceptorConfigurationError;
        }
    });
    var C = requireChannelz();
    Object.defineProperty(e, "getChannelzServiceDefinition", {
        enumerable: true,
        get: function() {
            return C.getChannelzServiceDefinition;
        }
    });
    Object.defineProperty(e, "getChannelzHandlers", {
        enumerable: true,
        get: function() {
            return C.getChannelzHandlers;
        }
    });
    var w = requireAdmin();
    Object.defineProperty(e, "addAdminServicesToServer", {
        enumerable: true,
        get: function() {
            return w.addAdminServicesToServer;
        }
    });
    var I = requireServerInterceptors();
    Object.defineProperty(e, "ServerListenerBuilder", {
        enumerable: true,
        get: function() {
            return I.ServerListenerBuilder;
        }
    });
    Object.defineProperty(e, "ResponderBuilder", {
        enumerable: true,
        get: function() {
            return I.ResponderBuilder;
        }
    });
    Object.defineProperty(e, "ServerInterceptingCall", {
        enumerable: true,
        get: function() {
            return I.ServerInterceptingCall;
        }
    });
    var T = requireOrca();
    Object.defineProperty(e, "ServerMetricRecorder", {
        enumerable: true,
        get: function() {
            return T.ServerMetricRecorder;
        }
    });
    const R = requireExperimental();
    e.experimental = R;
    const k = requireResolverDns();
    const P = requireResolverUds();
    const $ = requireResolverIp();
    const O = requireLoadBalancerPickFirst();
    const B = requireLoadBalancerRoundRobin();
    const N = requireLoadBalancerOutlierDetection();
    const D = requireLoadBalancerWeightedRoundRobin();
    const L = requireChannelz();
    (() => {
        k.setup();
        P.setup();
        $.setup();
        O.setup();
        B.setup();
        N.setup();
        D.setup();
        L.setup();
    })();
})(src$3);

var src = {};

var util$1 = {};

Object.defineProperty(util$1, "__esModule", {
    value: true
});

util$1.addCommonProtos = util$1.loadProtosWithOptionsSync = util$1.loadProtosWithOptions = void 0;

const fs = require$$0__default$5.default;

const path = require$$0__default$4.default;

const Protobuf = protobufjs;

function addIncludePathResolver(e, t) {
    const r = e.resolvePath;
    e.resolvePath = (e, n) => {
        if (path.isAbsolute(n)) {
            return n;
        }
        for (const e of t) {
            const t = path.join(e, n);
            try {
                fs.accessSync(t, fs.constants.R_OK);
                return t;
            } catch (e) {
                continue;
            }
        }
        process.emitWarning(`${n} not found in any of the include paths ${t}`);
        return r(e, n);
    };
}

async function loadProtosWithOptions(e, t) {
    const r = new Protobuf.Root;
    t = t || {};
    if (!!t.includeDirs) {
        if (!Array.isArray(t.includeDirs)) {
            return Promise.reject(new Error("The includeDirs option must be an array"));
        }
        addIncludePathResolver(r, t.includeDirs);
    }
    const n = await r.load(e, t);
    n.resolveAll();
    return n;
}

util$1.loadProtosWithOptions = loadProtosWithOptions;

function loadProtosWithOptionsSync(e, t) {
    const r = new Protobuf.Root;
    t = t || {};
    if (!!t.includeDirs) {
        if (!Array.isArray(t.includeDirs)) {
            throw new Error("The includeDirs option must be an array");
        }
        addIncludePathResolver(r, t.includeDirs);
    }
    const n = r.loadSync(e, t);
    n.resolveAll();
    return n;
}

util$1.loadProtosWithOptionsSync = loadProtosWithOptionsSync;

function addCommonProtos() {
    const e = require$$3$1;
    const t = require$$4;
    const r = require$$5;
    const n = require$$6;
    Protobuf.common("api", e.nested.google.nested.protobuf.nested);
    Protobuf.common("descriptor", t.nested.google.nested.protobuf.nested);
    Protobuf.common("source_context", r.nested.google.nested.protobuf.nested);
    Protobuf.common("type", n.nested.google.nested.protobuf.nested);
}

util$1.addCommonProtos = addCommonProtos;

(function(e) {
    Object.defineProperty(e, "__esModule", {
        value: true
    });
    e.loadFileDescriptorSetFromObject = e.loadFileDescriptorSetFromBuffer = e.fromJSON = e.loadSync = e.load = e.IdempotencyLevel = e.isAnyExtension = e.Long = void 0;
    const t = lodash_camelcase;
    const r = protobufjs;
    const n = descriptorExports;
    const s = util$1;
    const o = umdExports;
    e.Long = o;
    function a(e) {
        return "@type" in e && typeof e["@type"] === "string";
    }
    e.isAnyExtension = a;
    var l;
    (function(e) {
        e["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN";
        e["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS";
        e["IDEMPOTENT"] = "IDEMPOTENT";
    })(l = e.IdempotencyLevel || (e.IdempotencyLevel = {}));
    const c = {
        longs: String,
        enums: String,
        bytes: String,
        defaults: true,
        oneofs: true,
        json: true
    };
    function u(e, t) {
        if (e === "") {
            return t;
        } else {
            return e + "." + t;
        }
    }
    function d(e) {
        return e instanceof r.Service || e instanceof r.Type || e instanceof r.Enum;
    }
    function h(e) {
        return e instanceof r.Namespace || e instanceof r.Root;
    }
    function p(e, t) {
        const r = u(t, e.name);
        if (d(e)) {
            return [ [ r, e ] ];
        } else {
            if (h(e) && typeof e.nested !== "undefined") {
                return Object.keys(e.nested).map(t => p(e.nested[t], r)).reduce((e, t) => e.concat(t), []);
            }
        }
        return [];
    }
    function g(e, t) {
        return function r(n) {
            return e.toObject(e.decode(n), t);
        };
    }
    function m(e) {
        return function t(r) {
            if (Array.isArray(r)) {
                throw new Error(`Failed to serialize message: expected object with ${e.name} structure, got array instead`);
            }
            const n = e.fromObject(r);
            return e.encode(n).finish();
        };
    }
    function _(e) {
        return (e || []).reduce((e, t) => {
            for (const [r, n] of Object.entries(t)) {
                switch (r) {
                  case "uninterpreted_option":
                    e.uninterpreted_option.push(t.uninterpreted_option);
                    break;

                  default:
                    e[r] = n;
                }
            }
            return e;
        }, {
            deprecated: false,
            idempotency_level: l.IDEMPOTENCY_UNKNOWN,
            uninterpreted_option: []
        });
    }
    function E(e, r, n, s) {
        const o = e.resolvedRequestType;
        const a = e.resolvedResponseType;
        return {
            path: "/" + r + "/" + e.name,
            requestStream: !!e.requestStream,
            responseStream: !!e.responseStream,
            requestSerialize: m(o),
            requestDeserialize: g(o, n),
            responseSerialize: m(a),
            responseDeserialize: g(a, n),
            originalName: t(e.name),
            requestType: y(o, s),
            responseType: y(a, s),
            options: _(e.parsedOptions)
        };
    }
    function v(e, t, r, n) {
        const s = {};
        for (const o of e.methodsArray) {
            s[o.name] = E(o, t, r, n);
        }
        return s;
    }
    function y(e, t) {
        const r = e.toDescriptor("proto3");
        return {
            format: "Protocol Buffer 3 DescriptorProto",
            type: r.$type.toObject(r, c),
            fileDescriptorProtos: t
        };
    }
    function S(e, t) {
        const r = e.toDescriptor("proto3");
        return {
            format: "Protocol Buffer 3 EnumDescriptorProto",
            type: r.$type.toObject(r, c),
            fileDescriptorProtos: t
        };
    }
    function A(e, t, n, s) {
        if (e instanceof r.Service) {
            return v(e, t, n, s);
        } else if (e instanceof r.Type) {
            return y(e, s);
        } else if (e instanceof r.Enum) {
            return S(e, s);
        } else {
            throw new Error("Type mismatch in reflection object handling");
        }
    }
    function b(e, t) {
        const r = {};
        e.resolveAll();
        const s = e.toDescriptor("proto3").file;
        const o = s.map(e => Buffer.from(n.FileDescriptorProto.encode(e).finish()));
        for (const [n, s] of p(e, "")) {
            r[n] = A(s, n, t, o);
        }
        return r;
    }
    function C(e, t) {
        t = t || {};
        const n = r.Root.fromDescriptor(e);
        n.resolveAll();
        return b(n, t);
    }
    function w(e, t) {
        return (0, s.loadProtosWithOptions)(e, t).then(e => b(e, t));
    }
    e.load = w;
    function I(e, t) {
        const r = (0, s.loadProtosWithOptionsSync)(e, t);
        return b(r, t);
    }
    e.loadSync = I;
    function T(e, t) {
        t = t || {};
        const n = r.Root.fromJSON(e);
        n.resolveAll();
        return b(n, t);
    }
    e.fromJSON = T;
    function R(e, t) {
        const r = n.FileDescriptorSet.decode(e);
        return C(r, t);
    }
    e.loadFileDescriptorSetFromBuffer = R;
    function k(e, t) {
        const r = n.FileDescriptorSet.fromObject(e);
        return C(r, t);
    }
    e.loadFileDescriptorSetFromObject = k;
    (0, s.addCommonProtos)();
})(src);

const max = "ffffffff-ffff-ffff-ffff-ffffffffffff";

const nil = "00000000-0000-0000-0000-000000000000";

const REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;

function validate(e) {
    return typeof e === "string" && REGEX.test(e);
}

function parse(e) {
    if (!validate(e)) {
        throw TypeError("Invalid UUID");
    }
    var t;
    var r = new Uint8Array(16);
    r[0] = (t = parseInt(e.slice(0, 8), 16)) >>> 24;
    r[1] = t >>> 16 & 255;
    r[2] = t >>> 8 & 255;
    r[3] = t & 255;
    r[4] = (t = parseInt(e.slice(9, 13), 16)) >>> 8;
    r[5] = t & 255;
    r[6] = (t = parseInt(e.slice(14, 18), 16)) >>> 8;
    r[7] = t & 255;
    r[8] = (t = parseInt(e.slice(19, 23), 16)) >>> 8;
    r[9] = t & 255;
    r[10] = (t = parseInt(e.slice(24, 36), 16)) / 1099511627776 & 255;
    r[11] = t / 4294967296 & 255;
    r[12] = t >>> 24 & 255;
    r[13] = t >>> 16 & 255;
    r[14] = t >>> 8 & 255;
    r[15] = t & 255;
    return r;
}

var byteToHex = [];

for (var i = 0; i < 256; ++i) {
    byteToHex.push((i + 256).toString(16).slice(1));
}

function unsafeStringify(e, t = 0) {
    return (byteToHex[e[t + 0]] + byteToHex[e[t + 1]] + byteToHex[e[t + 2]] + byteToHex[e[t + 3]] + "-" + byteToHex[e[t + 4]] + byteToHex[e[t + 5]] + "-" + byteToHex[e[t + 6]] + byteToHex[e[t + 7]] + "-" + byteToHex[e[t + 8]] + byteToHex[e[t + 9]] + "-" + byteToHex[e[t + 10]] + byteToHex[e[t + 11]] + byteToHex[e[t + 12]] + byteToHex[e[t + 13]] + byteToHex[e[t + 14]] + byteToHex[e[t + 15]]).toLowerCase();
}

function stringify(e, t = 0) {
    var r = unsafeStringify(e, t);
    if (!validate(r)) {
        throw TypeError("Stringified UUID is invalid");
    }
    return r;
}

var getRandomValues;

var rnds8 = new Uint8Array(16);

function rng() {
    if (!getRandomValues) {
        getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
        if (!getRandomValues) {
            throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
        }
    }
    return getRandomValues(rnds8);
}

var _nodeId;

var _clockseq;

var _lastMSecs = 0;

var _lastNSecs = 0;

function v1(e, t, r) {
    var n = t && r || 0;
    var s = t || new Array(16);
    e = e || {};
    var o = e.node;
    var a = e.clockseq;
    if (!e._v6) {
        if (!o) {
            o = _nodeId;
        }
        if (a == null) {
            a = _clockseq;
        }
    }
    if (o == null || a == null) {
        var l = e.random || (e.rng || rng)();
        if (o == null) {
            o = [ l[0], l[1], l[2], l[3], l[4], l[5] ];
            if (!_nodeId && !e._v6) {
                o[0] |= 1;
                _nodeId = o;
            }
        }
        if (a == null) {
            a = (l[6] << 8 | l[7]) & 16383;
            if (_clockseq === undefined && !e._v6) {
                _clockseq = a;
            }
        }
    }
    var c = e.msecs !== undefined ? e.msecs : Date.now();
    var u = e.nsecs !== undefined ? e.nsecs : _lastNSecs + 1;
    var d = c - _lastMSecs + (u - _lastNSecs) / 1e4;
    if (d < 0 && e.clockseq === undefined) {
        a = a + 1 & 16383;
    }
    if ((d < 0 || c > _lastMSecs) && e.nsecs === undefined) {
        u = 0;
    }
    if (u >= 1e4) {
        throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
    }
    _lastMSecs = c;
    _lastNSecs = u;
    _clockseq = a;
    c += 122192928e5;
    var h = ((c & 268435455) * 1e4 + u) % 4294967296;
    s[n++] = h >>> 24 & 255;
    s[n++] = h >>> 16 & 255;
    s[n++] = h >>> 8 & 255;
    s[n++] = h & 255;
    var p = c / 4294967296 * 1e4 & 268435455;
    s[n++] = p >>> 8 & 255;
    s[n++] = p & 255;
    s[n++] = p >>> 24 & 15 | 16;
    s[n++] = p >>> 16 & 255;
    s[n++] = a >>> 8 | 128;
    s[n++] = a & 255;
    for (var g = 0; g < 6; ++g) {
        s[n + g] = o[g];
    }
    return t || unsafeStringify(s);
}

function v1ToV6(e) {
    var t = typeof e === "string" ? parse(e) : e;
    var r = _v1ToV6(t);
    return typeof e === "string" ? unsafeStringify(r) : r;
}

function _v1ToV6(e, t = false) {
    return Uint8Array.of((e[6] & 15) << 4 | e[7] >> 4 & 15, (e[7] & 15) << 4 | (e[4] & 240) >> 4, (e[4] & 15) << 4 | (e[5] & 240) >> 4, (e[5] & 15) << 4 | (e[0] & 240) >> 4, (e[0] & 15) << 4 | (e[1] & 240) >> 4, (e[1] & 15) << 4 | (e[2] & 240) >> 4, 96 | e[2] & 15, e[3], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]);
}

function stringToBytes(e) {
    e = unescape(encodeURIComponent(e));
    var t = [];
    for (var r = 0; r < e.length; ++r) {
        t.push(e.charCodeAt(r));
    }
    return t;
}

var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";

var URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";

function v35(e, t, r) {
    function n(e, n, s, o) {
        var a;
        if (typeof e === "string") {
            e = stringToBytes(e);
        }
        if (typeof n === "string") {
            n = parse(n);
        }
        if (((a = n) === null || a === void 0 ? void 0 : a.length) !== 16) {
            throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
        }
        var l = new Uint8Array(16 + e.length);
        l.set(n);
        l.set(e, n.length);
        l = r(l);
        l[6] = l[6] & 15 | t;
        l[8] = l[8] & 63 | 128;
        if (s) {
            o = o || 0;
            for (var c = 0; c < 16; ++c) {
                s[o + c] = l[c];
            }
            return s;
        }
        return unsafeStringify(l);
    }
    try {
        n.name = e;
    } catch (e) {}
    n.DNS = DNS;
    n.URL = URL;
    return n;
}

function md5(e) {
    if (typeof e === "string") {
        var t = unescape(encodeURIComponent(e));
        e = new Uint8Array(t.length);
        for (var r = 0; r < t.length; ++r) {
            e[r] = t.charCodeAt(r);
        }
    }
    return md5ToHexEncodedArray(wordsToMd5(bytesToWords(e), e.length * 8));
}

function md5ToHexEncodedArray(e) {
    var t = [];
    var r = e.length * 32;
    var n = "0123456789abcdef";
    for (var s = 0; s < r; s += 8) {
        var o = e[s >> 5] >>> s % 32 & 255;
        var a = parseInt(n.charAt(o >>> 4 & 15) + n.charAt(o & 15), 16);
        t.push(a);
    }
    return t;
}

function getOutputLength(e) {
    return (e + 64 >>> 9 << 4) + 14 + 1;
}

function wordsToMd5(e, t) {
    e[t >> 5] |= 128 << t % 32;
    e[getOutputLength(t) - 1] = t;
    var r = 1732584193;
    var n = -271733879;
    var s = -1732584194;
    var o = 271733878;
    for (var a = 0; a < e.length; a += 16) {
        var l = r;
        var c = n;
        var u = s;
        var d = o;
        r = md5ff(r, n, s, o, e[a], 7, -680876936);
        o = md5ff(o, r, n, s, e[a + 1], 12, -389564586);
        s = md5ff(s, o, r, n, e[a + 2], 17, 606105819);
        n = md5ff(n, s, o, r, e[a + 3], 22, -1044525330);
        r = md5ff(r, n, s, o, e[a + 4], 7, -176418897);
        o = md5ff(o, r, n, s, e[a + 5], 12, 1200080426);
        s = md5ff(s, o, r, n, e[a + 6], 17, -1473231341);
        n = md5ff(n, s, o, r, e[a + 7], 22, -45705983);
        r = md5ff(r, n, s, o, e[a + 8], 7, 1770035416);
        o = md5ff(o, r, n, s, e[a + 9], 12, -1958414417);
        s = md5ff(s, o, r, n, e[a + 10], 17, -42063);
        n = md5ff(n, s, o, r, e[a + 11], 22, -1990404162);
        r = md5ff(r, n, s, o, e[a + 12], 7, 1804603682);
        o = md5ff(o, r, n, s, e[a + 13], 12, -40341101);
        s = md5ff(s, o, r, n, e[a + 14], 17, -1502002290);
        n = md5ff(n, s, o, r, e[a + 15], 22, 1236535329);
        r = md5gg(r, n, s, o, e[a + 1], 5, -165796510);
        o = md5gg(o, r, n, s, e[a + 6], 9, -1069501632);
        s = md5gg(s, o, r, n, e[a + 11], 14, 643717713);
        n = md5gg(n, s, o, r, e[a], 20, -373897302);
        r = md5gg(r, n, s, o, e[a + 5], 5, -701558691);
        o = md5gg(o, r, n, s, e[a + 10], 9, 38016083);
        s = md5gg(s, o, r, n, e[a + 15], 14, -660478335);
        n = md5gg(n, s, o, r, e[a + 4], 20, -405537848);
        r = md5gg(r, n, s, o, e[a + 9], 5, 568446438);
        o = md5gg(o, r, n, s, e[a + 14], 9, -1019803690);
        s = md5gg(s, o, r, n, e[a + 3], 14, -187363961);
        n = md5gg(n, s, o, r, e[a + 8], 20, 1163531501);
        r = md5gg(r, n, s, o, e[a + 13], 5, -1444681467);
        o = md5gg(o, r, n, s, e[a + 2], 9, -51403784);
        s = md5gg(s, o, r, n, e[a + 7], 14, 1735328473);
        n = md5gg(n, s, o, r, e[a + 12], 20, -1926607734);
        r = md5hh(r, n, s, o, e[a + 5], 4, -378558);
        o = md5hh(o, r, n, s, e[a + 8], 11, -2022574463);
        s = md5hh(s, o, r, n, e[a + 11], 16, 1839030562);
        n = md5hh(n, s, o, r, e[a + 14], 23, -35309556);
        r = md5hh(r, n, s, o, e[a + 1], 4, -1530992060);
        o = md5hh(o, r, n, s, e[a + 4], 11, 1272893353);
        s = md5hh(s, o, r, n, e[a + 7], 16, -155497632);
        n = md5hh(n, s, o, r, e[a + 10], 23, -1094730640);
        r = md5hh(r, n, s, o, e[a + 13], 4, 681279174);
        o = md5hh(o, r, n, s, e[a], 11, -358537222);
        s = md5hh(s, o, r, n, e[a + 3], 16, -722521979);
        n = md5hh(n, s, o, r, e[a + 6], 23, 76029189);
        r = md5hh(r, n, s, o, e[a + 9], 4, -640364487);
        o = md5hh(o, r, n, s, e[a + 12], 11, -421815835);
        s = md5hh(s, o, r, n, e[a + 15], 16, 530742520);
        n = md5hh(n, s, o, r, e[a + 2], 23, -995338651);
        r = md5ii(r, n, s, o, e[a], 6, -198630844);
        o = md5ii(o, r, n, s, e[a + 7], 10, 1126891415);
        s = md5ii(s, o, r, n, e[a + 14], 15, -1416354905);
        n = md5ii(n, s, o, r, e[a + 5], 21, -57434055);
        r = md5ii(r, n, s, o, e[a + 12], 6, 1700485571);
        o = md5ii(o, r, n, s, e[a + 3], 10, -1894986606);
        s = md5ii(s, o, r, n, e[a + 10], 15, -1051523);
        n = md5ii(n, s, o, r, e[a + 1], 21, -2054922799);
        r = md5ii(r, n, s, o, e[a + 8], 6, 1873313359);
        o = md5ii(o, r, n, s, e[a + 15], 10, -30611744);
        s = md5ii(s, o, r, n, e[a + 6], 15, -1560198380);
        n = md5ii(n, s, o, r, e[a + 13], 21, 1309151649);
        r = md5ii(r, n, s, o, e[a + 4], 6, -145523070);
        o = md5ii(o, r, n, s, e[a + 11], 10, -1120210379);
        s = md5ii(s, o, r, n, e[a + 2], 15, 718787259);
        n = md5ii(n, s, o, r, e[a + 9], 21, -343485551);
        r = safeAdd(r, l);
        n = safeAdd(n, c);
        s = safeAdd(s, u);
        o = safeAdd(o, d);
    }
    return [ r, n, s, o ];
}

function bytesToWords(e) {
    if (e.length === 0) {
        return [];
    }
    var t = e.length * 8;
    var r = new Uint32Array(getOutputLength(t));
    for (var n = 0; n < t; n += 8) {
        r[n >> 5] |= (e[n / 8] & 255) << n % 32;
    }
    return r;
}

function safeAdd(e, t) {
    var r = (e & 65535) + (t & 65535);
    var n = (e >> 16) + (t >> 16) + (r >> 16);
    return n << 16 | r & 65535;
}

function bitRotateLeft(e, t) {
    return e << t | e >>> 32 - t;
}

function md5cmn(e, t, r, n, s, o) {
    return safeAdd(bitRotateLeft(safeAdd(safeAdd(t, e), safeAdd(n, o)), s), r);
}

function md5ff(e, t, r, n, s, o, a) {
    return md5cmn(t & r | ~t & n, e, t, s, o, a);
}

function md5gg(e, t, r, n, s, o, a) {
    return md5cmn(t & n | r & ~n, e, t, s, o, a);
}

function md5hh(e, t, r, n, s, o, a) {
    return md5cmn(t ^ r ^ n, e, t, s, o, a);
}

function md5ii(e, t, r, n, s, o, a) {
    return md5cmn(r ^ (t | ~n), e, t, s, o, a);
}

var v3 = v35("v3", 48, md5);

const v3_default = v3;

var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);

const native = {
    randomUUID: randomUUID
};

function v4(e, t, r) {
    if (native.randomUUID && !t && !e) {
        return native.randomUUID();
    }
    e = e || {};
    var n = e.random || (e.rng || rng)();
    n[6] = n[6] & 15 | 64;
    n[8] = n[8] & 63 | 128;
    if (t) {
        r = r || 0;
        for (var s = 0; s < 16; ++s) {
            t[r + s] = n[s];
        }
        return t;
    }
    return unsafeStringify(n);
}

function f(e, t, r, n) {
    switch (e) {
      case 0:
        return t & r ^ ~t & n;

      case 1:
        return t ^ r ^ n;

      case 2:
        return t & r ^ t & n ^ r & n;

      case 3:
        return t ^ r ^ n;
    }
}

function ROTL(e, t) {
    return e << t | e >>> 32 - t;
}

function sha1(e) {
    var t = [ 1518500249, 1859775393, 2400959708, 3395469782 ];
    var r = [ 1732584193, 4023233417, 2562383102, 271733878, 3285377520 ];
    if (typeof e === "string") {
        var n = unescape(encodeURIComponent(e));
        e = [];
        for (var s = 0; s < n.length; ++s) {
            e.push(n.charCodeAt(s));
        }
    } else if (!Array.isArray(e)) {
        e = Array.prototype.slice.call(e);
    }
    e.push(128);
    var o = e.length / 4 + 2;
    var a = Math.ceil(o / 16);
    var l = new Array(a);
    for (var c = 0; c < a; ++c) {
        var u = new Uint32Array(16);
        for (var d = 0; d < 16; ++d) {
            u[d] = e[c * 64 + d * 4] << 24 | e[c * 64 + d * 4 + 1] << 16 | e[c * 64 + d * 4 + 2] << 8 | e[c * 64 + d * 4 + 3];
        }
        l[c] = u;
    }
    l[a - 1][14] = (e.length - 1) * 8 / Math.pow(2, 32);
    l[a - 1][14] = Math.floor(l[a - 1][14]);
    l[a - 1][15] = (e.length - 1) * 8 & 4294967295;
    for (var h = 0; h < a; ++h) {
        var p = new Uint32Array(80);
        for (var g = 0; g < 16; ++g) {
            p[g] = l[h][g];
        }
        for (var m = 16; m < 80; ++m) {
            p[m] = ROTL(p[m - 3] ^ p[m - 8] ^ p[m - 14] ^ p[m - 16], 1);
        }
        var _ = r[0];
        var E = r[1];
        var v = r[2];
        var y = r[3];
        var S = r[4];
        for (var A = 0; A < 80; ++A) {
            var b = Math.floor(A / 20);
            var C = ROTL(_, 5) + f(b, E, v, y) + S + t[b] + p[A] >>> 0;
            S = y;
            y = v;
            v = ROTL(E, 30) >>> 0;
            E = _;
            _ = C;
        }
        r[0] = r[0] + _ >>> 0;
        r[1] = r[1] + E >>> 0;
        r[2] = r[2] + v >>> 0;
        r[3] = r[3] + y >>> 0;
        r[4] = r[4] + S >>> 0;
    }
    return [ r[0] >> 24 & 255, r[0] >> 16 & 255, r[0] >> 8 & 255, r[0] & 255, r[1] >> 24 & 255, r[1] >> 16 & 255, r[1] >> 8 & 255, r[1] & 255, r[2] >> 24 & 255, r[2] >> 16 & 255, r[2] >> 8 & 255, r[2] & 255, r[3] >> 24 & 255, r[3] >> 16 & 255, r[3] >> 8 & 255, r[3] & 255, r[4] >> 24 & 255, r[4] >> 16 & 255, r[4] >> 8 & 255, r[4] & 255 ];
}

var v5 = v35("v5", 80, sha1);

const v5_default = v5;

function ownKeys(e, t) {
    var r = Object.keys(e);
    if (Object.getOwnPropertySymbols) {
        var n = Object.getOwnPropertySymbols(e);
        t && (n = n.filter(function(t) {
            return Object.getOwnPropertyDescriptor(e, t).enumerable;
        })), r.push.apply(r, n);
    }
    return r;
}

function _objectSpread(e) {
    for (var t = 1; t < arguments.length; t++) {
        var r = null != arguments[t] ? arguments[t] : {};
        t % 2 ? ownKeys(Object(r), true).forEach(function(t) {
            _defineProperty(e, t, r[t]);
        }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(r)) : ownKeys(Object(r)).forEach(function(t) {
            Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(r, t));
        });
    }
    return e;
}

function _defineProperty(e, t, r) {
    return (t = _toPropertyKey(t)) in e ? Object.defineProperty(e, t, {
        value: r,
        enumerable: true,
        configurable: true,
        writable: true
    }) : e[t] = r, e;
}

function _toPropertyKey(e) {
    var t = _toPrimitive(e, "string");
    return "symbol" == typeof t ? t : t + "";
}

function _toPrimitive(e, t) {
    if ("object" != typeof e || !e) return e;
    var r = e[Symbol.toPrimitive];
    if (void 0 !== r) {
        var n = r.call(e, t);
        if ("object" != typeof n) return n;
        throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return String(e);
}

function v6(e = {}, t, r = 0) {
    var n = v1(_objectSpread(_objectSpread({}, e), {}, {
        _v6: true
    }), new Uint8Array(16));
    n = v1ToV6(n);
    if (t) {
        for (var s = 0; s < 16; s++) {
            t[r + s] = n[s];
        }
        return t;
    }
    return unsafeStringify(n);
}

function v6ToV1(e) {
    var t = typeof e === "string" ? parse(e) : e;
    var r = _v6ToV1(t);
    return typeof e === "string" ? unsafeStringify(r) : r;
}

function _v6ToV1(e) {
    return Uint8Array.of((e[3] & 15) << 4 | e[4] >> 4 & 15, (e[4] & 15) << 4 | (e[5] & 240) >> 4, (e[5] & 15) << 4 | e[6] & 15, e[7], (e[1] & 15) << 4 | (e[2] & 240) >> 4, (e[2] & 15) << 4 | (e[3] & 240) >> 4, 16 | (e[0] & 240) >> 4, (e[0] & 15) << 4 | (e[1] & 240) >> 4, e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15]);
}

var _seqLow = null;

var _seqHigh = null;

var _msecs = 0;

function v7(e, t, r) {
    e = e || {};
    var n = t && r || 0;
    var s = t || new Uint8Array(16);
    var o = e.random || (e.rng || rng)();
    var a = e.msecs !== undefined ? e.msecs : Date.now();
    var l = e.seq !== undefined ? e.seq : null;
    var c = _seqHigh;
    var u = _seqLow;
    if (a > _msecs && e.msecs === undefined) {
        _msecs = a;
        if (l !== null) {
            c = null;
            u = null;
        }
    }
    if (l !== null) {
        if (l > 2147483647) {
            l = 2147483647;
        }
        c = l >>> 19 & 4095;
        u = l & 524287;
    }
    if (c === null || u === null) {
        c = o[6] & 127;
        c = c << 8 | o[7];
        u = o[8] & 63;
        u = u << 8 | o[9];
        u = u << 5 | o[10] >>> 3;
    }
    if (a + 1e4 > _msecs && l === null) {
        if (++u > 524287) {
            u = 0;
            if (++c > 4095) {
                c = 0;
                _msecs++;
            }
        }
    } else {
        _msecs = a;
    }
    _seqHigh = c;
    _seqLow = u;
    s[n++] = _msecs / 1099511627776 & 255;
    s[n++] = _msecs / 4294967296 & 255;
    s[n++] = _msecs / 16777216 & 255;
    s[n++] = _msecs / 65536 & 255;
    s[n++] = _msecs / 256 & 255;
    s[n++] = _msecs & 255;
    s[n++] = c >>> 4 & 15 | 112;
    s[n++] = c & 255;
    s[n++] = u >>> 13 & 63 | 128;
    s[n++] = u >>> 5 & 255;
    s[n++] = u << 3 & 255 | o[10] & 7;
    s[n++] = o[11];
    s[n++] = o[12];
    s[n++] = o[13];
    s[n++] = o[14];
    s[n++] = o[15];
    return t || unsafeStringify(s);
}

function version(e) {
    if (!validate(e)) {
        throw TypeError("Invalid UUID");
    }
    return parseInt(e.slice(14, 15), 16);
}

const esmBrowser = Object.freeze(Object.defineProperty({
    __proto__: null,
    MAX: max,
    NIL: nil,
    parse: parse,
    stringify: stringify,
    v1: v1,
    v1ToV6: v1ToV6,
    v3: v3_default,
    v4: v4,
    v5: v5_default,
    v6: v6,
    v6ToV1: v6ToV1,
    v7: v7,
    validate: validate,
    version: version
}, Symbol.toStringTag, {
    value: "Module"
}));

const require$$3 = _commonjsHelpers.getAugmentedNamespace(esmBrowser);

var grpc = src$3, protoLoader = src, uuid = require$$3.v4;

function withSession$1(e, t, r) {
    const n = uuid();
    const s = {
        method: "POST",
        path: "/session",
        hijack: true,
        headers: {
            Upgrade: "h2c",
            "X-Docker-Expose-Session-Uuid": n,
            "X-Docker-Expose-Session-Name": "testcontainers"
        },
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    e.modem.dial(s, function(e, s) {
        if (e) {
            return r(e, null, () => undefined);
        }
        const o = new grpc.Server;
        const a = grpc.ServerCredentials.createInsecure();
        const l = o.createConnectionInjector(a);
        l.injectConnection(s);
        const c = protoLoader.fromJSON({
            nested: {
                moby: {
                    nested: {
                        filesync: {
                            nested: {
                                v1: {
                                    options: {
                                        go_package: "auth"
                                    },
                                    nested: {
                                        Auth: {
                                            methods: {
                                                Credentials: {
                                                    requestType: "CredentialsRequest",
                                                    responseType: "CredentialsResponse"
                                                },
                                                FetchToken: {
                                                    requestType: "FetchTokenRequest",
                                                    responseType: "FetchTokenResponse"
                                                },
                                                GetTokenAuthority: {
                                                    requestType: "GetTokenAuthorityRequest",
                                                    responseType: "GetTokenAuthorityResponse"
                                                },
                                                VerifyTokenAuthority: {
                                                    requestType: "VerifyTokenAuthorityRequest",
                                                    responseType: "VerifyTokenAuthorityResponse"
                                                }
                                            }
                                        },
                                        CredentialsRequest: {
                                            fields: {
                                                Host: {
                                                    type: "string",
                                                    id: 1
                                                }
                                            }
                                        },
                                        CredentialsResponse: {
                                            fields: {
                                                Username: {
                                                    type: "string",
                                                    id: 1
                                                },
                                                Secret: {
                                                    type: "string",
                                                    id: 2
                                                }
                                            }
                                        },
                                        FetchTokenRequest: {
                                            fields: {
                                                ClientID: {
                                                    type: "string",
                                                    id: 1
                                                },
                                                Host: {
                                                    type: "string",
                                                    id: 2
                                                },
                                                Realm: {
                                                    type: "string",
                                                    id: 3
                                                },
                                                Service: {
                                                    type: "string",
                                                    id: 4
                                                },
                                                Scopes: {
                                                    rule: "repeated",
                                                    type: "string",
                                                    id: 5
                                                }
                                            }
                                        },
                                        FetchTokenResponse: {
                                            fields: {
                                                Token: {
                                                    type: "string",
                                                    id: 1
                                                },
                                                ExpiresIn: {
                                                    type: "int64",
                                                    id: 2
                                                },
                                                IssuedAt: {
                                                    type: "int64",
                                                    id: 3
                                                }
                                            }
                                        },
                                        GetTokenAuthorityRequest: {
                                            fields: {
                                                Host: {
                                                    type: "string",
                                                    id: 1
                                                },
                                                Salt: {
                                                    type: "bytes",
                                                    id: 2
                                                }
                                            }
                                        },
                                        GetTokenAuthorityResponse: {
                                            fields: {
                                                PublicKey: {
                                                    type: "bytes",
                                                    id: 1
                                                }
                                            }
                                        },
                                        VerifyTokenAuthorityRequest: {
                                            fields: {
                                                Host: {
                                                    type: "string",
                                                    id: 1
                                                },
                                                Payload: {
                                                    type: "bytes",
                                                    id: 2
                                                },
                                                Salt: {
                                                    type: "bytes",
                                                    id: 3
                                                }
                                            }
                                        },
                                        VerifyTokenAuthorityResponse: {
                                            fields: {
                                                Signed: {
                                                    type: "bytes",
                                                    id: 1
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        const u = grpc.loadPackageDefinition(c);
        o.addService(u.moby.filesync.v1.Auth.service, {
            Credentials({request: e}, r) {
                if (t) {
                    r(null, {
                        Username: t.username,
                        Secret: t.password
                    });
                } else {
                    r(null, {});
                }
            }
        });
        function d() {
            o.forceShutdown();
            s.end();
        }
        r(null, n, d);
    });
}

var session = withSession$1;

var EventEmitter = require$$0__default$8.default.EventEmitter, Modem = modem, Container = container, Image = image, Volume = volume, Network = network, Service = service$2, Plugin = plugin, Secret = secret, Config = config, Task = task, Node = node, Exec = exec, util = utilExports, withSession = session, extend = util.extend;

var Docker = function(e) {
    if (!(this instanceof Docker)) return new Docker(e);
    var t = _commonjsHelpers.commonjsGlobal.Promise;
    if (e && e.Promise) {
        t = e.Promise;
        if (Object.keys(e).length === 1) {
            e = undefined;
        }
    }
    if (e && e.modem) {
        this.modem = e.modem;
    } else {
        this.modem = new Modem(e);
    }
    this.modem.Promise = t;
};

Docker.prototype.createContainer = function(e, t) {
    var r = this;
    var n = {
        path: "/containers/create?",
        method: "POST",
        options: e,
        authconfig: e.authconfig,
        abortSignal: e.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            400: "bad parameter",
            404: "no such container",
            406: "impossible to attach",
            500: "server error"
        }
    };
    delete e.authconfig;
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(n, s) {
                if (n) {
                    return t(n);
                }
                e(r.getContainer(s.Id));
            });
        });
    } else {
        this.modem.dial(n, function(e, n) {
            if (e) return t(e, n);
            t(e, r.getContainer(n.Id));
        });
    }
};

Docker.prototype.createImage = function(e, t, r) {
    var n = this;
    if (!r && typeof t === "function") {
        r = t;
        t = e;
        e = t.authconfig || undefined;
    } else if (!r && !t) {
        t = e;
        e = t.authconfig;
    }
    var s = {
        path: "/images/create?",
        method: "POST",
        options: t,
        authconfig: e,
        abortSignal: t.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            r(e, t);
        });
    }
};

Docker.prototype.loadImage = function(e, t, r) {
    var n = this;
    if (!r && typeof t === "function") {
        r = t;
        t = null;
    }
    var s = {
        path: "/images/load?",
        method: "POST",
        options: t,
        file: e,
        abortSignal: t && t.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            r(e, t);
        });
    }
};

Docker.prototype.importImage = function(e, t, r) {
    var n = this;
    if (!r && typeof t === "function") {
        r = t;
        t = undefined;
    }
    if (!t) t = {};
    t.fromSrc = "-";
    var s = {
        path: "/images/create?",
        method: "POST",
        options: t,
        file: e,
        abortSignal: t.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            r(e, t);
        });
    }
};

Docker.prototype.checkAuth = function(e, t) {
    var r = this;
    var n = {
        path: "/auth",
        method: "POST",
        options: e,
        abortSignal: e.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            500: "server error"
        }
    };
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(n, function(e, r) {
            t(e, r);
        });
    }
};

Docker.prototype.buildImage = function(e, t, r) {
    var n = this;
    if (!r && typeof t === "function") {
        r = t;
        t = null;
    }
    var s = {
        path: "/build?",
        method: "POST",
        file: undefined,
        options: t,
        abortSignal: t && t.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (t) {
        if (t.registryconfig) {
            s.registryconfig = s.options.registryconfig;
            delete s.options.registryconfig;
        }
        if (t.authconfig) {
            s.authconfig = s.options.authconfig;
            delete s.options.authconfig;
        }
        if (t.cachefrom && Array.isArray(t.cachefrom)) {
            s.options.cachefrom = JSON.stringify(t.cachefrom);
        }
    }
    function o(t) {
        util.prepareBuildContext(e, e => {
            s.file = e;
            n.modem.dial(s, t);
        });
    }
    function a(e) {
        if (t?.version === "2") {
            withSession(n, s.authconfig, (t, r, n) => {
                if (t) {
                    return e(t);
                }
                s.options.session = r;
                o((t, r) => {
                    e(t, r);
                    if (r) {
                        r.on("end", n);
                    }
                });
            });
        } else {
            o(e);
        }
    }
    if (r === undefined) {
        return new n.modem.Promise(function(e, t) {
            a(function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        a(r);
    }
};

Docker.prototype.getContainer = function(e) {
    return new Container(this.modem, e);
};

Docker.prototype.getImage = function(e) {
    return new Image(this.modem, e);
};

Docker.prototype.getVolume = function(e) {
    return new Volume(this.modem, e);
};

Docker.prototype.getPlugin = function(e, t) {
    return new Plugin(this.modem, e, t);
};

Docker.prototype.getService = function(e) {
    return new Service(this.modem, e);
};

Docker.prototype.getTask = function(e) {
    return new Task(this.modem, e);
};

Docker.prototype.getNode = function(e) {
    return new Node(this.modem, e);
};

Docker.prototype.getNetwork = function(e) {
    return new Network(this.modem, e);
};

Docker.prototype.getSecret = function(e) {
    return new Secret(this.modem, e);
};

Docker.prototype.getConfig = function(e) {
    return new Config(this.modem, e);
};

Docker.prototype.getExec = function(e) {
    return new Exec(this.modem, e);
};

Docker.prototype.listContainers = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/containers/json?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.listImages = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/images/json?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.getImages = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/images/get?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            400: "bad parameter",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.listServices = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/services?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.listNodes = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/nodes?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            404: "no such node",
            500: "server error",
            503: "node is not part of a swarm"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.listTasks = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/tasks?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.createSecret = function(e, t) {
    var r = util.processArgs(e, t);
    var n = this;
    var s = {
        path: "/secrets/create?",
        method: "POST",
        options: r.opts,
        abortSignal: r.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            406: "server error or node is not part of a swarm",
            409: "name conflicts with an existing object",
            500: "server error"
        }
    };
    if (r.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, s) {
                if (r) {
                    return t(r);
                }
                e(n.getSecret(s.ID));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return r.callback(e, t);
            r.callback(e, n.getSecret(t.ID));
        });
    }
};

Docker.prototype.createConfig = function(e, t) {
    var r = util.processArgs(e, t);
    var n = this;
    var s = {
        path: "/configs/create?",
        method: "POST",
        options: r.opts,
        abortSignal: r.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            406: "server error or node is not part of a swarm",
            409: "name conflicts with an existing object",
            500: "server error"
        }
    };
    if (r.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, s) {
                if (r) {
                    return t(r);
                }
                e(n.getConfig(s.ID));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return r.callback(e, t);
            r.callback(e, n.getConfig(t.ID));
        });
    }
};

Docker.prototype.listSecrets = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/secrets?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.listConfigs = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/configs?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.createPlugin = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/plugins/create?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            204: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(s, o) {
                if (s) {
                    return t(s);
                }
                e(r.getPlugin(n.opts.name));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, r.getPlugin(n.opts.name));
        });
    }
};

Docker.prototype.listPlugins = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/plugins?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pruneImages = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/images/prune?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pruneBuilder = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/build/prune",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pruneContainers = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/containers/prune?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pruneVolumes = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/volumes/prune?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pruneNetworks = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/networks/prune?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.createVolume = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/volumes/create?",
        method: "POST",
        allowEmpty: true,
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(n, s) {
                if (n) {
                    return t(n);
                }
                e(r.getVolume(s.Name));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, r.getVolume(t.Name));
        });
    }
};

Docker.prototype.createService = function(e, t, r) {
    if (!r && typeof t === "function") {
        r = t;
        t = e;
        e = t.authconfig || undefined;
    } else if (!t && !r) {
        t = e;
    }
    var n = this;
    var s = {
        path: "/services/create",
        method: "POST",
        options: t,
        authconfig: e,
        abortSignal: t && t.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            500: "server error"
        }
    };
    if (r === undefined) {
        return new this.modem.Promise(function(e, t) {
            n.modem.dial(s, function(r, s) {
                if (r) {
                    return t(r);
                }
                e(n.getService(s.ID || s.Id));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return r(e, t);
            r(e, n.getService(t.ID || t.Id));
        });
    }
};

Docker.prototype.listVolumes = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/volumes?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.createNetwork = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/networks/create?",
        method: "POST",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            201: true,
            404: "driver not found",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(n, s) {
                if (n) {
                    return t(n);
                }
                e(r.getNetwork(s.Id));
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            if (e) return n.callback(e, t);
            n.callback(e, r.getNetwork(t.Id));
        });
    }
};

Docker.prototype.listNetworks = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/networks?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.searchImages = function(e, t) {
    var r = this;
    var n = {
        path: "/images/search?",
        method: "GET",
        options: e,
        authconfig: e.authconfig,
        abortSignal: e.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (t === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(n, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(n, function(e, r) {
            t(e, r);
        });
    }
};

Docker.prototype.info = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var e = {
        path: "/info",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(t, n) {
            r.modem.dial(e, function(e, r) {
                if (e) {
                    return n(e);
                }
                t(r);
            });
        });
    } else {
        this.modem.dial(e, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.version = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var e = {
        path: "/version",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(t, n) {
            r.modem.dial(e, function(e, r) {
                if (e) {
                    return n(e);
                }
                t(r);
            });
        });
    } else {
        this.modem.dial(e, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.ping = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/_ping",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.df = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/system/df",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.getEvents = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/events?",
        method: "GET",
        options: n.opts,
        abortSignal: n.opts.abortSignal,
        isStream: true,
        statusCodes: {
            200: true,
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.pull = function(e, t, r, n) {
    var s = util.processArgs(t, r);
    var o = util.parseRepositoryTag(e);
    s.opts.fromImage = o.repository;
    s.opts.tag = o.tag || "latest";
    var a = [ s.opts, s.callback ];
    if (n) {
        a = [ n, s.opts, s.callback ];
    }
    return this.createImage.apply(this, a);
};

Docker.prototype.pullAll = function(e, t, r, n) {
    var s = util.processArgs(t, r);
    var o = util.parseRepositoryTag(e);
    s.opts.fromImage = o.repository;
    var a = [ s.opts, s.callback ];
    if (n) {
        a = [ n, s.opts, s.callback ];
    }
    return this.createImage.apply(this, a);
};

Docker.prototype.run = function(e, t, r, n, s, o) {
    if (typeof arguments[arguments.length - 1] === "function") {
        return this.runCallback(e, t, r, n, s, o);
    } else {
        return this.runPromise(e, t, r, n, s);
    }
};

Docker.prototype.runCallback = function(e, t, r, n, s, o) {
    if (!o && typeof n === "function") {
        o = n;
        n = {};
        s = {};
    } else if (!o && typeof s === "function") {
        o = s;
        s = {};
    }
    var a = new EventEmitter;
    function l(e, t) {
        if (e) return o(e, null, t);
        a.emit("container", t);
        t.attach({
            stream: true,
            stdout: true,
            stderr: true
        }, function e(n, l) {
            if (n) return o(n, null, t);
            a.emit("stream", l);
            if (r) {
                if (r instanceof Array) {
                    l.on("end", function() {
                        try {
                            r[0].end();
                        } catch (e) {}
                        try {
                            r[1].end();
                        } catch (e) {}
                    });
                    t.modem.demuxStream(l, r[0], r[1]);
                } else {
                    l.setEncoding("utf8");
                    l.pipe(r, {
                        end: true
                    });
                }
            }
            t.start(s, function(e, r) {
                if (e) return o(e, r, t);
                a.emit("start", t);
                t.wait(function(e, r) {
                    a.emit("data", r);
                    o(e, r, t);
                });
            });
        });
    }
    var c = {
        Hostname: "",
        User: "",
        AttachStdin: false,
        AttachStdout: true,
        AttachStderr: true,
        Tty: true,
        OpenStdin: false,
        StdinOnce: false,
        Env: null,
        Cmd: t,
        Image: e,
        Volumes: {},
        VolumesFrom: []
    };
    extend(c, n);
    this.createContainer(c, l);
    return a;
};

Docker.prototype.runPromise = function(e, t, r, n, s) {
    var o = this;
    n = n || {};
    s = s || {};
    var a = {
        Hostname: "",
        User: "",
        AttachStdin: false,
        AttachStdout: true,
        AttachStderr: true,
        Tty: true,
        OpenStdin: false,
        StdinOnce: false,
        Env: null,
        Cmd: t,
        Image: e,
        Volumes: {},
        VolumesFrom: []
    };
    extend(a, n);
    var l;
    return new this.modem.Promise(function(e, t) {
        o.createContainer(a).then(function(e) {
            l = e;
            return e.attach({
                stream: true,
                stdout: true,
                stderr: true
            });
        }).then(function(e) {
            if (r) {
                if (r instanceof Array) {
                    e.on("end", function() {
                        try {
                            r[0].end();
                        } catch (e) {}
                        try {
                            r[1].end();
                        } catch (e) {}
                    });
                    l.modem.demuxStream(e, r[0], r[1]);
                } else {
                    e.setEncoding("utf8");
                    e.pipe(r, {
                        end: true
                    });
                }
            }
            return l.start(s);
        }).then(function(e) {
            return l.wait();
        }).then(function(t) {
            e([ t, l ]);
        }).catch(function(e) {
            t(e);
        });
    });
};

Docker.prototype.swarmInit = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/swarm/init",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            406: "node is already part of a Swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.swarmJoin = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/swarm/join",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            406: "node is already part of a Swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.swarmLeave = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/swarm/leave?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            406: "node is not part of a Swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.swarmUpdate = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/swarm/update?",
        method: "POST",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            400: "bad parameter",
            406: "node is already part of a Swarm"
        },
        options: n.opts
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.prototype.swarmInspect = function(e, t) {
    var r = this;
    var n = util.processArgs(e, t);
    var s = {
        path: "/swarm",
        method: "GET",
        abortSignal: n.opts.abortSignal,
        statusCodes: {
            200: true,
            406: "This node is not a swarm manager",
            500: "server error"
        }
    };
    if (n.callback === undefined) {
        return new this.modem.Promise(function(e, t) {
            r.modem.dial(s, function(r, n) {
                if (r) {
                    return t(r);
                }
                e(n);
            });
        });
    } else {
        this.modem.dial(s, function(e, t) {
            n.callback(e, t);
        });
    }
};

Docker.Container = Container;

Docker.Image = Image;

Docker.Volume = Volume;

Docker.Network = Network;

Docker.Service = Service;

Docker.Plugin = Plugin;

Docker.Secret = Secret;

Docker.Task = Task;

Docker.Node = Node;

Docker.Exec = Exec;

var docker = Docker;

const Dockerode = _commonjsHelpers.getDefaultExportFromCjs(docker);

exports.DockerContainerTTY = class DockerContainerTTY extends Provider.Provider {
    #e;
    #t;
    async init() {
        this.#e = await this.container.exec(As.As({
            AttachStderr: true,
            AttachStdin: true,
            AttachStdout: true,
            Cmd: this.cmd ? Array.isArray(this.cmd) ? this.cmd : [ this.cmd ] : undefined,
            Tty: true,
            ConsoleSize: [ this.initialConsoleSize?.rows ? this.initialConsoleSize.rows : 0, this.initialConsoleSize?.cols ? this.initialConsoleSize.cols : 0 ]
        }));
        this.#t = await this.#e.start({
            hijack: true
        });
    }
    async destroy() {
        if (!this.#t.destroyed) {
            this.#t.removeAllListeners();
            this.#t.destroy();
        }
    }
    get raw() {
        return this.#t;
    }
    get writable() {
        return this.#t;
    }
    get readable() {
        return this.#t;
    }
    async resize(e) {
        await this.#e.resize({
            w: e.cols,
            h: e.rows
        });
    }
    onData(e) {
        this.#t.on("data", e);
    }
    write(e) {
        this.#t.write(e, e => {
            if (e) this.log.warn("Write data to duplex stream error: %s", e.message);
        });
    }
};

tslib_es6.__decorate([ Inject.Inject("log"), tslib_es6.__metadata("design:type", Logger.Logger) ], exports.DockerContainerTTY.prototype, "log", void 0);

tslib_es6.__decorate([ Configurable.Configurable(ObjectSchemaValidation.DTO.InstanceOf(Dockerode.Container)), tslib_es6.__metadata("design:type", Dockerode.Container) ], exports.DockerContainerTTY.prototype, "container", void 0);

tslib_es6.__decorate([ Configurable.Configurable(ObjectSchemaValidation.DTO.Alternatives(ObjectSchemaValidation.DTO.String(), ObjectSchemaValidation.DTO.Array(ObjectSchemaValidation.DTO.String()).min(1))), tslib_es6.__metadata("design:type", Object) ], exports.DockerContainerTTY.prototype, "cmd", void 0);

tslib_es6.__decorate([ Configurable.Configurable(ContainerTTYConsoleSizeOptions.ContainerTTYConsoleSizeOptions.optional()), tslib_es6.__metadata("design:type", ContainerTTYConsoleSizeOptions.ContainerTTYConsoleSizeOptions) ], exports.DockerContainerTTY.prototype, "initialConsoleSize", void 0);

tslib_es6.__decorate([ Accept.Accept(ContainerTTYConsoleSizeOptions.ContainerTTYConsoleSizeOptions.required()), tslib_es6.__metadata("design:type", Function), tslib_es6.__metadata("design:paramtypes", [ ContainerTTYConsoleSizeOptions.ContainerTTYConsoleSizeOptions ]), tslib_es6.__metadata("design:returntype", Promise) ], exports.DockerContainerTTY.prototype, "resize", null);

exports.DockerContainerTTY = tslib_es6.__decorate([ Lifetime.Transient() ], exports.DockerContainerTTY);

exports.Dockerode = Dockerode;