var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __hasOwnProp = Object.prototype.hasOwnProperty, __esmMin = (c, L) => () => (c && (L = c(c = 0)), L), __commonJSMin = (c, L) => () => (L || c((L = { exports: {} }).exports, L), L.exports), __export = (L, R) => {
    let z = {};
    for (var B in L)
        __defProp(z, B, {
            get: L[B],
            enumerable: !0
        });
    return R && __defProp(z, Symbol.toStringTag, { value: "Module" }), z;
}, __copyProps = (B, V, H, U) => {
    if (V && typeof V == "object" || typeof V == "function")
        for (var W = __getOwnPropNames(V), G = 0, K = W.length, q; G < K; G++)
            q = W[G], !__hasOwnProp.call(B, q) && q !== H && __defProp(B, q, {
                get: ((c) => V[c]).bind(null, q),
                enumerable: !(U = __getOwnPropDesc(V, q)) || U.enumerable
            });
    return B;
}, __toCommonJS = (L) => __hasOwnProp.call(L, "module.exports") ? L["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: !0 }), L), tslib_es6_exports = /* @__PURE__ */ __export({
    __assign: () => __assign,
    __asyncDelegator: () => __asyncDelegator,
    __asyncGenerator: () => __asyncGenerator,
    __asyncValues: () => __asyncValues,
    __await: () => __await,
    __awaiter: () => __awaiter,
    __classPrivateFieldGet: () => __classPrivateFieldGet,
    __classPrivateFieldSet: () => __classPrivateFieldSet,
    __createBinding: () => __createBinding,
    __decorate: () => __decorate,
    __exportStar: () => __exportStar,
    __extends: () => __extends,
    __generator: () => __generator,
    __importDefault: () => __importDefault,
    __importStar: () => __importStar,
    __makeTemplateObject: () => __makeTemplateObject,
    __metadata: () => __metadata,
    __param: () => __param,
    __read: () => __read,
    __rest: () => __rest,
    __spread: () => __spread,
    __spreadArrays: () => __spreadArrays,
    __values: () => __values
});
function __extends(c, L) {
    extendStatics(c, L);
    function R() {
        this.constructor = c;
    }
    c.prototype = L === null ? Object.create(L) : (R.prototype = L.prototype, new R());
}
function __rest(c, L) {
    var R = {};
    for (var z in c)
        Object.prototype.hasOwnProperty.call(c, z) && L.indexOf(z) < 0 && (R[z] = c[z]);
    if (c != null && typeof Object.getOwnPropertySymbols == "function")
        for (var B = 0, z = Object.getOwnPropertySymbols(c); B < z.length; B++)
            L.indexOf(z[B]) < 0 && Object.prototype.propertyIsEnumerable.call(c, z[B]) && (R[z[B]] = c[z[B]]);
    return R;
}
function __decorate(c, L, R, z) {
    var B = arguments.length, V = B < 3 ? L : z === null ? z = Object.getOwnPropertyDescriptor(L, R) : z, H;
    if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
        V = Reflect.decorate(c, L, R, z);
    else
        for (var U = c.length - 1; U >= 0; U--)
            (H = c[U]) && (V = (B < 3 ? H(V) : B > 3 ? H(L, R, V) : H(L, R)) || V);
    return B > 3 && V && Object.defineProperty(L, R, V), V;
}
function __param(c, L) {
    return function (R, z) {
        L(R, z, c);
    };
}
function __metadata(c, L) {
    if (typeof Reflect == "object" && typeof Reflect.metadata == "function")
        return Reflect.metadata(c, L);
}
function __awaiter(c, L, R, z) {
    function B(c) {
        return c instanceof R ? c : new R(function (L) {
            L(c);
        });
    }
    return new (R ||= Promise)(function (R, V) {
        function H(c) {
            try {
                W(z.next(c));
            }
            catch (c) {
                V(c);
            }
        }
        function U(c) {
            try {
                W(z.throw(c));
            }
            catch (c) {
                V(c);
            }
        }
        function W(c) {
            c.done ? R(c.value) : B(c.value).then(H, U);
        }
        W((z = z.apply(c, L || [])).next());
    });
}
function __generator(c, L) {
    var R = {
        label: 0,
        sent: function () {
            if (V[0] & 1)
                throw V[1];
            return V[1];
        },
        trys: [],
        ops: []
    }, z, B, V, H;
    return H = {
        next: U(0),
        throw: U(1),
        return: U(2)
    }, typeof Symbol == "function" && (H[Symbol.iterator] = function () {
        return this;
    }), H;
    function U(c) {
        return function (L) {
            return W([c, L]);
        };
    }
    function W(H) {
        if (z)
            throw TypeError("Generator is already executing.");
        for (; R;)
            try {
                if (z = 1, B && (V = H[0] & 2 ? B.return : H[0] ? B.throw || ((V = B.return) && V.call(B), 0) : B.next) && !(V = V.call(B, H[1])).done)
                    return V;
                switch (B = 0, V && (H = [H[0] & 2, V.value]), H[0]) {
                    case 0:
                    case 1:
                        V = H;
                        break;
                    case 4: return R.label++, {
                        value: H[1],
                        done: !1
                    };
                    case 5:
                        R.label++, B = H[1], H = [0];
                        continue;
                    case 7:
                        H = R.ops.pop(), R.trys.pop();
                        continue;
                    default:
                        if ((V = R.trys, !(V = V.length > 0 && V[V.length - 1])) && (H[0] === 6 || H[0] === 2)) {
                            R = 0;
                            continue;
                        }
                        if (H[0] === 3 && (!V || H[1] > V[0] && H[1] < V[3])) {
                            R.label = H[1];
                            break;
                        }
                        if (H[0] === 6 && R.label < V[1]) {
                            R.label = V[1], V = H;
                            break;
                        }
                        if (V && R.label < V[2]) {
                            R.label = V[2], R.ops.push(H);
                            break;
                        }
                        V[2] && R.ops.pop(), R.trys.pop();
                        continue;
                }
                H = L.call(c, R);
            }
            catch (c) {
                H = [6, c], B = 0;
            }
            finally {
                z = V = 0;
            }
        if (H[0] & 5)
            throw H[1];
        return {
            value: H[0] ? H[1] : void 0,
            done: !0
        };
    }
}
function __createBinding(c, L, R, z) {
    z === void 0 && (z = R), c[z] = L[R];
}
function __exportStar(c, L) {
    for (var R in c)
        R !== "default" && !L.hasOwnProperty(R) && (L[R] = c[R]);
}
function __values(c) {
    var L = typeof Symbol == "function" && Symbol.iterator, R = L && c[L], z = 0;
    if (R)
        return R.call(c);
    if (c && typeof c.length == "number")
        return { next: function () {
                return c && z >= c.length && (c = void 0), {
                    value: c && c[z++],
                    done: !c
                };
            } };
    throw TypeError(L ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(c, L) {
    var R = typeof Symbol == "function" && c[Symbol.iterator];
    if (!R)
        return c;
    var z = R.call(c), B, V = [], H;
    try {
        for (; (L === void 0 || L-- > 0) && !(B = z.next()).done;)
            V.push(B.value);
    }
    catch (c) {
        H = { error: c };
    }
    finally {
        try {
            B && !B.done && (R = z.return) && R.call(z);
        }
        finally {
            if (H)
                throw H.error;
        }
    }
    return V;
}
function __spread() {
    for (var c = [], L = 0; L < arguments.length; L++)
        c = c.concat(__read(arguments[L]));
    return c;
}
function __spreadArrays() {
    for (var c = 0, L = 0, R = arguments.length; L < R; L++)
        c += arguments[L].length;
    for (var z = Array(c), B = 0, L = 0; L < R; L++)
        for (var V = arguments[L], H = 0, U = V.length; H < U; H++, B++)
            z[B] = V[H];
    return z;
}
function __await(c) {
    return this instanceof __await ? (this.v = c, this) : new __await(c);
}
function __asyncGenerator(c, L, R) {
    if (!Symbol.asyncIterator)
        throw TypeError("Symbol.asyncIterator is not defined.");
    var z = R.apply(c, L || []), B, V = [];
    return B = {}, H("next"), H("throw"), H("return"), B[Symbol.asyncIterator] = function () {
        return this;
    }, B;
    function H(c) {
        z[c] && (B[c] = function (L) {
            return new Promise(function (R, z) {
                V.push([
                    c,
                    L,
                    R,
                    z
                ]) > 1 || U(c, L);
            });
        });
    }
    function U(c, L) {
        try {
            W(z[c](L));
        }
        catch (c) {
            q(V[0][3], c);
        }
    }
    function W(c) {
        c.value instanceof __await ? Promise.resolve(c.value.v).then(G, K) : q(V[0][2], c);
    }
    function G(c) {
        U("next", c);
    }
    function K(c) {
        U("throw", c);
    }
    function q(c, L) {
        c(L), V.shift(), V.length && U(V[0][0], V[0][1]);
    }
}
function __asyncDelegator(c) {
    var L, R;
    return L = {}, z("next"), z("throw", function (c) {
        throw c;
    }), z("return"), L[Symbol.iterator] = function () {
        return this;
    }, L;
    function z(z, B) {
        L[z] = c[z] ? function (L) {
            return (R = !R) ? {
                value: __await(c[z](L)),
                done: z === "return"
            } : B ? B(L) : L;
        } : B;
    }
}
function __asyncValues(c) {
    if (!Symbol.asyncIterator)
        throw TypeError("Symbol.asyncIterator is not defined.");
    var L = c[Symbol.asyncIterator], R;
    return L ? L.call(c) : (c = typeof __values == "function" ? __values(c) : c[Symbol.iterator](), R = {}, z("next"), z("throw"), z("return"), R[Symbol.asyncIterator] = function () {
        return this;
    }, R);
    function z(L) {
        R[L] = c[L] && function (R) {
            return new Promise(function (z, V) {
                R = c[L](R), B(z, V, R.done, R.value);
            });
        };
    }
    function B(c, L, R, z) {
        Promise.resolve(z).then(function (L) {
            c({
                value: L,
                done: R
            });
        }, L);
    }
}
function __makeTemplateObject(c, L) {
    return Object.defineProperty ? Object.defineProperty(c, "raw", { value: L }) : c.raw = L, c;
}
function __importStar(c) {
    if (c && c.__esModule)
        return c;
    var L = {};
    if (c != null)
        for (var R in c)
            Object.hasOwnProperty.call(c, R) && (L[R] = c[R]);
    return L.default = c, L;
}
function __importDefault(c) {
    return c && c.__esModule ? c : { default: c };
}
function __classPrivateFieldGet(c, L) {
    if (!L.has(c))
        throw TypeError("attempted to get private field on non-instance");
    return L.get(c);
}
function __classPrivateFieldSet(c, L, R) {
    if (!L.has(c))
        throw TypeError("attempted to set private field on non-instance");
    return L.set(c, R), R;
}
var extendStatics, __assign, init_tslib_es6 = __esmMin((() => {
    extendStatics = function (c, L) {
        return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (c, L) {
            c.__proto__ = L;
        } || function (c, L) {
            for (var R in L)
                L.hasOwnProperty(R) && (c[R] = L[R]);
        }, extendStatics(c, L);
    }, __assign = function () {
        return __assign = Object.assign || function (c) {
            for (var L, R = 1, z = arguments.length; R < z; R++)
                for (var B in L = arguments[R], L)
                    Object.prototype.hasOwnProperty.call(L, B) && (c[B] = L[B]);
            return c;
        }, __assign.apply(this, arguments);
    };
})), require_constants = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.MAX_HASHABLE_LENGTH = c.INIT = c.KEY = c.DIGEST_LENGTH = c.BLOCK_SIZE = void 0, c.BLOCK_SIZE = 64, c.DIGEST_LENGTH = 32, c.KEY = new Uint32Array([
        1116352408,
        1899447441,
        3049323471,
        3921009573,
        961987163,
        1508970993,
        2453635748,
        2870763221,
        3624381080,
        310598401,
        607225278,
        1426881987,
        1925078388,
        2162078206,
        2614888103,
        3248222580,
        3835390401,
        4022224774,
        264347078,
        604807628,
        770255983,
        1249150122,
        1555081692,
        1996064986,
        2554220882,
        2821834349,
        2952996808,
        3210313671,
        3336571891,
        3584528711,
        113926993,
        338241895,
        666307205,
        773529912,
        1294757372,
        1396182291,
        1695183700,
        1986661051,
        2177026350,
        2456956037,
        2730485921,
        2820302411,
        3259730800,
        3345764771,
        3516065817,
        3600352804,
        4094571909,
        275423344,
        430227734,
        506948616,
        659060556,
        883997877,
        958139571,
        1322822218,
        1537002063,
        1747873779,
        1955562222,
        2024104815,
        2227730452,
        2361852424,
        2428436474,
        2756734187,
        3204031479,
        3329325298
    ]), c.INIT = [
        1779033703,
        3144134277,
        1013904242,
        2773480762,
        1359893119,
        2600822924,
        528734635,
        1541459225
    ], c.MAX_HASHABLE_LENGTH = 2 ** 53 - 1;
})), require_RawSha256 = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.RawSha256 = void 0;
    var L = require_constants();
    c.RawSha256 = function () {
        function c() {
            this.state = Int32Array.from(L.INIT), this.temp = new Int32Array(64), this.buffer = new Uint8Array(64), this.bufferLength = 0, this.bytesHashed = 0, this.finished = !1;
        }
        return c.prototype.update = function (c) {
            if (this.finished)
                throw Error("Attempted to update an already finished hash.");
            var R = 0, z = c.byteLength;
            if (this.bytesHashed += z, this.bytesHashed * 8 > L.MAX_HASHABLE_LENGTH)
                throw Error("Cannot hash more than 2^53 - 1 bits");
            for (; z > 0;)
                this.buffer[this.bufferLength++] = c[R++], z--, this.bufferLength === L.BLOCK_SIZE && (this.hashBuffer(), this.bufferLength = 0);
        }, c.prototype.digest = function () {
            if (!this.finished) {
                var c = this.bytesHashed * 8, R = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength), z = this.bufferLength;
                if (R.setUint8(this.bufferLength++, 128), z % L.BLOCK_SIZE >= L.BLOCK_SIZE - 8) {
                    for (var B = this.bufferLength; B < L.BLOCK_SIZE; B++)
                        R.setUint8(B, 0);
                    this.hashBuffer(), this.bufferLength = 0;
                }
                for (var B = this.bufferLength; B < L.BLOCK_SIZE - 8; B++)
                    R.setUint8(B, 0);
                R.setUint32(L.BLOCK_SIZE - 8, Math.floor(c / 4294967296), !0), R.setUint32(L.BLOCK_SIZE - 4, c), this.hashBuffer(), this.finished = !0;
            }
            for (var V = new Uint8Array(L.DIGEST_LENGTH), B = 0; B < 8; B++)
                V[B * 4] = this.state[B] >>> 24 & 255, V[B * 4 + 1] = this.state[B] >>> 16 & 255, V[B * 4 + 2] = this.state[B] >>> 8 & 255, V[B * 4 + 3] = this.state[B] >>> 0 & 255;
            return V;
        }, c.prototype.hashBuffer = function () {
            for (var c = this, R = c.buffer, z = c.state, B = z[0], V = z[1], H = z[2], U = z[3], W = z[4], G = z[5], K = z[6], q = z[7], J = 0; J < L.BLOCK_SIZE; J++) {
                if (J < 16)
                    this.temp[J] = (R[J * 4] & 255) << 24 | (R[J * 4 + 1] & 255) << 16 | (R[J * 4 + 2] & 255) << 8 | R[J * 4 + 3] & 255;
                else {
                    var Y = this.temp[J - 2], X = (Y >>> 17 | Y << 15) ^ (Y >>> 19 | Y << 13) ^ Y >>> 10;
                    Y = this.temp[J - 15];
                    var Z = (Y >>> 7 | Y << 25) ^ (Y >>> 18 | Y << 14) ^ Y >>> 3;
                    this.temp[J] = (X + this.temp[J - 7] | 0) + (Z + this.temp[J - 16] | 0);
                }
                var Q = (((W >>> 6 | W << 26) ^ (W >>> 11 | W << 21) ^ (W >>> 25 | W << 7)) + (W & G ^ ~W & K) | 0) + (q + (L.KEY[J] + this.temp[J] | 0) | 0) | 0, $ = ((B >>> 2 | B << 30) ^ (B >>> 13 | B << 19) ^ (B >>> 22 | B << 10)) + (B & V ^ B & H ^ V & H) | 0;
                q = K, K = G, G = W, W = U + Q | 0, U = H, H = V, V = B, B = Q + $ | 0;
            }
            z[0] += B, z[1] += V, z[2] += H, z[3] += U, z[4] += W, z[5] += G, z[6] += K, z[7] += q;
        }, c;
    }();
})), fromUtf8$1, toUtf8, init_pureJs = __esmMin((() => {
    fromUtf8$1 = (c) => {
        let L = [];
        for (let R = 0, z = c.length; R < z; R++) {
            let z = c.charCodeAt(R);
            if (z < 128)
                L.push(z);
            else if (z < 2048)
                L.push(z >> 6 | 192, z & 63 | 128);
            else if (R + 1 < c.length && (z & 64512) == 55296 && (c.charCodeAt(R + 1) & 64512) == 56320) {
                let B = 65536 + ((z & 1023) << 10) + (c.charCodeAt(++R) & 1023);
                L.push(B >> 18 | 240, B >> 12 & 63 | 128, B >> 6 & 63 | 128, B & 63 | 128);
            }
            else
                L.push(z >> 12 | 224, z >> 6 & 63 | 128, z & 63 | 128);
        }
        return Uint8Array.from(L);
    }, toUtf8 = (c) => {
        let L = "";
        for (let R = 0, z = c.length; R < z; R++) {
            let z = c[R];
            if (z < 128)
                L += String.fromCharCode(z);
            else if (192 <= z && z < 224) {
                let B = c[++R];
                L += String.fromCharCode((z & 31) << 6 | B & 63);
            }
            else if (240 <= z && z < 365) {
                let B = "%" + [
                    z,
                    c[++R],
                    c[++R],
                    c[++R]
                ].map((c) => c.toString(16)).join("%");
                L += decodeURIComponent(B);
            }
            else
                L += String.fromCharCode((z & 15) << 12 | (c[++R] & 63) << 6 | c[++R] & 63);
        }
        return L;
    };
}));
function fromUtf8$2(c) {
    return new TextEncoder().encode(c);
}
function toUtf8$1(c) {
    return new TextDecoder("utf-8").decode(c);
}
var init_whatwgEncodingApi = __esmMin((() => { })), dist_es_exports = /* @__PURE__ */ __export({
    fromUtf8: () => fromUtf8$3,
    toUtf8: () => toUtf8$2
}), fromUtf8$3, toUtf8$2, init_dist_es = __esmMin((() => {
    init_pureJs(), init_whatwgEncodingApi(), fromUtf8$3 = (c) => typeof TextEncoder == "function" ? fromUtf8$2(c) : fromUtf8$1(c), toUtf8$2 = (c) => typeof TextDecoder == "function" ? toUtf8$1(c) : toUtf8(c);
})), require_convertToBuffer = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.convertToBuffer = void 0;
    var L = (init_dist_es(), __toCommonJS(dist_es_exports)), R = typeof Buffer < "u" && Buffer.from ? function (c) {
        return Buffer.from(c, "utf8");
    } : L.fromUtf8;
    function z(c) {
        return c instanceof Uint8Array ? c : typeof c == "string" ? R(c) : ArrayBuffer.isView(c) ? new Uint8Array(c.buffer, c.byteOffset, c.byteLength / Uint8Array.BYTES_PER_ELEMENT) : new Uint8Array(c);
    }
    c.convertToBuffer = z;
})), require_isEmptyData = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.isEmptyData = void 0;
    function L(c) {
        return typeof c == "string" ? c.length === 0 : c.byteLength === 0;
    }
    c.isEmptyData = L;
})), require_numToUint8 = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.numToUint8 = void 0;
    function L(c) {
        return new Uint8Array([
            (c & 4278190080) >> 24,
            (c & 16711680) >> 16,
            (c & 65280) >> 8,
            c & 255
        ]);
    }
    c.numToUint8 = L;
})), require_uint32ArrayFrom = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.uint32ArrayFrom = void 0;
    function L(c) {
        if (!Uint32Array.from) {
            for (var L = new Uint32Array(c.length), R = 0; R < c.length;)
                L[R] = c[R], R += 1;
            return L;
        }
        return Uint32Array.from(c);
    }
    c.uint32ArrayFrom = L;
})), require_build$1 = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.uint32ArrayFrom = c.numToUint8 = c.isEmptyData = c.convertToBuffer = void 0;
    var L = require_convertToBuffer();
    Object.defineProperty(c, "convertToBuffer", {
        enumerable: !0,
        get: function () {
            return L.convertToBuffer;
        }
    });
    var R = require_isEmptyData();
    Object.defineProperty(c, "isEmptyData", {
        enumerable: !0,
        get: function () {
            return R.isEmptyData;
        }
    });
    var z = require_numToUint8();
    Object.defineProperty(c, "numToUint8", {
        enumerable: !0,
        get: function () {
            return z.numToUint8;
        }
    });
    var B = require_uint32ArrayFrom();
    Object.defineProperty(c, "uint32ArrayFrom", {
        enumerable: !0,
        get: function () {
            return B.uint32ArrayFrom;
        }
    });
})), require_jsSha256 = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), c.Sha256 = void 0;
    var L = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)), R = require_constants(), z = require_RawSha256(), B = require_build$1();
    c.Sha256 = function () {
        function c(c) {
            this.secret = c, this.hash = new z.RawSha256(), this.reset();
        }
        return c.prototype.update = function (c) {
            if (!((0, B.isEmptyData)(c) || this.error))
                try {
                    this.hash.update((0, B.convertToBuffer)(c));
                }
                catch (c) {
                    this.error = c;
                }
        }, c.prototype.digestSync = function () {
            if (this.error)
                throw this.error;
            return this.outer ? (this.outer.finished || this.outer.update(this.hash.digest()), this.outer.digest()) : this.hash.digest();
        }, c.prototype.digest = function () {
            return L.__awaiter(this, void 0, void 0, function () {
                return L.__generator(this, function (c) {
                    return [2, this.digestSync()];
                });
            });
        }, c.prototype.reset = function () {
            if (this.hash = new z.RawSha256(), this.secret) {
                this.outer = new z.RawSha256();
                var c = V(this.secret), L = new Uint8Array(R.BLOCK_SIZE);
                L.set(c);
                for (var B = 0; B < R.BLOCK_SIZE; B++)
                    c[B] ^= 54, L[B] ^= 92;
                this.hash.update(c), this.outer.update(L);
                for (var B = 0; B < c.byteLength; B++)
                    c[B] = 0;
            }
        }, c;
    }();
    function V(c) {
        var L = (0, B.convertToBuffer)(c);
        if (L.byteLength > R.BLOCK_SIZE) {
            var V = new z.RawSha256();
            V.update(L), L = V.digest();
        }
        var H = new Uint8Array(R.BLOCK_SIZE);
        return H.set(L), H;
    }
})), require_build = /* @__PURE__ */ __commonJSMin(((c) => {
    Object.defineProperty(c, "__esModule", { value: !0 }), (init_tslib_es6(), __toCommonJS(tslib_es6_exports)).__exportStar(require_jsSha256(), c);
})), import_build$1 = require_build();
function wrapDucklakeQuery(c, L) {
    let R = `ATTACH 'ducklake://${L}' AS dl;USE dl;\n`;
    return c.replace(/^(--.*\n)*/, (c) => c + R);
}
function getIntrospectionQuery(c) {
    let L = {
        descriptions: !0,
        specifiedByUrl: !1,
        directiveIsRepeatable: !1,
        schemaDescription: !1,
        inputValueDeprecation: !1,
        oneOf: !1,
        ...c
    }, R = L.descriptions ? "description" : "", z = L.specifiedByUrl ? "specifiedByURL" : "", B = L.directiveIsRepeatable ? "isRepeatable" : "", V = L.schemaDescription ? R : "";
    function H(c) {
        return L.inputValueDeprecation ? c : "";
    }
    let U = L.oneOf ? "isOneOf" : "";
    return `
    query IntrospectionQuery {
      __schema {
        ${V}
        queryType { name kind }
        mutationType { name kind }
        subscriptionType { name kind }
        types {
          ...FullType
        }
        directives {
          name
          ${R}
          ${B}
          locations
          args${H("(includeDeprecated: true)")} {
            ...InputValue
          }
        }
      }
    }

    fragment FullType on __Type {
      kind
      name
      ${R}
      ${z}
      ${U}
      fields(includeDeprecated: true) {
        name
        ${R}
        args${H("(includeDeprecated: true)")} {
          ...InputValue
        }
        type {
          ...TypeRef
        }
        isDeprecated
        deprecationReason
      }
      inputFields${H("(includeDeprecated: true)")} {
        ...InputValue
      }
      interfaces {
        ...TypeRef
      }
      enumValues(includeDeprecated: true) {
        name
        ${R}
        isDeprecated
        deprecationReason
      }
      possibleTypes {
        ...TypeRef
      }
    }

    fragment InputValue on __InputValue {
      name
      ${R}
      type { ...TypeRef }
      defaultValue
      ${H("isDeprecated")}
      ${H("deprecationReason")}
    }

    fragment TypeRef on __Type {
      kind
      name
      ofType {
        kind
        name
        ofType {
          kind
          name
          ofType {
            kind
            name
            ofType {
              kind
              name
              ofType {
                kind
                name
                ofType {
                  kind
                  name
                  ofType {
                    kind
                    name
                    ofType {
                      kind
                      name
                      ofType {
                        kind
                        name
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  `;
}
let ColumnIdentity = /* @__PURE__ */ function (c) {
    return c.ByDefault = "By Default", c.Always = "Always", c.No = "No", c;
}({});
getIntrospectionQuery();
function buildVisibleFieldList(c, L) {
    return c.filter((c) => c && c.ignored !== !0).map((c) => {
        switch (L) {
            case "postgresql": return `"${c?.field}"`;
            case "ms_sql_server": return `[${c?.field}]`;
            case "mysql": return `\`${c?.field}\``;
            case "snowflake": return `"${c?.field}"`;
            case "bigquery": return `\`${c?.field}\``;
            case "duckdb": return `"${c?.field}"`;
            default: throw Error("Unsupported database type: " + L);
        }
    });
}
function getLanguageByResourceType(c) {
    return {
        postgresql: "postgresql",
        mysql: "mysql",
        ms_sql_server: "mssql",
        snowflake: "snowflake",
        snowflake_oauth: "snowflake",
        bigquery: "bigquery",
        duckdb: "duckdb"
    }[c];
}
function buildParameters(c, L) {
    return c.map((c, R) => {
        switch (L) {
            case "postgresql": return `-- $${R + 1} ${c.field}`;
            case "mysql": return `-- :${c.field} (${c.datatype.split("(")[0]})`;
            case "ms_sql_server": return `-- @p${R + 1} ${c.field} (${c.datatype.split("(")[0]})`;
            case "snowflake": return `-- ? ${c.field} (${c.datatype.split("(")[0]})`;
            case "bigquery": return `-- @${c.field} (${c.datatype.split("(")[0]})`;
            case "duckdb": return `-- $${c.field} (${c.datatype.split("(")[0]})`;
        }
    }).join("\n");
}
function getPrimaryKeys(c) {
    let L = c?.filter((c) => c.isprimarykey)?.map((c) => c.field) ?? [];
    return L?.length === 0 && (L = c?.map((c) => c.field) ?? []), L ?? [];
}
function makeCountQuery(c, L, R = void 0, z) {
    let B = " WHERE ", V = " AND ", H = "", U = buildParameters([{
            field: "quicksearch",
            datatype: c === "bigquery" ? "string" : "text"
        }], c);
    U += "\n", R && (H = ` ${R} AND `);
    let W = buildVisibleFieldList(z, c);
    switch (c) {
        case "mysql":
            W.length > 0 ? H += ` (:quicksearch = '' OR CONCAT_WS(' ', ${W.join(", ")}) LIKE CONCAT('%', :quicksearch, '%'))` : H += " (:quicksearch = '' OR 1 = 1)", U += `SELECT COUNT(*) as count FROM ${L}`;
            break;
        case "postgresql":
            W.length > 0 ? H += `($1 = '' OR CONCAT(${W.join(", ")}) ILIKE '%' || $1 || '%')` : H += "($1 = '' OR 1 = 1)", U += `SELECT COUNT(*) as count FROM ${L}`;
            break;
        case "ms_sql_server":
            W.length > 0 ? H += `(@p1 = '' OR CONCAT(${W.join(", +")}) LIKE '%' + @p1 + '%')` : H += "(@p1 = '' OR 1 = 1)", U += `SELECT COUNT(*) as count FROM [${L}]`;
            break;
        case "snowflake":
            U = "", W.length > 0 ? (U += buildParameters([{
                    field: "quicksearch",
                    datatype: "text"
                }, {
                    field: "quicksearch",
                    datatype: "text"
                }], c), U += "\n", H += `(? = '' OR CONCAT(${W.join(", ")}) ILIKE '%' || ? || '%')`) : (U += buildParameters([{
                    field: "quicksearch",
                    datatype: "text"
                }], c), U += "\n", H += "(? = '' OR 1 = 1)"), U += `SELECT COUNT(*) as count FROM ${L}`;
            break;
        case "bigquery":
            if (W.length > 0) {
                let c = W.map((c) => {
                    let L = z.find((L) => L.field === c.slice(1, -1));
                    return L?.datatype === "JSON" || L?.datatype.startsWith("STRUCT") || L?.datatype.startsWith("ARRAY") ? `TO_JSON_STRING(${c})` : `${c}`;
                }).join(",");
                H += `(@quicksearch = '' OR REGEXP_CONTAINS(CONCAT(${c}), '(?i)' || @quicksearch))`;
            }
            else
                H += "(@quicksearch = '' OR 1 = 1)";
            U += `SELECT COUNT(*) as count FROM \`${L}\``;
            break;
        case "duckdb":
            W.length > 0 ? H += ` ($quicksearch = '' OR CONCAT(' ', ${W.join(", ")}) LIKE CONCAT('%', $quicksearch, '%'))` : H += " ($quicksearch = '' OR 1 = 1)", U += `SELECT COUNT(*) as count FROM ${L}`;
            break;
        default: throw Error("Unsupported database type:" + c);
    }
    return R ? U += `${B}${H}` : (U += c === "ms_sql_server" && !R ? B : V, U += H), !R && (c === "mysql" || c === "postgresql" || c === "snowflake" || c === "bigquery" || c === "duckdb") && (U = U.replace(`${V}`, B)), U;
}
function getCountInput(c, L, R, z) {
    if (c.type == "ducklake" && !c.ducklake || c.type == "database" && !c.resourcePath || !L || !R?.length)
        return;
    let B = c.type === "ducklake" ? "duckdb" : c.resourceType, V = makeCountQuery(B, L, z, R);
    return c.type === "ducklake" && (V = wrapDucklakeQuery(V, c.ducklake)), {
        runnable: {
            name: "AppDbExplorer",
            type: "inline",
            inlineScript: {
                content: V,
                language: getLanguageByResourceType(B),
                schema: {
                    $schema: "https://json-schema.org/draft/2020-12/schema",
                    properties: c.type === "database" ? { database: {
                            description: "Database name",
                            type: "object",
                            format: `resource-${B}`
                        } } : {},
                    required: ["database"],
                    type: "object"
                }
            }
        },
        fields: c.type === "database" ? { database: {
                type: "static",
                value: `$res:${c.resourcePath}`,
                fieldType: "object",
                format: `resource-${B}`
            } } : {},
        type: "runnable",
        fieldType: "object"
    };
}
function makeDeleteQuery(c, L, R) {
    let z = buildParameters(R === "snowflake" ? L.flatMap((c) => [c, c]) : L, R);
    switch (R) {
        case "postgresql": {
            let R = L.map((c, L) => `($${L + 1}::text::${c.datatype} IS NULL AND ${c.field} IS NULL OR ${c.field} = $${L + 1}::text::${c.datatype})`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R} RETURNING 1;`, z;
        }
        case "mysql": {
            let R = L.map((c) => `(:${c.field} IS NULL AND ${c.field} IS NULL OR ${c.field} = :${c.field})`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R}`, z;
        }
        case "ms_sql_server": {
            let R = L.map((c, L) => `(@p${L + 1} IS NULL AND ${c.field} IS NULL OR ${c.field} = @p${L + 1})`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R}`, z;
        }
        case "snowflake": {
            let R = L.map((c, L) => `(? = 'null' AND ${c.field} IS NULL OR ${c.field} = ?)`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R}`, z;
        }
        case "bigquery": {
            let R = L.map((c, L) => `(CAST(@${c.field} AS STRING) = 'null' AND ${c.field} IS NULL OR ${c.field} = @${c.field})`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R}`, z;
        }
        case "duckdb": {
            let R = L.map((c) => `($${c.field} IS NULL AND ${c.field} IS NULL OR ${c.field} = $${c.field})`).join("\n    AND ");
            return z += `\nDELETE FROM ${c} \nWHERE ${R}`, z;
        }
        default: throw Error("Unsupported database type");
    }
}
function getDeleteInput(c, L, R) {
    if (c.type == "ducklake" && !c.ducklake || c.type == "database" && !c.resourcePath || !L)
        return;
    let z = c.type === "ducklake" ? "duckdb" : c.resourceType, B = makeDeleteQuery(L, R, z);
    return c.type === "ducklake" && (B = wrapDucklakeQuery(B, c.ducklake)), {
        runnable: {
            name: "AppDbExplorer",
            type: "inline",
            inlineScript: {
                content: B,
                language: getLanguageByResourceType(z),
                schema: {
                    $schema: "https://json-schema.org/draft/2020-12/schema",
                    properties: {},
                    required: ["database"],
                    type: "object"
                }
            }
        },
        fields: c.type == "database" ? { database: {
                type: "static",
                value: `$res:${c.resourcePath}`,
                fieldType: "object",
                format: `resource-${z}`
            } } : {},
        type: "runnable",
        fieldType: "object"
    };
}
function formatInsertValues(c, L, R = 1) {
    switch (L) {
        case "mysql": return c.map((c) => `:${c.field}`).join(", ");
        case "postgresql": return c.map((c, L) => `$${R + L}::${c.datatype}`).join(", ");
        case "ms_sql_server": return c.map((c, L) => `@p${R + L}`).join(", ");
        case "snowflake": return c.map(() => "?").join(", ");
        case "bigquery": return c.map((c) => `@${c.field}`).join(", ");
        case "duckdb": return c.map((c) => `$${c.field}`).join(", ");
        default: throw Error("Unsupported database type");
    }
}
function formatColumnNames(c) {
    return c.map((c) => c.field).join(", ");
}
function getUserDefaultValue(c) {
    if (c.defaultValueNull)
        return "NULL";
    if (c.defaultUserValue)
        return typeof c.defaultUserValue == "string" ? `'${c.defaultUserValue}'` : c.defaultUserValue;
}
function formatDefaultValues(c) {
    return c.map((c) => {
        let L = getUserDefaultValue(c);
        return c.overrideDefaultValue === !0 ? L : L ?? c.defaultvalue;
    }).join(", ");
}
function shouldOmitColumnInInsert(c) {
    if (!c.hideInsert || c.isidentity === ColumnIdentity.Always)
        return !0;
    let L = c.defaultUserValue !== void 0 && c.defaultUserValue !== "" || c.defaultValueNull === !0, R = !!c.defaultvalue;
    if (c.isnullable === "NO") {
        if (!L && !R && c.isidentity === ColumnIdentity.No)
            throw Error(`Column ${c.field} is not nullable and has no default value`);
        return !L && !R ? c.isidentity !== ColumnIdentity.No : !L && R;
    }
    else if (c.isnullable === "YES")
        return !L;
    return !1;
}
function makeInsertQuery(c, L, R) {
    if (!c)
        throw Error("Table name is required");
    let z = L.filter((c) => !c.hideInsert && !(R == "postgresql" && c.defaultvalue?.startsWith("nextval("))), B = L.filter((c) => !shouldOmitColumnInInsert(c)), V = z.concat(B), H = buildParameters(z, R);
    H += "\n";
    let U = B.length > 0, W = formatColumnNames(V), G = formatInsertValues(z, R), K = formatDefaultValues(B);
    return H += `INSERT INTO ${c} (${W}) VALUES (${G}${U ? ", " : ""}${K})`, H;
}
function getInsertInput(c, L, R) {
    let z = c.type === "ducklake" ? "duckdb" : c.resourceType, B = makeInsertQuery(L, R, z);
    return c.type === "ducklake" && (B = wrapDucklakeQuery(B, c.ducklake)), {
        runnable: {
            name: "AppDbExplorer",
            type: "inline",
            inlineScript: {
                content: B,
                language: getLanguageByResourceType(z),
                schema: {
                    $schema: "https://json-schema.org/draft/2020-12/schema",
                    properties: {},
                    required: ["database"],
                    type: "object"
                }
            }
        },
        fields: c.type === "database" ? { database: {
                type: "static",
                value: `$res:${c.resourcePath}`,
                fieldType: "object",
                format: `resource-${z}`
            } } : {},
        type: "runnable",
        fieldType: "object"
    };
}
function makeSnowflakeSelectQuery(c, L, R, z) {
    let B = coerceToNumber(z?.limit) || 100, V = coerceToNumber(z?.offset) || 0, H = [{
            field: "quicksearch",
            datatype: "text"
        }], U = "";
    U += "\n";
    let W = buildVisibleFieldList(L, "snowflake"), G = W.join(", ");
    U += `SELECT ${G} FROM ${c}`;
    let K = ["LENGTH(?) = 0", ...W.map((c) => (H.push({
            field: "quicksearch",
            datatype: "text"
        }), `CONCAT(${c}) ILIKE CONCAT('%', ?, '%')`))].join(" OR ");
    R ? U += ` WHERE ${R} AND (${K})` : U += ` WHERE ${K}`;
    let q = L.map((c) => (H.push({
        field: "order_by",
        datatype: "text"
    }, {
        field: "is_desc",
        datatype: "boolean"
    }, {
        field: "order_by",
        datatype: "text"
    }, {
        field: "is_desc",
        datatype: "boolean"
    }), `CASE WHEN ? = '${c.field}' AND ? = FALSE THEN "${c.field}" END ASC,
		CASE WHEN ? = '${c.field}' AND ? = TRUE THEN "${c.field}" END DESC`));
    return U += ` ORDER BY ${q.join(",\n")}`, U += ` LIMIT ${B} OFFSET ${V}`, U = buildParameters(H, "snowflake") + "\n" + U, U;
}
function makeSelectQuery(c, L, R, z, B) {
    if (!c)
        throw Error("Table name is required");
    let V = "", H = buildParameters([
        {
            field: "limit",
            datatype: z === "bigquery" ? "integer" : "int"
        },
        {
            field: "offset",
            datatype: z === "bigquery" ? "integer" : "int"
        },
        {
            field: "quicksearch",
            datatype: z === "bigquery" ? "string" : "text"
        },
        {
            field: "order_by",
            datatype: z === "bigquery" ? "string" : "text"
        },
        {
            field: "is_desc",
            datatype: z === "bigquery" ? "bool" : "boolean"
        }
    ], z);
    H += "\n";
    let U = buildVisibleFieldList(L, z), W = U.join(", ");
    switch (z) {
        case "mysql": {
            let z = L.map((c) => `
CASE WHEN :order_by = '${c.field}' AND :is_desc IS false THEN \`${c.field}\` END,
CASE WHEN :order_by = '${c.field}' AND :is_desc IS true THEN \`${c.field}\` END DESC`).join(",\n");
            V = ` (:quicksearch = '' OR CONCAT_WS(' ', ${U.join(", ")}) LIKE CONCAT('%', :quicksearch, '%'))`, H += `SELECT ${W} FROM ${c}`, H += ` WHERE ${R ? `${R} AND` : ""} ${V}`, H += ` ORDER BY ${z}`, H += " LIMIT :limit OFFSET :offset";
            break;
        }
        case "postgresql": {
            let z = `
      ${L.map((c) => `
      (CASE WHEN $4 = '${c.field}' AND $5 IS false THEN "${c.field}"::text END),
      (CASE WHEN $4 = '${c.field}' AND $5 IS true THEN "${c.field}"::text END) DESC`).join(",\n")}`;
            V = `($3 = '' OR CONCAT(${U.join(", ")}) ILIKE '%' || $3 || '%')`, H += `SELECT ${U.map((c) => `${c}::text`).join(", ")} FROM ${c}\n`, H += ` WHERE ${R ? `${R} AND` : ""} ${V}\n`, H += ` ORDER BY ${z}\n`, H += " LIMIT $1::INT OFFSET $2::INT";
            break;
        }
        case "ms_sql_server":
            let z = L.map((c) => `
(CASE WHEN @p4 = '${c.field}' AND @p5 = 0 THEN ${c.field} END) ASC,
(CASE WHEN @p4 = '${c.field}' AND @p5 = 1 THEN ${c.field} END) DESC`).join(",\n");
            V = ` (@p3 = '' OR CONCAT(${W}) LIKE '%' + @p3 + '%')`, H += `SELECT ${W} FROM ${c}`, H += ` WHERE ${R ? `${R} AND` : ""} ${V}`, H += ` ORDER BY ${z}`, H += " OFFSET @p2 ROWS FETCH NEXT @p1 ROWS ONLY";
            break;
        case "snowflake": return makeSnowflakeSelectQuery(c, L, R, B);
        case "bigquery": {
            let z = L.map((c) => c.datatype === "JSON" || c.datatype.startsWith("STRUCT") || c.datatype.startsWith("ARRAY") || c.datatype === "GEOGRAPHY" ? `
(CASE WHEN @order_by = '${c.field}' AND @is_desc = false THEN TO_JSON_STRING(${c.field}) END) ASC,
(CASE WHEN @order_by = '${c.field}' AND @is_desc = true THEN TO_JSON_STRING(${c.field}) END) DESC` : `
(CASE WHEN @order_by = '${c.field}' AND @is_desc = false THEN ${c.field} END) ASC,
(CASE WHEN @order_by = '${c.field}' AND @is_desc = true THEN ${c.field} END) DESC`).join(",\n");
            V = ` (@quicksearch = '' OR REGEXP_CONTAINS(CONCAT(${U.map((c) => {
                let R = L.find((L) => L.field === c.slice(1, -1));
                return R?.datatype === "JSON" || R?.datatype.startsWith("STRUCT") || R?.datatype.startsWith("ARRAY") || R?.datatype === "GEOGRAPHY" ? `TO_JSON_STRING(${c})` : `CAST(${c} AS STRING)`;
            }).join(",")}), '(?i)' || @quicksearch))`, H += `SELECT ${W} FROM ${c}`, H += ` WHERE ${R ? `${R} AND` : ""} ${V}`, H += ` ORDER BY ${z}`, H += " LIMIT @limit OFFSET @offset";
            break;
        }
        case "duckdb": {
            let z = `
      ${L.map((c) => `
      (CASE WHEN $order_by = '${c.field}' AND $is_desc IS false THEN "${c.field}"::text END),
      (CASE WHEN $order_by = '${c.field}' AND $is_desc IS true THEN "${c.field}"::text END) DESC`).join(",\n")}`;
            V = `($quicksearch = '' OR CONCAT(${U.join(", ")}) ILIKE '%' || $quicksearch || '%')`, H += `SELECT ${U.join(", ")} FROM ${c}\n`, H += ` WHERE ${R ? `${R} AND` : ""} ${V}\n`, H += ` ORDER BY ${z}\n`, H += " LIMIT $limit::INT OFFSET $offset::INT";
            break;
        }
        default: throw Error("Unsupported database type");
    }
    return H;
}
function coerceToNumber(c) {
    return typeof c == "number" ? c : typeof c == "string" ? parseInt(c, 10) : 0;
}
function getSelectInput(c, L, R, z, B) {
    if (c.type == "ducklake" && !c.ducklake || c.type == "database" && !c.resourcePath || !L || !R?.length)
        return;
    let V = c.type === "ducklake" ? "duckdb" : c.resourceType, H = makeSelectQuery(L, R, z, V, B);
    return c.type === "ducklake" && (H = wrapDucklakeQuery(H, c.ducklake)), {
        runnable: {
            name: "AppDbExplorer",
            type: "inline",
            inlineScript: {
                content: H,
                language: getLanguageByResourceType(V)
            }
        },
        fields: c.type === "database" ? { database: {
                type: "static",
                value: `$res:${c.resourcePath}`,
                fieldType: "object",
                format: `resource-${V}`
            } } : {},
        type: "runnable",
        fieldType: "object",
        hideRefreshButton: !0
    };
}
function makeUpdateQuery(c, L, R, z) {
    let B = buildParameters([{
            field: "value_to_update",
            datatype: L.datatype
        }, ...z === "snowflake" ? R.flatMap((c) => [c, c]) : R], z);
    switch (B += "\n", z) {
        case "postgresql": {
            let z = R.map((c, L) => `($${L + 2}::text::${c.datatype} IS NULL AND ${c.field} IS NULL OR ${c.field} = $${L + 2}::text::${c.datatype})`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = $1::text::${L.datatype} \nWHERE ${z}	RETURNING 1`, B;
        }
        case "mysql": {
            let z = R.map((c) => `(:${c.field} IS NULL AND ${c.field} IS NULL OR ${c.field} = :${c.field})`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = :value_to_update \nWHERE ${z}`, B;
        }
        case "ms_sql_server": {
            let z = R.map((c, L) => `(@p${L + 2} IS NULL AND ${c.field} IS NULL OR ${c.field} = @p${L + 2})`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = @p1 \nWHERE ${z}`, B;
        }
        case "snowflake": {
            let z = R.map((c, L) => `(? = 'null' AND ${c.field} IS NULL OR ${c.field} = ?)`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = ? \nWHERE ${z}`, B;
        }
        case "bigquery": {
            let z = R.map((c, L) => `(CAST(@${c.field} AS STRING) = 'null' AND ${c.field} IS NULL OR ${c.field} = @${c.field})`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = @value_to_update \nWHERE ${z}`, B;
        }
        case "duckdb": {
            let z = R.map((c) => `($${c.field} IS NULL AND ${c.field} IS NULL OR ${c.field} = $${c.field})`).join("\n    AND ");
            return B += `\nUPDATE ${c} SET ${L.field} = $value_to_update \nWHERE ${z}`, B;
        }
        default: throw Error("Unsupported database type");
    }
}
function getUpdateInput(c, L, R, z) {
    if (c.type == "ducklake" && !c.ducklake || c.type == "database" && !c.resourcePath || !L)
        return;
    let B = c.type === "ducklake" ? "duckdb" : c.resourceType, V = makeUpdateQuery(L, R, z, B);
    return c.type === "ducklake" && (V = wrapDucklakeQuery(V, c.ducklake)), {
        runnable: {
            name: "AppDbExplorer",
            type: "inline",
            inlineScript: {
                content: V,
                language: getLanguageByResourceType(B),
                schema: {
                    $schema: "https://json-schema.org/draft/2020-12/schema",
                    properties: {},
                    required: ["database"],
                    type: "object"
                }
            }
        },
        fields: c.type === "database" ? { database: {
                type: "static",
                value: `$res:${c.resourcePath}`,
                fieldType: "object",
                format: `resource-${B}`
            } } : {},
        type: "runnable",
        fieldType: "object"
    };
}
function isRunnableByPath(c) {
    return c?.type == "runnableByPath" || c?.type == "path";
}
function isRunnableByName(c) {
    return c?.type == "runnableByName" || c?.type == "inline";
}
function findGridItemById(c, L, R) {
    for (let z of allItems(c, L))
        if (z.id === R)
            return z;
}
function allItems(c, L) {
    return L == null ? c ?? [] : [...c ?? [], ...Object.values(L).flat()];
}
function findGridItem(c, L) {
    return findGridItemById(c.grid, c.subgrids, L);
}
function collectOneOfFields(c, L) {
    return Object.fromEntries(Object.entries(c ?? {}).filter(([c, L]) => L.type == "evalv2").map(([c, R]) => {
        let z = R;
        if (!z.connections || z.connections.length !== 1)
            return [c, void 0];
        let B = z.connections[0], V = findGridItem(L, B.componentId);
        if (z.expr !== B.componentId + "." + B.id)
            return [c, void 0];
        if (V) {
            let L = V.data;
            if (L && (L.type === "resourceselectcomponent" || L.type === "selectcomponent" || L.type === "multiselectcomponent" || L.type === "multiselectcomponentv2")) {
                if ((L.type === "selectcomponent" || L.type === "multiselectcomponent" || L.type === "multiselectcomponentv2") && L.configuration?.create?.type === "static" && L.configuration?.create?.value === !0)
                    return [c, void 0];
                if (L.configuration?.items?.type === "static") {
                    let R = L.configuration.items.value;
                    if (R && Array.isArray(R))
                        return L.type === "multiselectcomponent" || L.type === "multiselectcomponentv2" ? [c, R] : [c, R.filter((c) => c && typeof c == "object" && "value" in c && c.value).map((c) => c.value)];
                }
            }
        }
        return [c, void 0];
    }).filter(([c, L]) => L !== void 0));
}
function filenameExprToRegex(c) {
    return `^${c.replaceAll("${file.name}", "<file_name>").slice(1, -1).replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replaceAll("<file_name>", "[^/]+")}$`;
}
function staticToRegex(c) {
    return `^${c.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
}
function checkIfExprIsString(c) {
    return /^(['"`])[^'"`]*\1$/g.test(c);
}
function checkIfEvalIsStringWithFilename(c) {
    return c.connections.length > 0 ? !1 : checkIfExprIsString(c.expr.replaceAll("${file.name}", ""));
}
function removeResourcePrefix(c) {
    return c.replace(/^\$res:/, "");
}
function computeWorkspaceS3FileInputPolicy() {
    return {
        allow_workspace_resource: !0,
        allowed_resources: [],
        allow_user_resources: !1,
        file_key_regex: ""
    };
}
function computeS3FileInputPolicy(c, L) {
    let R = c?.resource, z = c?.pathTemplate, B = !R || R.type === "static" && !R.value, V = R ? R.type === "static" ? R.value ? [removeResourcePrefix(R.value)] : [] : collectOneOfFields({ s3_resource: R }, L).s3_resource?.map((c) => removeResourcePrefix(c)) ?? [] : [], H = (R?.type === "evalv2" && R?.allowUserResources) ?? !1, U = "^.*$";
    return z && (z.type === "static" ? U = staticToRegex(z.value) : z.type === "evalv2" && checkIfEvalIsStringWithFilename(z) && (U = filenameExprToRegex(z.expr))), {
        allow_workspace_resource: B,
        allowed_resources: V,
        allow_user_resources: H,
        file_key_regex: U
    };
}
function isPartialS3Object(c) {
    return typeof c == "object" && !!c && typeof c.s3 == "string";
}
function computeS3FileViewerPolicy(c) {
    if (c.source.type === "uploadS3" && isPartialS3Object(c.source.value))
        return {
            s3_path: c.source.value.s3,
            storage: c.source.value.storage
        };
    if (c.source.type === "static" && typeof c.source.value == "string" && (c.sourceKind.type === "static" && c.sourceKind.value === "s3 (workspace storage)" || c.source.value.startsWith("s3://")))
        return {
            s3_path: c.source.value.replace("s3://", ""),
            storage: void 0
        };
}
function collectStaticFields(c) {
    return Object.fromEntries(Object.entries(c ?? {}).filter(([c, L]) => L.type == "static").map(([c, L]) => [c, L.value]));
}
async function hash(c) {
    try {
        let L = new TextEncoder().encode(c), R = await crypto.subtle.digest("SHA-256", L);
        return Array.from(new Uint8Array(R)).map((c) => c.toString(16).padStart(2, "0")).join("");
    }
    catch {
        let L = new import_build$1.Sha256();
        return L.update(c ?? ""), Array.from(await L.digest()).map((c) => c.toString(16).padStart(2, "0")).join("");
    }
}
var import_build = require_build();
async function updatePolicy(c, L) {
    let R = allItems(c.grid, c.subgrids), z = await Promise.all(R.flatMap((L) => {
        let R = L.data, z = [{
                input: R.componentInput,
                id: L.id
            }];
        if (R.type === "tablecomponent" && z.push(...R.actionButtons.map((c) => ({
            input: c.componentInput,
            id: c.id
        }))), (R.type === "aggridcomponent" || R.type === "aggridcomponentee" || R.type === "dbexplorercomponent" || R.type === "aggridinfinitecomponent" || R.type === "aggridinfinitecomponentee") && Array.isArray(R.actions) && z.push(...R.actions.map((c) => ({
            input: c.componentInput,
            id: c.id
        }))), R.type === "menucomponent" && z.push(...R.menuItems.map((c) => ({
            input: c.componentInput,
            id: c.id
        }))), R.type === "dbexplorercomponent") {
            let c = [], B = R.configuration, V = B?.type?.selected, H = B?.type?.configuration?.[V];
            if (H && V) {
                let { table: c, resource: U, ducklake: W } = H, G = c.value, K = U?.value.split("$res:")[1] ?? (W?.value)?.split("ducklake://")[1], q = R.configuration.columnDefs.value, J = R.configuration.whereClause.value;
                if (G && K && q) {
                    let c = W ? {
                        type: "ducklake",
                        ducklake: K
                    } : {
                        type: "database",
                        resourcePath: K,
                        resourceType: V
                    };
                    z.push({
                        input: getSelectInput(c, G, q, J),
                        id: L.id
                    }), z.push({
                        input: getCountInput(c, G, q, J),
                        id: L.id + "_count"
                    }), z.push({
                        input: getInsertInput(c, G, q),
                        id: L.id + "_insert"
                    });
                    let R = getPrimaryKeys(q), H = q?.filter((c) => R.includes(c.field));
                    z.push({
                        input: getDeleteInput(c, G, H),
                        id: L.id + "_delete"
                    }), q.filter((c) => c.editable || B.allEditable.value).forEach((R) => {
                        z.push({
                            input: getUpdateInput(c, G, R, H),
                            id: L.id + "_update"
                        });
                    });
                }
            }
            z.push(...c);
        }
        return z.filter((c) => c.input).map(async (L) => {
            if (L.input?.type == "runnable")
                return await processRunnable$1(L.id, L.input.runnable, L.input.fields, c);
        });
    }).concat(Object.values(c.hiddenInlineScripts ?? {}).map(async (L, R) => await processRunnable$1("bg_" + R, L, L.fields, c)))), B = Object.fromEntries(z.filter(Boolean)), V = R.filter((c) => c.data.type === "s3fileinputcomponent").map((L) => {
        let R = L.data.configuration;
        return computeS3FileInputPolicy(R?.type?.configuration?.s3, c);
    }).filter(Boolean);
    R.findIndex((c) => {
        let L = c.data;
        if (L.type === "schemaformcomponent" || L.type === "formbuttoncomponent" || L.type === "formcomponent") {
            let c = L.type === "schemaformcomponent" ? L.componentInput?.value?.properties : isRunnableByName(L.componentInput?.runnable) ? L.componentInput?.runnable?.inlineScript?.schema?.properties : L.componentInput?.runnable?.schema?.properties;
            return Object.values(c ?? {}).findIndex((c) => c?.type === "object" && c?.format === "resource-s3_object" || c?.type === "array" && (c?.items?.resourceType === "s3object" || c?.items?.resourceType === "s3_object")) !== -1;
        }
        else
            return !1;
    }) !== -1 && V.push(computeWorkspaceS3FileInputPolicy());
    let H = R.filter((c) => c.data.type === "imagecomponent" || c.data.type === "pdfcomponent" || c.data.type === "downloadcomponent").map((c) => {
        let L = c.data.configuration;
        return computeS3FileViewerPolicy(L);
    }).filter(Boolean);
    return {
        ...L ?? {},
        allowed_s3_keys: H,
        s3_inputs: V,
        triggerables_v2: B
    };
}
async function processRunnable$1(c, L, R, z) {
    let B = collectStaticFields(R), V = collectOneOfFields(R, z), H = Object.entries(R).map(([c, L]) => L.allowUserResources ? c : void 0).filter(Boolean);
    if (isRunnableByName(L)) {
        let R = await hash$1(L.inlineScript?.content);
        return console.debug("hex", R, c), [`${c}:rawscript/${R}`, {
                static_inputs: B,
                one_of_inputs: V,
                allow_user_resources: H
            }];
    }
    else if (isRunnableByPath(L))
        return [`${c}:${L.runType === "hubscript" ? "script" : L.runType}/${L.path}`, {
                static_inputs: B,
                one_of_inputs: V,
                allow_user_resources: H
            }];
}
async function hash$1(c) {
    try {
        let L = new TextEncoder().encode(c), R = await crypto.subtle.digest("SHA-256", L);
        return Array.from(new Uint8Array(R)).map((c) => c.toString(16).padStart(2, "0")).join("");
    }
    catch {
        let L = new import_build.Sha256();
        return L.update(c ?? ""), Array.from(await L.digest()).map((c) => c.toString(16).padStart(2, "0")).join("");
    }
}
function schemaToTsType(c) {
    let L = c.properties, R = c.required;
    return !c || !L ? "any" : `{ ${Object.keys(L).map((c) => {
        let z = L[c], B = `${c}${R?.includes(c) ? "" : "?"}`, V = "any";
        return z.type === "string" ? V = "string" : z.type === "number" || z.type === "integer" ? V = "number" : z.type === "boolean" ? V = "boolean" : z.type === "array" ? (V = z.items?.type ?? "any", V === "integer" && (V = "number"), V = `${V}[]`) : z.type === "object" && z.properties && (V = schemaToTsType(z)), `${B}: ${V}`;
    }).join("; ")} }`;
}
function removeStaticFields(c, L) {
    let R = Object.keys(L).filter((c) => L[c].type == "static");
    return {
        ...c,
        properties: { ...Object.fromEntries(Object.entries(c.properties ?? {}).filter(([c]) => !R.includes(c))) }
    };
}
function hiddenRunnableToTsType(c) {
    return isRunnableByName(c) ? c?.inlineScript?.schema ? schemaToTsType(removeStaticFields(c?.inlineScript?.schema, c?.fields ?? {})) : "{}" : isRunnableByPath(c) ? schemaToTsType(removeStaticFields(c?.schema, c?.fields ?? {})) : "{}";
}
function genWmillTs(c) {
    return `// THIS FILE IS READ-ONLY
// AND GENERATED AUTOMATICALLY FROM YOUR RUNNABLES

export declare const backend: {
${Object.entries(c).map(([c, L]) => `  ${c}: (args: ${hiddenRunnableToTsType(L)}) => Promise<any>;`).join("\n")}
};

export declare const backendAsync: {
${Object.entries(c).map(([c, L]) => `  ${c}: (args: ${hiddenRunnableToTsType(L)}) => Promise<string>;`).join("\n")}
};

export type Job = {
  type: "QueuedJob" | "CompletedJob";
  id: string;
  created_at: number;
  started_at: number | undefined;
  duration_ms: number;
  success: boolean;
  args: any;
  result: any;
};

/**
 * Execute a job and wait for it to complete and return the completed job
 * @param id
 */
export declare function waitJob(id: string): Promise<Job>;

/**
 * Get a job by id and return immediately with the current state of the job
 * @param id
 */
export declare function getJob(id: string): Promise<Job>;
`;
}
async function updateRawAppPolicy(c, L) {
    let R = Object.fromEntries(await Promise.all(Object.entries(c).map(async ([c, L]) => await processRunnable(c, L, L?.fields ?? {}))));
    return {
        ...L,
        triggerables_v2: R
    };
}
async function processRunnable(c, L, R) {
    let z = collectStaticFields(R), B = Object.entries(R).map(([c, L]) => L.allowUserResources ? c : void 0).filter(Boolean);
    if (isRunnableByName(L)) {
        let R = await hash(L.inlineScript?.content);
        return console.log("hex", R, c), [`${c}:rawscript/${R}`, {
                static_inputs: z,
                one_of_inputs: {},
                allow_user_resources: B
            }];
    }
    else if (isRunnableByPath(L))
        return [`${c}:${L.runType === "hubscript" ? "script" : L.runType}/${L.path}`, {
                static_inputs: z,
                one_of_inputs: {},
                allow_user_resources: B
            }];
}
var rawAppWmillTs_exports = /* @__PURE__ */ __export({ default: () => rawAppWmillTs_default }), rawAppWmillTs_default = "let reqs: Record<string, any> = {}\n\nfunction doRequest(type: string, o: object) {\n    return new Promise((resolve, reject) => {\n        const reqId = Math.random().toString(36)\n        reqs[reqId] = { resolve, reject }\n        parent.postMessage({ ...o, type, reqId }, '*')\n    })\n}\n\nexport const backend = new Proxy(\n    {},\n    {\n        get(_, runnable_id: string) {\n            return (v: any) => {\n                return doRequest('backend', { runnable_id, v })\n            }\n        }\n    })\n\nexport const backendAsync = new Proxy(\n    {},\n    {\n        get(_, runnable_id: string) {\n            return (v: any) => {\n                return doRequest('backendAsync', { runnable_id, v })\n            }\n        }\n    })\n\nexport function waitJob(jobId: string) {\n    return doRequest('waitJob', { jobId })\n}\n\nexport function getJob(jobId: string) {\n    return doRequest('getJob', { jobId })\n}\n\n\nwindow.addEventListener('message', (e) => {\n    if (e.data.type == 'backendRes' || e.data.type == 'backendAsyncRes') {\n        console.log('Message from parent backend', e.data)\n        let job = reqs[e.data.reqId]\n        if (job) {\n            const result = e.data.result\n            if (e.data.error) {\n                job.reject(new Error(result.stack ?? result.message))\n            } else {\n                job.resolve(result)\n            }\n        } else {\n            console.error('No job found for', e.data.reqId)\n        }\n    }\n})";
function capitalize(c) {
    return c ? c.charAt(0).toUpperCase() + c.slice(1) : "";
}
export { capitalize, genWmillTs, updatePolicy, updateRawAppPolicy, rawAppWmillTs_exports as wmillTsRaw };
