(function(global) { "use strict";
var __defProp2 = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp2 = (obj, key2, value) => key2 in obj ? __defProp2(obj, key2, { enumerable: true, configurable: true, writable: true, value }) : obj[key2] = value;
var __publicField2 = (obj, key2, value) => __defNormalProp2(obj, typeof key2 !== "symbol" ? key2 + "" : key2, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var __privateWrapper = (obj, member, setter, getter) => ({
  set _(value) {
    __privateSet(obj, member, value, setter);
  },
  get _() {
    return __privateGet(obj, member, getter);
  }
});
var _a2, _b, _provider, _providerCalled, _c, _focused, _cleanup, _setup, _d, _online, _cleanup2, _setup2, _e, _gcTimeout, _f, _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, dispatch_fn, _g, _client2, _currentQuery, _currentQueryInitialState, _currentResult, _currentResultState, _currentResultOptions, _currentThenable, _selectError, _selectFn, _selectResult, _lastQueryWithDefinedData, _staleTimeoutId, _refetchIntervalId, _currentRefetchInterval, _trackedProps, _QueryObserver_instances, executeFetch_fn, updateStaleTimeout_fn, computeRefetchInterval_fn, updateRefetchInterval_fn, updateTimers_fn, clearStaleTimeout_fn, clearRefetchInterval_fn, updateQuery_fn, notify_fn, _h, _client3, _observers, _mutationCache, _retryer2, _Mutation_instances, dispatch_fn2, _i, _mutations, _scopes, _mutationId, _j, _client4, _currentResult2, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn2, _k, _queries, _l, _queryCache, _mutationCache2, _defaultOptions2, _queryDefaults, _mutationDefaults, _mountCount, _unsubscribeFocus, _unsubscribeOnline, _m;
const uxp = require("uxp");
const photoshop = require("photoshop");
var commonjsGlobal$1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs$1(x2) {
  return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
}
function getAugmentedNamespace$1(n2) {
  if (Object.prototype.hasOwnProperty.call(n2, "__esModule")) return n2;
  var f2 = n2.default;
  if (typeof f2 == "function") {
    var a2 = function a3() {
      if (this instanceof a3) {
        return Reflect.construct(f2, arguments, this.constructor);
      }
      return f2.apply(this, arguments);
    };
    a2.prototype = f2.prototype;
  } else a2 = {};
  Object.defineProperty(a2, "__esModule", { value: true });
  Object.keys(n2).forEach(function(k2) {
    var d = Object.getOwnPropertyDescriptor(n2, k2);
    Object.defineProperty(a2, k2, d.get ? d : {
      enumerable: true,
      get: function() {
        return n2[k2];
      }
    });
  });
  return a2;
}
var buffer$1 = {};
var base64Js = {};
var hasRequiredBase64Js;
function requireBase64Js() {
  if (hasRequiredBase64Js) return base64Js;
  hasRequiredBase64Js = 1;
  base64Js.byteLength = byteLength2;
  base64Js.toByteArray = toByteArray2;
  base64Js.fromByteArray = fromByteArray2;
  var lookup2 = [];
  var revLookup2 = [];
  var Arr2 = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i2 = 0, len = code.length; i2 < len; ++i2) {
    lookup2[i2] = code[i2];
    revLookup2[code.charCodeAt(i2)] = i2;
  }
  revLookup2["-".charCodeAt(0)] = 62;
  revLookup2["_".charCodeAt(0)] = 63;
  function getLens(b64) {
    var len2 = b64.length;
    if (len2 % 4 > 0) {
      throw new Error("Invalid string. Length must be a multiple of 4");
    }
    var validLen = b64.indexOf("=");
    if (validLen === -1) validLen = len2;
    var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
    return [validLen, placeHoldersLen];
  }
  function byteLength2(b64) {
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function _byteLength(b64, validLen, placeHoldersLen) {
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function toByteArray2(b64) {
    var tmp;
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    var arr = new Arr2(_byteLength(b64, validLen, placeHoldersLen));
    var curByte = 0;
    var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
    var i3;
    for (i3 = 0; i3 < len2; i3 += 4) {
      tmp = revLookup2[b64.charCodeAt(i3)] << 18 | revLookup2[b64.charCodeAt(i3 + 1)] << 12 | revLookup2[b64.charCodeAt(i3 + 2)] << 6 | revLookup2[b64.charCodeAt(i3 + 3)];
      arr[curByte++] = tmp >> 16 & 255;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 2) {
      tmp = revLookup2[b64.charCodeAt(i3)] << 2 | revLookup2[b64.charCodeAt(i3 + 1)] >> 4;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 1) {
      tmp = revLookup2[b64.charCodeAt(i3)] << 10 | revLookup2[b64.charCodeAt(i3 + 1)] << 4 | revLookup2[b64.charCodeAt(i3 + 2)] >> 2;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    return arr;
  }
  function tripletToBase642(num) {
    return lookup2[num >> 18 & 63] + lookup2[num >> 12 & 63] + lookup2[num >> 6 & 63] + lookup2[num & 63];
  }
  function encodeChunk2(uint8, start, end) {
    var tmp;
    var output = [];
    for (var i3 = start; i3 < end; i3 += 3) {
      tmp = (uint8[i3] << 16 & 16711680) + (uint8[i3 + 1] << 8 & 65280) + (uint8[i3 + 2] & 255);
      output.push(tripletToBase642(tmp));
    }
    return output.join("");
  }
  function fromByteArray2(uint8) {
    var tmp;
    var len2 = uint8.length;
    var extraBytes = len2 % 3;
    var parts = [];
    var maxChunkLength = 16383;
    for (var i3 = 0, len22 = len2 - extraBytes; i3 < len22; i3 += maxChunkLength) {
      parts.push(encodeChunk2(uint8, i3, i3 + maxChunkLength > len22 ? len22 : i3 + maxChunkLength));
    }
    if (extraBytes === 1) {
      tmp = uint8[len2 - 1];
      parts.push(
        lookup2[tmp >> 2] + lookup2[tmp << 4 & 63] + "=="
      );
    } else if (extraBytes === 2) {
      tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
      parts.push(
        lookup2[tmp >> 10] + lookup2[tmp >> 4 & 63] + lookup2[tmp << 2 & 63] + "="
      );
    }
    return parts.join("");
  }
  return base64Js;
}
var ieee754$1 = {};
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
var hasRequiredIeee754;
function requireIeee754() {
  if (hasRequiredIeee754) return ieee754$1;
  hasRequiredIeee754 = 1;
  ieee754$1.read = function(buffer2, offset, isLE, mLen, nBytes) {
    var e4, m;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i2 = isLE ? nBytes - 1 : 0;
    var d = isLE ? -1 : 1;
    var s2 = buffer2[offset + i2];
    i2 += d;
    e4 = s2 & (1 << -nBits) - 1;
    s2 >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e4 = e4 * 256 + buffer2[offset + i2], i2 += d, nBits -= 8) {
    }
    m = e4 & (1 << -nBits) - 1;
    e4 >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m = m * 256 + buffer2[offset + i2], i2 += d, nBits -= 8) {
    }
    if (e4 === 0) {
      e4 = 1 - eBias;
    } else if (e4 === eMax) {
      return m ? NaN : (s2 ? -1 : 1) * Infinity;
    } else {
      m = m + Math.pow(2, mLen);
      e4 = e4 - eBias;
    }
    return (s2 ? -1 : 1) * m * Math.pow(2, e4 - mLen);
  };
  ieee754$1.write = function(buffer2, value, offset, isLE, mLen, nBytes) {
    var e4, m, c2;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i2 = isLE ? 0 : nBytes - 1;
    var d = isLE ? 1 : -1;
    var s2 = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0;
      e4 = eMax;
    } else {
      e4 = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c2 = Math.pow(2, -e4)) < 1) {
        e4--;
        c2 *= 2;
      }
      if (e4 + eBias >= 1) {
        value += rt / c2;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c2 >= 2) {
        e4++;
        c2 /= 2;
      }
      if (e4 + eBias >= eMax) {
        m = 0;
        e4 = eMax;
      } else if (e4 + eBias >= 1) {
        m = (value * c2 - 1) * Math.pow(2, mLen);
        e4 = e4 + eBias;
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e4 = 0;
      }
    }
    for (; mLen >= 8; buffer2[offset + i2] = m & 255, i2 += d, m /= 256, mLen -= 8) {
    }
    e4 = e4 << mLen | m;
    eLen += mLen;
    for (; eLen > 0; buffer2[offset + i2] = e4 & 255, i2 += d, e4 /= 256, eLen -= 8) {
    }
    buffer2[offset + i2 - d] |= s2 * 128;
  };
  return ieee754$1;
}
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
var hasRequiredBuffer$1;
function requireBuffer$1() {
  if (hasRequiredBuffer$1) return buffer$1;
  hasRequiredBuffer$1 = 1;
  (function(exports) {
    const base64 = requireBase64Js();
    const ieee7542 = requireIeee754();
    const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
    exports.Buffer = Buffer2;
    exports.SlowBuffer = SlowBuffer;
    exports.INSPECT_MAX_BYTES = 50;
    const K_MAX_LENGTH = 2147483647;
    exports.kMaxLength = K_MAX_LENGTH;
    Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
    if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
      console.error(
        "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
      );
    }
    function typedArraySupport() {
      try {
        const arr = new Uint8Array(1);
        const proto = { foo: function() {
          return 42;
        } };
        Object.setPrototypeOf(proto, Uint8Array.prototype);
        Object.setPrototypeOf(arr, proto);
        return arr.foo() === 42;
      } catch (e4) {
        return false;
      }
    }
    Object.defineProperty(Buffer2.prototype, "parent", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this)) return void 0;
        return this.buffer;
      }
    });
    Object.defineProperty(Buffer2.prototype, "offset", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this)) return void 0;
        return this.byteOffset;
      }
    });
    function createBuffer2(length) {
      if (length > K_MAX_LENGTH) {
        throw new RangeError('The value "' + length + '" is invalid for option "size"');
      }
      const buf = new Uint8Array(length);
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function Buffer2(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        if (typeof encodingOrOffset === "string") {
          throw new TypeError(
            'The "string" argument must be of type string. Received type number'
          );
        }
        return allocUnsafe2(arg);
      }
      return from2(arg, encodingOrOffset, length);
    }
    Buffer2.poolSize = 8192;
    function from2(value, encodingOrOffset, length) {
      if (typeof value === "string") {
        return fromString2(value, encodingOrOffset);
      }
      if (ArrayBuffer.isView(value)) {
        return fromArrayView(value);
      }
      if (value == null) {
        throw new TypeError(
          "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
        );
      }
      if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
        return fromArrayBuffer2(value, encodingOrOffset, length);
      }
      if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
        return fromArrayBuffer2(value, encodingOrOffset, length);
      }
      if (typeof value === "number") {
        throw new TypeError(
          'The "value" argument must not be of type number. Received type number'
        );
      }
      const valueOf = value.valueOf && value.valueOf();
      if (valueOf != null && valueOf !== value) {
        return Buffer2.from(valueOf, encodingOrOffset, length);
      }
      const b2 = fromObject2(value);
      if (b2) return b2;
      if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
        return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
      }
      throw new TypeError(
        "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
      );
    }
    Buffer2.from = function(value, encodingOrOffset, length) {
      return from2(value, encodingOrOffset, length);
    };
    Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
    Object.setPrototypeOf(Buffer2, Uint8Array);
    function assertSize2(size) {
      if (typeof size !== "number") {
        throw new TypeError('"size" argument must be of type number');
      } else if (size < 0) {
        throw new RangeError('The value "' + size + '" is invalid for option "size"');
      }
    }
    function alloc2(size, fill, encoding) {
      assertSize2(size);
      if (size <= 0) {
        return createBuffer2(size);
      }
      if (fill !== void 0) {
        return typeof encoding === "string" ? createBuffer2(size).fill(fill, encoding) : createBuffer2(size).fill(fill);
      }
      return createBuffer2(size);
    }
    Buffer2.alloc = function(size, fill, encoding) {
      return alloc2(size, fill, encoding);
    };
    function allocUnsafe2(size) {
      assertSize2(size);
      return createBuffer2(size < 0 ? 0 : checked2(size) | 0);
    }
    Buffer2.allocUnsafe = function(size) {
      return allocUnsafe2(size);
    };
    Buffer2.allocUnsafeSlow = function(size) {
      return allocUnsafe2(size);
    };
    function fromString2(string, encoding) {
      if (typeof encoding !== "string" || encoding === "") {
        encoding = "utf8";
      }
      if (!Buffer2.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      const length = byteLength2(string, encoding) | 0;
      let buf = createBuffer2(length);
      const actual = buf.write(string, encoding);
      if (actual !== length) {
        buf = buf.slice(0, actual);
      }
      return buf;
    }
    function fromArrayLike2(array) {
      const length = array.length < 0 ? 0 : checked2(array.length) | 0;
      const buf = createBuffer2(length);
      for (let i2 = 0; i2 < length; i2 += 1) {
        buf[i2] = array[i2] & 255;
      }
      return buf;
    }
    function fromArrayView(arrayView) {
      if (isInstance(arrayView, Uint8Array)) {
        const copy2 = new Uint8Array(arrayView);
        return fromArrayBuffer2(copy2.buffer, copy2.byteOffset, copy2.byteLength);
      }
      return fromArrayLike2(arrayView);
    }
    function fromArrayBuffer2(array, byteOffset, length) {
      if (byteOffset < 0 || array.byteLength < byteOffset) {
        throw new RangeError('"offset" is outside of buffer bounds');
      }
      if (array.byteLength < byteOffset + (length || 0)) {
        throw new RangeError('"length" is outside of buffer bounds');
      }
      let buf;
      if (byteOffset === void 0 && length === void 0) {
        buf = new Uint8Array(array);
      } else if (length === void 0) {
        buf = new Uint8Array(array, byteOffset);
      } else {
        buf = new Uint8Array(array, byteOffset, length);
      }
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function fromObject2(obj) {
      if (Buffer2.isBuffer(obj)) {
        const len = checked2(obj.length) | 0;
        const buf = createBuffer2(len);
        if (buf.length === 0) {
          return buf;
        }
        obj.copy(buf, 0, 0, len);
        return buf;
      }
      if (obj.length !== void 0) {
        if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
          return createBuffer2(0);
        }
        return fromArrayLike2(obj);
      }
      if (obj.type === "Buffer" && Array.isArray(obj.data)) {
        return fromArrayLike2(obj.data);
      }
    }
    function checked2(length) {
      if (length >= K_MAX_LENGTH) {
        throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
      }
      return length | 0;
    }
    function SlowBuffer(length) {
      if (+length != length) {
        length = 0;
      }
      return Buffer2.alloc(+length);
    }
    Buffer2.isBuffer = function isBuffer2(b2) {
      return b2 != null && b2._isBuffer === true && b2 !== Buffer2.prototype;
    };
    Buffer2.compare = function compare(a2, b2) {
      if (isInstance(a2, Uint8Array)) a2 = Buffer2.from(a2, a2.offset, a2.byteLength);
      if (isInstance(b2, Uint8Array)) b2 = Buffer2.from(b2, b2.offset, b2.byteLength);
      if (!Buffer2.isBuffer(a2) || !Buffer2.isBuffer(b2)) {
        throw new TypeError(
          'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
        );
      }
      if (a2 === b2) return 0;
      let x2 = a2.length;
      let y2 = b2.length;
      for (let i2 = 0, len = Math.min(x2, y2); i2 < len; ++i2) {
        if (a2[i2] !== b2[i2]) {
          x2 = a2[i2];
          y2 = b2[i2];
          break;
        }
      }
      if (x2 < y2) return -1;
      if (y2 < x2) return 1;
      return 0;
    };
    Buffer2.isEncoding = function isEncoding(encoding) {
      switch (String(encoding).toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "latin1":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return true;
        default:
          return false;
      }
    };
    Buffer2.concat = function concat(list, length) {
      if (!Array.isArray(list)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      }
      if (list.length === 0) {
        return Buffer2.alloc(0);
      }
      let i2;
      if (length === void 0) {
        length = 0;
        for (i2 = 0; i2 < list.length; ++i2) {
          length += list[i2].length;
        }
      }
      const buffer2 = Buffer2.allocUnsafe(length);
      let pos = 0;
      for (i2 = 0; i2 < list.length; ++i2) {
        let buf = list[i2];
        if (isInstance(buf, Uint8Array)) {
          if (pos + buf.length > buffer2.length) {
            if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
            buf.copy(buffer2, pos);
          } else {
            Uint8Array.prototype.set.call(
              buffer2,
              buf,
              pos
            );
          }
        } else if (!Buffer2.isBuffer(buf)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        } else {
          buf.copy(buffer2, pos);
        }
        pos += buf.length;
      }
      return buffer2;
    };
    function byteLength2(string, encoding) {
      if (Buffer2.isBuffer(string)) {
        return string.length;
      }
      if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
        return string.byteLength;
      }
      if (typeof string !== "string") {
        throw new TypeError(
          'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
        );
      }
      const len = string.length;
      const mustMatch = arguments.length > 2 && arguments[2] === true;
      if (!mustMatch && len === 0) return 0;
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "ascii":
          case "latin1":
          case "binary":
            return len;
          case "utf8":
          case "utf-8":
            return utf8ToBytes2(string).length;
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return len * 2;
          case "hex":
            return len >>> 1;
          case "base64":
            return base64ToBytes2(string).length;
          default:
            if (loweredCase) {
              return mustMatch ? -1 : utf8ToBytes2(string).length;
            }
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.byteLength = byteLength2;
    function slowToString2(encoding, start, end) {
      let loweredCase = false;
      if (start === void 0 || start < 0) {
        start = 0;
      }
      if (start > this.length) {
        return "";
      }
      if (end === void 0 || end > this.length) {
        end = this.length;
      }
      if (end <= 0) {
        return "";
      }
      end >>>= 0;
      start >>>= 0;
      if (end <= start) {
        return "";
      }
      if (!encoding) encoding = "utf8";
      while (true) {
        switch (encoding) {
          case "hex":
            return hexSlice2(this, start, end);
          case "utf8":
          case "utf-8":
            return utf8Slice2(this, start, end);
          case "ascii":
            return asciiSlice2(this, start, end);
          case "latin1":
          case "binary":
            return latin1Slice2(this, start, end);
          case "base64":
            return base64Slice2(this, start, end);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return utf16leSlice2(this, start, end);
          default:
            if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
            encoding = (encoding + "").toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.prototype._isBuffer = true;
    function swap2(b2, n2, m) {
      const i2 = b2[n2];
      b2[n2] = b2[m];
      b2[m] = i2;
    }
    Buffer2.prototype.swap16 = function swap16() {
      const len = this.length;
      if (len % 2 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 16-bits");
      }
      for (let i2 = 0; i2 < len; i2 += 2) {
        swap2(this, i2, i2 + 1);
      }
      return this;
    };
    Buffer2.prototype.swap32 = function swap32() {
      const len = this.length;
      if (len % 4 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 32-bits");
      }
      for (let i2 = 0; i2 < len; i2 += 4) {
        swap2(this, i2, i2 + 3);
        swap2(this, i2 + 1, i2 + 2);
      }
      return this;
    };
    Buffer2.prototype.swap64 = function swap64() {
      const len = this.length;
      if (len % 8 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 64-bits");
      }
      for (let i2 = 0; i2 < len; i2 += 8) {
        swap2(this, i2, i2 + 7);
        swap2(this, i2 + 1, i2 + 6);
        swap2(this, i2 + 2, i2 + 5);
        swap2(this, i2 + 3, i2 + 4);
      }
      return this;
    };
    Buffer2.prototype.toString = function toString2() {
      const length = this.length;
      if (length === 0) return "";
      if (arguments.length === 0) return utf8Slice2(this, 0, length);
      return slowToString2.apply(this, arguments);
    };
    Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
    Buffer2.prototype.equals = function equals(b2) {
      if (!Buffer2.isBuffer(b2)) throw new TypeError("Argument must be a Buffer");
      if (this === b2) return true;
      return Buffer2.compare(this, b2) === 0;
    };
    Buffer2.prototype.inspect = function inspect() {
      let str = "";
      const max2 = exports.INSPECT_MAX_BYTES;
      str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim();
      if (this.length > max2) str += " ... ";
      return "<Buffer " + str + ">";
    };
    if (customInspectSymbol) {
      Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
    }
    Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
      if (isInstance(target, Uint8Array)) {
        target = Buffer2.from(target, target.offset, target.byteLength);
      }
      if (!Buffer2.isBuffer(target)) {
        throw new TypeError(
          'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
        );
      }
      if (start === void 0) {
        start = 0;
      }
      if (end === void 0) {
        end = target ? target.length : 0;
      }
      if (thisStart === void 0) {
        thisStart = 0;
      }
      if (thisEnd === void 0) {
        thisEnd = this.length;
      }
      if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
        throw new RangeError("out of range index");
      }
      if (thisStart >= thisEnd && start >= end) {
        return 0;
      }
      if (thisStart >= thisEnd) {
        return -1;
      }
      if (start >= end) {
        return 1;
      }
      start >>>= 0;
      end >>>= 0;
      thisStart >>>= 0;
      thisEnd >>>= 0;
      if (this === target) return 0;
      let x2 = thisEnd - thisStart;
      let y2 = end - start;
      const len = Math.min(x2, y2);
      const thisCopy = this.slice(thisStart, thisEnd);
      const targetCopy = target.slice(start, end);
      for (let i2 = 0; i2 < len; ++i2) {
        if (thisCopy[i2] !== targetCopy[i2]) {
          x2 = thisCopy[i2];
          y2 = targetCopy[i2];
          break;
        }
      }
      if (x2 < y2) return -1;
      if (y2 < x2) return 1;
      return 0;
    };
    function bidirectionalIndexOf2(buffer2, val, byteOffset, encoding, dir) {
      if (buffer2.length === 0) return -1;
      if (typeof byteOffset === "string") {
        encoding = byteOffset;
        byteOffset = 0;
      } else if (byteOffset > 2147483647) {
        byteOffset = 2147483647;
      } else if (byteOffset < -2147483648) {
        byteOffset = -2147483648;
      }
      byteOffset = +byteOffset;
      if (numberIsNaN(byteOffset)) {
        byteOffset = dir ? 0 : buffer2.length - 1;
      }
      if (byteOffset < 0) byteOffset = buffer2.length + byteOffset;
      if (byteOffset >= buffer2.length) {
        if (dir) return -1;
        else byteOffset = buffer2.length - 1;
      } else if (byteOffset < 0) {
        if (dir) byteOffset = 0;
        else return -1;
      }
      if (typeof val === "string") {
        val = Buffer2.from(val, encoding);
      }
      if (Buffer2.isBuffer(val)) {
        if (val.length === 0) {
          return -1;
        }
        return arrayIndexOf2(buffer2, val, byteOffset, encoding, dir);
      } else if (typeof val === "number") {
        val = val & 255;
        if (typeof Uint8Array.prototype.indexOf === "function") {
          if (dir) {
            return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
          } else {
            return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
          }
        }
        return arrayIndexOf2(buffer2, [val], byteOffset, encoding, dir);
      }
      throw new TypeError("val must be string, number or Buffer");
    }
    function arrayIndexOf2(arr, val, byteOffset, encoding, dir) {
      let indexSize = 1;
      let arrLength = arr.length;
      let valLength = val.length;
      if (encoding !== void 0) {
        encoding = String(encoding).toLowerCase();
        if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
          if (arr.length < 2 || val.length < 2) {
            return -1;
          }
          indexSize = 2;
          arrLength /= 2;
          valLength /= 2;
          byteOffset /= 2;
        }
      }
      function read2(buf, i3) {
        if (indexSize === 1) {
          return buf[i3];
        } else {
          return buf.readUInt16BE(i3 * indexSize);
        }
      }
      let i2;
      if (dir) {
        let foundIndex = -1;
        for (i2 = byteOffset; i2 < arrLength; i2++) {
          if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) {
            if (foundIndex === -1) foundIndex = i2;
            if (i2 - foundIndex + 1 === valLength) return foundIndex * indexSize;
          } else {
            if (foundIndex !== -1) i2 -= i2 - foundIndex;
            foundIndex = -1;
          }
        }
      } else {
        if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
        for (i2 = byteOffset; i2 >= 0; i2--) {
          let found = true;
          for (let j = 0; j < valLength; j++) {
            if (read2(arr, i2 + j) !== read2(val, j)) {
              found = false;
              break;
            }
          }
          if (found) return i2;
        }
      }
      return -1;
    }
    Buffer2.prototype.includes = function includes2(val, byteOffset, encoding) {
      return this.indexOf(val, byteOffset, encoding) !== -1;
    };
    Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf2(this, val, byteOffset, encoding, true);
    };
    Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf2(this, val, byteOffset, encoding, false);
    };
    function hexWrite2(buf, string, offset, length) {
      offset = Number(offset) || 0;
      const remaining = buf.length - offset;
      if (!length) {
        length = remaining;
      } else {
        length = Number(length);
        if (length > remaining) {
          length = remaining;
        }
      }
      const strLen = string.length;
      if (length > strLen / 2) {
        length = strLen / 2;
      }
      let i2;
      for (i2 = 0; i2 < length; ++i2) {
        const parsed = parseInt(string.substr(i2 * 2, 2), 16);
        if (numberIsNaN(parsed)) return i2;
        buf[offset + i2] = parsed;
      }
      return i2;
    }
    function utf8Write2(buf, string, offset, length) {
      return blitBuffer2(utf8ToBytes2(string, buf.length - offset), buf, offset, length);
    }
    function asciiWrite2(buf, string, offset, length) {
      return blitBuffer2(asciiToBytes2(string), buf, offset, length);
    }
    function base64Write2(buf, string, offset, length) {
      return blitBuffer2(base64ToBytes2(string), buf, offset, length);
    }
    function ucs2Write2(buf, string, offset, length) {
      return blitBuffer2(utf16leToBytes2(string, buf.length - offset), buf, offset, length);
    }
    Buffer2.prototype.write = function write2(string, offset, length, encoding) {
      if (offset === void 0) {
        encoding = "utf8";
        length = this.length;
        offset = 0;
      } else if (length === void 0 && typeof offset === "string") {
        encoding = offset;
        length = this.length;
        offset = 0;
      } else if (isFinite(offset)) {
        offset = offset >>> 0;
        if (isFinite(length)) {
          length = length >>> 0;
          if (encoding === void 0) encoding = "utf8";
        } else {
          encoding = length;
          length = void 0;
        }
      } else {
        throw new Error(
          "Buffer.write(string, encoding, offset[, length]) is no longer supported"
        );
      }
      const remaining = this.length - offset;
      if (length === void 0 || length > remaining) length = remaining;
      if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
        throw new RangeError("Attempt to write outside buffer bounds");
      }
      if (!encoding) encoding = "utf8";
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "hex":
            return hexWrite2(this, string, offset, length);
          case "utf8":
          case "utf-8":
            return utf8Write2(this, string, offset, length);
          case "ascii":
          case "latin1":
          case "binary":
            return asciiWrite2(this, string, offset, length);
          case "base64":
            return base64Write2(this, string, offset, length);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return ucs2Write2(this, string, offset, length);
          default:
            if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    };
    Buffer2.prototype.toJSON = function toJSON() {
      return {
        type: "Buffer",
        data: Array.prototype.slice.call(this._arr || this, 0)
      };
    };
    function base64Slice2(buf, start, end) {
      if (start === 0 && end === buf.length) {
        return base64.fromByteArray(buf);
      } else {
        return base64.fromByteArray(buf.slice(start, end));
      }
    }
    function utf8Slice2(buf, start, end) {
      end = Math.min(buf.length, end);
      const res = [];
      let i2 = start;
      while (i2 < end) {
        const firstByte = buf[i2];
        let codePoint = null;
        let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
        if (i2 + bytesPerSequence <= end) {
          let secondByte, thirdByte, fourthByte, tempCodePoint;
          switch (bytesPerSequence) {
            case 1:
              if (firstByte < 128) {
                codePoint = firstByte;
              }
              break;
            case 2:
              secondByte = buf[i2 + 1];
              if ((secondByte & 192) === 128) {
                tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                if (tempCodePoint > 127) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 3:
              secondByte = buf[i2 + 1];
              thirdByte = buf[i2 + 2];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
                if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 4:
              secondByte = buf[i2 + 1];
              thirdByte = buf[i2 + 2];
              fourthByte = buf[i2 + 3];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
                if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                  codePoint = tempCodePoint;
                }
              }
          }
        }
        if (codePoint === null) {
          codePoint = 65533;
          bytesPerSequence = 1;
        } else if (codePoint > 65535) {
          codePoint -= 65536;
          res.push(codePoint >>> 10 & 1023 | 55296);
          codePoint = 56320 | codePoint & 1023;
        }
        res.push(codePoint);
        i2 += bytesPerSequence;
      }
      return decodeCodePointsArray2(res);
    }
    const MAX_ARGUMENTS_LENGTH2 = 4096;
    function decodeCodePointsArray2(codePoints) {
      const len = codePoints.length;
      if (len <= MAX_ARGUMENTS_LENGTH2) {
        return String.fromCharCode.apply(String, codePoints);
      }
      let res = "";
      let i2 = 0;
      while (i2 < len) {
        res += String.fromCharCode.apply(
          String,
          codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH2)
        );
      }
      return res;
    }
    function asciiSlice2(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i2 = start; i2 < end; ++i2) {
        ret += String.fromCharCode(buf[i2] & 127);
      }
      return ret;
    }
    function latin1Slice2(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i2 = start; i2 < end; ++i2) {
        ret += String.fromCharCode(buf[i2]);
      }
      return ret;
    }
    function hexSlice2(buf, start, end) {
      const len = buf.length;
      if (!start || start < 0) start = 0;
      if (!end || end < 0 || end > len) end = len;
      let out = "";
      for (let i2 = start; i2 < end; ++i2) {
        out += hexSliceLookupTable[buf[i2]];
      }
      return out;
    }
    function utf16leSlice2(buf, start, end) {
      const bytes = buf.slice(start, end);
      let res = "";
      for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) {
        res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256);
      }
      return res;
    }
    Buffer2.prototype.slice = function slice(start, end) {
      const len = this.length;
      start = ~~start;
      end = end === void 0 ? len : ~~end;
      if (start < 0) {
        start += len;
        if (start < 0) start = 0;
      } else if (start > len) {
        start = len;
      }
      if (end < 0) {
        end += len;
        if (end < 0) end = 0;
      } else if (end > len) {
        end = len;
      }
      if (end < start) end = start;
      const newBuf = this.subarray(start, end);
      Object.setPrototypeOf(newBuf, Buffer2.prototype);
      return newBuf;
    };
    function checkOffset2(offset, ext, length) {
      if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
      if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
    }
    Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset2(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i2 = 0;
      while (++i2 < byteLength3 && (mul *= 256)) {
        val += this[offset + i2] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        checkOffset2(offset, byteLength3, this.length);
      }
      let val = this[offset + --byteLength3];
      let mul = 1;
      while (byteLength3 > 0 && (mul *= 256)) {
        val += this[offset + --byteLength3] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 1, this.length);
      return this[offset];
    };
    Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 2, this.length);
      return this[offset] | this[offset + 1] << 8;
    };
    Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 2, this.length);
      return this[offset] << 8 | this[offset + 1];
    };
    Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
    };
    Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
    };
    Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
      const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
      return BigInt(lo) + (BigInt(hi) << BigInt(32));
    });
    Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
      const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
      return (BigInt(hi) << BigInt(32)) + BigInt(lo);
    });
    Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset2(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i2 = 0;
      while (++i2 < byteLength3 && (mul *= 256)) {
        val += this[offset + i2] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset2(offset, byteLength3, this.length);
      let i2 = byteLength3;
      let mul = 1;
      let val = this[offset + --i2];
      while (i2 > 0 && (mul *= 256)) {
        val += this[offset + --i2] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 1, this.length);
      if (!(this[offset] & 128)) return this[offset];
      return (255 - this[offset] + 1) * -1;
    };
    Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 2, this.length);
      const val = this[offset] | this[offset + 1] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 2, this.length);
      const val = this[offset + 1] | this[offset] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
    };
    Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
    };
    Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
      return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
    });
    Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = (first << 24) + // Overflow
      this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
      return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
    });
    Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return ieee7542.read(this, offset, true, 23, 4);
    };
    Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 4, this.length);
      return ieee7542.read(this, offset, false, 23, 4);
    };
    Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 8, this.length);
      return ieee7542.read(this, offset, true, 52, 8);
    };
    Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset2(offset, 8, this.length);
      return ieee7542.read(this, offset, false, 52, 8);
    };
    function checkInt2(buf, value, offset, ext, max2, min2) {
      if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
      if (value > max2 || value < min2) throw new RangeError('"value" argument is out of bounds');
      if (offset + ext > buf.length) throw new RangeError("Index out of range");
    }
    Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt2(this, value, offset, byteLength3, maxBytes, 0);
      }
      let mul = 1;
      let i2 = 0;
      this[offset] = value & 255;
      while (++i2 < byteLength3 && (mul *= 256)) {
        this[offset + i2] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt2(this, value, offset, byteLength3, maxBytes, 0);
      }
      let i2 = byteLength3 - 1;
      let mul = 1;
      this[offset + i2] = value & 255;
      while (--i2 >= 0 && (mul *= 256)) {
        this[offset + i2] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 1, 255, 0);
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 2, 65535, 0);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 2, 65535, 0);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 4, 4294967295, 0);
      this[offset + 3] = value >>> 24;
      this[offset + 2] = value >>> 16;
      this[offset + 1] = value >>> 8;
      this[offset] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 4, 4294967295, 0);
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    function wrtBigUInt64LE(buf, value, offset, min2, max2) {
      checkIntBI(value, min2, max2, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      return offset;
    }
    function wrtBigUInt64BE(buf, value, offset, min2, max2) {
      checkIntBI(value, min2, max2, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset + 7] = lo;
      lo = lo >> 8;
      buf[offset + 6] = lo;
      lo = lo >> 8;
      buf[offset + 5] = lo;
      lo = lo >> 8;
      buf[offset + 4] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset + 3] = hi;
      hi = hi >> 8;
      buf[offset + 2] = hi;
      hi = hi >> 8;
      buf[offset + 1] = hi;
      hi = hi >> 8;
      buf[offset] = hi;
      return offset + 8;
    }
    Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit = Math.pow(2, 8 * byteLength3 - 1);
        checkInt2(this, value, offset, byteLength3, limit - 1, -limit);
      }
      let i2 = 0;
      let mul = 1;
      let sub = 0;
      this[offset] = value & 255;
      while (++i2 < byteLength3 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) {
          sub = 1;
        }
        this[offset + i2] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit = Math.pow(2, 8 * byteLength3 - 1);
        checkInt2(this, value, offset, byteLength3, limit - 1, -limit);
      }
      let i2 = byteLength3 - 1;
      let mul = 1;
      let sub = 0;
      this[offset + i2] = value & 255;
      while (--i2 >= 0 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) {
          sub = 1;
        }
        this[offset + i2] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 1, 127, -128);
      if (value < 0) value = 255 + value + 1;
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 2, 32767, -32768);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 2, 32767, -32768);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 4, 2147483647, -2147483648);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      this[offset + 2] = value >>> 16;
      this[offset + 3] = value >>> 24;
      return offset + 4;
    };
    Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt2(this, value, offset, 4, 2147483647, -2147483648);
      if (value < 0) value = 4294967295 + value + 1;
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    function checkIEEE7542(buf, value, offset, ext, max2, min2) {
      if (offset + ext > buf.length) throw new RangeError("Index out of range");
      if (offset < 0) throw new RangeError("Index out of range");
    }
    function writeFloat2(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE7542(buf, value, offset, 4);
      }
      ieee7542.write(buf, value, offset, littleEndian, 23, 4);
      return offset + 4;
    }
    Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
      return writeFloat2(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
      return writeFloat2(this, value, offset, false, noAssert);
    };
    function writeDouble2(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE7542(buf, value, offset, 8);
      }
      ieee7542.write(buf, value, offset, littleEndian, 52, 8);
      return offset + 8;
    }
    Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
      return writeDouble2(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
      return writeDouble2(this, value, offset, false, noAssert);
    };
    Buffer2.prototype.copy = function copy2(target, targetStart, start, end) {
      if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
      if (!start) start = 0;
      if (!end && end !== 0) end = this.length;
      if (targetStart >= target.length) targetStart = target.length;
      if (!targetStart) targetStart = 0;
      if (end > 0 && end < start) end = start;
      if (end === start) return 0;
      if (target.length === 0 || this.length === 0) return 0;
      if (targetStart < 0) {
        throw new RangeError("targetStart out of bounds");
      }
      if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
      if (end < 0) throw new RangeError("sourceEnd out of bounds");
      if (end > this.length) end = this.length;
      if (target.length - targetStart < end - start) {
        end = target.length - targetStart + start;
      }
      const len = end - start;
      if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
        this.copyWithin(targetStart, start, end);
      } else {
        Uint8Array.prototype.set.call(
          target,
          this.subarray(start, end),
          targetStart
        );
      }
      return len;
    };
    Buffer2.prototype.fill = function fill(val, start, end, encoding) {
      if (typeof val === "string") {
        if (typeof start === "string") {
          encoding = start;
          start = 0;
          end = this.length;
        } else if (typeof end === "string") {
          encoding = end;
          end = this.length;
        }
        if (encoding !== void 0 && typeof encoding !== "string") {
          throw new TypeError("encoding must be a string");
        }
        if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        if (val.length === 1) {
          const code = val.charCodeAt(0);
          if (encoding === "utf8" && code < 128 || encoding === "latin1") {
            val = code;
          }
        }
      } else if (typeof val === "number") {
        val = val & 255;
      } else if (typeof val === "boolean") {
        val = Number(val);
      }
      if (start < 0 || this.length < start || this.length < end) {
        throw new RangeError("Out of range index");
      }
      if (end <= start) {
        return this;
      }
      start = start >>> 0;
      end = end === void 0 ? this.length : end >>> 0;
      if (!val) val = 0;
      let i2;
      if (typeof val === "number") {
        for (i2 = start; i2 < end; ++i2) {
          this[i2] = val;
        }
      } else {
        const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
        const len = bytes.length;
        if (len === 0) {
          throw new TypeError('The value "' + val + '" is invalid for argument "value"');
        }
        for (i2 = 0; i2 < end - start; ++i2) {
          this[i2 + start] = bytes[i2 % len];
        }
      }
      return this;
    };
    const errors = {};
    function E2(sym, getMessage, Base) {
      errors[sym] = class NodeError extends Base {
        constructor() {
          super();
          Object.defineProperty(this, "message", {
            value: getMessage.apply(this, arguments),
            writable: true,
            configurable: true
          });
          this.name = `${this.name} [${sym}]`;
          this.stack;
          delete this.name;
        }
        get code() {
          return sym;
        }
        set code(value) {
          Object.defineProperty(this, "code", {
            configurable: true,
            enumerable: true,
            value,
            writable: true
          });
        }
        toString() {
          return `${this.name} [${sym}]: ${this.message}`;
        }
      };
    }
    E2(
      "ERR_BUFFER_OUT_OF_BOUNDS",
      function(name) {
        if (name) {
          return `${name} is outside of buffer bounds`;
        }
        return "Attempt to access memory outside buffer bounds";
      },
      RangeError
    );
    E2(
      "ERR_INVALID_ARG_TYPE",
      function(name, actual) {
        return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
      },
      TypeError
    );
    E2(
      "ERR_OUT_OF_RANGE",
      function(str, range2, input) {
        let msg = `The value of "${str}" is out of range.`;
        let received = input;
        if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
          received = addNumericalSeparator(String(input));
        } else if (typeof input === "bigint") {
          received = String(input);
          if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
            received = addNumericalSeparator(received);
          }
          received += "n";
        }
        msg += ` It must be ${range2}. Received ${received}`;
        return msg;
      },
      RangeError
    );
    function addNumericalSeparator(val) {
      let res = "";
      let i2 = val.length;
      const start = val[0] === "-" ? 1 : 0;
      for (; i2 >= start + 4; i2 -= 3) {
        res = `_${val.slice(i2 - 3, i2)}${res}`;
      }
      return `${val.slice(0, i2)}${res}`;
    }
    function checkBounds(buf, offset, byteLength3) {
      validateNumber(offset, "offset");
      if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) {
        boundsError(offset, buf.length - (byteLength3 + 1));
      }
    }
    function checkIntBI(value, min2, max2, buf, offset, byteLength3) {
      if (value > max2 || value < min2) {
        const n2 = typeof min2 === "bigint" ? "n" : "";
        let range2;
        {
          if (min2 === 0 || min2 === BigInt(0)) {
            range2 = `>= 0${n2} and < 2${n2} ** ${(byteLength3 + 1) * 8}${n2}`;
          } else {
            range2 = `>= -(2${n2} ** ${(byteLength3 + 1) * 8 - 1}${n2}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n2}`;
          }
        }
        throw new errors.ERR_OUT_OF_RANGE("value", range2, value);
      }
      checkBounds(buf, offset, byteLength3);
    }
    function validateNumber(value, name) {
      if (typeof value !== "number") {
        throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
      }
    }
    function boundsError(value, length, type2) {
      if (Math.floor(value) !== value) {
        validateNumber(value, type2);
        throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value);
      }
      if (length < 0) {
        throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
      }
      throw new errors.ERR_OUT_OF_RANGE(
        "offset",
        `>= ${0} and <= ${length}`,
        value
      );
    }
    const INVALID_BASE64_RE2 = /[^+/0-9A-Za-z-_]/g;
    function base64clean2(str) {
      str = str.split("=")[0];
      str = str.trim().replace(INVALID_BASE64_RE2, "");
      if (str.length < 2) return "";
      while (str.length % 4 !== 0) {
        str = str + "=";
      }
      return str;
    }
    function utf8ToBytes2(string, units) {
      units = units || Infinity;
      let codePoint;
      const length = string.length;
      let leadSurrogate = null;
      const bytes = [];
      for (let i2 = 0; i2 < length; ++i2) {
        codePoint = string.charCodeAt(i2);
        if (codePoint > 55295 && codePoint < 57344) {
          if (!leadSurrogate) {
            if (codePoint > 56319) {
              if ((units -= 3) > -1) bytes.push(239, 191, 189);
              continue;
            } else if (i2 + 1 === length) {
              if ((units -= 3) > -1) bytes.push(239, 191, 189);
              continue;
            }
            leadSurrogate = codePoint;
            continue;
          }
          if (codePoint < 56320) {
            if ((units -= 3) > -1) bytes.push(239, 191, 189);
            leadSurrogate = codePoint;
            continue;
          }
          codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
        } else if (leadSurrogate) {
          if ((units -= 3) > -1) bytes.push(239, 191, 189);
        }
        leadSurrogate = null;
        if (codePoint < 128) {
          if ((units -= 1) < 0) break;
          bytes.push(codePoint);
        } else if (codePoint < 2048) {
          if ((units -= 2) < 0) break;
          bytes.push(
            codePoint >> 6 | 192,
            codePoint & 63 | 128
          );
        } else if (codePoint < 65536) {
          if ((units -= 3) < 0) break;
          bytes.push(
            codePoint >> 12 | 224,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else if (codePoint < 1114112) {
          if ((units -= 4) < 0) break;
          bytes.push(
            codePoint >> 18 | 240,
            codePoint >> 12 & 63 | 128,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else {
          throw new Error("Invalid code point");
        }
      }
      return bytes;
    }
    function asciiToBytes2(str) {
      const byteArray = [];
      for (let i2 = 0; i2 < str.length; ++i2) {
        byteArray.push(str.charCodeAt(i2) & 255);
      }
      return byteArray;
    }
    function utf16leToBytes2(str, units) {
      let c2, hi, lo;
      const byteArray = [];
      for (let i2 = 0; i2 < str.length; ++i2) {
        if ((units -= 2) < 0) break;
        c2 = str.charCodeAt(i2);
        hi = c2 >> 8;
        lo = c2 % 256;
        byteArray.push(lo);
        byteArray.push(hi);
      }
      return byteArray;
    }
    function base64ToBytes2(str) {
      return base64.toByteArray(base64clean2(str));
    }
    function blitBuffer2(src2, dst, offset, length) {
      let i2;
      for (i2 = 0; i2 < length; ++i2) {
        if (i2 + offset >= dst.length || i2 >= src2.length) break;
        dst[i2 + offset] = src2[i2];
      }
      return i2;
    }
    function isInstance(obj, type2) {
      return obj instanceof type2 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type2.name;
    }
    function numberIsNaN(obj) {
      return obj !== obj;
    }
    const hexSliceLookupTable = function() {
      const alphabet2 = "0123456789abcdef";
      const table = new Array(256);
      for (let i2 = 0; i2 < 16; ++i2) {
        const i16 = i2 * 16;
        for (let j = 0; j < 16; ++j) {
          table[i16 + j] = alphabet2[i2] + alphabet2[j];
        }
      }
      return table;
    }();
    function defineBigIntMethod(fn) {
      return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
    }
    function BufferBigIntNotDefined() {
      throw new Error("BigInt not supported");
    }
  })(buffer$1);
  return buffer$1;
}
var bufferExports = requireBuffer$1();
globalThis.Buffer = bufferExports.Buffer;
var ResourceType;
(function(ResourceType2) {
  ResourceType2["Data"] = "DATA";
  ResourceType2["Api"] = "API";
  ResourceType2["Menu"] = "MENU";
  ResourceType2["Ui"] = "UI";
  ResourceType2["Button"] = "BUTTON";
})(ResourceType || (ResourceType = {}));
var PolicyAssignmentTargetType;
(function(PolicyAssignmentTargetType2) {
  PolicyAssignmentTargetType2["User"] = "USER";
  PolicyAssignmentTargetType2["Role"] = "ROLE";
  PolicyAssignmentTargetType2["Group"] = "GROUP";
  PolicyAssignmentTargetType2["Org"] = "ORG";
  PolicyAssignmentTargetType2["AkSk"] = "AK_SK";
})(PolicyAssignmentTargetType || (PolicyAssignmentTargetType = {}));
var Operator;
(function(Operator2) {
  Operator2["And"] = "AND";
  Operator2["Or"] = "OR";
})(Operator || (Operator = {}));
var EmailTemplateType;
(function(EmailTemplateType2) {
  EmailTemplateType2["ResetPassword"] = "RESET_PASSWORD";
  EmailTemplateType2["PasswordResetedNotification"] = "PASSWORD_RESETED_NOTIFICATION";
  EmailTemplateType2["ChangePassword"] = "CHANGE_PASSWORD";
  EmailTemplateType2["Welcome"] = "WELCOME";
  EmailTemplateType2["VerifyEmail"] = "VERIFY_EMAIL";
  EmailTemplateType2["ChangeEmail"] = "CHANGE_EMAIL";
})(EmailTemplateType || (EmailTemplateType = {}));
var SortByEnum;
(function(SortByEnum2) {
  SortByEnum2["CreatedatDesc"] = "CREATEDAT_DESC";
  SortByEnum2["CreatedatAsc"] = "CREATEDAT_ASC";
  SortByEnum2["UpdatedatDesc"] = "UPDATEDAT_DESC";
  SortByEnum2["UpdatedatAsc"] = "UPDATEDAT_ASC";
})(SortByEnum || (SortByEnum = {}));
var UserStatus;
(function(UserStatus2) {
  UserStatus2["Suspended"] = "Suspended";
  UserStatus2["Resigned"] = "Resigned";
  UserStatus2["Activated"] = "Activated";
  UserStatus2["Archived"] = "Archived";
})(UserStatus || (UserStatus = {}));
var UdfDataType;
(function(UdfDataType2) {
  UdfDataType2["String"] = "STRING";
  UdfDataType2["Number"] = "NUMBER";
  UdfDataType2["Datetime"] = "DATETIME";
  UdfDataType2["Boolean"] = "BOOLEAN";
  UdfDataType2["Object"] = "OBJECT";
  UdfDataType2["Select"] = "SELECT";
})(UdfDataType || (UdfDataType = {}));
var PolicyEffect;
(function(PolicyEffect2) {
  PolicyEffect2["Allow"] = "ALLOW";
  PolicyEffect2["Deny"] = "DENY";
})(PolicyEffect || (PolicyEffect = {}));
var UdfTargetType;
(function(UdfTargetType2) {
  UdfTargetType2["Node"] = "NODE";
  UdfTargetType2["Org"] = "ORG";
  UdfTargetType2["User"] = "USER";
  UdfTargetType2["Userpool"] = "USERPOOL";
  UdfTargetType2["Role"] = "ROLE";
  UdfTargetType2["Permission"] = "PERMISSION";
  UdfTargetType2["Application"] = "APPLICATION";
})(UdfTargetType || (UdfTargetType = {}));
var WhitelistType;
(function(WhitelistType2) {
  WhitelistType2["Username"] = "USERNAME";
  WhitelistType2["Email"] = "EMAIL";
  WhitelistType2["Phone"] = "PHONE";
})(WhitelistType || (WhitelistType = {}));
var EmailScene;
(function(EmailScene2) {
  EmailScene2["ResetPassword"] = "RESET_PASSWORD";
  EmailScene2["RESET_PASSWORD_VERIFY_CODE"] = "RESET_PASSWORD_VERIFY_CODE";
  EmailScene2["VerifyEmail"] = "VERIFY_EMAIL";
  EmailScene2["FIRST_EMAIL_LOGIN_VERIFY"] = "FIRST_EMAIL_LOGIN_VERIFY";
  EmailScene2["CONSOLE_CONDUCTED_VERIFY"] = "CONSOLE_CONDUCTED_VERIFY";
  EmailScene2["ChangeEmail"] = "CHANGE_EMAIL";
  EmailScene2["EMAIL_BIND_VERIFY_CODE"] = "EMAIL_BIND_VERIFY_CODE";
  EmailScene2["EMAIL_UNBIND_VERIFY_CODE"] = "EMAIL_UNBIND_VERIFY_CODE";
  EmailScene2["MfaVerify"] = "MFA_VERIFY";
  EmailScene2["VerifyCode"] = "VERIFY_CODE";
  EmailScene2["REGISTER_VERIFY_CODE"] = "REGISTER_VERIFY_CODE";
  EmailScene2["LOGIN_VERIFY_CODE"] = "LOGIN_VERIFY_CODE";
  EmailScene2["MFA_VERIFY_CODE"] = "MFA_VERIFY_CODE";
  EmailScene2["INFORMATION_COMPLETION_VERIFY_CODE"] = "INFORMATION_COMPLETION_VERIFY_CODE";
})(EmailScene || (EmailScene = {}));
var BindEmailDocument = "\n    mutation bindEmail($email: String!, $emailCode: String!) {\n  bindEmail(email: $email, emailCode: $emailCode) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var BindPhoneDocument = "\n    mutation bindPhone($phone: String!, $phoneCode: String!, $phoneCountryCode: String) {\n  bindPhone(phone: $phone, phoneCode: $phoneCode, phoneCountryCode: $phoneCountryCode) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var LoginByEmailDocument = "\n    mutation loginByEmail($input: LoginByEmailInput!) {\n  loginByEmail(input: $input) {\n    id\n    arn\n    status\n    userPoolId\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    newlyCreated\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var LoginByPhoneCodeDocument = "\n    mutation loginByPhoneCode($input: LoginByPhoneCodeInput!) {\n  loginByPhoneCode(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    newlyCreated\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var LoginByPhonePasswordDocument = "\n    mutation loginByPhonePassword($input: LoginByPhonePasswordInput!) {\n  loginByPhonePassword(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    newlyCreated\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var LoginBySubAccountDocument = "\n    mutation loginBySubAccount($account: String!, $password: String!, $captchaCode: String, $clientIp: String) {\n  loginBySubAccount(account: $account, password: $password, captchaCode: $captchaCode, clientIp: $clientIp) {\n    id\n    arn\n    status\n    userPoolId\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    newlyCreated\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var LoginByUsernameDocument = "\n    mutation loginByUsername($input: LoginByUsernameInput!) {\n  loginByUsername(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    newlyCreated\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var RefreshTokenDocument = "\n    mutation refreshToken($id: String) {\n  refreshToken(id: $id) {\n    token\n    iat\n    exp\n  }\n}\n    ";
var RegisterByEmailDocument = "\n    mutation registerByEmail($input: RegisterByEmailInput!) {\n  registerByEmail(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n  }\n}\n    ";
var RegisterByPhoneCodeDocument = "\n    mutation registerByPhoneCode($input: RegisterByPhoneCodeInput!) {\n  registerByPhoneCode(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n  }\n}\n    ";
var RegisterByUsernameDocument = "\n    mutation registerByUsername($input: RegisterByUsernameInput!) {\n  registerByUsername(input: $input) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n  }\n}\n    ";
var RemoveUdvDocument = "\n    mutation removeUdv($targetType: UDFTargetType!, $targetId: String!, $key: String!) {\n  removeUdv(targetType: $targetType, targetId: $targetId, key: $key) {\n    key\n    dataType\n    value\n    label\n  }\n}\n    ";
var ResetPasswordDocument = "\n    mutation resetPassword($phone: String, $phoneCountryCode: String, $email: String, $code: String!, $newPassword: String!) {\n  resetPassword(phone: $phone, phoneCountryCode: $phoneCountryCode, email: $email, code: $code, newPassword: $newPassword) {\n    message\n    code\n  }\n}\n    ";
var ResetPasswordByFirstLoginTokenDocument = "\n    mutation resetPasswordByFirstLoginToken($token: String!, $password: String!) {\n  resetPasswordByFirstLoginToken(token: $token, password: $password) {\n    message\n    code\n  }\n}\n    ";
var ResetPasswordByForceResetTokenDocument = "\n    mutation resetPasswordByForceResetToken($token: String!, $oldPassword: String!, $newPassword: String!) {\n  resetPasswordByForceResetToken(token: $token, oldPassword: $oldPassword, newPassword: $newPassword) {\n    message\n    code\n  }\n}\n    ";
var SendEmailDocument = "\n    mutation sendEmail($email: String!, $scene: EmailScene!) {\n  sendEmail(email: $email, scene: $scene) {\n    message\n    code\n  }\n}\n    ";
var SetUdvDocument = "\n    mutation setUdv($targetType: UDFTargetType!, $targetId: String!, $key: String!, $value: String!) {\n  setUdv(targetType: $targetType, targetId: $targetId, key: $key, value: $value) {\n    key\n    dataType\n    value\n    label\n  }\n}\n    ";
var SetUdvBatchDocument = "\n    mutation setUdvBatch($targetType: UDFTargetType!, $targetId: String!, $udvList: [UserDefinedDataInput!]) {\n  setUdvBatch(targetType: $targetType, targetId: $targetId, udvList: $udvList) {\n    key\n    dataType\n    value\n    label\n  }\n}\n    ";
var UnbindEmailDocument = "\n    mutation unbindEmail {\n  unbindEmail {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var UnbindPhoneDocument = "\n    mutation unbindPhone {\n  unbindPhone {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var UpdateEmailDocument = "\n    mutation updateEmail($email: String!, $emailCode: String!, $oldEmail: String, $oldEmailCode: String) {\n  updateEmail(email: $email, emailCode: $emailCode, oldEmail: $oldEmail, oldEmailCode: $oldEmailCode) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var UpdatePasswordDocument = "\n    mutation updatePassword($newPassword: String!, $oldPassword: String) {\n  updatePassword(newPassword: $newPassword, oldPassword: $oldPassword) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var UpdatePhoneDocument = "\n    mutation updatePhone($phone: String!, $phoneCode: String!, $oldPhone: String, $oldPhoneCode: String, $phoneCountryCode: String, $oldPhoneCountryCode: String) {\n  updatePhone(phone: $phone, phoneCode: $phoneCode, oldPhone: $oldPhone, oldPhoneCode: $oldPhoneCode, phoneCountryCode: $phoneCountryCode, oldPhoneCountryCode: $oldPhoneCountryCode) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    phoneCountryCode\n  }\n}\n    ";
var UpdateUserDocument = "\n    mutation updateUser($id: String, $input: UpdateUserInput!, $emailToken: String, $phoneToken: String) {\n  updateUser(id: $id, input: $input, emailToken: $emailToken, phoneToken: $phoneToken) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    expiredAt\n    directManagement\n  }\n}\n    ";
var CheckLoginStatusDocument = "\n    query checkLoginStatus($token: String) {\n  checkLoginStatus(token: $token) {\n    code\n    message\n    status\n    exp\n    iat\n    data {\n      id\n      userPoolId\n      arn\n    }\n  }\n}\n    ";
var CheckPasswordStrengthDocument = "\n    query checkPasswordStrength($password: String!) {\n  checkPasswordStrength(password: $password) {\n    valid\n    message\n  }\n}\n    ";
var GetUserDepartmentsDocument = "\n    query getUserDepartments($id: String!, $orgId: String) {\n  user(id: $id) {\n    departments(orgId: $orgId) {\n      totalCount\n      list {\n        department {\n          id\n          orgId\n          name\n          nameI18n\n          description\n          descriptionI18n\n          order\n          code\n          root\n          depth\n          path\n          codePath\n          namePath\n          createdAt\n          updatedAt\n          children\n          isVirtualNode\n        }\n        isMainDepartment\n        joinedAt\n      }\n    }\n  }\n}\n    ";
var GetUserRolesDocument = "\n    query getUserRoles($id: String!, $namespace: String) {\n  user(id: $id) {\n    roles(namespace: $namespace) {\n      totalCount\n      list {\n        id\n        code\n        namespace\n        arn\n        description\n        createdAt\n        updatedAt\n        parent {\n          code\n          namespace\n          arn\n          description\n          createdAt\n          updatedAt\n        }\n      }\n    }\n  }\n}\n    ";
var IsUserExistsDocument = "\n    query isUserExists($email: String, $phone: String, $username: String, $externalId: String) {\n  isUserExists(email: $email, phone: $phone, username: $username, externalId: $externalId)\n}\n    ";
var ListUserAuthorizedResourcesDocument = "\n    query listUserAuthorizedResources($id: String!, $namespace: String, $resourceType: String) {\n  user(id: $id) {\n    authorizedResources(namespace: $namespace, resourceType: $resourceType) {\n      totalCount\n      list {\n        code\n        type\n        actions\n        apiIdentifier\n      }\n    }\n  }\n}\n    ";
var UdvDocument = "\n    query udv($targetType: UDFTargetType!, $targetId: String!) {\n  udv(targetType: $targetType, targetId: $targetId) {\n    key\n    dataType\n    value\n    label\n  }\n}\n    ";
var UserDocument = "\n    query user($id: String) {\n  user(id: $id) {\n    id\n    arn\n    userPoolId\n    status\n    username\n    email\n    emailVerified\n    phone\n    phoneVerified\n    identities {\n      openid\n      userIdInIdp\n      userId\n      connectionId\n      isSocial\n      provider\n      type\n      userPoolId\n      extIdpId\n    }\n    unionid\n    openid\n    nickname\n    registerSource\n    photo\n    password\n    oauth\n    token\n    tokenExpiredAt\n    loginsCount\n    lastLogin\n    lastIP\n    signedUp\n    blocked\n    isDeleted\n    device\n    browser\n    company\n    name\n    givenName\n    familyName\n    middleName\n    profile\n    preferredUsername\n    website\n    gender\n    birthdate\n    zoneinfo\n    locale\n    address\n    formatted\n    streetAddress\n    locality\n    region\n    postalCode\n    city\n    province\n    country\n    createdAt\n    updatedAt\n    externalId\n    phoneCountryCode\n    customData {\n      key\n      value\n      dataType\n      label\n    }\n  }\n}\n    ";
var cryptoJs$1 = { exports: {} };
function commonjsRequire$1(path) {
  throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var core$3 = { exports: {} };
var cryptoBrowserify = {};
var browser$g = { exports: {} };
var safeBuffer$1 = { exports: {} };
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
var hasRequiredSafeBuffer$1;
function requireSafeBuffer$1() {
  if (hasRequiredSafeBuffer$1) return safeBuffer$1.exports;
  hasRequiredSafeBuffer$1 = 1;
  (function(module2, exports) {
    var buffer2 = requireBuffer$1();
    var Buffer2 = buffer2.Buffer;
    function copyProps(src2, dst) {
      for (var key2 in src2) {
        dst[key2] = src2[key2];
      }
    }
    if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
      module2.exports = buffer2;
    } else {
      copyProps(buffer2, exports);
      exports.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer2(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer2.prototype);
    copyProps(Buffer2, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer2(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer2(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer2(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer2.SlowBuffer(size);
    };
  })(safeBuffer$1, safeBuffer$1.exports);
  return safeBuffer$1.exports;
}
var hasRequiredBrowser$e;
function requireBrowser$e() {
  if (hasRequiredBrowser$e) return browser$g.exports;
  hasRequiredBrowser$e = 1;
  var MAX_BYTES = 65536;
  var MAX_UINT32 = 4294967295;
  function oldBrowser() {
    throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11");
  }
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var crypto2 = commonjsGlobal$1.crypto || commonjsGlobal$1.msCrypto;
  if (crypto2 && crypto2.getRandomValues) {
    browser$g.exports = randomBytes;
  } else {
    browser$g.exports = oldBrowser;
  }
  function randomBytes(size, cb) {
    if (size > MAX_UINT32) throw new RangeError("requested too many random bytes");
    var bytes = Buffer2.allocUnsafe(size);
    if (size > 0) {
      if (size > MAX_BYTES) {
        for (var generated = 0; generated < size; generated += MAX_BYTES) {
          crypto2.getRandomValues(bytes.slice(generated, generated + MAX_BYTES));
        }
      } else {
        crypto2.getRandomValues(bytes);
      }
    }
    if (typeof cb === "function") {
      return process.nextTick(function() {
        cb(null, bytes);
      });
    }
    return bytes;
  }
  return browser$g.exports;
}
var inherits_browser = { exports: {} };
var hasRequiredInherits_browser;
function requireInherits_browser() {
  if (hasRequiredInherits_browser) return inherits_browser.exports;
  hasRequiredInherits_browser = 1;
  if (typeof Object.create === "function") {
    inherits_browser.exports = function inherits(ctor, superCtor) {
      if (superCtor) {
        ctor.super_ = superCtor;
        ctor.prototype = Object.create(superCtor.prototype, {
          constructor: {
            value: ctor,
            enumerable: false,
            writable: true,
            configurable: true
          }
        });
      }
    };
  } else {
    inherits_browser.exports = function inherits(ctor, superCtor) {
      if (superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {
        };
        TempCtor.prototype = superCtor.prototype;
        ctor.prototype = new TempCtor();
        ctor.prototype.constructor = ctor;
      }
    };
  }
  return inherits_browser.exports;
}
var componentEmitter = { exports: {} };
var hasRequiredComponentEmitter;
function requireComponentEmitter() {
  if (hasRequiredComponentEmitter) return componentEmitter.exports;
  hasRequiredComponentEmitter = 1;
  (function(module2) {
    function Emitter(object) {
      if (object) {
        return mixin(object);
      }
      this._callbacks = /* @__PURE__ */ new Map();
    }
    function mixin(object) {
      Object.assign(object, Emitter.prototype);
      object._callbacks = /* @__PURE__ */ new Map();
      return object;
    }
    Emitter.prototype.on = function(event, listener) {
      const callbacks = this._callbacks.get(event) ?? [];
      callbacks.push(listener);
      this._callbacks.set(event, callbacks);
      return this;
    };
    Emitter.prototype.once = function(event, listener) {
      const on = (...arguments_) => {
        this.off(event, on);
        listener.apply(this, arguments_);
      };
      on.fn = listener;
      this.on(event, on);
      return this;
    };
    Emitter.prototype.off = function(event, listener) {
      if (event === void 0 && listener === void 0) {
        this._callbacks.clear();
        return this;
      }
      if (listener === void 0) {
        this._callbacks.delete(event);
        return this;
      }
      const callbacks = this._callbacks.get(event);
      if (callbacks) {
        for (const [index2, callback] of callbacks.entries()) {
          if (callback === listener || callback.fn === listener) {
            callbacks.splice(index2, 1);
            break;
          }
        }
        if (callbacks.length === 0) {
          this._callbacks.delete(event);
        } else {
          this._callbacks.set(event, callbacks);
        }
      }
      return this;
    };
    Emitter.prototype.emit = function(event, ...arguments_) {
      const callbacks = this._callbacks.get(event);
      if (callbacks) {
        const callbacksCopy = [...callbacks];
        for (const callback of callbacksCopy) {
          callback.apply(this, arguments_);
        }
      }
      return this;
    };
    Emitter.prototype.listeners = function(event) {
      return this._callbacks.get(event) ?? [];
    };
    Emitter.prototype.listenerCount = function(event) {
      if (event) {
        return this.listeners(event).length;
      }
      let totalCount = 0;
      for (const callbacks of this._callbacks.values()) {
        totalCount += callbacks.length;
      }
      return totalCount;
    };
    Emitter.prototype.hasListeners = function(event) {
      return this.listenerCount(event) > 0;
    };
    Emitter.prototype.addEventListener = Emitter.prototype.on;
    Emitter.prototype.removeListener = Emitter.prototype.off;
    Emitter.prototype.removeEventListener = Emitter.prototype.off;
    Emitter.prototype.removeAllListeners = Emitter.prototype.off;
    {
      module2.exports = Emitter;
    }
  })(componentEmitter);
  return componentEmitter.exports;
}
var stream$1;
var hasRequiredStream;
function requireStream() {
  if (hasRequiredStream) return stream$1;
  hasRequiredStream = 1;
  var Emitter = /* @__PURE__ */ requireComponentEmitter();
  function Stream2() {
    Emitter.call(this);
  }
  Stream2.prototype = new Emitter();
  stream$1 = Stream2;
  Stream2.Stream = Stream2;
  Stream2.prototype.pipe = function(dest, options2) {
    var source = this;
    function ondata(chunk) {
      if (dest.writable) {
        if (false === dest.write(chunk) && source.pause) {
          source.pause();
        }
      }
    }
    source.on("data", ondata);
    function ondrain() {
      if (source.readable && source.resume) {
        source.resume();
      }
    }
    dest.on("drain", ondrain);
    if (!dest._isStdio && (!options2 || options2.end !== false)) {
      source.on("end", onend);
      source.on("close", onclose);
    }
    var didOnEnd = false;
    function onend() {
      if (didOnEnd) return;
      didOnEnd = true;
      dest.end();
    }
    function onclose() {
      if (didOnEnd) return;
      didOnEnd = true;
      if (typeof dest.destroy === "function") dest.destroy();
    }
    function onerror(er) {
      cleanup();
      if (!this.hasListeners("error")) {
        throw er;
      }
    }
    source.on("error", onerror);
    dest.on("error", onerror);
    function cleanup() {
      source.off("data", ondata);
      dest.off("drain", ondrain);
      source.off("end", onend);
      source.off("close", onclose);
      source.off("error", onerror);
      dest.off("error", onerror);
      source.off("end", cleanup);
      source.off("close", cleanup);
      dest.off("end", cleanup);
      dest.off("close", cleanup);
    }
    source.on("end", cleanup);
    source.on("close", cleanup);
    dest.on("end", cleanup);
    dest.on("close", cleanup);
    dest.emit("pipe", source);
    return dest;
  };
  return stream$1;
}
var hashBase$1;
var hasRequiredHashBase$1;
function requireHashBase$1() {
  if (hasRequiredHashBase$1) return hashBase$1;
  hasRequiredHashBase$1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var Transform = requireStream().Transform;
  var inherits = requireInherits_browser();
  function HashBase(blockSize) {
    Transform.call(this);
    this._block = Buffer2.allocUnsafe(blockSize);
    this._blockSize = blockSize;
    this._blockOffset = 0;
    this._length = [0, 0, 0, 0];
    this._finalized = false;
  }
  inherits(HashBase, Transform);
  HashBase.prototype._transform = function(chunk, encoding, callback) {
    var error = null;
    try {
      this.update(chunk, encoding);
    } catch (err) {
      error = err;
    }
    callback(error);
  };
  HashBase.prototype._flush = function(callback) {
    var error = null;
    try {
      this.push(this.digest());
    } catch (err) {
      error = err;
    }
    callback(error);
  };
  var useUint8Array = typeof Uint8Array !== "undefined";
  var useArrayBuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined" && ArrayBuffer.isView && (Buffer2.prototype instanceof Uint8Array || Buffer2.TYPED_ARRAY_SUPPORT);
  function toBuffer2(data2, encoding) {
    if (data2 instanceof Buffer2) return data2;
    if (typeof data2 === "string") return Buffer2.from(data2, encoding);
    if (useArrayBuffer && ArrayBuffer.isView(data2)) {
      if (data2.byteLength === 0) return Buffer2.alloc(0);
      var res = Buffer2.from(data2.buffer, data2.byteOffset, data2.byteLength);
      if (res.byteLength === data2.byteLength) return res;
    }
    if (useUint8Array && data2 instanceof Uint8Array) return Buffer2.from(data2);
    if (Buffer2.isBuffer(data2) && data2.constructor && typeof data2.constructor.isBuffer === "function" && data2.constructor.isBuffer(data2)) {
      return Buffer2.from(data2);
    }
    throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.');
  }
  HashBase.prototype.update = function(data2, encoding) {
    if (this._finalized) throw new Error("Digest already called");
    data2 = toBuffer2(data2, encoding);
    var block = this._block;
    var offset = 0;
    while (this._blockOffset + data2.length - offset >= this._blockSize) {
      for (var i2 = this._blockOffset; i2 < this._blockSize; ) block[i2++] = data2[offset++];
      this._update();
      this._blockOffset = 0;
    }
    while (offset < data2.length) block[this._blockOffset++] = data2[offset++];
    for (var j = 0, carry = data2.length * 8; carry > 0; ++j) {
      this._length[j] += carry;
      carry = this._length[j] / 4294967296 | 0;
      if (carry > 0) this._length[j] -= 4294967296 * carry;
    }
    return this;
  };
  HashBase.prototype._update = function() {
    throw new Error("_update is not implemented");
  };
  HashBase.prototype.digest = function(encoding) {
    if (this._finalized) throw new Error("Digest already called");
    this._finalized = true;
    var digest = this._digest();
    if (encoding !== void 0) digest = digest.toString(encoding);
    this._block.fill(0);
    this._blockOffset = 0;
    for (var i2 = 0; i2 < 4; ++i2) this._length[i2] = 0;
    return digest;
  };
  HashBase.prototype._digest = function() {
    throw new Error("_digest is not implemented");
  };
  hashBase$1 = HashBase;
  return hashBase$1;
}
var md5_js;
var hasRequiredMd5_js;
function requireMd5_js() {
  if (hasRequiredMd5_js) return md5_js;
  hasRequiredMd5_js = 1;
  var inherits = requireInherits_browser();
  var HashBase = requireHashBase$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var ARRAY16 = new Array(16);
  function MD5() {
    HashBase.call(this, 64);
    this._a = 1732584193;
    this._b = 4023233417;
    this._c = 2562383102;
    this._d = 271733878;
  }
  inherits(MD5, HashBase);
  MD5.prototype._update = function() {
    var M2 = ARRAY16;
    for (var i2 = 0; i2 < 16; ++i2) M2[i2] = this._block.readInt32LE(i2 * 4);
    var a2 = this._a;
    var b2 = this._b;
    var c2 = this._c;
    var d = this._d;
    a2 = fnF(a2, b2, c2, d, M2[0], 3614090360, 7);
    d = fnF(d, a2, b2, c2, M2[1], 3905402710, 12);
    c2 = fnF(c2, d, a2, b2, M2[2], 606105819, 17);
    b2 = fnF(b2, c2, d, a2, M2[3], 3250441966, 22);
    a2 = fnF(a2, b2, c2, d, M2[4], 4118548399, 7);
    d = fnF(d, a2, b2, c2, M2[5], 1200080426, 12);
    c2 = fnF(c2, d, a2, b2, M2[6], 2821735955, 17);
    b2 = fnF(b2, c2, d, a2, M2[7], 4249261313, 22);
    a2 = fnF(a2, b2, c2, d, M2[8], 1770035416, 7);
    d = fnF(d, a2, b2, c2, M2[9], 2336552879, 12);
    c2 = fnF(c2, d, a2, b2, M2[10], 4294925233, 17);
    b2 = fnF(b2, c2, d, a2, M2[11], 2304563134, 22);
    a2 = fnF(a2, b2, c2, d, M2[12], 1804603682, 7);
    d = fnF(d, a2, b2, c2, M2[13], 4254626195, 12);
    c2 = fnF(c2, d, a2, b2, M2[14], 2792965006, 17);
    b2 = fnF(b2, c2, d, a2, M2[15], 1236535329, 22);
    a2 = fnG(a2, b2, c2, d, M2[1], 4129170786, 5);
    d = fnG(d, a2, b2, c2, M2[6], 3225465664, 9);
    c2 = fnG(c2, d, a2, b2, M2[11], 643717713, 14);
    b2 = fnG(b2, c2, d, a2, M2[0], 3921069994, 20);
    a2 = fnG(a2, b2, c2, d, M2[5], 3593408605, 5);
    d = fnG(d, a2, b2, c2, M2[10], 38016083, 9);
    c2 = fnG(c2, d, a2, b2, M2[15], 3634488961, 14);
    b2 = fnG(b2, c2, d, a2, M2[4], 3889429448, 20);
    a2 = fnG(a2, b2, c2, d, M2[9], 568446438, 5);
    d = fnG(d, a2, b2, c2, M2[14], 3275163606, 9);
    c2 = fnG(c2, d, a2, b2, M2[3], 4107603335, 14);
    b2 = fnG(b2, c2, d, a2, M2[8], 1163531501, 20);
    a2 = fnG(a2, b2, c2, d, M2[13], 2850285829, 5);
    d = fnG(d, a2, b2, c2, M2[2], 4243563512, 9);
    c2 = fnG(c2, d, a2, b2, M2[7], 1735328473, 14);
    b2 = fnG(b2, c2, d, a2, M2[12], 2368359562, 20);
    a2 = fnH(a2, b2, c2, d, M2[5], 4294588738, 4);
    d = fnH(d, a2, b2, c2, M2[8], 2272392833, 11);
    c2 = fnH(c2, d, a2, b2, M2[11], 1839030562, 16);
    b2 = fnH(b2, c2, d, a2, M2[14], 4259657740, 23);
    a2 = fnH(a2, b2, c2, d, M2[1], 2763975236, 4);
    d = fnH(d, a2, b2, c2, M2[4], 1272893353, 11);
    c2 = fnH(c2, d, a2, b2, M2[7], 4139469664, 16);
    b2 = fnH(b2, c2, d, a2, M2[10], 3200236656, 23);
    a2 = fnH(a2, b2, c2, d, M2[13], 681279174, 4);
    d = fnH(d, a2, b2, c2, M2[0], 3936430074, 11);
    c2 = fnH(c2, d, a2, b2, M2[3], 3572445317, 16);
    b2 = fnH(b2, c2, d, a2, M2[6], 76029189, 23);
    a2 = fnH(a2, b2, c2, d, M2[9], 3654602809, 4);
    d = fnH(d, a2, b2, c2, M2[12], 3873151461, 11);
    c2 = fnH(c2, d, a2, b2, M2[15], 530742520, 16);
    b2 = fnH(b2, c2, d, a2, M2[2], 3299628645, 23);
    a2 = fnI(a2, b2, c2, d, M2[0], 4096336452, 6);
    d = fnI(d, a2, b2, c2, M2[7], 1126891415, 10);
    c2 = fnI(c2, d, a2, b2, M2[14], 2878612391, 15);
    b2 = fnI(b2, c2, d, a2, M2[5], 4237533241, 21);
    a2 = fnI(a2, b2, c2, d, M2[12], 1700485571, 6);
    d = fnI(d, a2, b2, c2, M2[3], 2399980690, 10);
    c2 = fnI(c2, d, a2, b2, M2[10], 4293915773, 15);
    b2 = fnI(b2, c2, d, a2, M2[1], 2240044497, 21);
    a2 = fnI(a2, b2, c2, d, M2[8], 1873313359, 6);
    d = fnI(d, a2, b2, c2, M2[15], 4264355552, 10);
    c2 = fnI(c2, d, a2, b2, M2[6], 2734768916, 15);
    b2 = fnI(b2, c2, d, a2, M2[13], 1309151649, 21);
    a2 = fnI(a2, b2, c2, d, M2[4], 4149444226, 6);
    d = fnI(d, a2, b2, c2, M2[11], 3174756917, 10);
    c2 = fnI(c2, d, a2, b2, M2[2], 718787259, 15);
    b2 = fnI(b2, c2, d, a2, M2[9], 3951481745, 21);
    this._a = this._a + a2 | 0;
    this._b = this._b + b2 | 0;
    this._c = this._c + c2 | 0;
    this._d = this._d + d | 0;
  };
  MD5.prototype._digest = function() {
    this._block[this._blockOffset++] = 128;
    if (this._blockOffset > 56) {
      this._block.fill(0, this._blockOffset, 64);
      this._update();
      this._blockOffset = 0;
    }
    this._block.fill(0, this._blockOffset, 56);
    this._block.writeUInt32LE(this._length[0], 56);
    this._block.writeUInt32LE(this._length[1], 60);
    this._update();
    var buffer2 = Buffer2.allocUnsafe(16);
    buffer2.writeInt32LE(this._a, 0);
    buffer2.writeInt32LE(this._b, 4);
    buffer2.writeInt32LE(this._c, 8);
    buffer2.writeInt32LE(this._d, 12);
    return buffer2;
  };
  function rotl2(x2, n2) {
    return x2 << n2 | x2 >>> 32 - n2;
  }
  function fnF(a2, b2, c2, d, m, k2, s2) {
    return rotl2(a2 + (b2 & c2 | ~b2 & d) + m + k2 | 0, s2) + b2 | 0;
  }
  function fnG(a2, b2, c2, d, m, k2, s2) {
    return rotl2(a2 + (b2 & d | c2 & ~d) + m + k2 | 0, s2) + b2 | 0;
  }
  function fnH(a2, b2, c2, d, m, k2, s2) {
    return rotl2(a2 + (b2 ^ c2 ^ d) + m + k2 | 0, s2) + b2 | 0;
  }
  function fnI(a2, b2, c2, d, m, k2, s2) {
    return rotl2(a2 + (c2 ^ (b2 | ~d)) + m + k2 | 0, s2) + b2 | 0;
  }
  md5_js = MD5;
  return md5_js;
}
var isarray$1;
var hasRequiredIsarray$1;
function requireIsarray$1() {
  if (hasRequiredIsarray$1) return isarray$1;
  hasRequiredIsarray$1 = 1;
  var toString2 = {}.toString;
  isarray$1 = Array.isArray || function(arr) {
    return toString2.call(arr) == "[object Array]";
  };
  return isarray$1;
}
var type$2;
var hasRequiredType;
function requireType() {
  if (hasRequiredType) return type$2;
  hasRequiredType = 1;
  type$2 = TypeError;
  return type$2;
}
var esObjectAtoms;
var hasRequiredEsObjectAtoms;
function requireEsObjectAtoms() {
  if (hasRequiredEsObjectAtoms) return esObjectAtoms;
  hasRequiredEsObjectAtoms = 1;
  esObjectAtoms = Object;
  return esObjectAtoms;
}
var esErrors;
var hasRequiredEsErrors;
function requireEsErrors() {
  if (hasRequiredEsErrors) return esErrors;
  hasRequiredEsErrors = 1;
  esErrors = Error;
  return esErrors;
}
var _eval;
var hasRequired_eval;
function require_eval() {
  if (hasRequired_eval) return _eval;
  hasRequired_eval = 1;
  _eval = EvalError;
  return _eval;
}
var range;
var hasRequiredRange;
function requireRange() {
  if (hasRequiredRange) return range;
  hasRequiredRange = 1;
  range = RangeError;
  return range;
}
var ref$1;
var hasRequiredRef$1;
function requireRef$1() {
  if (hasRequiredRef$1) return ref$1;
  hasRequiredRef$1 = 1;
  ref$1 = ReferenceError;
  return ref$1;
}
var syntax;
var hasRequiredSyntax;
function requireSyntax() {
  if (hasRequiredSyntax) return syntax;
  hasRequiredSyntax = 1;
  syntax = SyntaxError;
  return syntax;
}
var uri;
var hasRequiredUri;
function requireUri() {
  if (hasRequiredUri) return uri;
  hasRequiredUri = 1;
  uri = URIError;
  return uri;
}
var abs;
var hasRequiredAbs;
function requireAbs() {
  if (hasRequiredAbs) return abs;
  hasRequiredAbs = 1;
  abs = Math.abs;
  return abs;
}
var floor;
var hasRequiredFloor;
function requireFloor() {
  if (hasRequiredFloor) return floor;
  hasRequiredFloor = 1;
  floor = Math.floor;
  return floor;
}
var max$1;
var hasRequiredMax;
function requireMax() {
  if (hasRequiredMax) return max$1;
  hasRequiredMax = 1;
  max$1 = Math.max;
  return max$1;
}
var min;
var hasRequiredMin;
function requireMin() {
  if (hasRequiredMin) return min;
  hasRequiredMin = 1;
  min = Math.min;
  return min;
}
var pow;
var hasRequiredPow;
function requirePow() {
  if (hasRequiredPow) return pow;
  hasRequiredPow = 1;
  pow = Math.pow;
  return pow;
}
var round$1;
var hasRequiredRound;
function requireRound() {
  if (hasRequiredRound) return round$1;
  hasRequiredRound = 1;
  round$1 = Math.round;
  return round$1;
}
var _isNaN;
var hasRequired_isNaN;
function require_isNaN() {
  if (hasRequired_isNaN) return _isNaN;
  hasRequired_isNaN = 1;
  _isNaN = Number.isNaN || function isNaN2(a2) {
    return a2 !== a2;
  };
  return _isNaN;
}
var sign$1;
var hasRequiredSign$1;
function requireSign$1() {
  if (hasRequiredSign$1) return sign$1;
  hasRequiredSign$1 = 1;
  var $isNaN = /* @__PURE__ */ require_isNaN();
  sign$1 = function sign2(number) {
    if ($isNaN(number) || number === 0) {
      return number;
    }
    return number < 0 ? -1 : 1;
  };
  return sign$1;
}
var gOPD;
var hasRequiredGOPD;
function requireGOPD() {
  if (hasRequiredGOPD) return gOPD;
  hasRequiredGOPD = 1;
  gOPD = Object.getOwnPropertyDescriptor;
  return gOPD;
}
var gopd;
var hasRequiredGopd;
function requireGopd() {
  if (hasRequiredGopd) return gopd;
  hasRequiredGopd = 1;
  var $gOPD = /* @__PURE__ */ requireGOPD();
  if ($gOPD) {
    try {
      $gOPD([], "length");
    } catch (e4) {
      $gOPD = null;
    }
  }
  gopd = $gOPD;
  return gopd;
}
var esDefineProperty;
var hasRequiredEsDefineProperty;
function requireEsDefineProperty() {
  if (hasRequiredEsDefineProperty) return esDefineProperty;
  hasRequiredEsDefineProperty = 1;
  var $defineProperty = Object.defineProperty || false;
  if ($defineProperty) {
    try {
      $defineProperty({}, "a", { value: 1 });
    } catch (e4) {
      $defineProperty = false;
    }
  }
  esDefineProperty = $defineProperty;
  return esDefineProperty;
}
var shams$1;
var hasRequiredShams$1;
function requireShams$1() {
  if (hasRequiredShams$1) return shams$1;
  hasRequiredShams$1 = 1;
  shams$1 = function hasSymbols2() {
    if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
      return false;
    }
    if (typeof Symbol.iterator === "symbol") {
      return true;
    }
    var obj = {};
    var sym = Symbol("test");
    var symObj = Object(sym);
    if (typeof sym === "string") {
      return false;
    }
    if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
      return false;
    }
    if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
      return false;
    }
    var symVal = 42;
    obj[sym] = symVal;
    for (var _2 in obj) {
      return false;
    }
    if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
      return false;
    }
    if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
      return false;
    }
    var syms = Object.getOwnPropertySymbols(obj);
    if (syms.length !== 1 || syms[0] !== sym) {
      return false;
    }
    if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
      return false;
    }
    if (typeof Object.getOwnPropertyDescriptor === "function") {
      var descriptor = (
        /** @type {PropertyDescriptor} */
        Object.getOwnPropertyDescriptor(obj, sym)
      );
      if (descriptor.value !== symVal || descriptor.enumerable !== true) {
        return false;
      }
    }
    return true;
  };
  return shams$1;
}
var hasSymbols;
var hasRequiredHasSymbols;
function requireHasSymbols() {
  if (hasRequiredHasSymbols) return hasSymbols;
  hasRequiredHasSymbols = 1;
  var origSymbol = typeof Symbol !== "undefined" && Symbol;
  var hasSymbolSham = requireShams$1();
  hasSymbols = function hasNativeSymbols() {
    if (typeof origSymbol !== "function") {
      return false;
    }
    if (typeof Symbol !== "function") {
      return false;
    }
    if (typeof origSymbol("foo") !== "symbol") {
      return false;
    }
    if (typeof Symbol("bar") !== "symbol") {
      return false;
    }
    return hasSymbolSham();
  };
  return hasSymbols;
}
var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;
function requireReflect_getPrototypeOf() {
  if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
  hasRequiredReflect_getPrototypeOf = 1;
  Reflect_getPrototypeOf = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  return Reflect_getPrototypeOf;
}
var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;
function requireObject_getPrototypeOf() {
  if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
  hasRequiredObject_getPrototypeOf = 1;
  var $Object = /* @__PURE__ */ requireEsObjectAtoms();
  Object_getPrototypeOf = $Object.getPrototypeOf || null;
  return Object_getPrototypeOf;
}
var implementation;
var hasRequiredImplementation;
function requireImplementation() {
  if (hasRequiredImplementation) return implementation;
  hasRequiredImplementation = 1;
  var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
  var toStr = Object.prototype.toString;
  var max2 = Math.max;
  var funcType = "[object Function]";
  var concatty = function concatty2(a2, b2) {
    var arr = [];
    for (var i2 = 0; i2 < a2.length; i2 += 1) {
      arr[i2] = a2[i2];
    }
    for (var j = 0; j < b2.length; j += 1) {
      arr[j + a2.length] = b2[j];
    }
    return arr;
  };
  var slicy = function slicy2(arrLike, offset) {
    var arr = [];
    for (var i2 = offset, j = 0; i2 < arrLike.length; i2 += 1, j += 1) {
      arr[j] = arrLike[i2];
    }
    return arr;
  };
  var joiny = function(arr, joiner) {
    var str = "";
    for (var i2 = 0; i2 < arr.length; i2 += 1) {
      str += arr[i2];
      if (i2 + 1 < arr.length) {
        str += joiner;
      }
    }
    return str;
  };
  implementation = function bind2(that) {
    var target = this;
    if (typeof target !== "function" || toStr.apply(target) !== funcType) {
      throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slicy(arguments, 1);
    var bound;
    var binder = function() {
      if (this instanceof bound) {
        var result = target.apply(
          this,
          concatty(args, arguments)
        );
        if (Object(result) === result) {
          return result;
        }
        return this;
      }
      return target.apply(
        that,
        concatty(args, arguments)
      );
    };
    var boundLength = max2(0, target.length - args.length);
    var boundArgs = [];
    for (var i2 = 0; i2 < boundLength; i2++) {
      boundArgs[i2] = "$" + i2;
    }
    bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
    if (target.prototype) {
      var Empty = function Empty2() {
      };
      Empty.prototype = target.prototype;
      bound.prototype = new Empty();
      Empty.prototype = null;
    }
    return bound;
  };
  return implementation;
}
var functionBind;
var hasRequiredFunctionBind;
function requireFunctionBind() {
  if (hasRequiredFunctionBind) return functionBind;
  hasRequiredFunctionBind = 1;
  var implementation2 = requireImplementation();
  functionBind = Function.prototype.bind || implementation2;
  return functionBind;
}
var functionCall;
var hasRequiredFunctionCall;
function requireFunctionCall() {
  if (hasRequiredFunctionCall) return functionCall;
  hasRequiredFunctionCall = 1;
  functionCall = Function.prototype.call;
  return functionCall;
}
var functionApply;
var hasRequiredFunctionApply;
function requireFunctionApply() {
  if (hasRequiredFunctionApply) return functionApply;
  hasRequiredFunctionApply = 1;
  functionApply = Function.prototype.apply;
  return functionApply;
}
var reflectApply;
var hasRequiredReflectApply;
function requireReflectApply() {
  if (hasRequiredReflectApply) return reflectApply;
  hasRequiredReflectApply = 1;
  reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  return reflectApply;
}
var actualApply;
var hasRequiredActualApply;
function requireActualApply() {
  if (hasRequiredActualApply) return actualApply;
  hasRequiredActualApply = 1;
  var bind2 = requireFunctionBind();
  var $apply = requireFunctionApply();
  var $call = requireFunctionCall();
  var $reflectApply = requireReflectApply();
  actualApply = $reflectApply || bind2.call($call, $apply);
  return actualApply;
}
var callBindApplyHelpers;
var hasRequiredCallBindApplyHelpers;
function requireCallBindApplyHelpers() {
  if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
  hasRequiredCallBindApplyHelpers = 1;
  var bind2 = requireFunctionBind();
  var $TypeError = /* @__PURE__ */ requireType();
  var $call = requireFunctionCall();
  var $actualApply = requireActualApply();
  callBindApplyHelpers = function callBindBasic(args) {
    if (args.length < 1 || typeof args[0] !== "function") {
      throw new $TypeError("a function is required");
    }
    return $actualApply(bind2, $call, args);
  };
  return callBindApplyHelpers;
}
var get$1;
var hasRequiredGet;
function requireGet() {
  if (hasRequiredGet) return get$1;
  hasRequiredGet = 1;
  var callBind2 = requireCallBindApplyHelpers();
  var gOPD2 = /* @__PURE__ */ requireGopd();
  var hasProtoAccessor;
  try {
    hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
    [].__proto__ === Array.prototype;
  } catch (e4) {
    if (!e4 || typeof e4 !== "object" || !("code" in e4) || e4.code !== "ERR_PROTO_ACCESS") {
      throw e4;
    }
  }
  var desc = !!hasProtoAccessor && gOPD2 && gOPD2(
    Object.prototype,
    /** @type {keyof typeof Object.prototype} */
    "__proto__"
  );
  var $Object = Object;
  var $getPrototypeOf = $Object.getPrototypeOf;
  get$1 = desc && typeof desc.get === "function" ? callBind2([desc.get]) : typeof $getPrototypeOf === "function" ? (
    /** @type {import('./get')} */
    function getDunder(value) {
      return $getPrototypeOf(value == null ? value : $Object(value));
    }
  ) : false;
  return get$1;
}
var getProto;
var hasRequiredGetProto;
function requireGetProto() {
  if (hasRequiredGetProto) return getProto;
  hasRequiredGetProto = 1;
  var reflectGetProto = requireReflect_getPrototypeOf();
  var originalGetProto = requireObject_getPrototypeOf();
  var getDunderProto = /* @__PURE__ */ requireGet();
  getProto = reflectGetProto ? function getProto2(O2) {
    return reflectGetProto(O2);
  } : originalGetProto ? function getProto2(O2) {
    if (!O2 || typeof O2 !== "object" && typeof O2 !== "function") {
      throw new TypeError("getProto: not an object");
    }
    return originalGetProto(O2);
  } : getDunderProto ? function getProto2(O2) {
    return getDunderProto(O2);
  } : null;
  return getProto;
}
var hasown;
var hasRequiredHasown;
function requireHasown() {
  if (hasRequiredHasown) return hasown;
  hasRequiredHasown = 1;
  var call = Function.prototype.call;
  var $hasOwn = Object.prototype.hasOwnProperty;
  var bind2 = requireFunctionBind();
  hasown = bind2.call(call, $hasOwn);
  return hasown;
}
var getIntrinsic;
var hasRequiredGetIntrinsic;
function requireGetIntrinsic() {
  if (hasRequiredGetIntrinsic) return getIntrinsic;
  hasRequiredGetIntrinsic = 1;
  var undefined$1;
  var $Object = /* @__PURE__ */ requireEsObjectAtoms();
  var $Error = /* @__PURE__ */ requireEsErrors();
  var $EvalError = /* @__PURE__ */ require_eval();
  var $RangeError = /* @__PURE__ */ requireRange();
  var $ReferenceError = /* @__PURE__ */ requireRef$1();
  var $SyntaxError = /* @__PURE__ */ requireSyntax();
  var $TypeError = /* @__PURE__ */ requireType();
  var $URIError = /* @__PURE__ */ requireUri();
  var abs2 = /* @__PURE__ */ requireAbs();
  var floor2 = /* @__PURE__ */ requireFloor();
  var max2 = /* @__PURE__ */ requireMax();
  var min2 = /* @__PURE__ */ requireMin();
  var pow2 = /* @__PURE__ */ requirePow();
  var round2 = /* @__PURE__ */ requireRound();
  var sign2 = /* @__PURE__ */ requireSign$1();
  var $Function = Function;
  var getEvalledConstructor = function(expressionSyntax) {
    try {
      return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
    } catch (e4) {
    }
  };
  var $gOPD = /* @__PURE__ */ requireGopd();
  var $defineProperty = /* @__PURE__ */ requireEsDefineProperty();
  var throwTypeError = function() {
    throw new $TypeError();
  };
  var ThrowTypeError = $gOPD ? function() {
    try {
      arguments.callee;
      return throwTypeError;
    } catch (calleeThrows) {
      try {
        return $gOPD(arguments, "callee").get;
      } catch (gOPDthrows) {
        return throwTypeError;
      }
    }
  }() : throwTypeError;
  var hasSymbols2 = requireHasSymbols()();
  var getProto2 = requireGetProto();
  var $ObjectGPO = requireObject_getPrototypeOf();
  var $ReflectGPO = requireReflect_getPrototypeOf();
  var $apply = requireFunctionApply();
  var $call = requireFunctionCall();
  var needsEval = {};
  var TypedArray = typeof Uint8Array === "undefined" || !getProto2 ? undefined$1 : getProto2(Uint8Array);
  var INTRINSICS = {
    __proto__: null,
    "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError,
    "%Array%": Array,
    "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer,
    "%ArrayIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2([][Symbol.iterator]()) : undefined$1,
    "%AsyncFromSyncIteratorPrototype%": undefined$1,
    "%AsyncFunction%": needsEval,
    "%AsyncGenerator%": needsEval,
    "%AsyncGeneratorFunction%": needsEval,
    "%AsyncIteratorPrototype%": needsEval,
    "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics,
    "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt,
    "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array,
    "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array,
    "%Boolean%": Boolean,
    "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView,
    "%Date%": Date,
    "%decodeURI%": decodeURI,
    "%decodeURIComponent%": decodeURIComponent,
    "%encodeURI%": encodeURI,
    "%encodeURIComponent%": encodeURIComponent,
    "%Error%": $Error,
    "%eval%": eval,
    // eslint-disable-line no-eval
    "%EvalError%": $EvalError,
    "%Float16Array%": typeof Float16Array === "undefined" ? undefined$1 : Float16Array,
    "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array,
    "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array,
    "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry,
    "%Function%": $Function,
    "%GeneratorFunction%": needsEval,
    "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array,
    "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array,
    "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array,
    "%isFinite%": isFinite,
    "%isNaN%": isNaN,
    "%IteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1,
    "%JSON%": typeof JSON === "object" ? JSON : undefined$1,
    "%Map%": typeof Map === "undefined" ? undefined$1 : Map,
    "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
    "%Math%": Math,
    "%Number%": Number,
    "%Object%": $Object,
    "%Object.getOwnPropertyDescriptor%": $gOPD,
    "%parseFloat%": parseFloat,
    "%parseInt%": parseInt,
    "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise,
    "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy,
    "%RangeError%": $RangeError,
    "%ReferenceError%": $ReferenceError,
    "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect,
    "%RegExp%": RegExp,
    "%Set%": typeof Set === "undefined" ? undefined$1 : Set,
    "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
    "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer,
    "%String%": String,
    "%StringIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(""[Symbol.iterator]()) : undefined$1,
    "%Symbol%": hasSymbols2 ? Symbol : undefined$1,
    "%SyntaxError%": $SyntaxError,
    "%ThrowTypeError%": ThrowTypeError,
    "%TypedArray%": TypedArray,
    "%TypeError%": $TypeError,
    "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array,
    "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray,
    "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array,
    "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array,
    "%URIError%": $URIError,
    "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap,
    "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef,
    "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet,
    "%Function.prototype.call%": $call,
    "%Function.prototype.apply%": $apply,
    "%Object.defineProperty%": $defineProperty,
    "%Object.getPrototypeOf%": $ObjectGPO,
    "%Math.abs%": abs2,
    "%Math.floor%": floor2,
    "%Math.max%": max2,
    "%Math.min%": min2,
    "%Math.pow%": pow2,
    "%Math.round%": round2,
    "%Math.sign%": sign2,
    "%Reflect.getPrototypeOf%": $ReflectGPO
  };
  if (getProto2) {
    try {
      null.error;
    } catch (e4) {
      var errorProto = getProto2(getProto2(e4));
      INTRINSICS["%Error.prototype%"] = errorProto;
    }
  }
  var doEval = function doEval2(name) {
    var value;
    if (name === "%AsyncFunction%") {
      value = getEvalledConstructor("async function () {}");
    } else if (name === "%GeneratorFunction%") {
      value = getEvalledConstructor("function* () {}");
    } else if (name === "%AsyncGeneratorFunction%") {
      value = getEvalledConstructor("async function* () {}");
    } else if (name === "%AsyncGenerator%") {
      var fn = doEval2("%AsyncGeneratorFunction%");
      if (fn) {
        value = fn.prototype;
      }
    } else if (name === "%AsyncIteratorPrototype%") {
      var gen = doEval2("%AsyncGenerator%");
      if (gen && getProto2) {
        value = getProto2(gen.prototype);
      }
    }
    INTRINSICS[name] = value;
    return value;
  };
  var LEGACY_ALIASES = {
    __proto__: null,
    "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
    "%ArrayPrototype%": ["Array", "prototype"],
    "%ArrayProto_entries%": ["Array", "prototype", "entries"],
    "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
    "%ArrayProto_keys%": ["Array", "prototype", "keys"],
    "%ArrayProto_values%": ["Array", "prototype", "values"],
    "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
    "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
    "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
    "%BooleanPrototype%": ["Boolean", "prototype"],
    "%DataViewPrototype%": ["DataView", "prototype"],
    "%DatePrototype%": ["Date", "prototype"],
    "%ErrorPrototype%": ["Error", "prototype"],
    "%EvalErrorPrototype%": ["EvalError", "prototype"],
    "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
    "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
    "%FunctionPrototype%": ["Function", "prototype"],
    "%Generator%": ["GeneratorFunction", "prototype"],
    "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
    "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
    "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
    "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
    "%JSONParse%": ["JSON", "parse"],
    "%JSONStringify%": ["JSON", "stringify"],
    "%MapPrototype%": ["Map", "prototype"],
    "%NumberPrototype%": ["Number", "prototype"],
    "%ObjectPrototype%": ["Object", "prototype"],
    "%ObjProto_toString%": ["Object", "prototype", "toString"],
    "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
    "%PromisePrototype%": ["Promise", "prototype"],
    "%PromiseProto_then%": ["Promise", "prototype", "then"],
    "%Promise_all%": ["Promise", "all"],
    "%Promise_reject%": ["Promise", "reject"],
    "%Promise_resolve%": ["Promise", "resolve"],
    "%RangeErrorPrototype%": ["RangeError", "prototype"],
    "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
    "%RegExpPrototype%": ["RegExp", "prototype"],
    "%SetPrototype%": ["Set", "prototype"],
    "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
    "%StringPrototype%": ["String", "prototype"],
    "%SymbolPrototype%": ["Symbol", "prototype"],
    "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
    "%TypedArrayPrototype%": ["TypedArray", "prototype"],
    "%TypeErrorPrototype%": ["TypeError", "prototype"],
    "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
    "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
    "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
    "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
    "%URIErrorPrototype%": ["URIError", "prototype"],
    "%WeakMapPrototype%": ["WeakMap", "prototype"],
    "%WeakSetPrototype%": ["WeakSet", "prototype"]
  };
  var bind2 = requireFunctionBind();
  var hasOwn2 = /* @__PURE__ */ requireHasown();
  var $concat = bind2.call($call, Array.prototype.concat);
  var $spliceApply = bind2.call($apply, Array.prototype.splice);
  var $replace = bind2.call($call, String.prototype.replace);
  var $strSlice = bind2.call($call, String.prototype.slice);
  var $exec = bind2.call($call, RegExp.prototype.exec);
  var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
  var reEscapeChar = /\\(\\)?/g;
  var stringToPath = function stringToPath2(string) {
    var first = $strSlice(string, 0, 1);
    var last = $strSlice(string, -1);
    if (first === "%" && last !== "%") {
      throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
    } else if (last === "%" && first !== "%") {
      throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
    }
    var result = [];
    $replace(string, rePropName, function(match, number, quote, subString) {
      result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
    });
    return result;
  };
  var getBaseIntrinsic = function getBaseIntrinsic2(name, allowMissing) {
    var intrinsicName = name;
    var alias;
    if (hasOwn2(LEGACY_ALIASES, intrinsicName)) {
      alias = LEGACY_ALIASES[intrinsicName];
      intrinsicName = "%" + alias[0] + "%";
    }
    if (hasOwn2(INTRINSICS, intrinsicName)) {
      var value = INTRINSICS[intrinsicName];
      if (value === needsEval) {
        value = doEval(intrinsicName);
      }
      if (typeof value === "undefined" && !allowMissing) {
        throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
      }
      return {
        alias,
        name: intrinsicName,
        value
      };
    }
    throw new $SyntaxError("intrinsic " + name + " does not exist!");
  };
  getIntrinsic = function GetIntrinsic(name, allowMissing) {
    if (typeof name !== "string" || name.length === 0) {
      throw new $TypeError("intrinsic name must be a non-empty string");
    }
    if (arguments.length > 1 && typeof allowMissing !== "boolean") {
      throw new $TypeError('"allowMissing" argument must be a boolean');
    }
    if ($exec(/^%?[^%]*%?$/, name) === null) {
      throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
    }
    var parts = stringToPath(name);
    var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
    var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
    var intrinsicRealName = intrinsic.name;
    var value = intrinsic.value;
    var skipFurtherCaching = false;
    var alias = intrinsic.alias;
    if (alias) {
      intrinsicBaseName = alias[0];
      $spliceApply(parts, $concat([0, 1], alias));
    }
    for (var i2 = 1, isOwn = true; i2 < parts.length; i2 += 1) {
      var part = parts[i2];
      var first = $strSlice(part, 0, 1);
      var last = $strSlice(part, -1);
      if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
        throw new $SyntaxError("property names with quotes must have matching quotes");
      }
      if (part === "constructor" || !isOwn) {
        skipFurtherCaching = true;
      }
      intrinsicBaseName += "." + part;
      intrinsicRealName = "%" + intrinsicBaseName + "%";
      if (hasOwn2(INTRINSICS, intrinsicRealName)) {
        value = INTRINSICS[intrinsicRealName];
      } else if (value != null) {
        if (!(part in value)) {
          if (!allowMissing) {
            throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
          }
          return void 0;
        }
        if ($gOPD && i2 + 1 >= parts.length) {
          var desc = $gOPD(value, part);
          isOwn = !!desc;
          if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
            value = desc.get;
          } else {
            value = value[part];
          }
        } else {
          isOwn = hasOwn2(value, part);
          value = value[part];
        }
        if (isOwn && !skipFurtherCaching) {
          INTRINSICS[intrinsicRealName] = value;
        }
      }
    }
    return value;
  };
  return getIntrinsic;
}
var callBound;
var hasRequiredCallBound;
function requireCallBound() {
  if (hasRequiredCallBound) return callBound;
  hasRequiredCallBound = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var callBindBasic = requireCallBindApplyHelpers();
  var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
  callBound = function callBoundIntrinsic(name, allowMissing) {
    var intrinsic = (
      /** @type {(this: unknown, ...args: unknown[]) => unknown} */
      GetIntrinsic(name, !!allowMissing)
    );
    if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1) {
      return callBindBasic(
        /** @type {const} */
        [intrinsic]
      );
    }
    return intrinsic;
  };
  return callBound;
}
var isCallable;
var hasRequiredIsCallable;
function requireIsCallable() {
  if (hasRequiredIsCallable) return isCallable;
  hasRequiredIsCallable = 1;
  var fnToStr = Function.prototype.toString;
  var reflectApply2 = typeof Reflect === "object" && Reflect !== null && Reflect.apply;
  var badArrayLike;
  var isCallableMarker;
  if (typeof reflectApply2 === "function" && typeof Object.defineProperty === "function") {
    try {
      badArrayLike = Object.defineProperty({}, "length", {
        get: function() {
          throw isCallableMarker;
        }
      });
      isCallableMarker = {};
      reflectApply2(function() {
        throw 42;
      }, null, badArrayLike);
    } catch (_2) {
      if (_2 !== isCallableMarker) {
        reflectApply2 = null;
      }
    }
  } else {
    reflectApply2 = null;
  }
  var constructorRegex = /^\s*class\b/;
  var isES6ClassFn = function isES6ClassFunction(value) {
    try {
      var fnStr = fnToStr.call(value);
      return constructorRegex.test(fnStr);
    } catch (e4) {
      return false;
    }
  };
  var tryFunctionObject = function tryFunctionToStr(value) {
    try {
      if (isES6ClassFn(value)) {
        return false;
      }
      fnToStr.call(value);
      return true;
    } catch (e4) {
      return false;
    }
  };
  var toStr = Object.prototype.toString;
  var objectClass = "[object Object]";
  var fnClass = "[object Function]";
  var genClass = "[object GeneratorFunction]";
  var ddaClass = "[object HTMLAllCollection]";
  var ddaClass2 = "[object HTML document.all class]";
  var ddaClass3 = "[object HTMLCollection]";
  var hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag;
  var isIE68 = !(0 in [,]);
  var isDDA = function isDocumentDotAll() {
    return false;
  };
  if (typeof document === "object") {
    var all = document.all;
    if (toStr.call(all) === toStr.call(document.all)) {
      isDDA = function isDocumentDotAll(value) {
        if ((isIE68 || !value) && (typeof value === "undefined" || typeof value === "object")) {
          try {
            var str = toStr.call(value);
            return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null;
          } catch (e4) {
          }
        }
        return false;
      };
    }
  }
  isCallable = reflectApply2 ? function isCallable2(value) {
    if (isDDA(value)) {
      return true;
    }
    if (!value) {
      return false;
    }
    if (typeof value !== "function" && typeof value !== "object") {
      return false;
    }
    try {
      reflectApply2(value, null, badArrayLike);
    } catch (e4) {
      if (e4 !== isCallableMarker) {
        return false;
      }
    }
    return !isES6ClassFn(value) && tryFunctionObject(value);
  } : function isCallable2(value) {
    if (isDDA(value)) {
      return true;
    }
    if (!value) {
      return false;
    }
    if (typeof value !== "function" && typeof value !== "object") {
      return false;
    }
    if (hasToStringTag) {
      return tryFunctionObject(value);
    }
    if (isES6ClassFn(value)) {
      return false;
    }
    var strClass = toStr.call(value);
    if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass)) {
      return false;
    }
    return tryFunctionObject(value);
  };
  return isCallable;
}
var forEach;
var hasRequiredForEach;
function requireForEach() {
  if (hasRequiredForEach) return forEach;
  hasRequiredForEach = 1;
  var isCallable2 = requireIsCallable();
  var toStr = Object.prototype.toString;
  var hasOwnProperty = Object.prototype.hasOwnProperty;
  var forEachArray = function forEachArray2(array, iterator, receiver) {
    for (var i2 = 0, len = array.length; i2 < len; i2++) {
      if (hasOwnProperty.call(array, i2)) {
        if (receiver == null) {
          iterator(array[i2], i2, array);
        } else {
          iterator.call(receiver, array[i2], i2, array);
        }
      }
    }
  };
  var forEachString = function forEachString2(string, iterator, receiver) {
    for (var i2 = 0, len = string.length; i2 < len; i2++) {
      if (receiver == null) {
        iterator(string.charAt(i2), i2, string);
      } else {
        iterator.call(receiver, string.charAt(i2), i2, string);
      }
    }
  };
  var forEachObject = function forEachObject2(object, iterator, receiver) {
    for (var k2 in object) {
      if (hasOwnProperty.call(object, k2)) {
        if (receiver == null) {
          iterator(object[k2], k2, object);
        } else {
          iterator.call(receiver, object[k2], k2, object);
        }
      }
    }
  };
  function isArray2(x2) {
    return toStr.call(x2) === "[object Array]";
  }
  forEach = function forEach2(list, iterator, thisArg) {
    if (!isCallable2(iterator)) {
      throw new TypeError("iterator must be a function");
    }
    var receiver;
    if (arguments.length >= 3) {
      receiver = thisArg;
    }
    if (isArray2(list)) {
      forEachArray(list, iterator, receiver);
    } else if (typeof list === "string") {
      forEachString(list, iterator, receiver);
    } else {
      forEachObject(list, iterator, receiver);
    }
  };
  return forEach;
}
var possibleTypedArrayNames;
var hasRequiredPossibleTypedArrayNames;
function requirePossibleTypedArrayNames() {
  if (hasRequiredPossibleTypedArrayNames) return possibleTypedArrayNames;
  hasRequiredPossibleTypedArrayNames = 1;
  possibleTypedArrayNames = [
    "Float16Array",
    "Float32Array",
    "Float64Array",
    "Int8Array",
    "Int16Array",
    "Int32Array",
    "Uint8Array",
    "Uint8ClampedArray",
    "Uint16Array",
    "Uint32Array",
    "BigInt64Array",
    "BigUint64Array"
  ];
  return possibleTypedArrayNames;
}
var availableTypedArrays;
var hasRequiredAvailableTypedArrays;
function requireAvailableTypedArrays() {
  if (hasRequiredAvailableTypedArrays) return availableTypedArrays;
  hasRequiredAvailableTypedArrays = 1;
  var possibleNames = /* @__PURE__ */ requirePossibleTypedArrayNames();
  var g = typeof globalThis === "undefined" ? commonjsGlobal$1 : globalThis;
  availableTypedArrays = function availableTypedArrays2() {
    var out = [];
    for (var i2 = 0; i2 < possibleNames.length; i2++) {
      if (typeof g[possibleNames[i2]] === "function") {
        out[out.length] = possibleNames[i2];
      }
    }
    return out;
  };
  return availableTypedArrays;
}
var callBind = { exports: {} };
var defineDataProperty;
var hasRequiredDefineDataProperty;
function requireDefineDataProperty() {
  if (hasRequiredDefineDataProperty) return defineDataProperty;
  hasRequiredDefineDataProperty = 1;
  var $defineProperty = /* @__PURE__ */ requireEsDefineProperty();
  var $SyntaxError = /* @__PURE__ */ requireSyntax();
  var $TypeError = /* @__PURE__ */ requireType();
  var gopd2 = /* @__PURE__ */ requireGopd();
  defineDataProperty = function defineDataProperty2(obj, property, value) {
    if (!obj || typeof obj !== "object" && typeof obj !== "function") {
      throw new $TypeError("`obj` must be an object or a function`");
    }
    if (typeof property !== "string" && typeof property !== "symbol") {
      throw new $TypeError("`property` must be a string or a symbol`");
    }
    if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) {
      throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
    }
    if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) {
      throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
    }
    if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) {
      throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
    }
    if (arguments.length > 6 && typeof arguments[6] !== "boolean") {
      throw new $TypeError("`loose`, if provided, must be a boolean");
    }
    var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
    var nonWritable = arguments.length > 4 ? arguments[4] : null;
    var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
    var loose = arguments.length > 6 ? arguments[6] : false;
    var desc = !!gopd2 && gopd2(obj, property);
    if ($defineProperty) {
      $defineProperty(obj, property, {
        configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
        enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
        value,
        writable: nonWritable === null && desc ? desc.writable : !nonWritable
      });
    } else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) {
      obj[property] = value;
    } else {
      throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
    }
  };
  return defineDataProperty;
}
var hasPropertyDescriptors_1;
var hasRequiredHasPropertyDescriptors;
function requireHasPropertyDescriptors() {
  if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1;
  hasRequiredHasPropertyDescriptors = 1;
  var $defineProperty = /* @__PURE__ */ requireEsDefineProperty();
  var hasPropertyDescriptors = function hasPropertyDescriptors2() {
    return !!$defineProperty;
  };
  hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
    if (!$defineProperty) {
      return null;
    }
    try {
      return $defineProperty([], "length", { value: 1 }).length !== 1;
    } catch (e4) {
      return true;
    }
  };
  hasPropertyDescriptors_1 = hasPropertyDescriptors;
  return hasPropertyDescriptors_1;
}
var setFunctionLength;
var hasRequiredSetFunctionLength;
function requireSetFunctionLength() {
  if (hasRequiredSetFunctionLength) return setFunctionLength;
  hasRequiredSetFunctionLength = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var define = /* @__PURE__ */ requireDefineDataProperty();
  var hasDescriptors = /* @__PURE__ */ requireHasPropertyDescriptors()();
  var gOPD2 = /* @__PURE__ */ requireGopd();
  var $TypeError = /* @__PURE__ */ requireType();
  var $floor = GetIntrinsic("%Math.floor%");
  setFunctionLength = function setFunctionLength2(fn, length) {
    if (typeof fn !== "function") {
      throw new $TypeError("`fn` is not a function");
    }
    if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length) {
      throw new $TypeError("`length` must be a positive 32-bit integer");
    }
    var loose = arguments.length > 2 && !!arguments[2];
    var functionLengthIsConfigurable = true;
    var functionLengthIsWritable = true;
    if ("length" in fn && gOPD2) {
      var desc = gOPD2(fn, "length");
      if (desc && !desc.configurable) {
        functionLengthIsConfigurable = false;
      }
      if (desc && !desc.writable) {
        functionLengthIsWritable = false;
      }
    }
    if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) {
      if (hasDescriptors) {
        define(
          /** @type {Parameters<define>[0]} */
          fn,
          "length",
          length,
          true,
          true
        );
      } else {
        define(
          /** @type {Parameters<define>[0]} */
          fn,
          "length",
          length
        );
      }
    }
    return fn;
  };
  return setFunctionLength;
}
var applyBind;
var hasRequiredApplyBind;
function requireApplyBind() {
  if (hasRequiredApplyBind) return applyBind;
  hasRequiredApplyBind = 1;
  var bind2 = requireFunctionBind();
  var $apply = requireFunctionApply();
  var actualApply2 = requireActualApply();
  applyBind = function applyBind2() {
    return actualApply2(bind2, $apply, arguments);
  };
  return applyBind;
}
var hasRequiredCallBind;
function requireCallBind() {
  if (hasRequiredCallBind) return callBind.exports;
  hasRequiredCallBind = 1;
  (function(module2) {
    var setFunctionLength2 = /* @__PURE__ */ requireSetFunctionLength();
    var $defineProperty = /* @__PURE__ */ requireEsDefineProperty();
    var callBindBasic = requireCallBindApplyHelpers();
    var applyBind2 = requireApplyBind();
    module2.exports = function callBind2(originalFunction) {
      var func = callBindBasic(arguments);
      var adjustedLength = originalFunction.length - (arguments.length - 1);
      return setFunctionLength2(
        func,
        1 + (adjustedLength > 0 ? adjustedLength : 0),
        true
      );
    };
    if ($defineProperty) {
      $defineProperty(module2.exports, "apply", { value: applyBind2 });
    } else {
      module2.exports.apply = applyBind2;
    }
  })(callBind);
  return callBind.exports;
}
var shams;
var hasRequiredShams;
function requireShams() {
  if (hasRequiredShams) return shams;
  hasRequiredShams = 1;
  var hasSymbols2 = requireShams$1();
  shams = function hasToStringTagShams() {
    return hasSymbols2() && !!Symbol.toStringTag;
  };
  return shams;
}
var whichTypedArray;
var hasRequiredWhichTypedArray;
function requireWhichTypedArray() {
  if (hasRequiredWhichTypedArray) return whichTypedArray;
  hasRequiredWhichTypedArray = 1;
  var forEach2 = requireForEach();
  var availableTypedArrays2 = /* @__PURE__ */ requireAvailableTypedArrays();
  var callBind2 = requireCallBind();
  var callBound2 = /* @__PURE__ */ requireCallBound();
  var gOPD2 = /* @__PURE__ */ requireGopd();
  var getProto2 = requireGetProto();
  var $toString = callBound2("Object.prototype.toString");
  var hasToStringTag = requireShams()();
  var g = typeof globalThis === "undefined" ? commonjsGlobal$1 : globalThis;
  var typedArrays = availableTypedArrays2();
  var $slice = callBound2("String.prototype.slice");
  var $indexOf = callBound2("Array.prototype.indexOf", true) || function indexOf(array, value) {
    for (var i2 = 0; i2 < array.length; i2 += 1) {
      if (array[i2] === value) {
        return i2;
      }
    }
    return -1;
  };
  var cache2 = { __proto__: null };
  if (hasToStringTag && gOPD2 && getProto2) {
    forEach2(typedArrays, function(typedArray) {
      var arr = new g[typedArray]();
      if (Symbol.toStringTag in arr && getProto2) {
        var proto = getProto2(arr);
        var descriptor = gOPD2(proto, Symbol.toStringTag);
        if (!descriptor && proto) {
          var superProto = getProto2(proto);
          descriptor = gOPD2(superProto, Symbol.toStringTag);
        }
        cache2["$" + typedArray] = callBind2(descriptor.get);
      }
    });
  } else {
    forEach2(typedArrays, function(typedArray) {
      var arr = new g[typedArray]();
      var fn = arr.slice || arr.set;
      if (fn) {
        cache2[
          /** @type {`$${import('.').TypedArrayName}`} */
          "$" + typedArray
        ] = /** @type {import('./types').BoundSlice | import('./types').BoundSet} */
        // @ts-expect-error TODO FIXME
        callBind2(fn);
      }
    });
  }
  var tryTypedArrays = function tryAllTypedArrays(value) {
    var found = false;
    forEach2(
      /** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */
      cache2,
      /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
      function(getter, typedArray) {
        if (!found) {
          try {
            if ("$" + getter(value) === typedArray) {
              found = /** @type {import('.').TypedArrayName} */
              $slice(typedArray, 1);
            }
          } catch (e4) {
          }
        }
      }
    );
    return found;
  };
  var trySlices = function tryAllSlices(value) {
    var found = false;
    forEach2(
      /** @type {Record<`\$${import('.').TypedArrayName}`, Getter>} */
      cache2,
      /** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
      function(getter, name) {
        if (!found) {
          try {
            getter(value);
            found = /** @type {import('.').TypedArrayName} */
            $slice(name, 1);
          } catch (e4) {
          }
        }
      }
    );
    return found;
  };
  whichTypedArray = function whichTypedArray2(value) {
    if (!value || typeof value !== "object") {
      return false;
    }
    if (!hasToStringTag) {
      var tag = $slice($toString(value), 8, -1);
      if ($indexOf(typedArrays, tag) > -1) {
        return tag;
      }
      if (tag !== "Object") {
        return false;
      }
      return trySlices(value);
    }
    if (!gOPD2) {
      return null;
    }
    return tryTypedArrays(value);
  };
  return whichTypedArray;
}
var isTypedArray;
var hasRequiredIsTypedArray;
function requireIsTypedArray() {
  if (hasRequiredIsTypedArray) return isTypedArray;
  hasRequiredIsTypedArray = 1;
  var whichTypedArray2 = /* @__PURE__ */ requireWhichTypedArray();
  isTypedArray = function isTypedArray2(value) {
    return !!whichTypedArray2(value);
  };
  return isTypedArray;
}
var typedArrayBuffer;
var hasRequiredTypedArrayBuffer;
function requireTypedArrayBuffer() {
  if (hasRequiredTypedArrayBuffer) return typedArrayBuffer;
  hasRequiredTypedArrayBuffer = 1;
  var $TypeError = /* @__PURE__ */ requireType();
  var callBound2 = /* @__PURE__ */ requireCallBound();
  var $typedArrayBuffer = callBound2("TypedArray.prototype.buffer", true);
  var isTypedArray2 = /* @__PURE__ */ requireIsTypedArray();
  typedArrayBuffer = $typedArrayBuffer || function typedArrayBuffer2(x2) {
    if (!isTypedArray2(x2)) {
      throw new $TypeError("Not a Typed Array");
    }
    return x2.buffer;
  };
  return typedArrayBuffer;
}
var toBuffer;
var hasRequiredToBuffer$2;
function requireToBuffer$2() {
  if (hasRequiredToBuffer$2) return toBuffer;
  hasRequiredToBuffer$2 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var isArray2 = requireIsarray$1();
  var typedArrayBuffer2 = /* @__PURE__ */ requireTypedArrayBuffer();
  var isView = ArrayBuffer.isView || function isView2(obj) {
    try {
      typedArrayBuffer2(obj);
      return true;
    } catch (e4) {
      return false;
    }
  };
  var useUint8Array = typeof Uint8Array !== "undefined";
  var useArrayBuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
  var useFromArrayBuffer = useArrayBuffer && (Buffer2.prototype instanceof Uint8Array || Buffer2.TYPED_ARRAY_SUPPORT);
  toBuffer = function toBuffer2(data2, encoding) {
    if (Buffer2.isBuffer(data2)) {
      if (data2.constructor && !("isBuffer" in data2)) {
        return Buffer2.from(data2);
      }
      return data2;
    }
    if (typeof data2 === "string") {
      return Buffer2.from(data2, encoding);
    }
    if (useArrayBuffer && isView(data2)) {
      if (data2.byteLength === 0) {
        return Buffer2.alloc(0);
      }
      if (useFromArrayBuffer) {
        var res = Buffer2.from(data2.buffer, data2.byteOffset, data2.byteLength);
        if (res.byteLength === data2.byteLength) {
          return res;
        }
      }
      var uint8 = data2 instanceof Uint8Array ? data2 : new Uint8Array(data2.buffer, data2.byteOffset, data2.byteLength);
      var result = Buffer2.from(uint8);
      if (result.length === data2.byteLength) {
        return result;
      }
    }
    if (useUint8Array && data2 instanceof Uint8Array) {
      return Buffer2.from(data2);
    }
    var isArr = isArray2(data2);
    if (isArr) {
      for (var i2 = 0; i2 < data2.length; i2 += 1) {
        var x2 = data2[i2];
        if (typeof x2 !== "number" || x2 < 0 || x2 > 255 || ~~x2 !== x2) {
          throw new RangeError("Array items must be numbers in the range 0-255.");
        }
      }
    }
    if (isArr || Buffer2.isBuffer(data2) && data2.constructor && typeof data2.constructor.isBuffer === "function" && data2.constructor.isBuffer(data2)) {
      return Buffer2.from(data2);
    }
    throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
  };
  return toBuffer;
}
var toBuffer_1$1;
var hasRequiredToBuffer$1;
function requireToBuffer$1() {
  if (hasRequiredToBuffer$1) return toBuffer_1$1;
  hasRequiredToBuffer$1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var toBuffer2 = /* @__PURE__ */ requireToBuffer$2();
  var useUint8Array = typeof Uint8Array !== "undefined";
  var useArrayBuffer = useUint8Array && typeof ArrayBuffer !== "undefined";
  var isView = useArrayBuffer && ArrayBuffer.isView;
  toBuffer_1$1 = function(thing, encoding) {
    if (typeof thing === "string" || Buffer2.isBuffer(thing) || useUint8Array && thing instanceof Uint8Array || isView && isView(thing)) {
      return toBuffer2(thing, encoding);
    }
    throw new TypeError('The "data" argument must be a string, a Buffer, a Uint8Array, or a DataView');
  };
  return toBuffer_1$1;
}
var readableBrowser = { exports: {} };
var processNextickArgs = { exports: {} };
var hasRequiredProcessNextickArgs;
function requireProcessNextickArgs() {
  if (hasRequiredProcessNextickArgs) return processNextickArgs.exports;
  hasRequiredProcessNextickArgs = 1;
  if (typeof process === "undefined" || !process.version || process.version.indexOf("v0.") === 0 || process.version.indexOf("v1.") === 0 && process.version.indexOf("v1.8.") !== 0) {
    processNextickArgs.exports = { nextTick };
  } else {
    processNextickArgs.exports = process;
  }
  function nextTick(fn, arg1, arg2, arg3) {
    if (typeof fn !== "function") {
      throw new TypeError('"callback" argument must be a function');
    }
    var len = arguments.length;
    var args, i2;
    switch (len) {
      case 0:
      case 1:
        return process.nextTick(fn);
      case 2:
        return process.nextTick(function afterTickOne() {
          fn.call(null, arg1);
        });
      case 3:
        return process.nextTick(function afterTickTwo() {
          fn.call(null, arg1, arg2);
        });
      case 4:
        return process.nextTick(function afterTickThree() {
          fn.call(null, arg1, arg2, arg3);
        });
      default:
        args = new Array(len - 1);
        i2 = 0;
        while (i2 < args.length) {
          args[i2++] = arguments[i2];
        }
        return process.nextTick(function afterTick() {
          fn.apply(null, args);
        });
    }
  }
  return processNextickArgs.exports;
}
var isarray;
var hasRequiredIsarray;
function requireIsarray() {
  if (hasRequiredIsarray) return isarray;
  hasRequiredIsarray = 1;
  var toString2 = {}.toString;
  isarray = Array.isArray || function(arr) {
    return toString2.call(arr) == "[object Array]";
  };
  return isarray;
}
var events = { exports: {} };
var hasRequiredEvents;
function requireEvents() {
  if (hasRequiredEvents) return events.exports;
  hasRequiredEvents = 1;
  var R2 = typeof Reflect === "object" ? Reflect : null;
  var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) {
    return Function.prototype.apply.call(target, receiver, args);
  };
  var ReflectOwnKeys;
  if (R2 && typeof R2.ownKeys === "function") {
    ReflectOwnKeys = R2.ownKeys;
  } else if (Object.getOwnPropertySymbols) {
    ReflectOwnKeys = function ReflectOwnKeys2(target) {
      return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target));
    };
  } else {
    ReflectOwnKeys = function ReflectOwnKeys2(target) {
      return Object.getOwnPropertyNames(target);
    };
  }
  function ProcessEmitWarning(warning) {
    if (console && console.warn) console.warn(warning);
  }
  var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) {
    return value !== value;
  };
  function EventEmitter2() {
    EventEmitter2.init.call(this);
  }
  events.exports = EventEmitter2;
  events.exports.once = once;
  EventEmitter2.EventEmitter = EventEmitter2;
  EventEmitter2.prototype._events = void 0;
  EventEmitter2.prototype._eventsCount = 0;
  EventEmitter2.prototype._maxListeners = void 0;
  var defaultMaxListeners = 10;
  function checkListener(listener) {
    if (typeof listener !== "function") {
      throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
    }
  }
  Object.defineProperty(EventEmitter2, "defaultMaxListeners", {
    enumerable: true,
    get: function() {
      return defaultMaxListeners;
    },
    set: function(arg) {
      if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) {
        throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + ".");
      }
      defaultMaxListeners = arg;
    }
  });
  EventEmitter2.init = function() {
    if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) {
      this._events = /* @__PURE__ */ Object.create(null);
      this._eventsCount = 0;
    }
    this._maxListeners = this._maxListeners || void 0;
  };
  EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n2) {
    if (typeof n2 !== "number" || n2 < 0 || NumberIsNaN(n2)) {
      throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n2 + ".");
    }
    this._maxListeners = n2;
    return this;
  };
  function _getMaxListeners(that) {
    if (that._maxListeners === void 0)
      return EventEmitter2.defaultMaxListeners;
    return that._maxListeners;
  }
  EventEmitter2.prototype.getMaxListeners = function getMaxListeners() {
    return _getMaxListeners(this);
  };
  EventEmitter2.prototype.emit = function emit(type2) {
    var args = [];
    for (var i2 = 1; i2 < arguments.length; i2++) args.push(arguments[i2]);
    var doError = type2 === "error";
    var events2 = this._events;
    if (events2 !== void 0)
      doError = doError && events2.error === void 0;
    else if (!doError)
      return false;
    if (doError) {
      var er;
      if (args.length > 0)
        er = args[0];
      if (er instanceof Error) {
        throw er;
      }
      var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : ""));
      err.context = er;
      throw err;
    }
    var handler = events2[type2];
    if (handler === void 0)
      return false;
    if (typeof handler === "function") {
      ReflectApply(handler, this, args);
    } else {
      var len = handler.length;
      var listeners = arrayClone(handler, len);
      for (var i2 = 0; i2 < len; ++i2)
        ReflectApply(listeners[i2], this, args);
    }
    return true;
  };
  function _addListener(target, type2, listener, prepend) {
    var m;
    var events2;
    var existing;
    checkListener(listener);
    events2 = target._events;
    if (events2 === void 0) {
      events2 = target._events = /* @__PURE__ */ Object.create(null);
      target._eventsCount = 0;
    } else {
      if (events2.newListener !== void 0) {
        target.emit(
          "newListener",
          type2,
          listener.listener ? listener.listener : listener
        );
        events2 = target._events;
      }
      existing = events2[type2];
    }
    if (existing === void 0) {
      existing = events2[type2] = listener;
      ++target._eventsCount;
    } else {
      if (typeof existing === "function") {
        existing = events2[type2] = prepend ? [listener, existing] : [existing, listener];
      } else if (prepend) {
        existing.unshift(listener);
      } else {
        existing.push(listener);
      }
      m = _getMaxListeners(target);
      if (m > 0 && existing.length > m && !existing.warned) {
        existing.warned = true;
        var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type2) + " listeners added. Use emitter.setMaxListeners() to increase limit");
        w.name = "MaxListenersExceededWarning";
        w.emitter = target;
        w.type = type2;
        w.count = existing.length;
        ProcessEmitWarning(w);
      }
    }
    return target;
  }
  EventEmitter2.prototype.addListener = function addListener(type2, listener) {
    return _addListener(this, type2, listener, false);
  };
  EventEmitter2.prototype.on = EventEmitter2.prototype.addListener;
  EventEmitter2.prototype.prependListener = function prependListener(type2, listener) {
    return _addListener(this, type2, listener, true);
  };
  function onceWrapper() {
    if (!this.fired) {
      this.target.removeListener(this.type, this.wrapFn);
      this.fired = true;
      if (arguments.length === 0)
        return this.listener.call(this.target);
      return this.listener.apply(this.target, arguments);
    }
  }
  function _onceWrap(target, type2, listener) {
    var state = { fired: false, wrapFn: void 0, target, type: type2, listener };
    var wrapped = onceWrapper.bind(state);
    wrapped.listener = listener;
    state.wrapFn = wrapped;
    return wrapped;
  }
  EventEmitter2.prototype.once = function once2(type2, listener) {
    checkListener(listener);
    this.on(type2, _onceWrap(this, type2, listener));
    return this;
  };
  EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type2, listener) {
    checkListener(listener);
    this.prependListener(type2, _onceWrap(this, type2, listener));
    return this;
  };
  EventEmitter2.prototype.removeListener = function removeListener(type2, listener) {
    var list, events2, position, i2, originalListener;
    checkListener(listener);
    events2 = this._events;
    if (events2 === void 0)
      return this;
    list = events2[type2];
    if (list === void 0)
      return this;
    if (list === listener || list.listener === listener) {
      if (--this._eventsCount === 0)
        this._events = /* @__PURE__ */ Object.create(null);
      else {
        delete events2[type2];
        if (events2.removeListener)
          this.emit("removeListener", type2, list.listener || listener);
      }
    } else if (typeof list !== "function") {
      position = -1;
      for (i2 = list.length - 1; i2 >= 0; i2--) {
        if (list[i2] === listener || list[i2].listener === listener) {
          originalListener = list[i2].listener;
          position = i2;
          break;
        }
      }
      if (position < 0)
        return this;
      if (position === 0)
        list.shift();
      else {
        spliceOne(list, position);
      }
      if (list.length === 1)
        events2[type2] = list[0];
      if (events2.removeListener !== void 0)
        this.emit("removeListener", type2, originalListener || listener);
    }
    return this;
  };
  EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener;
  EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type2) {
    var listeners, events2, i2;
    events2 = this._events;
    if (events2 === void 0)
      return this;
    if (events2.removeListener === void 0) {
      if (arguments.length === 0) {
        this._events = /* @__PURE__ */ Object.create(null);
        this._eventsCount = 0;
      } else if (events2[type2] !== void 0) {
        if (--this._eventsCount === 0)
          this._events = /* @__PURE__ */ Object.create(null);
        else
          delete events2[type2];
      }
      return this;
    }
    if (arguments.length === 0) {
      var keys = Object.keys(events2);
      var key2;
      for (i2 = 0; i2 < keys.length; ++i2) {
        key2 = keys[i2];
        if (key2 === "removeListener") continue;
        this.removeAllListeners(key2);
      }
      this.removeAllListeners("removeListener");
      this._events = /* @__PURE__ */ Object.create(null);
      this._eventsCount = 0;
      return this;
    }
    listeners = events2[type2];
    if (typeof listeners === "function") {
      this.removeListener(type2, listeners);
    } else if (listeners !== void 0) {
      for (i2 = listeners.length - 1; i2 >= 0; i2--) {
        this.removeListener(type2, listeners[i2]);
      }
    }
    return this;
  };
  function _listeners(target, type2, unwrap) {
    var events2 = target._events;
    if (events2 === void 0)
      return [];
    var evlistener = events2[type2];
    if (evlistener === void 0)
      return [];
    if (typeof evlistener === "function")
      return unwrap ? [evlistener.listener || evlistener] : [evlistener];
    return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  }
  EventEmitter2.prototype.listeners = function listeners(type2) {
    return _listeners(this, type2, true);
  };
  EventEmitter2.prototype.rawListeners = function rawListeners(type2) {
    return _listeners(this, type2, false);
  };
  EventEmitter2.listenerCount = function(emitter, type2) {
    if (typeof emitter.listenerCount === "function") {
      return emitter.listenerCount(type2);
    } else {
      return listenerCount.call(emitter, type2);
    }
  };
  EventEmitter2.prototype.listenerCount = listenerCount;
  function listenerCount(type2) {
    var events2 = this._events;
    if (events2 !== void 0) {
      var evlistener = events2[type2];
      if (typeof evlistener === "function") {
        return 1;
      } else if (evlistener !== void 0) {
        return evlistener.length;
      }
    }
    return 0;
  }
  EventEmitter2.prototype.eventNames = function eventNames() {
    return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
  };
  function arrayClone(arr, n2) {
    var copy2 = new Array(n2);
    for (var i2 = 0; i2 < n2; ++i2)
      copy2[i2] = arr[i2];
    return copy2;
  }
  function spliceOne(list, index2) {
    for (; index2 + 1 < list.length; index2++)
      list[index2] = list[index2 + 1];
    list.pop();
  }
  function unwrapListeners(arr) {
    var ret = new Array(arr.length);
    for (var i2 = 0; i2 < ret.length; ++i2) {
      ret[i2] = arr[i2].listener || arr[i2];
    }
    return ret;
  }
  function once(emitter, name) {
    return new Promise(function(resolve2, reject2) {
      function errorListener(err) {
        emitter.removeListener(name, resolver);
        reject2(err);
      }
      function resolver() {
        if (typeof emitter.removeListener === "function") {
          emitter.removeListener("error", errorListener);
        }
        resolve2([].slice.call(arguments));
      }
      eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
      if (name !== "error") {
        addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
      }
    });
  }
  function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
    if (typeof emitter.on === "function") {
      eventTargetAgnosticAddListener(emitter, "error", handler, flags);
    }
  }
  function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
    if (typeof emitter.on === "function") {
      if (flags.once) {
        emitter.once(name, listener);
      } else {
        emitter.on(name, listener);
      }
    } else if (typeof emitter.addEventListener === "function") {
      emitter.addEventListener(name, function wrapListener(arg) {
        if (flags.once) {
          emitter.removeEventListener(name, wrapListener);
        }
        listener(arg);
      });
    } else {
      throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
    }
  }
  return events.exports;
}
var streamBrowser;
var hasRequiredStreamBrowser;
function requireStreamBrowser() {
  if (hasRequiredStreamBrowser) return streamBrowser;
  hasRequiredStreamBrowser = 1;
  streamBrowser = requireEvents().EventEmitter;
  return streamBrowser;
}
var safeBuffer = { exports: {} };
var hasRequiredSafeBuffer;
function requireSafeBuffer() {
  if (hasRequiredSafeBuffer) return safeBuffer.exports;
  hasRequiredSafeBuffer = 1;
  (function(module2, exports) {
    var buffer2 = requireBuffer$1();
    var Buffer2 = buffer2.Buffer;
    function copyProps(src2, dst) {
      for (var key2 in src2) {
        dst[key2] = src2[key2];
      }
    }
    if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
      module2.exports = buffer2;
    } else {
      copyProps(buffer2, exports);
      exports.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer2(arg, encodingOrOffset, length);
    }
    copyProps(Buffer2, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer2(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer2(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer2(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer2.SlowBuffer(size);
    };
  })(safeBuffer, safeBuffer.exports);
  return safeBuffer.exports;
}
var util$4 = {};
var hasRequiredUtil$1;
function requireUtil$1() {
  if (hasRequiredUtil$1) return util$4;
  hasRequiredUtil$1 = 1;
  function isArray2(arg) {
    if (Array.isArray) {
      return Array.isArray(arg);
    }
    return objectToString(arg) === "[object Array]";
  }
  util$4.isArray = isArray2;
  function isBoolean(arg) {
    return typeof arg === "boolean";
  }
  util$4.isBoolean = isBoolean;
  function isNull(arg) {
    return arg === null;
  }
  util$4.isNull = isNull;
  function isNullOrUndefined(arg) {
    return arg == null;
  }
  util$4.isNullOrUndefined = isNullOrUndefined;
  function isNumber(arg) {
    return typeof arg === "number";
  }
  util$4.isNumber = isNumber;
  function isString2(arg) {
    return typeof arg === "string";
  }
  util$4.isString = isString2;
  function isSymbol(arg) {
    return typeof arg === "symbol";
  }
  util$4.isSymbol = isSymbol;
  function isUndefined(arg) {
    return arg === void 0;
  }
  util$4.isUndefined = isUndefined;
  function isRegExp(re) {
    return objectToString(re) === "[object RegExp]";
  }
  util$4.isRegExp = isRegExp;
  function isObject(arg) {
    return typeof arg === "object" && arg !== null;
  }
  util$4.isObject = isObject;
  function isDate(d) {
    return objectToString(d) === "[object Date]";
  }
  util$4.isDate = isDate;
  function isError(e4) {
    return objectToString(e4) === "[object Error]" || e4 instanceof Error;
  }
  util$4.isError = isError;
  function isFunction(arg) {
    return typeof arg === "function";
  }
  util$4.isFunction = isFunction;
  function isPrimitive(arg) {
    return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol
    typeof arg === "undefined";
  }
  util$4.isPrimitive = isPrimitive;
  util$4.isBuffer = requireBuffer$1().Buffer.isBuffer;
  function objectToString(o2) {
    return Object.prototype.toString.call(o2);
  }
  return util$4;
}
const __viteBrowserExternal = new Proxy({}, {
  get(_2, key2) {
    throw new Error(`Module "" has been externalized for browser compatibility. Cannot access ".${key2}" in client code.  See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  }
});
const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: __viteBrowserExternal
}, Symbol.toStringTag, { value: "Module" }));
const require$$0$2 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal$1);
var BufferList = { exports: {} };
var hasRequiredBufferList;
function requireBufferList() {
  if (hasRequiredBufferList) return BufferList.exports;
  hasRequiredBufferList = 1;
  (function(module2) {
    function _classCallCheck(instance2, Constructor) {
      if (!(instance2 instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    var Buffer2 = requireSafeBuffer().Buffer;
    var util2 = require$$0$2;
    function copyBuffer(src2, target, offset) {
      src2.copy(target, offset);
    }
    module2.exports = function() {
      function BufferList2() {
        _classCallCheck(this, BufferList2);
        this.head = null;
        this.tail = null;
        this.length = 0;
      }
      BufferList2.prototype.push = function push(v2) {
        var entry = { data: v2, next: null };
        if (this.length > 0) this.tail.next = entry;
        else this.head = entry;
        this.tail = entry;
        ++this.length;
      };
      BufferList2.prototype.unshift = function unshift(v2) {
        var entry = { data: v2, next: this.head };
        if (this.length === 0) this.tail = entry;
        this.head = entry;
        ++this.length;
      };
      BufferList2.prototype.shift = function shift() {
        if (this.length === 0) return;
        var ret = this.head.data;
        if (this.length === 1) this.head = this.tail = null;
        else this.head = this.head.next;
        --this.length;
        return ret;
      };
      BufferList2.prototype.clear = function clear() {
        this.head = this.tail = null;
        this.length = 0;
      };
      BufferList2.prototype.join = function join(s2) {
        if (this.length === 0) return "";
        var p2 = this.head;
        var ret = "" + p2.data;
        while (p2 = p2.next) {
          ret += s2 + p2.data;
        }
        return ret;
      };
      BufferList2.prototype.concat = function concat(n2) {
        if (this.length === 0) return Buffer2.alloc(0);
        var ret = Buffer2.allocUnsafe(n2 >>> 0);
        var p2 = this.head;
        var i2 = 0;
        while (p2) {
          copyBuffer(p2.data, ret, i2);
          i2 += p2.data.length;
          p2 = p2.next;
        }
        return ret;
      };
      return BufferList2;
    }();
    if (util2 && util2.inspect && util2.inspect.custom) {
      module2.exports.prototype[util2.inspect.custom] = function() {
        var obj = util2.inspect({ length: this.length });
        return this.constructor.name + " " + obj;
      };
    }
  })(BufferList);
  return BufferList.exports;
}
var destroy_1;
var hasRequiredDestroy;
function requireDestroy() {
  if (hasRequiredDestroy) return destroy_1;
  hasRequiredDestroy = 1;
  var pna = requireProcessNextickArgs();
  function destroy(err, cb) {
    var _this = this;
    var readableDestroyed = this._readableState && this._readableState.destroyed;
    var writableDestroyed = this._writableState && this._writableState.destroyed;
    if (readableDestroyed || writableDestroyed) {
      if (cb) {
        cb(err);
      } else if (err) {
        if (!this._writableState) {
          pna.nextTick(emitErrorNT, this, err);
        } else if (!this._writableState.errorEmitted) {
          this._writableState.errorEmitted = true;
          pna.nextTick(emitErrorNT, this, err);
        }
      }
      return this;
    }
    if (this._readableState) {
      this._readableState.destroyed = true;
    }
    if (this._writableState) {
      this._writableState.destroyed = true;
    }
    this._destroy(err || null, function(err2) {
      if (!cb && err2) {
        if (!_this._writableState) {
          pna.nextTick(emitErrorNT, _this, err2);
        } else if (!_this._writableState.errorEmitted) {
          _this._writableState.errorEmitted = true;
          pna.nextTick(emitErrorNT, _this, err2);
        }
      } else if (cb) {
        cb(err2);
      }
    });
    return this;
  }
  function undestroy() {
    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 emitErrorNT(self2, err) {
    self2.emit("error", err);
  }
  destroy_1 = {
    destroy,
    undestroy
  };
  return destroy_1;
}
var browser$f;
var hasRequiredBrowser$d;
function requireBrowser$d() {
  if (hasRequiredBrowser$d) return browser$f;
  hasRequiredBrowser$d = 1;
  browser$f = deprecate;
  function deprecate(fn, msg) {
    if (config("noDeprecation")) {
      return fn;
    }
    var warned = false;
    function deprecated() {
      if (!warned) {
        if (config("throwDeprecation")) {
          throw new Error(msg);
        } else if (config("traceDeprecation")) {
          console.trace(msg);
        } else {
          console.warn(msg);
        }
        warned = true;
      }
      return fn.apply(this, arguments);
    }
    return deprecated;
  }
  function config(name) {
    try {
      if (!commonjsGlobal$1.localStorage) return false;
    } catch (_2) {
      return false;
    }
    var val = commonjsGlobal$1.localStorage[name];
    if (null == val) return false;
    return String(val).toLowerCase() === "true";
  }
  return browser$f;
}
var _stream_writable;
var hasRequired_stream_writable;
function require_stream_writable() {
  if (hasRequired_stream_writable) return _stream_writable;
  hasRequired_stream_writable = 1;
  var pna = requireProcessNextickArgs();
  _stream_writable = Writable;
  function CorkedRequest(state) {
    var _this = this;
    this.next = null;
    this.entry = null;
    this.finish = function() {
      onCorkedFinish(_this, state);
    };
  }
  var asyncWrite = !process.browser && ["v0.10", "v0.9."].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  var Duplex;
  Writable.WritableState = WritableState;
  var util2 = Object.create(requireUtil$1());
  util2.inherits = requireInherits_browser();
  var internalUtil = {
    deprecate: requireBrowser$d()
  };
  var Stream2 = requireStreamBrowser();
  var Buffer2 = requireSafeBuffer().Buffer;
  var OurUint8Array = (typeof commonjsGlobal$1 !== "undefined" ? commonjsGlobal$1 : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {
  };
  function _uint8ArrayToBuffer(chunk) {
    return Buffer2.from(chunk);
  }
  function _isUint8Array(obj) {
    return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array;
  }
  var destroyImpl = requireDestroy();
  util2.inherits(Writable, Stream2);
  function nop() {
  }
  function WritableState(options2, stream2) {
    Duplex = Duplex || require_stream_duplex();
    options2 = options2 || {};
    var isDuplex = stream2 instanceof Duplex;
    this.objectMode = !!options2.objectMode;
    if (isDuplex) this.objectMode = this.objectMode || !!options2.writableObjectMode;
    var hwm = options2.highWaterMark;
    var writableHwm = options2.writableHighWaterMark;
    var defaultHwm = this.objectMode ? 16 : 16 * 1024;
    if (hwm || hwm === 0) this.highWaterMark = hwm;
    else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;
    else this.highWaterMark = defaultHwm;
    this.highWaterMark = Math.floor(this.highWaterMark);
    this.finalCalled = false;
    this.needDrain = false;
    this.ending = false;
    this.ended = false;
    this.finished = false;
    this.destroyed = false;
    var noDecode = options2.decodeStrings === false;
    this.decodeStrings = !noDecode;
    this.defaultEncoding = options2.defaultEncoding || "utf8";
    this.length = 0;
    this.writing = false;
    this.corked = 0;
    this.sync = true;
    this.bufferProcessing = false;
    this.onwrite = function(er) {
      onwrite(stream2, er);
    };
    this.writecb = null;
    this.writelen = 0;
    this.bufferedRequest = null;
    this.lastBufferedRequest = null;
    this.pendingcb = 0;
    this.prefinished = false;
    this.errorEmitted = false;
    this.bufferedRequestCount = 0;
    this.corkedRequestsFree = new CorkedRequest(this);
  }
  WritableState.prototype.getBuffer = function getBuffer() {
    var current = this.bufferedRequest;
    var out = [];
    while (current) {
      out.push(current);
      current = current.next;
    }
    return out;
  };
  (function() {
    try {
      Object.defineProperty(WritableState.prototype, "buffer", {
        get: internalUtil.deprecate(function() {
          return this.getBuffer();
        }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003")
      });
    } catch (_2) {
    }
  })();
  var realHasInstance;
  if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") {
    realHasInstance = Function.prototype[Symbol.hasInstance];
    Object.defineProperty(Writable, Symbol.hasInstance, {
      value: function(object) {
        if (realHasInstance.call(this, object)) return true;
        if (this !== Writable) return false;
        return object && object._writableState instanceof WritableState;
      }
    });
  } else {
    realHasInstance = function(object) {
      return object instanceof this;
    };
  }
  function Writable(options2) {
    Duplex = Duplex || require_stream_duplex();
    if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
      return new Writable(options2);
    }
    this._writableState = new WritableState(options2, this);
    this.writable = true;
    if (options2) {
      if (typeof options2.write === "function") this._write = options2.write;
      if (typeof options2.writev === "function") this._writev = options2.writev;
      if (typeof options2.destroy === "function") this._destroy = options2.destroy;
      if (typeof options2.final === "function") this._final = options2.final;
    }
    Stream2.call(this);
  }
  Writable.prototype.pipe = function() {
    this.emit("error", new Error("Cannot pipe, not readable"));
  };
  function writeAfterEnd(stream2, cb) {
    var er = new Error("write after end");
    stream2.emit("error", er);
    pna.nextTick(cb, er);
  }
  function validChunk(stream2, state, chunk, cb) {
    var valid = true;
    var er = false;
    if (chunk === null) {
      er = new TypeError("May not write null values to stream");
    } else if (typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) {
      er = new TypeError("Invalid non-string/buffer chunk");
    }
    if (er) {
      stream2.emit("error", er);
      pna.nextTick(cb, er);
      valid = false;
    }
    return valid;
  }
  Writable.prototype.write = function(chunk, encoding, cb) {
    var state = this._writableState;
    var ret = false;
    var isBuf = !state.objectMode && _isUint8Array(chunk);
    if (isBuf && !Buffer2.isBuffer(chunk)) {
      chunk = _uint8ArrayToBuffer(chunk);
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = null;
    }
    if (isBuf) encoding = "buffer";
    else if (!encoding) encoding = state.defaultEncoding;
    if (typeof cb !== "function") cb = nop;
    if (state.ended) writeAfterEnd(this, cb);
    else if (isBuf || validChunk(this, state, chunk, cb)) {
      state.pendingcb++;
      ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
    }
    return ret;
  };
  Writable.prototype.cork = function() {
    var state = this._writableState;
    state.corked++;
  };
  Writable.prototype.uncork = function() {
    var state = this._writableState;
    if (state.corked) {
      state.corked--;
      if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
    }
  };
  Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
    if (typeof encoding === "string") encoding = encoding.toLowerCase();
    if (!(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((encoding + "").toLowerCase()) > -1)) throw new TypeError("Unknown encoding: " + encoding);
    this._writableState.defaultEncoding = encoding;
    return this;
  };
  function decodeChunk(state, chunk, encoding) {
    if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") {
      chunk = Buffer2.from(chunk, encoding);
    }
    return chunk;
  }
  Object.defineProperty(Writable.prototype, "writableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function() {
      return this._writableState.highWaterMark;
    }
  });
  function writeOrBuffer(stream2, state, isBuf, chunk, encoding, cb) {
    if (!isBuf) {
      var newChunk = decodeChunk(state, chunk, encoding);
      if (chunk !== newChunk) {
        isBuf = true;
        encoding = "buffer";
        chunk = newChunk;
      }
    }
    var len = state.objectMode ? 1 : chunk.length;
    state.length += len;
    var ret = state.length < state.highWaterMark;
    if (!ret) state.needDrain = true;
    if (state.writing || state.corked) {
      var last = state.lastBufferedRequest;
      state.lastBufferedRequest = {
        chunk,
        encoding,
        isBuf,
        callback: cb,
        next: null
      };
      if (last) {
        last.next = state.lastBufferedRequest;
      } else {
        state.bufferedRequest = state.lastBufferedRequest;
      }
      state.bufferedRequestCount += 1;
    } else {
      doWrite(stream2, state, false, len, chunk, encoding, cb);
    }
    return ret;
  }
  function doWrite(stream2, state, writev, len, chunk, encoding, cb) {
    state.writelen = len;
    state.writecb = cb;
    state.writing = true;
    state.sync = true;
    if (writev) stream2._writev(chunk, state.onwrite);
    else stream2._write(chunk, encoding, state.onwrite);
    state.sync = false;
  }
  function onwriteError(stream2, state, sync, er, cb) {
    --state.pendingcb;
    if (sync) {
      pna.nextTick(cb, er);
      pna.nextTick(finishMaybe, stream2, state);
      stream2._writableState.errorEmitted = true;
      stream2.emit("error", er);
    } else {
      cb(er);
      stream2._writableState.errorEmitted = true;
      stream2.emit("error", er);
      finishMaybe(stream2, state);
    }
  }
  function onwriteStateUpdate(state) {
    state.writing = false;
    state.writecb = null;
    state.length -= state.writelen;
    state.writelen = 0;
  }
  function onwrite(stream2, er) {
    var state = stream2._writableState;
    var sync = state.sync;
    var cb = state.writecb;
    onwriteStateUpdate(state);
    if (er) onwriteError(stream2, state, sync, er, cb);
    else {
      var finished = needFinish(state);
      if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
        clearBuffer(stream2, state);
      }
      if (sync) {
        asyncWrite(afterWrite, stream2, state, finished, cb);
      } else {
        afterWrite(stream2, state, finished, cb);
      }
    }
  }
  function afterWrite(stream2, state, finished, cb) {
    if (!finished) onwriteDrain(stream2, state);
    state.pendingcb--;
    cb();
    finishMaybe(stream2, state);
  }
  function onwriteDrain(stream2, state) {
    if (state.length === 0 && state.needDrain) {
      state.needDrain = false;
      stream2.emit("drain");
    }
  }
  function clearBuffer(stream2, state) {
    state.bufferProcessing = true;
    var entry = state.bufferedRequest;
    if (stream2._writev && entry && entry.next) {
      var l2 = state.bufferedRequestCount;
      var buffer2 = new Array(l2);
      var holder = state.corkedRequestsFree;
      holder.entry = entry;
      var count = 0;
      var allBuffers = true;
      while (entry) {
        buffer2[count] = entry;
        if (!entry.isBuf) allBuffers = false;
        entry = entry.next;
        count += 1;
      }
      buffer2.allBuffers = allBuffers;
      doWrite(stream2, state, true, state.length, buffer2, "", holder.finish);
      state.pendingcb++;
      state.lastBufferedRequest = null;
      if (holder.next) {
        state.corkedRequestsFree = holder.next;
        holder.next = null;
      } else {
        state.corkedRequestsFree = new CorkedRequest(state);
      }
      state.bufferedRequestCount = 0;
    } else {
      while (entry) {
        var chunk = entry.chunk;
        var encoding = entry.encoding;
        var cb = entry.callback;
        var len = state.objectMode ? 1 : chunk.length;
        doWrite(stream2, state, false, len, chunk, encoding, cb);
        entry = entry.next;
        state.bufferedRequestCount--;
        if (state.writing) {
          break;
        }
      }
      if (entry === null) state.lastBufferedRequest = null;
    }
    state.bufferedRequest = entry;
    state.bufferProcessing = false;
  }
  Writable.prototype._write = function(chunk, encoding, cb) {
    cb(new Error("_write() is not implemented"));
  };
  Writable.prototype._writev = null;
  Writable.prototype.end = function(chunk, encoding, cb) {
    var state = this._writableState;
    if (typeof chunk === "function") {
      cb = chunk;
      chunk = null;
      encoding = null;
    } else if (typeof encoding === "function") {
      cb = encoding;
      encoding = null;
    }
    if (chunk !== null && chunk !== void 0) this.write(chunk, encoding);
    if (state.corked) {
      state.corked = 1;
      this.uncork();
    }
    if (!state.ending) endWritable(this, state, cb);
  };
  function needFinish(state) {
    return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  }
  function callFinal(stream2, state) {
    stream2._final(function(err) {
      state.pendingcb--;
      if (err) {
        stream2.emit("error", err);
      }
      state.prefinished = true;
      stream2.emit("prefinish");
      finishMaybe(stream2, state);
    });
  }
  function prefinish(stream2, state) {
    if (!state.prefinished && !state.finalCalled) {
      if (typeof stream2._final === "function") {
        state.pendingcb++;
        state.finalCalled = true;
        pna.nextTick(callFinal, stream2, state);
      } else {
        state.prefinished = true;
        stream2.emit("prefinish");
      }
    }
  }
  function finishMaybe(stream2, state) {
    var need = needFinish(state);
    if (need) {
      prefinish(stream2, state);
      if (state.pendingcb === 0) {
        state.finished = true;
        stream2.emit("finish");
      }
    }
    return need;
  }
  function endWritable(stream2, state, cb) {
    state.ending = true;
    finishMaybe(stream2, state);
    if (cb) {
      if (state.finished) pna.nextTick(cb);
      else stream2.once("finish", cb);
    }
    state.ended = true;
    stream2.writable = false;
  }
  function onCorkedFinish(corkReq, state, err) {
    var entry = corkReq.entry;
    corkReq.entry = null;
    while (entry) {
      var cb = entry.callback;
      state.pendingcb--;
      cb(err);
      entry = entry.next;
    }
    state.corkedRequestsFree.next = corkReq;
  }
  Object.defineProperty(Writable.prototype, "destroyed", {
    get: function() {
      if (this._writableState === void 0) {
        return false;
      }
      return this._writableState.destroyed;
    },
    set: function(value) {
      if (!this._writableState) {
        return;
      }
      this._writableState.destroyed = value;
    }
  });
  Writable.prototype.destroy = destroyImpl.destroy;
  Writable.prototype._undestroy = destroyImpl.undestroy;
  Writable.prototype._destroy = function(err, cb) {
    this.end();
    cb(err);
  };
  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 pna = requireProcessNextickArgs();
  var objectKeys = Object.keys || function(obj) {
    var keys2 = [];
    for (var key2 in obj) {
      keys2.push(key2);
    }
    return keys2;
  };
  _stream_duplex = Duplex;
  var util2 = Object.create(requireUtil$1());
  util2.inherits = requireInherits_browser();
  var Readable = require_stream_readable();
  var Writable = require_stream_writable();
  util2.inherits(Duplex, Readable);
  {
    var keys = objectKeys(Writable.prototype);
    for (var v2 = 0; v2 < keys.length; v2++) {
      var method = keys[v2];
      if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
    }
  }
  function Duplex(options2) {
    if (!(this instanceof Duplex)) return new Duplex(options2);
    Readable.call(this, options2);
    Writable.call(this, options2);
    if (options2 && options2.readable === false) this.readable = false;
    if (options2 && options2.writable === false) this.writable = false;
    this.allowHalfOpen = true;
    if (options2 && options2.allowHalfOpen === false) this.allowHalfOpen = false;
    this.once("end", onend);
  }
  Object.defineProperty(Duplex.prototype, "writableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function() {
      return this._writableState.highWaterMark;
    }
  });
  function onend() {
    if (this.allowHalfOpen || this._writableState.ended) return;
    pna.nextTick(onEndNT, this);
  }
  function onEndNT(self2) {
    self2.end();
  }
  Object.defineProperty(Duplex.prototype, "destroyed", {
    get: function() {
      if (this._readableState === void 0 || this._writableState === void 0) {
        return false;
      }
      return this._readableState.destroyed && this._writableState.destroyed;
    },
    set: function(value) {
      if (this._readableState === void 0 || this._writableState === void 0) {
        return;
      }
      this._readableState.destroyed = value;
      this._writableState.destroyed = value;
    }
  });
  Duplex.prototype._destroy = function(err, cb) {
    this.push(null);
    this.end();
    pna.nextTick(cb, err);
  };
  return _stream_duplex;
}
var string_decoder$1 = {};
var hasRequiredString_decoder$1;
function requireString_decoder$1() {
  if (hasRequiredString_decoder$1) return string_decoder$1;
  hasRequiredString_decoder$1 = 1;
  var Buffer2 = requireSafeBuffer().Buffer;
  var isEncoding = Buffer2.isEncoding || function(encoding) {
    encoding = "" + encoding;
    switch (encoding && encoding.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 _normalizeEncoding(enc) {
    if (!enc) return "utf8";
    var retried;
    while (true) {
      switch (enc) {
        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 enc;
        default:
          if (retried) return;
          enc = ("" + enc).toLowerCase();
          retried = true;
      }
    }
  }
  function normalizeEncoding(enc) {
    var nenc = _normalizeEncoding(enc);
    if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc);
    return nenc || enc;
  }
  string_decoder$1.StringDecoder = StringDecoder;
  function StringDecoder(encoding) {
    this.encoding = normalizeEncoding(encoding);
    var nb;
    switch (this.encoding) {
      case "utf16le":
        this.text = utf16Text;
        this.end = utf16End;
        nb = 4;
        break;
      case "utf8":
        this.fillLast = utf8FillLast;
        nb = 4;
        break;
      case "base64":
        this.text = base64Text;
        this.end = base64End;
        nb = 3;
        break;
      default:
        this.write = simpleWrite;
        this.end = simpleEnd;
        return;
    }
    this.lastNeed = 0;
    this.lastTotal = 0;
    this.lastChar = Buffer2.allocUnsafe(nb);
  }
  StringDecoder.prototype.write = function(buf) {
    if (buf.length === 0) return "";
    var r2;
    var i2;
    if (this.lastNeed) {
      r2 = this.fillLast(buf);
      if (r2 === void 0) return "";
      i2 = this.lastNeed;
      this.lastNeed = 0;
    } else {
      i2 = 0;
    }
    if (i2 < buf.length) return r2 ? r2 + this.text(buf, i2) : this.text(buf, i2);
    return r2 || "";
  };
  StringDecoder.prototype.end = utf8End;
  StringDecoder.prototype.text = utf8Text;
  StringDecoder.prototype.fillLast = function(buf) {
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
    this.lastNeed -= buf.length;
  };
  function utf8CheckByte(byte) {
    if (byte <= 127) return 0;
    else if (byte >> 5 === 6) return 2;
    else if (byte >> 4 === 14) return 3;
    else if (byte >> 3 === 30) return 4;
    return byte >> 6 === 2 ? -1 : -2;
  }
  function utf8CheckIncomplete(self2, buf, i2) {
    var j = buf.length - 1;
    if (j < i2) return 0;
    var nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self2.lastNeed = nb - 1;
      return nb;
    }
    if (--j < i2 || nb === -2) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self2.lastNeed = nb - 2;
      return nb;
    }
    if (--j < i2 || nb === -2) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) {
        if (nb === 2) nb = 0;
        else self2.lastNeed = nb - 3;
      }
      return nb;
    }
    return 0;
  }
  function utf8CheckExtraBytes(self2, buf, p2) {
    if ((buf[0] & 192) !== 128) {
      self2.lastNeed = 0;
      return "�";
    }
    if (self2.lastNeed > 1 && buf.length > 1) {
      if ((buf[1] & 192) !== 128) {
        self2.lastNeed = 1;
        return "�";
      }
      if (self2.lastNeed > 2 && buf.length > 2) {
        if ((buf[2] & 192) !== 128) {
          self2.lastNeed = 2;
          return "�";
        }
      }
    }
  }
  function utf8FillLast(buf) {
    var p2 = this.lastTotal - this.lastNeed;
    var r2 = utf8CheckExtraBytes(this, buf);
    if (r2 !== void 0) return r2;
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, p2, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, p2, 0, buf.length);
    this.lastNeed -= buf.length;
  }
  function utf8Text(buf, i2) {
    var total = utf8CheckIncomplete(this, buf, i2);
    if (!this.lastNeed) return buf.toString("utf8", i2);
    this.lastTotal = total;
    var end = buf.length - (total - this.lastNeed);
    buf.copy(this.lastChar, 0, end);
    return buf.toString("utf8", i2, end);
  }
  function utf8End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) return r2 + "�";
    return r2;
  }
  function utf16Text(buf, i2) {
    if ((buf.length - i2) % 2 === 0) {
      var r2 = buf.toString("utf16le", i2);
      if (r2) {
        var c2 = r2.charCodeAt(r2.length - 1);
        if (c2 >= 55296 && c2 <= 56319) {
          this.lastNeed = 2;
          this.lastTotal = 4;
          this.lastChar[0] = buf[buf.length - 2];
          this.lastChar[1] = buf[buf.length - 1];
          return r2.slice(0, -1);
        }
      }
      return r2;
    }
    this.lastNeed = 1;
    this.lastTotal = 2;
    this.lastChar[0] = buf[buf.length - 1];
    return buf.toString("utf16le", i2, buf.length - 1);
  }
  function utf16End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) {
      var end = this.lastTotal - this.lastNeed;
      return r2 + this.lastChar.toString("utf16le", 0, end);
    }
    return r2;
  }
  function base64Text(buf, i2) {
    var n2 = (buf.length - i2) % 3;
    if (n2 === 0) return buf.toString("base64", i2);
    this.lastNeed = 3 - n2;
    this.lastTotal = 3;
    if (n2 === 1) {
      this.lastChar[0] = buf[buf.length - 1];
    } else {
      this.lastChar[0] = buf[buf.length - 2];
      this.lastChar[1] = buf[buf.length - 1];
    }
    return buf.toString("base64", i2, buf.length - n2);
  }
  function base64End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) return r2 + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
    return r2;
  }
  function simpleWrite(buf) {
    return buf.toString(this.encoding);
  }
  function simpleEnd(buf) {
    return buf && buf.length ? this.write(buf) : "";
  }
  return string_decoder$1;
}
var _stream_readable;
var hasRequired_stream_readable;
function require_stream_readable() {
  if (hasRequired_stream_readable) return _stream_readable;
  hasRequired_stream_readable = 1;
  var pna = requireProcessNextickArgs();
  _stream_readable = Readable;
  var isArray2 = requireIsarray();
  var Duplex;
  Readable.ReadableState = ReadableState;
  requireEvents().EventEmitter;
  var EElistenerCount = function(emitter, type2) {
    return emitter.listeners(type2).length;
  };
  var Stream2 = requireStreamBrowser();
  var Buffer2 = requireSafeBuffer().Buffer;
  var OurUint8Array = (typeof commonjsGlobal$1 !== "undefined" ? commonjsGlobal$1 : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {
  };
  function _uint8ArrayToBuffer(chunk) {
    return Buffer2.from(chunk);
  }
  function _isUint8Array(obj) {
    return Buffer2.isBuffer(obj) || obj instanceof OurUint8Array;
  }
  var util2 = Object.create(requireUtil$1());
  util2.inherits = requireInherits_browser();
  var debugUtil = require$$0$2;
  var debug2 = void 0;
  if (debugUtil && debugUtil.debuglog) {
    debug2 = debugUtil.debuglog("stream");
  } else {
    debug2 = function() {
    };
  }
  var BufferList2 = requireBufferList();
  var destroyImpl = requireDestroy();
  var StringDecoder;
  util2.inherits(Readable, Stream2);
  var kProxyEvents = ["error", "close", "destroy", "pause", "resume"];
  function prependListener(emitter, event, fn) {
    if (typeof emitter.prependListener === "function") return emitter.prependListener(event, fn);
    if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);
    else if (isArray2(emitter._events[event])) emitter._events[event].unshift(fn);
    else emitter._events[event] = [fn, emitter._events[event]];
  }
  function ReadableState(options2, stream2) {
    Duplex = Duplex || require_stream_duplex();
    options2 = options2 || {};
    var isDuplex = stream2 instanceof Duplex;
    this.objectMode = !!options2.objectMode;
    if (isDuplex) this.objectMode = this.objectMode || !!options2.readableObjectMode;
    var hwm = options2.highWaterMark;
    var readableHwm = options2.readableHighWaterMark;
    var defaultHwm = this.objectMode ? 16 : 16 * 1024;
    if (hwm || hwm === 0) this.highWaterMark = hwm;
    else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;
    else this.highWaterMark = defaultHwm;
    this.highWaterMark = Math.floor(this.highWaterMark);
    this.buffer = new BufferList2();
    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.destroyed = false;
    this.defaultEncoding = options2.defaultEncoding || "utf8";
    this.awaitDrain = 0;
    this.readingMore = false;
    this.decoder = null;
    this.encoding = null;
    if (options2.encoding) {
      if (!StringDecoder) StringDecoder = requireString_decoder$1().StringDecoder;
      this.decoder = new StringDecoder(options2.encoding);
      this.encoding = options2.encoding;
    }
  }
  function Readable(options2) {
    Duplex = Duplex || require_stream_duplex();
    if (!(this instanceof Readable)) return new Readable(options2);
    this._readableState = new ReadableState(options2, this);
    this.readable = true;
    if (options2) {
      if (typeof options2.read === "function") this._read = options2.read;
      if (typeof options2.destroy === "function") this._destroy = options2.destroy;
    }
    Stream2.call(this);
  }
  Object.defineProperty(Readable.prototype, "destroyed", {
    get: function() {
      if (this._readableState === void 0) {
        return false;
      }
      return this._readableState.destroyed;
    },
    set: function(value) {
      if (!this._readableState) {
        return;
      }
      this._readableState.destroyed = value;
    }
  });
  Readable.prototype.destroy = destroyImpl.destroy;
  Readable.prototype._undestroy = destroyImpl.undestroy;
  Readable.prototype._destroy = function(err, cb) {
    this.push(null);
    cb(err);
  };
  Readable.prototype.push = function(chunk, encoding) {
    var state = this._readableState;
    var skipChunkCheck;
    if (!state.objectMode) {
      if (typeof chunk === "string") {
        encoding = encoding || state.defaultEncoding;
        if (encoding !== state.encoding) {
          chunk = Buffer2.from(chunk, encoding);
          encoding = "";
        }
        skipChunkCheck = true;
      }
    } else {
      skipChunkCheck = true;
    }
    return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  };
  Readable.prototype.unshift = function(chunk) {
    return readableAddChunk(this, chunk, null, true, false);
  };
  function readableAddChunk(stream2, chunk, encoding, addToFront, skipChunkCheck) {
    var state = stream2._readableState;
    if (chunk === null) {
      state.reading = false;
      onEofChunk(stream2, state);
    } else {
      var er;
      if (!skipChunkCheck) er = chunkInvalid(state, chunk);
      if (er) {
        stream2.emit("error", er);
      } else if (state.objectMode || chunk && chunk.length > 0) {
        if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer2.prototype) {
          chunk = _uint8ArrayToBuffer(chunk);
        }
        if (addToFront) {
          if (state.endEmitted) stream2.emit("error", new Error("stream.unshift() after end event"));
          else addChunk(stream2, state, chunk, true);
        } else if (state.ended) {
          stream2.emit("error", new Error("stream.push() after EOF"));
        } else {
          state.reading = false;
          if (state.decoder && !encoding) {
            chunk = state.decoder.write(chunk);
            if (state.objectMode || chunk.length !== 0) addChunk(stream2, state, chunk, false);
            else maybeReadMore(stream2, state);
          } else {
            addChunk(stream2, state, chunk, false);
          }
        }
      } else if (!addToFront) {
        state.reading = false;
      }
    }
    return needMoreData(state);
  }
  function addChunk(stream2, state, chunk, addToFront) {
    if (state.flowing && state.length === 0 && !state.sync) {
      stream2.emit("data", chunk);
      stream2.read(0);
    } else {
      state.length += state.objectMode ? 1 : chunk.length;
      if (addToFront) state.buffer.unshift(chunk);
      else state.buffer.push(chunk);
      if (state.needReadable) emitReadable(stream2);
    }
    maybeReadMore(stream2, state);
  }
  function chunkInvalid(state, chunk) {
    var er;
    if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) {
      er = new TypeError("Invalid non-string/buffer chunk");
    }
    return er;
  }
  function needMoreData(state) {
    return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  }
  Readable.prototype.isPaused = function() {
    return this._readableState.flowing === false;
  };
  Readable.prototype.setEncoding = function(enc) {
    if (!StringDecoder) StringDecoder = requireString_decoder$1().StringDecoder;
    this._readableState.decoder = new StringDecoder(enc);
    this._readableState.encoding = enc;
    return this;
  };
  var MAX_HWM = 8388608;
  function computeNewHighWaterMark(n2) {
    if (n2 >= MAX_HWM) {
      n2 = MAX_HWM;
    } else {
      n2--;
      n2 |= n2 >>> 1;
      n2 |= n2 >>> 2;
      n2 |= n2 >>> 4;
      n2 |= n2 >>> 8;
      n2 |= n2 >>> 16;
      n2++;
    }
    return n2;
  }
  function howMuchToRead(n2, state) {
    if (n2 <= 0 || state.length === 0 && state.ended) return 0;
    if (state.objectMode) return 1;
    if (n2 !== n2) {
      if (state.flowing && state.length) return state.buffer.head.data.length;
      else return state.length;
    }
    if (n2 > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n2);
    if (n2 <= state.length) return n2;
    if (!state.ended) {
      state.needReadable = true;
      return 0;
    }
    return state.length;
  }
  Readable.prototype.read = function(n2) {
    debug2("read", n2);
    n2 = parseInt(n2, 10);
    var state = this._readableState;
    var nOrig = n2;
    if (n2 !== 0) state.emittedReadable = false;
    if (n2 === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
      debug2("read: emitReadable", state.length, state.ended);
      if (state.length === 0 && state.ended) endReadable(this);
      else emitReadable(this);
      return null;
    }
    n2 = howMuchToRead(n2, state);
    if (n2 === 0 && state.ended) {
      if (state.length === 0) endReadable(this);
      return null;
    }
    var doRead = state.needReadable;
    debug2("need readable", doRead);
    if (state.length === 0 || state.length - n2 < state.highWaterMark) {
      doRead = true;
      debug2("length less than watermark", doRead);
    }
    if (state.ended || state.reading) {
      doRead = false;
      debug2("reading or ended", doRead);
    } else if (doRead) {
      debug2("do read");
      state.reading = true;
      state.sync = true;
      if (state.length === 0) state.needReadable = true;
      this._read(state.highWaterMark);
      state.sync = false;
      if (!state.reading) n2 = howMuchToRead(nOrig, state);
    }
    var ret;
    if (n2 > 0) ret = fromList(n2, state);
    else ret = null;
    if (ret === null) {
      state.needReadable = true;
      n2 = 0;
    } else {
      state.length -= n2;
    }
    if (state.length === 0) {
      if (!state.ended) state.needReadable = true;
      if (nOrig !== n2 && state.ended) endReadable(this);
    }
    if (ret !== null) this.emit("data", ret);
    return ret;
  };
  function onEofChunk(stream2, state) {
    if (state.ended) return;
    if (state.decoder) {
      var chunk = state.decoder.end();
      if (chunk && chunk.length) {
        state.buffer.push(chunk);
        state.length += state.objectMode ? 1 : chunk.length;
      }
    }
    state.ended = true;
    emitReadable(stream2);
  }
  function emitReadable(stream2) {
    var state = stream2._readableState;
    state.needReadable = false;
    if (!state.emittedReadable) {
      debug2("emitReadable", state.flowing);
      state.emittedReadable = true;
      if (state.sync) pna.nextTick(emitReadable_, stream2);
      else emitReadable_(stream2);
    }
  }
  function emitReadable_(stream2) {
    debug2("emit readable");
    stream2.emit("readable");
    flow(stream2);
  }
  function maybeReadMore(stream2, state) {
    if (!state.readingMore) {
      state.readingMore = true;
      pna.nextTick(maybeReadMore_, stream2, state);
    }
  }
  function maybeReadMore_(stream2, state) {
    var len = state.length;
    while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
      debug2("maybeReadMore read 0");
      stream2.read(0);
      if (len === state.length)
        break;
      else len = state.length;
    }
    state.readingMore = false;
  }
  Readable.prototype._read = function(n2) {
    this.emit("error", new Error("_read() is not implemented"));
  };
  Readable.prototype.pipe = function(dest, pipeOpts) {
    var src2 = this;
    var state = this._readableState;
    switch (state.pipesCount) {
      case 0:
        state.pipes = dest;
        break;
      case 1:
        state.pipes = [state.pipes, dest];
        break;
      default:
        state.pipes.push(dest);
        break;
    }
    state.pipesCount += 1;
    debug2("pipe count=%d opts=%j", state.pipesCount, pipeOpts);
    var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
    var endFn = doEnd ? onend : unpipe;
    if (state.endEmitted) pna.nextTick(endFn);
    else src2.once("end", endFn);
    dest.on("unpipe", onunpipe);
    function onunpipe(readable, unpipeInfo) {
      debug2("onunpipe");
      if (readable === src2) {
        if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
          unpipeInfo.hasUnpiped = true;
          cleanup();
        }
      }
    }
    function onend() {
      debug2("onend");
      dest.end();
    }
    var ondrain = pipeOnDrain(src2);
    dest.on("drain", ondrain);
    var cleanedUp = false;
    function cleanup() {
      debug2("cleanup");
      dest.removeListener("close", onclose);
      dest.removeListener("finish", onfinish);
      dest.removeListener("drain", ondrain);
      dest.removeListener("error", onerror);
      dest.removeListener("unpipe", onunpipe);
      src2.removeListener("end", onend);
      src2.removeListener("end", unpipe);
      src2.removeListener("data", ondata);
      cleanedUp = true;
      if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
    }
    var increasedAwaitDrain = false;
    src2.on("data", ondata);
    function ondata(chunk) {
      debug2("ondata");
      increasedAwaitDrain = false;
      var ret = dest.write(chunk);
      if (false === ret && !increasedAwaitDrain) {
        if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
          debug2("false write response, pause", state.awaitDrain);
          state.awaitDrain++;
          increasedAwaitDrain = true;
        }
        src2.pause();
      }
    }
    function onerror(er) {
      debug2("onerror", er);
      unpipe();
      dest.removeListener("error", onerror);
      if (EElistenerCount(dest, "error") === 0) dest.emit("error", er);
    }
    prependListener(dest, "error", onerror);
    function onclose() {
      dest.removeListener("finish", onfinish);
      unpipe();
    }
    dest.once("close", onclose);
    function onfinish() {
      debug2("onfinish");
      dest.removeListener("close", onclose);
      unpipe();
    }
    dest.once("finish", onfinish);
    function unpipe() {
      debug2("unpipe");
      src2.unpipe(dest);
    }
    dest.emit("pipe", src2);
    if (!state.flowing) {
      debug2("pipe resume");
      src2.resume();
    }
    return dest;
  };
  function pipeOnDrain(src2) {
    return function() {
      var state = src2._readableState;
      debug2("pipeOnDrain", state.awaitDrain);
      if (state.awaitDrain) state.awaitDrain--;
      if (state.awaitDrain === 0 && EElistenerCount(src2, "data")) {
        state.flowing = true;
        flow(src2);
      }
    };
  }
  Readable.prototype.unpipe = function(dest) {
    var state = this._readableState;
    var unpipeInfo = { hasUnpiped: false };
    if (state.pipesCount === 0) return this;
    if (state.pipesCount === 1) {
      if (dest && dest !== state.pipes) return this;
      if (!dest) dest = state.pipes;
      state.pipes = null;
      state.pipesCount = 0;
      state.flowing = false;
      if (dest) dest.emit("unpipe", this, unpipeInfo);
      return this;
    }
    if (!dest) {
      var dests = state.pipes;
      var len = state.pipesCount;
      state.pipes = null;
      state.pipesCount = 0;
      state.flowing = false;
      for (var i2 = 0; i2 < len; i2++) {
        dests[i2].emit("unpipe", this, { hasUnpiped: false });
      }
      return this;
    }
    var index2 = indexOf(state.pipes, dest);
    if (index2 === -1) return this;
    state.pipes.splice(index2, 1);
    state.pipesCount -= 1;
    if (state.pipesCount === 1) state.pipes = state.pipes[0];
    dest.emit("unpipe", this, unpipeInfo);
    return this;
  };
  Readable.prototype.on = function(ev, fn) {
    var res = Stream2.prototype.on.call(this, ev, fn);
    if (ev === "data") {
      if (this._readableState.flowing !== false) this.resume();
    } else if (ev === "readable") {
      var state = this._readableState;
      if (!state.endEmitted && !state.readableListening) {
        state.readableListening = state.needReadable = true;
        state.emittedReadable = false;
        if (!state.reading) {
          pna.nextTick(nReadingNextTick, this);
        } else if (state.length) {
          emitReadable(this);
        }
      }
    }
    return res;
  };
  Readable.prototype.addListener = Readable.prototype.on;
  function nReadingNextTick(self2) {
    debug2("readable nexttick read 0");
    self2.read(0);
  }
  Readable.prototype.resume = function() {
    var state = this._readableState;
    if (!state.flowing) {
      debug2("resume");
      state.flowing = true;
      resume(this, state);
    }
    return this;
  };
  function resume(stream2, state) {
    if (!state.resumeScheduled) {
      state.resumeScheduled = true;
      pna.nextTick(resume_, stream2, state);
    }
  }
  function resume_(stream2, state) {
    if (!state.reading) {
      debug2("resume read 0");
      stream2.read(0);
    }
    state.resumeScheduled = false;
    state.awaitDrain = 0;
    stream2.emit("resume");
    flow(stream2);
    if (state.flowing && !state.reading) stream2.read(0);
  }
  Readable.prototype.pause = function() {
    debug2("call pause flowing=%j", this._readableState.flowing);
    if (false !== this._readableState.flowing) {
      debug2("pause");
      this._readableState.flowing = false;
      this.emit("pause");
    }
    return this;
  };
  function flow(stream2) {
    var state = stream2._readableState;
    debug2("flow", state.flowing);
    while (state.flowing && stream2.read() !== null) {
    }
  }
  Readable.prototype.wrap = function(stream2) {
    var _this = this;
    var state = this._readableState;
    var paused = false;
    stream2.on("end", function() {
      debug2("wrapped end");
      if (state.decoder && !state.ended) {
        var chunk = state.decoder.end();
        if (chunk && chunk.length) _this.push(chunk);
      }
      _this.push(null);
    });
    stream2.on("data", function(chunk) {
      debug2("wrapped data");
      if (state.decoder) chunk = state.decoder.write(chunk);
      if (state.objectMode && (chunk === null || chunk === void 0)) return;
      else if (!state.objectMode && (!chunk || !chunk.length)) return;
      var ret = _this.push(chunk);
      if (!ret) {
        paused = true;
        stream2.pause();
      }
    });
    for (var i2 in stream2) {
      if (this[i2] === void 0 && typeof stream2[i2] === "function") {
        this[i2] = /* @__PURE__ */ function(method) {
          return function() {
            return stream2[method].apply(stream2, arguments);
          };
        }(i2);
      }
    }
    for (var n2 = 0; n2 < kProxyEvents.length; n2++) {
      stream2.on(kProxyEvents[n2], this.emit.bind(this, kProxyEvents[n2]));
    }
    this._read = function(n3) {
      debug2("wrapped _read", n3);
      if (paused) {
        paused = false;
        stream2.resume();
      }
    };
    return this;
  };
  Object.defineProperty(Readable.prototype, "readableHighWaterMark", {
    // making it explicit this property is not enumerable
    // because otherwise some prototype manipulation in
    // userland will fail
    enumerable: false,
    get: function() {
      return this._readableState.highWaterMark;
    }
  });
  Readable._fromList = fromList;
  function fromList(n2, state) {
    if (state.length === 0) return null;
    var ret;
    if (state.objectMode) ret = state.buffer.shift();
    else if (!n2 || n2 >= state.length) {
      if (state.decoder) ret = state.buffer.join("");
      else if (state.buffer.length === 1) ret = state.buffer.head.data;
      else ret = state.buffer.concat(state.length);
      state.buffer.clear();
    } else {
      ret = fromListPartial(n2, state.buffer, state.decoder);
    }
    return ret;
  }
  function fromListPartial(n2, list, hasStrings) {
    var ret;
    if (n2 < list.head.data.length) {
      ret = list.head.data.slice(0, n2);
      list.head.data = list.head.data.slice(n2);
    } else if (n2 === list.head.data.length) {
      ret = list.shift();
    } else {
      ret = hasStrings ? copyFromBufferString(n2, list) : copyFromBuffer(n2, list);
    }
    return ret;
  }
  function copyFromBufferString(n2, list) {
    var p2 = list.head;
    var c2 = 1;
    var ret = p2.data;
    n2 -= ret.length;
    while (p2 = p2.next) {
      var str = p2.data;
      var nb = n2 > str.length ? str.length : n2;
      if (nb === str.length) ret += str;
      else ret += str.slice(0, n2);
      n2 -= nb;
      if (n2 === 0) {
        if (nb === str.length) {
          ++c2;
          if (p2.next) list.head = p2.next;
          else list.head = list.tail = null;
        } else {
          list.head = p2;
          p2.data = str.slice(nb);
        }
        break;
      }
      ++c2;
    }
    list.length -= c2;
    return ret;
  }
  function copyFromBuffer(n2, list) {
    var ret = Buffer2.allocUnsafe(n2);
    var p2 = list.head;
    var c2 = 1;
    p2.data.copy(ret);
    n2 -= p2.data.length;
    while (p2 = p2.next) {
      var buf = p2.data;
      var nb = n2 > buf.length ? buf.length : n2;
      buf.copy(ret, ret.length - n2, 0, nb);
      n2 -= nb;
      if (n2 === 0) {
        if (nb === buf.length) {
          ++c2;
          if (p2.next) list.head = p2.next;
          else list.head = list.tail = null;
        } else {
          list.head = p2;
          p2.data = buf.slice(nb);
        }
        break;
      }
      ++c2;
    }
    list.length -= c2;
    return ret;
  }
  function endReadable(stream2) {
    var state = stream2._readableState;
    if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
    if (!state.endEmitted) {
      state.ended = true;
      pna.nextTick(endReadableNT, state, stream2);
    }
  }
  function endReadableNT(state, stream2) {
    if (!state.endEmitted && state.length === 0) {
      state.endEmitted = true;
      stream2.readable = false;
      stream2.emit("end");
    }
  }
  function indexOf(xs, x2) {
    for (var i2 = 0, l2 = xs.length; i2 < l2; i2++) {
      if (xs[i2] === x2) return i2;
    }
    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 = Transform;
  var Duplex = require_stream_duplex();
  var util2 = Object.create(requireUtil$1());
  util2.inherits = requireInherits_browser();
  util2.inherits(Transform, Duplex);
  function afterTransform(er, data2) {
    var ts = this._transformState;
    ts.transforming = false;
    var cb = ts.writecb;
    if (!cb) {
      return this.emit("error", new Error("write callback called multiple times"));
    }
    ts.writechunk = null;
    ts.writecb = null;
    if (data2 != null)
      this.push(data2);
    cb(er);
    var rs = this._readableState;
    rs.reading = false;
    if (rs.needReadable || rs.length < rs.highWaterMark) {
      this._read(rs.highWaterMark);
    }
  }
  function Transform(options2) {
    if (!(this instanceof Transform)) return new Transform(options2);
    Duplex.call(this, options2);
    this._transformState = {
      afterTransform: afterTransform.bind(this),
      needTransform: false,
      transforming: false,
      writecb: null,
      writechunk: null,
      writeencoding: null
    };
    this._readableState.needReadable = true;
    this._readableState.sync = false;
    if (options2) {
      if (typeof options2.transform === "function") this._transform = options2.transform;
      if (typeof options2.flush === "function") this._flush = options2.flush;
    }
    this.on("prefinish", prefinish);
  }
  function prefinish() {
    var _this = this;
    if (typeof this._flush === "function") {
      this._flush(function(er, data2) {
        done(_this, er, data2);
      });
    } else {
      done(this, null, null);
    }
  }
  Transform.prototype.push = function(chunk, encoding) {
    this._transformState.needTransform = false;
    return Duplex.prototype.push.call(this, chunk, encoding);
  };
  Transform.prototype._transform = function(chunk, encoding, cb) {
    throw new Error("_transform() is not implemented");
  };
  Transform.prototype._write = function(chunk, encoding, cb) {
    var ts = this._transformState;
    ts.writecb = cb;
    ts.writechunk = chunk;
    ts.writeencoding = encoding;
    if (!ts.transforming) {
      var rs = this._readableState;
      if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
    }
  };
  Transform.prototype._read = function(n2) {
    var ts = this._transformState;
    if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
      ts.transforming = true;
      this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
    } else {
      ts.needTransform = true;
    }
  };
  Transform.prototype._destroy = function(err, cb) {
    var _this2 = this;
    Duplex.prototype._destroy.call(this, err, function(err2) {
      cb(err2);
      _this2.emit("close");
    });
  };
  function done(stream2, er, data2) {
    if (er) return stream2.emit("error", er);
    if (data2 != null)
      stream2.push(data2);
    if (stream2._writableState.length) throw new Error("Calling transform done when ws.length != 0");
    if (stream2._transformState.transforming) throw new Error("Calling transform done when still transforming");
    return stream2.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 = PassThrough;
  var Transform = require_stream_transform();
  var util2 = Object.create(requireUtil$1());
  util2.inherits = requireInherits_browser();
  util2.inherits(PassThrough, Transform);
  function PassThrough(options2) {
    if (!(this instanceof PassThrough)) return new PassThrough(options2);
    Transform.call(this, options2);
  }
  PassThrough.prototype._transform = function(chunk, encoding, cb) {
    cb(null, chunk);
  };
  return _stream_passthrough;
}
var hasRequiredReadableBrowser;
function requireReadableBrowser() {
  if (hasRequiredReadableBrowser) return readableBrowser.exports;
  hasRequiredReadableBrowser = 1;
  (function(module2, exports) {
    exports = module2.exports = require_stream_readable();
    exports.Stream = exports;
    exports.Readable = exports;
    exports.Writable = require_stream_writable();
    exports.Duplex = require_stream_duplex();
    exports.Transform = require_stream_transform();
    exports.PassThrough = require_stream_passthrough();
  })(readableBrowser, readableBrowser.exports);
  return readableBrowser.exports;
}
var hashBase;
var hasRequiredHashBase;
function requireHashBase() {
  if (hasRequiredHashBase) return hashBase;
  hasRequiredHashBase = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var toBuffer2 = requireToBuffer$1();
  var Transform = requireReadableBrowser().Transform;
  var inherits = requireInherits_browser();
  function HashBase(blockSize) {
    Transform.call(this);
    this._block = Buffer2.allocUnsafe(blockSize);
    this._blockSize = blockSize;
    this._blockOffset = 0;
    this._length = [0, 0, 0, 0];
    this._finalized = false;
  }
  inherits(HashBase, Transform);
  HashBase.prototype._transform = function(chunk, encoding, callback) {
    var error = null;
    try {
      this.update(chunk, encoding);
    } catch (err) {
      error = err;
    }
    callback(error);
  };
  HashBase.prototype._flush = function(callback) {
    var error = null;
    try {
      this.push(this.digest());
    } catch (err) {
      error = err;
    }
    callback(error);
  };
  HashBase.prototype.update = function(data2, encoding) {
    if (this._finalized) {
      throw new Error("Digest already called");
    }
    var dataBuffer = toBuffer2(data2, encoding);
    var block = this._block;
    var offset = 0;
    while (this._blockOffset + dataBuffer.length - offset >= this._blockSize) {
      for (var i2 = this._blockOffset; i2 < this._blockSize; ) {
        block[i2] = dataBuffer[offset];
        i2 += 1;
        offset += 1;
      }
      this._update();
      this._blockOffset = 0;
    }
    while (offset < dataBuffer.length) {
      block[this._blockOffset] = dataBuffer[offset];
      this._blockOffset += 1;
      offset += 1;
    }
    for (var j = 0, carry = dataBuffer.length * 8; carry > 0; ++j) {
      this._length[j] += carry;
      carry = this._length[j] / 4294967296 | 0;
      if (carry > 0) {
        this._length[j] -= 4294967296 * carry;
      }
    }
    return this;
  };
  HashBase.prototype._update = function() {
    throw new Error("_update is not implemented");
  };
  HashBase.prototype.digest = function(encoding) {
    if (this._finalized) {
      throw new Error("Digest already called");
    }
    this._finalized = true;
    var digest = this._digest();
    if (encoding !== void 0) {
      digest = digest.toString(encoding);
    }
    this._block.fill(0);
    this._blockOffset = 0;
    for (var i2 = 0; i2 < 4; ++i2) {
      this._length[i2] = 0;
    }
    return digest;
  };
  HashBase.prototype._digest = function() {
    throw new Error("_digest is not implemented");
  };
  hashBase = HashBase;
  return hashBase;
}
var ripemd160$2;
var hasRequiredRipemd160$1;
function requireRipemd160$1() {
  if (hasRequiredRipemd160$1) return ripemd160$2;
  hasRequiredRipemd160$1 = 1;
  var Buffer2 = requireBuffer$1().Buffer;
  var inherits = requireInherits_browser();
  var HashBase = requireHashBase();
  var ARRAY16 = new Array(16);
  var zl = [
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    7,
    4,
    13,
    1,
    10,
    6,
    15,
    3,
    12,
    0,
    9,
    5,
    2,
    14,
    11,
    8,
    3,
    10,
    14,
    4,
    9,
    15,
    8,
    1,
    2,
    7,
    0,
    6,
    13,
    11,
    5,
    12,
    1,
    9,
    11,
    10,
    0,
    8,
    12,
    4,
    13,
    3,
    7,
    15,
    14,
    5,
    6,
    2,
    4,
    0,
    5,
    9,
    7,
    12,
    2,
    10,
    14,
    1,
    3,
    8,
    11,
    6,
    15,
    13
  ];
  var zr = [
    5,
    14,
    7,
    0,
    9,
    2,
    11,
    4,
    13,
    6,
    15,
    8,
    1,
    10,
    3,
    12,
    6,
    11,
    3,
    7,
    0,
    13,
    5,
    10,
    14,
    15,
    8,
    12,
    4,
    9,
    1,
    2,
    15,
    5,
    1,
    3,
    7,
    14,
    6,
    9,
    11,
    8,
    12,
    2,
    10,
    0,
    4,
    13,
    8,
    6,
    4,
    1,
    3,
    11,
    15,
    0,
    5,
    12,
    2,
    13,
    9,
    7,
    10,
    14,
    12,
    15,
    10,
    4,
    1,
    5,
    8,
    7,
    6,
    2,
    13,
    14,
    0,
    3,
    9,
    11
  ];
  var sl = [
    11,
    14,
    15,
    12,
    5,
    8,
    7,
    9,
    11,
    13,
    14,
    15,
    6,
    7,
    9,
    8,
    7,
    6,
    8,
    13,
    11,
    9,
    7,
    15,
    7,
    12,
    15,
    9,
    11,
    7,
    13,
    12,
    11,
    13,
    6,
    7,
    14,
    9,
    13,
    15,
    14,
    8,
    13,
    6,
    5,
    12,
    7,
    5,
    11,
    12,
    14,
    15,
    14,
    15,
    9,
    8,
    9,
    14,
    5,
    6,
    8,
    6,
    5,
    12,
    9,
    15,
    5,
    11,
    6,
    8,
    13,
    12,
    5,
    12,
    13,
    14,
    11,
    8,
    5,
    6
  ];
  var sr = [
    8,
    9,
    9,
    11,
    13,
    15,
    15,
    5,
    7,
    7,
    8,
    11,
    14,
    14,
    12,
    6,
    9,
    13,
    15,
    7,
    12,
    8,
    9,
    11,
    7,
    7,
    12,
    7,
    6,
    15,
    13,
    11,
    9,
    7,
    15,
    11,
    8,
    6,
    6,
    14,
    12,
    13,
    5,
    14,
    13,
    13,
    7,
    5,
    15,
    5,
    8,
    11,
    14,
    14,
    6,
    14,
    6,
    9,
    12,
    9,
    12,
    5,
    15,
    8,
    8,
    5,
    12,
    9,
    12,
    5,
    14,
    6,
    8,
    13,
    6,
    5,
    15,
    13,
    11,
    11
  ];
  var hl = [0, 1518500249, 1859775393, 2400959708, 2840853838];
  var hr = [1352829926, 1548603684, 1836072691, 2053994217, 0];
  function rotl2(x2, n2) {
    return x2 << n2 | x2 >>> 32 - n2;
  }
  function fn1(a2, b2, c2, d, e4, m, k2, s2) {
    return rotl2(a2 + (b2 ^ c2 ^ d) + m + k2 | 0, s2) + e4 | 0;
  }
  function fn2(a2, b2, c2, d, e4, m, k2, s2) {
    return rotl2(a2 + (b2 & c2 | ~b2 & d) + m + k2 | 0, s2) + e4 | 0;
  }
  function fn3(a2, b2, c2, d, e4, m, k2, s2) {
    return rotl2(a2 + ((b2 | ~c2) ^ d) + m + k2 | 0, s2) + e4 | 0;
  }
  function fn4(a2, b2, c2, d, e4, m, k2, s2) {
    return rotl2(a2 + (b2 & d | c2 & ~d) + m + k2 | 0, s2) + e4 | 0;
  }
  function fn5(a2, b2, c2, d, e4, m, k2, s2) {
    return rotl2(a2 + (b2 ^ (c2 | ~d)) + m + k2 | 0, s2) + e4 | 0;
  }
  function RIPEMD160() {
    HashBase.call(this, 64);
    this._a = 1732584193;
    this._b = 4023233417;
    this._c = 2562383102;
    this._d = 271733878;
    this._e = 3285377520;
  }
  inherits(RIPEMD160, HashBase);
  RIPEMD160.prototype._update = function() {
    var words = ARRAY16;
    for (var j = 0; j < 16; ++j) {
      words[j] = this._block.readInt32LE(j * 4);
    }
    var al = this._a | 0;
    var bl = this._b | 0;
    var cl = this._c | 0;
    var dl = this._d | 0;
    var el = this._e | 0;
    var ar = this._a | 0;
    var br = this._b | 0;
    var cr = this._c | 0;
    var dr = this._d | 0;
    var er = this._e | 0;
    for (var i2 = 0; i2 < 80; i2 += 1) {
      var tl;
      var tr;
      if (i2 < 16) {
        tl = fn1(al, bl, cl, dl, el, words[zl[i2]], hl[0], sl[i2]);
        tr = fn5(ar, br, cr, dr, er, words[zr[i2]], hr[0], sr[i2]);
      } else if (i2 < 32) {
        tl = fn2(al, bl, cl, dl, el, words[zl[i2]], hl[1], sl[i2]);
        tr = fn4(ar, br, cr, dr, er, words[zr[i2]], hr[1], sr[i2]);
      } else if (i2 < 48) {
        tl = fn3(al, bl, cl, dl, el, words[zl[i2]], hl[2], sl[i2]);
        tr = fn3(ar, br, cr, dr, er, words[zr[i2]], hr[2], sr[i2]);
      } else if (i2 < 64) {
        tl = fn4(al, bl, cl, dl, el, words[zl[i2]], hl[3], sl[i2]);
        tr = fn2(ar, br, cr, dr, er, words[zr[i2]], hr[3], sr[i2]);
      } else {
        tl = fn5(al, bl, cl, dl, el, words[zl[i2]], hl[4], sl[i2]);
        tr = fn1(ar, br, cr, dr, er, words[zr[i2]], hr[4], sr[i2]);
      }
      al = el;
      el = dl;
      dl = rotl2(cl, 10);
      cl = bl;
      bl = tl;
      ar = er;
      er = dr;
      dr = rotl2(cr, 10);
      cr = br;
      br = tr;
    }
    var t2 = this._b + cl + dr | 0;
    this._b = this._c + dl + er | 0;
    this._c = this._d + el + ar | 0;
    this._d = this._e + al + br | 0;
    this._e = this._a + bl + cr | 0;
    this._a = t2;
  };
  RIPEMD160.prototype._digest = function() {
    this._block[this._blockOffset] = 128;
    this._blockOffset += 1;
    if (this._blockOffset > 56) {
      this._block.fill(0, this._blockOffset, 64);
      this._update();
      this._blockOffset = 0;
    }
    this._block.fill(0, this._blockOffset, 56);
    this._block.writeUInt32LE(this._length[0], 56);
    this._block.writeUInt32LE(this._length[1], 60);
    this._update();
    var buffer2 = Buffer2.alloc ? Buffer2.alloc(20) : new Buffer2(20);
    buffer2.writeInt32LE(this._a, 0);
    buffer2.writeInt32LE(this._b, 4);
    buffer2.writeInt32LE(this._c, 8);
    buffer2.writeInt32LE(this._d, 12);
    buffer2.writeInt32LE(this._e, 16);
    return buffer2;
  };
  ripemd160$2 = RIPEMD160;
  return ripemd160$2;
}
var sha_js = { exports: {} };
var hash$1;
var hasRequiredHash$1;
function requireHash$1() {
  if (hasRequiredHash$1) return hash$1;
  hasRequiredHash$1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var toBuffer2 = /* @__PURE__ */ requireToBuffer$2();
  function Hash(blockSize, finalSize) {
    this._block = Buffer2.alloc(blockSize);
    this._finalSize = finalSize;
    this._blockSize = blockSize;
    this._len = 0;
  }
  Hash.prototype.update = function(data2, enc) {
    data2 = toBuffer2(data2, enc || "utf8");
    var block = this._block;
    var blockSize = this._blockSize;
    var length = data2.length;
    var accum = this._len;
    for (var offset = 0; offset < length; ) {
      var assigned = accum % blockSize;
      var remainder = Math.min(length - offset, blockSize - assigned);
      for (var i2 = 0; i2 < remainder; i2++) {
        block[assigned + i2] = data2[offset + i2];
      }
      accum += remainder;
      offset += remainder;
      if (accum % blockSize === 0) {
        this._update(block);
      }
    }
    this._len += length;
    return this;
  };
  Hash.prototype.digest = function(enc) {
    var rem = this._len % this._blockSize;
    this._block[rem] = 128;
    this._block.fill(0, rem + 1);
    if (rem >= this._finalSize) {
      this._update(this._block);
      this._block.fill(0);
    }
    var bits = this._len * 8;
    if (bits <= 4294967295) {
      this._block.writeUInt32BE(bits, this._blockSize - 4);
    } else {
      var lowBits = (bits & 4294967295) >>> 0;
      var highBits = (bits - lowBits) / 4294967296;
      this._block.writeUInt32BE(highBits, this._blockSize - 8);
      this._block.writeUInt32BE(lowBits, this._blockSize - 4);
    }
    this._update(this._block);
    var hash2 = this._hash();
    return enc ? hash2.toString(enc) : hash2;
  };
  Hash.prototype._update = function() {
    throw new Error("_update must be implemented by subclass");
  };
  hash$1 = Hash;
  return hash$1;
}
var sha$1;
var hasRequiredSha$1;
function requireSha$1() {
  if (hasRequiredSha$1) return sha$1;
  hasRequiredSha$1 = 1;
  var inherits = requireInherits_browser();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var K = [
    1518500249,
    1859775393,
    2400959708 | 0,
    3395469782 | 0
  ];
  var W = new Array(80);
  function Sha() {
    this.init();
    this._w = W;
    Hash.call(this, 64, 56);
  }
  inherits(Sha, Hash);
  Sha.prototype.init = function() {
    this._a = 1732584193;
    this._b = 4023233417;
    this._c = 2562383102;
    this._d = 271733878;
    this._e = 3285377520;
    return this;
  };
  function rotl5(num) {
    return num << 5 | num >>> 27;
  }
  function rotl30(num) {
    return num << 30 | num >>> 2;
  }
  function ft(s2, b2, c2, d) {
    if (s2 === 0) {
      return b2 & c2 | ~b2 & d;
    }
    if (s2 === 2) {
      return b2 & c2 | b2 & d | c2 & d;
    }
    return b2 ^ c2 ^ d;
  }
  Sha.prototype._update = function(M2) {
    var w = this._w;
    var a2 = this._a | 0;
    var b2 = this._b | 0;
    var c2 = this._c | 0;
    var d = this._d | 0;
    var e4 = this._e | 0;
    for (var i2 = 0; i2 < 16; ++i2) {
      w[i2] = M2.readInt32BE(i2 * 4);
    }
    for (; i2 < 80; ++i2) {
      w[i2] = w[i2 - 3] ^ w[i2 - 8] ^ w[i2 - 14] ^ w[i2 - 16];
    }
    for (var j = 0; j < 80; ++j) {
      var s2 = ~~(j / 20);
      var t2 = rotl5(a2) + ft(s2, b2, c2, d) + e4 + w[j] + K[s2] | 0;
      e4 = d;
      d = c2;
      c2 = rotl30(b2);
      b2 = a2;
      a2 = t2;
    }
    this._a = a2 + this._a | 0;
    this._b = b2 + this._b | 0;
    this._c = c2 + this._c | 0;
    this._d = d + this._d | 0;
    this._e = e4 + this._e | 0;
  };
  Sha.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(20);
    H.writeInt32BE(this._a | 0, 0);
    H.writeInt32BE(this._b | 0, 4);
    H.writeInt32BE(this._c | 0, 8);
    H.writeInt32BE(this._d | 0, 12);
    H.writeInt32BE(this._e | 0, 16);
    return H;
  };
  sha$1 = Sha;
  return sha$1;
}
var sha1$2;
var hasRequiredSha1$1;
function requireSha1$1() {
  if (hasRequiredSha1$1) return sha1$2;
  hasRequiredSha1$1 = 1;
  var inherits = requireInherits_browser();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var K = [
    1518500249,
    1859775393,
    2400959708 | 0,
    3395469782 | 0
  ];
  var W = new Array(80);
  function Sha1() {
    this.init();
    this._w = W;
    Hash.call(this, 64, 56);
  }
  inherits(Sha1, Hash);
  Sha1.prototype.init = function() {
    this._a = 1732584193;
    this._b = 4023233417;
    this._c = 2562383102;
    this._d = 271733878;
    this._e = 3285377520;
    return this;
  };
  function rotl1(num) {
    return num << 1 | num >>> 31;
  }
  function rotl5(num) {
    return num << 5 | num >>> 27;
  }
  function rotl30(num) {
    return num << 30 | num >>> 2;
  }
  function ft(s2, b2, c2, d) {
    if (s2 === 0) {
      return b2 & c2 | ~b2 & d;
    }
    if (s2 === 2) {
      return b2 & c2 | b2 & d | c2 & d;
    }
    return b2 ^ c2 ^ d;
  }
  Sha1.prototype._update = function(M2) {
    var w = this._w;
    var a2 = this._a | 0;
    var b2 = this._b | 0;
    var c2 = this._c | 0;
    var d = this._d | 0;
    var e4 = this._e | 0;
    for (var i2 = 0; i2 < 16; ++i2) {
      w[i2] = M2.readInt32BE(i2 * 4);
    }
    for (; i2 < 80; ++i2) {
      w[i2] = rotl1(w[i2 - 3] ^ w[i2 - 8] ^ w[i2 - 14] ^ w[i2 - 16]);
    }
    for (var j = 0; j < 80; ++j) {
      var s2 = ~~(j / 20);
      var t2 = rotl5(a2) + ft(s2, b2, c2, d) + e4 + w[j] + K[s2] | 0;
      e4 = d;
      d = c2;
      c2 = rotl30(b2);
      b2 = a2;
      a2 = t2;
    }
    this._a = a2 + this._a | 0;
    this._b = b2 + this._b | 0;
    this._c = c2 + this._c | 0;
    this._d = d + this._d | 0;
    this._e = e4 + this._e | 0;
  };
  Sha1.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(20);
    H.writeInt32BE(this._a | 0, 0);
    H.writeInt32BE(this._b | 0, 4);
    H.writeInt32BE(this._c | 0, 8);
    H.writeInt32BE(this._d | 0, 12);
    H.writeInt32BE(this._e | 0, 16);
    return H;
  };
  sha1$2 = Sha1;
  return sha1$2;
}
var sha256$4;
var hasRequiredSha256$1;
function requireSha256$1() {
  if (hasRequiredSha256$1) return sha256$4;
  hasRequiredSha256$1 = 1;
  var inherits = requireInherits_browser();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var K = [
    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
  ];
  var W = new Array(64);
  function Sha256() {
    this.init();
    this._w = W;
    Hash.call(this, 64, 56);
  }
  inherits(Sha256, Hash);
  Sha256.prototype.init = function() {
    this._a = 1779033703;
    this._b = 3144134277;
    this._c = 1013904242;
    this._d = 2773480762;
    this._e = 1359893119;
    this._f = 2600822924;
    this._g = 528734635;
    this._h = 1541459225;
    return this;
  };
  function ch(x2, y2, z2) {
    return z2 ^ x2 & (y2 ^ z2);
  }
  function maj(x2, y2, z2) {
    return x2 & y2 | z2 & (x2 | y2);
  }
  function sigma0(x2) {
    return (x2 >>> 2 | x2 << 30) ^ (x2 >>> 13 | x2 << 19) ^ (x2 >>> 22 | x2 << 10);
  }
  function sigma1(x2) {
    return (x2 >>> 6 | x2 << 26) ^ (x2 >>> 11 | x2 << 21) ^ (x2 >>> 25 | x2 << 7);
  }
  function gamma0(x2) {
    return (x2 >>> 7 | x2 << 25) ^ (x2 >>> 18 | x2 << 14) ^ x2 >>> 3;
  }
  function gamma1(x2) {
    return (x2 >>> 17 | x2 << 15) ^ (x2 >>> 19 | x2 << 13) ^ x2 >>> 10;
  }
  Sha256.prototype._update = function(M2) {
    var w = this._w;
    var a2 = this._a | 0;
    var b2 = this._b | 0;
    var c2 = this._c | 0;
    var d = this._d | 0;
    var e4 = this._e | 0;
    var f2 = this._f | 0;
    var g = this._g | 0;
    var h2 = this._h | 0;
    for (var i2 = 0; i2 < 16; ++i2) {
      w[i2] = M2.readInt32BE(i2 * 4);
    }
    for (; i2 < 64; ++i2) {
      w[i2] = gamma1(w[i2 - 2]) + w[i2 - 7] + gamma0(w[i2 - 15]) + w[i2 - 16] | 0;
    }
    for (var j = 0; j < 64; ++j) {
      var T1 = h2 + sigma1(e4) + ch(e4, f2, g) + K[j] + w[j] | 0;
      var T2 = sigma0(a2) + maj(a2, b2, c2) | 0;
      h2 = g;
      g = f2;
      f2 = e4;
      e4 = d + T1 | 0;
      d = c2;
      c2 = b2;
      b2 = a2;
      a2 = T1 + T2 | 0;
    }
    this._a = a2 + this._a | 0;
    this._b = b2 + this._b | 0;
    this._c = c2 + this._c | 0;
    this._d = d + this._d | 0;
    this._e = e4 + this._e | 0;
    this._f = f2 + this._f | 0;
    this._g = g + this._g | 0;
    this._h = h2 + this._h | 0;
  };
  Sha256.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(32);
    H.writeInt32BE(this._a, 0);
    H.writeInt32BE(this._b, 4);
    H.writeInt32BE(this._c, 8);
    H.writeInt32BE(this._d, 12);
    H.writeInt32BE(this._e, 16);
    H.writeInt32BE(this._f, 20);
    H.writeInt32BE(this._g, 24);
    H.writeInt32BE(this._h, 28);
    return H;
  };
  sha256$4 = Sha256;
  return sha256$4;
}
var sha224$3;
var hasRequiredSha224$1;
function requireSha224$1() {
  if (hasRequiredSha224$1) return sha224$3;
  hasRequiredSha224$1 = 1;
  var inherits = requireInherits_browser();
  var Sha256 = requireSha256$1();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var W = new Array(64);
  function Sha224() {
    this.init();
    this._w = W;
    Hash.call(this, 64, 56);
  }
  inherits(Sha224, Sha256);
  Sha224.prototype.init = function() {
    this._a = 3238371032;
    this._b = 914150663;
    this._c = 812702999;
    this._d = 4144912697;
    this._e = 4290775857;
    this._f = 1750603025;
    this._g = 1694076839;
    this._h = 3204075428;
    return this;
  };
  Sha224.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(28);
    H.writeInt32BE(this._a, 0);
    H.writeInt32BE(this._b, 4);
    H.writeInt32BE(this._c, 8);
    H.writeInt32BE(this._d, 12);
    H.writeInt32BE(this._e, 16);
    H.writeInt32BE(this._f, 20);
    H.writeInt32BE(this._g, 24);
    return H;
  };
  sha224$3 = Sha224;
  return sha224$3;
}
var sha512$3;
var hasRequiredSha512$1;
function requireSha512$1() {
  if (hasRequiredSha512$1) return sha512$3;
  hasRequiredSha512$1 = 1;
  var inherits = requireInherits_browser();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var K = [
    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
  ];
  var W = new Array(160);
  function Sha512() {
    this.init();
    this._w = W;
    Hash.call(this, 128, 112);
  }
  inherits(Sha512, Hash);
  Sha512.prototype.init = function() {
    this._ah = 1779033703;
    this._bh = 3144134277;
    this._ch = 1013904242;
    this._dh = 2773480762;
    this._eh = 1359893119;
    this._fh = 2600822924;
    this._gh = 528734635;
    this._hh = 1541459225;
    this._al = 4089235720;
    this._bl = 2227873595;
    this._cl = 4271175723;
    this._dl = 1595750129;
    this._el = 2917565137;
    this._fl = 725511199;
    this._gl = 4215389547;
    this._hl = 327033209;
    return this;
  };
  function Ch(x2, y2, z2) {
    return z2 ^ x2 & (y2 ^ z2);
  }
  function maj(x2, y2, z2) {
    return x2 & y2 | z2 & (x2 | y2);
  }
  function sigma0(x2, xl) {
    return (x2 >>> 28 | xl << 4) ^ (xl >>> 2 | x2 << 30) ^ (xl >>> 7 | x2 << 25);
  }
  function sigma1(x2, xl) {
    return (x2 >>> 14 | xl << 18) ^ (x2 >>> 18 | xl << 14) ^ (xl >>> 9 | x2 << 23);
  }
  function Gamma0(x2, xl) {
    return (x2 >>> 1 | xl << 31) ^ (x2 >>> 8 | xl << 24) ^ x2 >>> 7;
  }
  function Gamma0l(x2, xl) {
    return (x2 >>> 1 | xl << 31) ^ (x2 >>> 8 | xl << 24) ^ (x2 >>> 7 | xl << 25);
  }
  function Gamma1(x2, xl) {
    return (x2 >>> 19 | xl << 13) ^ (xl >>> 29 | x2 << 3) ^ x2 >>> 6;
  }
  function Gamma1l(x2, xl) {
    return (x2 >>> 19 | xl << 13) ^ (xl >>> 29 | x2 << 3) ^ (x2 >>> 6 | xl << 26);
  }
  function getCarry(a2, b2) {
    return a2 >>> 0 < b2 >>> 0 ? 1 : 0;
  }
  Sha512.prototype._update = function(M2) {
    var w = this._w;
    var ah = this._ah | 0;
    var bh = this._bh | 0;
    var ch = this._ch | 0;
    var dh2 = this._dh | 0;
    var eh = this._eh | 0;
    var fh = this._fh | 0;
    var gh = this._gh | 0;
    var hh = this._hh | 0;
    var al = this._al | 0;
    var bl = this._bl | 0;
    var cl = this._cl | 0;
    var dl = this._dl | 0;
    var el = this._el | 0;
    var fl = this._fl | 0;
    var gl = this._gl | 0;
    var hl = this._hl | 0;
    for (var i2 = 0; i2 < 32; i2 += 2) {
      w[i2] = M2.readInt32BE(i2 * 4);
      w[i2 + 1] = M2.readInt32BE(i2 * 4 + 4);
    }
    for (; i2 < 160; i2 += 2) {
      var xh = w[i2 - 15 * 2];
      var xl = w[i2 - 15 * 2 + 1];
      var gamma0 = Gamma0(xh, xl);
      var gamma0l = Gamma0l(xl, xh);
      xh = w[i2 - 2 * 2];
      xl = w[i2 - 2 * 2 + 1];
      var gamma1 = Gamma1(xh, xl);
      var gamma1l = Gamma1l(xl, xh);
      var Wi7h = w[i2 - 7 * 2];
      var Wi7l = w[i2 - 7 * 2 + 1];
      var Wi16h = w[i2 - 16 * 2];
      var Wi16l = w[i2 - 16 * 2 + 1];
      var Wil = gamma0l + Wi7l | 0;
      var Wih = gamma0 + Wi7h + getCarry(Wil, gamma0l) | 0;
      Wil = Wil + gamma1l | 0;
      Wih = Wih + gamma1 + getCarry(Wil, gamma1l) | 0;
      Wil = Wil + Wi16l | 0;
      Wih = Wih + Wi16h + getCarry(Wil, Wi16l) | 0;
      w[i2] = Wih;
      w[i2 + 1] = Wil;
    }
    for (var j = 0; j < 160; j += 2) {
      Wih = w[j];
      Wil = w[j + 1];
      var majh = maj(ah, bh, ch);
      var majl = maj(al, bl, cl);
      var sigma0h = sigma0(ah, al);
      var sigma0l = sigma0(al, ah);
      var sigma1h = sigma1(eh, el);
      var sigma1l = sigma1(el, eh);
      var Kih = K[j];
      var Kil = K[j + 1];
      var chh = Ch(eh, fh, gh);
      var chl = Ch(el, fl, gl);
      var t1l = hl + sigma1l | 0;
      var t1h = hh + sigma1h + getCarry(t1l, hl) | 0;
      t1l = t1l + chl | 0;
      t1h = t1h + chh + getCarry(t1l, chl) | 0;
      t1l = t1l + Kil | 0;
      t1h = t1h + Kih + getCarry(t1l, Kil) | 0;
      t1l = t1l + Wil | 0;
      t1h = t1h + Wih + getCarry(t1l, Wil) | 0;
      var t2l = sigma0l + majl | 0;
      var t2h = sigma0h + majh + getCarry(t2l, sigma0l) | 0;
      hh = gh;
      hl = gl;
      gh = fh;
      gl = fl;
      fh = eh;
      fl = el;
      el = dl + t1l | 0;
      eh = dh2 + t1h + getCarry(el, dl) | 0;
      dh2 = ch;
      dl = cl;
      ch = bh;
      cl = bl;
      bh = ah;
      bl = al;
      al = t1l + t2l | 0;
      ah = t1h + t2h + getCarry(al, t1l) | 0;
    }
    this._al = this._al + al | 0;
    this._bl = this._bl + bl | 0;
    this._cl = this._cl + cl | 0;
    this._dl = this._dl + dl | 0;
    this._el = this._el + el | 0;
    this._fl = this._fl + fl | 0;
    this._gl = this._gl + gl | 0;
    this._hl = this._hl + hl | 0;
    this._ah = this._ah + ah + getCarry(this._al, al) | 0;
    this._bh = this._bh + bh + getCarry(this._bl, bl) | 0;
    this._ch = this._ch + ch + getCarry(this._cl, cl) | 0;
    this._dh = this._dh + dh2 + getCarry(this._dl, dl) | 0;
    this._eh = this._eh + eh + getCarry(this._el, el) | 0;
    this._fh = this._fh + fh + getCarry(this._fl, fl) | 0;
    this._gh = this._gh + gh + getCarry(this._gl, gl) | 0;
    this._hh = this._hh + hh + getCarry(this._hl, hl) | 0;
  };
  Sha512.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(64);
    function writeInt64BE(h2, l2, offset) {
      H.writeInt32BE(h2, offset);
      H.writeInt32BE(l2, offset + 4);
    }
    writeInt64BE(this._ah, this._al, 0);
    writeInt64BE(this._bh, this._bl, 8);
    writeInt64BE(this._ch, this._cl, 16);
    writeInt64BE(this._dh, this._dl, 24);
    writeInt64BE(this._eh, this._el, 32);
    writeInt64BE(this._fh, this._fl, 40);
    writeInt64BE(this._gh, this._gl, 48);
    writeInt64BE(this._hh, this._hl, 56);
    return H;
  };
  sha512$3 = Sha512;
  return sha512$3;
}
var sha384$3;
var hasRequiredSha384$1;
function requireSha384$1() {
  if (hasRequiredSha384$1) return sha384$3;
  hasRequiredSha384$1 = 1;
  var inherits = requireInherits_browser();
  var SHA512 = requireSha512$1();
  var Hash = requireHash$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var W = new Array(160);
  function Sha384() {
    this.init();
    this._w = W;
    Hash.call(this, 128, 112);
  }
  inherits(Sha384, SHA512);
  Sha384.prototype.init = function() {
    this._ah = 3418070365;
    this._bh = 1654270250;
    this._ch = 2438529370;
    this._dh = 355462360;
    this._eh = 1731405415;
    this._fh = 2394180231;
    this._gh = 3675008525;
    this._hh = 1203062813;
    this._al = 3238371032;
    this._bl = 914150663;
    this._cl = 812702999;
    this._dl = 4144912697;
    this._el = 4290775857;
    this._fl = 1750603025;
    this._gl = 1694076839;
    this._hl = 3204075428;
    return this;
  };
  Sha384.prototype._hash = function() {
    var H = Buffer2.allocUnsafe(48);
    function writeInt64BE(h2, l2, offset) {
      H.writeInt32BE(h2, offset);
      H.writeInt32BE(l2, offset + 4);
    }
    writeInt64BE(this._ah, this._al, 0);
    writeInt64BE(this._bh, this._bl, 8);
    writeInt64BE(this._ch, this._cl, 16);
    writeInt64BE(this._dh, this._dl, 24);
    writeInt64BE(this._eh, this._el, 32);
    writeInt64BE(this._fh, this._fl, 40);
    return H;
  };
  sha384$3 = Sha384;
  return sha384$3;
}
var hasRequiredSha_js;
function requireSha_js() {
  if (hasRequiredSha_js) return sha_js.exports;
  hasRequiredSha_js = 1;
  (function(module2) {
    module2.exports = function SHA(algorithm) {
      var alg = algorithm.toLowerCase();
      var Algorithm = module2.exports[alg];
      if (!Algorithm) {
        throw new Error(alg + " is not supported (we accept pull requests)");
      }
      return new Algorithm();
    };
    module2.exports.sha = requireSha$1();
    module2.exports.sha1 = requireSha1$1();
    module2.exports.sha224 = requireSha224$1();
    module2.exports.sha256 = requireSha256$1();
    module2.exports.sha384 = requireSha384$1();
    module2.exports.sha512 = requireSha512$1();
  })(sha_js);
  return sha_js.exports;
}
var string_decoder = {};
var hasRequiredString_decoder;
function requireString_decoder() {
  if (hasRequiredString_decoder) return string_decoder;
  hasRequiredString_decoder = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var isEncoding = Buffer2.isEncoding || function(encoding) {
    encoding = "" + encoding;
    switch (encoding && encoding.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 _normalizeEncoding(enc) {
    if (!enc) return "utf8";
    var retried;
    while (true) {
      switch (enc) {
        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 enc;
        default:
          if (retried) return;
          enc = ("" + enc).toLowerCase();
          retried = true;
      }
    }
  }
  function normalizeEncoding(enc) {
    var nenc = _normalizeEncoding(enc);
    if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc))) throw new Error("Unknown encoding: " + enc);
    return nenc || enc;
  }
  string_decoder.StringDecoder = StringDecoder;
  function StringDecoder(encoding) {
    this.encoding = normalizeEncoding(encoding);
    var nb;
    switch (this.encoding) {
      case "utf16le":
        this.text = utf16Text;
        this.end = utf16End;
        nb = 4;
        break;
      case "utf8":
        this.fillLast = utf8FillLast;
        nb = 4;
        break;
      case "base64":
        this.text = base64Text;
        this.end = base64End;
        nb = 3;
        break;
      default:
        this.write = simpleWrite;
        this.end = simpleEnd;
        return;
    }
    this.lastNeed = 0;
    this.lastTotal = 0;
    this.lastChar = Buffer2.allocUnsafe(nb);
  }
  StringDecoder.prototype.write = function(buf) {
    if (buf.length === 0) return "";
    var r2;
    var i2;
    if (this.lastNeed) {
      r2 = this.fillLast(buf);
      if (r2 === void 0) return "";
      i2 = this.lastNeed;
      this.lastNeed = 0;
    } else {
      i2 = 0;
    }
    if (i2 < buf.length) return r2 ? r2 + this.text(buf, i2) : this.text(buf, i2);
    return r2 || "";
  };
  StringDecoder.prototype.end = utf8End;
  StringDecoder.prototype.text = utf8Text;
  StringDecoder.prototype.fillLast = function(buf) {
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
    this.lastNeed -= buf.length;
  };
  function utf8CheckByte(byte) {
    if (byte <= 127) return 0;
    else if (byte >> 5 === 6) return 2;
    else if (byte >> 4 === 14) return 3;
    else if (byte >> 3 === 30) return 4;
    return byte >> 6 === 2 ? -1 : -2;
  }
  function utf8CheckIncomplete(self2, buf, i2) {
    var j = buf.length - 1;
    if (j < i2) return 0;
    var nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self2.lastNeed = nb - 1;
      return nb;
    }
    if (--j < i2 || nb === -2) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) self2.lastNeed = nb - 2;
      return nb;
    }
    if (--j < i2 || nb === -2) return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) {
        if (nb === 2) nb = 0;
        else self2.lastNeed = nb - 3;
      }
      return nb;
    }
    return 0;
  }
  function utf8CheckExtraBytes(self2, buf, p2) {
    if ((buf[0] & 192) !== 128) {
      self2.lastNeed = 0;
      return "�";
    }
    if (self2.lastNeed > 1 && buf.length > 1) {
      if ((buf[1] & 192) !== 128) {
        self2.lastNeed = 1;
        return "�";
      }
      if (self2.lastNeed > 2 && buf.length > 2) {
        if ((buf[2] & 192) !== 128) {
          self2.lastNeed = 2;
          return "�";
        }
      }
    }
  }
  function utf8FillLast(buf) {
    var p2 = this.lastTotal - this.lastNeed;
    var r2 = utf8CheckExtraBytes(this, buf);
    if (r2 !== void 0) return r2;
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, p2, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, p2, 0, buf.length);
    this.lastNeed -= buf.length;
  }
  function utf8Text(buf, i2) {
    var total = utf8CheckIncomplete(this, buf, i2);
    if (!this.lastNeed) return buf.toString("utf8", i2);
    this.lastTotal = total;
    var end = buf.length - (total - this.lastNeed);
    buf.copy(this.lastChar, 0, end);
    return buf.toString("utf8", i2, end);
  }
  function utf8End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) return r2 + "�";
    return r2;
  }
  function utf16Text(buf, i2) {
    if ((buf.length - i2) % 2 === 0) {
      var r2 = buf.toString("utf16le", i2);
      if (r2) {
        var c2 = r2.charCodeAt(r2.length - 1);
        if (c2 >= 55296 && c2 <= 56319) {
          this.lastNeed = 2;
          this.lastTotal = 4;
          this.lastChar[0] = buf[buf.length - 2];
          this.lastChar[1] = buf[buf.length - 1];
          return r2.slice(0, -1);
        }
      }
      return r2;
    }
    this.lastNeed = 1;
    this.lastTotal = 2;
    this.lastChar[0] = buf[buf.length - 1];
    return buf.toString("utf16le", i2, buf.length - 1);
  }
  function utf16End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) {
      var end = this.lastTotal - this.lastNeed;
      return r2 + this.lastChar.toString("utf16le", 0, end);
    }
    return r2;
  }
  function base64Text(buf, i2) {
    var n2 = (buf.length - i2) % 3;
    if (n2 === 0) return buf.toString("base64", i2);
    this.lastNeed = 3 - n2;
    this.lastTotal = 3;
    if (n2 === 1) {
      this.lastChar[0] = buf[buf.length - 1];
    } else {
      this.lastChar[0] = buf[buf.length - 2];
      this.lastChar[1] = buf[buf.length - 1];
    }
    return buf.toString("base64", i2, buf.length - n2);
  }
  function base64End(buf) {
    var r2 = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) return r2 + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
    return r2;
  }
  function simpleWrite(buf) {
    return buf.toString(this.encoding);
  }
  function simpleEnd(buf) {
    return buf && buf.length ? this.write(buf) : "";
  }
  return string_decoder;
}
var cipherBase;
var hasRequiredCipherBase;
function requireCipherBase() {
  if (hasRequiredCipherBase) return cipherBase;
  hasRequiredCipherBase = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var Transform = requireStream().Transform;
  var StringDecoder = requireString_decoder().StringDecoder;
  var inherits = requireInherits_browser();
  var toBuffer2 = /* @__PURE__ */ requireToBuffer$2();
  function CipherBase(hashMode) {
    Transform.call(this);
    this.hashMode = typeof hashMode === "string";
    if (this.hashMode) {
      this[hashMode] = this._finalOrDigest;
    } else {
      this["final"] = this._finalOrDigest;
    }
    if (this._final) {
      this.__final = this._final;
      this._final = null;
    }
    this._decoder = null;
    this._encoding = null;
  }
  inherits(CipherBase, Transform);
  CipherBase.prototype.update = function(data2, inputEnc, outputEnc) {
    var bufferData = toBuffer2(data2, inputEnc);
    var outData = this._update(bufferData);
    if (this.hashMode) {
      return this;
    }
    if (outputEnc) {
      outData = this._toString(outData, outputEnc);
    }
    return outData;
  };
  CipherBase.prototype.setAutoPadding = function() {
  };
  CipherBase.prototype.getAuthTag = function() {
    throw new Error("trying to get auth tag in unsupported state");
  };
  CipherBase.prototype.setAuthTag = function() {
    throw new Error("trying to set auth tag in unsupported state");
  };
  CipherBase.prototype.setAAD = function() {
    throw new Error("trying to set aad in unsupported state");
  };
  CipherBase.prototype._transform = function(data2, _2, next) {
    var err;
    try {
      if (this.hashMode) {
        this._update(data2);
      } else {
        this.push(this._update(data2));
      }
    } catch (e4) {
      err = e4;
    } finally {
      next(err);
    }
  };
  CipherBase.prototype._flush = function(done) {
    var err;
    try {
      this.push(this.__final());
    } catch (e4) {
      err = e4;
    }
    done(err);
  };
  CipherBase.prototype._finalOrDigest = function(outputEnc) {
    var outData = this.__final() || Buffer2.alloc(0);
    if (outputEnc) {
      outData = this._toString(outData, outputEnc, true);
    }
    return outData;
  };
  CipherBase.prototype._toString = function(value, enc, fin) {
    if (!this._decoder) {
      this._decoder = new StringDecoder(enc);
      this._encoding = enc;
    }
    if (this._encoding !== enc) {
      throw new Error("can’t switch encodings");
    }
    var out = this._decoder.write(value);
    if (fin) {
      out += this._decoder.end();
    }
    return out;
  };
  cipherBase = CipherBase;
  return cipherBase;
}
var browser$e;
var hasRequiredBrowser$c;
function requireBrowser$c() {
  if (hasRequiredBrowser$c) return browser$e;
  hasRequiredBrowser$c = 1;
  var inherits = requireInherits_browser();
  var MD5 = requireMd5_js();
  var RIPEMD160 = requireRipemd160$1();
  var sha2 = requireSha_js();
  var Base = requireCipherBase();
  function Hash(hash2) {
    Base.call(this, "digest");
    this._hash = hash2;
  }
  inherits(Hash, Base);
  Hash.prototype._update = function(data2) {
    this._hash.update(data2);
  };
  Hash.prototype._final = function() {
    return this._hash.digest();
  };
  browser$e = function createHash(alg) {
    alg = alg.toLowerCase();
    if (alg === "md5") return new MD5();
    if (alg === "rmd160" || alg === "ripemd160") return new RIPEMD160();
    return new Hash(sha2(alg));
  };
  return browser$e;
}
var legacy;
var hasRequiredLegacy;
function requireLegacy() {
  if (hasRequiredLegacy) return legacy;
  hasRequiredLegacy = 1;
  var inherits = requireInherits_browser();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var Base = requireCipherBase();
  var ZEROS = Buffer2.alloc(128);
  var blocksize = 64;
  function Hmac(alg, key2) {
    Base.call(this, "digest");
    if (typeof key2 === "string") {
      key2 = Buffer2.from(key2);
    }
    this._alg = alg;
    this._key = key2;
    if (key2.length > blocksize) {
      key2 = alg(key2);
    } else if (key2.length < blocksize) {
      key2 = Buffer2.concat([key2, ZEROS], blocksize);
    }
    var ipad = this._ipad = Buffer2.allocUnsafe(blocksize);
    var opad = this._opad = Buffer2.allocUnsafe(blocksize);
    for (var i2 = 0; i2 < blocksize; i2++) {
      ipad[i2] = key2[i2] ^ 54;
      opad[i2] = key2[i2] ^ 92;
    }
    this._hash = [ipad];
  }
  inherits(Hmac, Base);
  Hmac.prototype._update = function(data2) {
    this._hash.push(data2);
  };
  Hmac.prototype._final = function() {
    var h2 = this._alg(Buffer2.concat(this._hash));
    return this._alg(Buffer2.concat([this._opad, h2]));
  };
  legacy = Hmac;
  return legacy;
}
var md5$2;
var hasRequiredMd5$1;
function requireMd5$1() {
  if (hasRequiredMd5$1) return md5$2;
  hasRequiredMd5$1 = 1;
  var MD5 = requireMd5_js();
  md5$2 = function(buffer2) {
    return new MD5().update(buffer2).digest();
  };
  return md5$2;
}
var browser$d;
var hasRequiredBrowser$b;
function requireBrowser$b() {
  if (hasRequiredBrowser$b) return browser$d;
  hasRequiredBrowser$b = 1;
  var inherits = requireInherits_browser();
  var Legacy = requireLegacy();
  var Base = requireCipherBase();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var md52 = requireMd5$1();
  var RIPEMD160 = requireRipemd160$1();
  var sha2 = requireSha_js();
  var ZEROS = Buffer2.alloc(128);
  function Hmac(alg, key2) {
    Base.call(this, "digest");
    if (typeof key2 === "string") {
      key2 = Buffer2.from(key2);
    }
    var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64;
    this._alg = alg;
    this._key = key2;
    if (key2.length > blocksize) {
      var hash2 = alg === "rmd160" ? new RIPEMD160() : sha2(alg);
      key2 = hash2.update(key2).digest();
    } else if (key2.length < blocksize) {
      key2 = Buffer2.concat([key2, ZEROS], blocksize);
    }
    var ipad = this._ipad = Buffer2.allocUnsafe(blocksize);
    var opad = this._opad = Buffer2.allocUnsafe(blocksize);
    for (var i2 = 0; i2 < blocksize; i2++) {
      ipad[i2] = key2[i2] ^ 54;
      opad[i2] = key2[i2] ^ 92;
    }
    this._hash = alg === "rmd160" ? new RIPEMD160() : sha2(alg);
    this._hash.update(ipad);
  }
  inherits(Hmac, Base);
  Hmac.prototype._update = function(data2) {
    this._hash.update(data2);
  };
  Hmac.prototype._final = function() {
    var h2 = this._hash.digest();
    var hash2 = this._alg === "rmd160" ? new RIPEMD160() : sha2(this._alg);
    return hash2.update(this._opad).update(h2).digest();
  };
  browser$d = function createHmac(alg, key2) {
    alg = alg.toLowerCase();
    if (alg === "rmd160" || alg === "ripemd160") {
      return new Hmac("rmd160", key2);
    }
    if (alg === "md5") {
      return new Legacy(md52, key2);
    }
    return new Hmac(alg, key2);
  };
  return browser$d;
}
const sha224WithRSAEncryption = { "sign": "rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" };
const sha256WithRSAEncryption = { "sign": "rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" };
const sha384WithRSAEncryption = { "sign": "rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" };
const sha512WithRSAEncryption = { "sign": "rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" };
const sha256$3 = { "sign": "ecdsa", "hash": "sha256", "id": "" };
const sha224$2 = { "sign": "ecdsa", "hash": "sha224", "id": "" };
const sha384$2 = { "sign": "ecdsa", "hash": "sha384", "id": "" };
const sha512$2 = { "sign": "ecdsa", "hash": "sha512", "id": "" };
const DSA = { "sign": "dsa", "hash": "sha1", "id": "" };
const ripemd160WithRSA = { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" };
const md5WithRSAEncryption = { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" };
const require$$6 = {
  sha224WithRSAEncryption,
  "RSA-SHA224": { "sign": "ecdsa/rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" },
  sha256WithRSAEncryption,
  "RSA-SHA256": { "sign": "ecdsa/rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" },
  sha384WithRSAEncryption,
  "RSA-SHA384": { "sign": "ecdsa/rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" },
  sha512WithRSAEncryption,
  "RSA-SHA512": { "sign": "ecdsa/rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" },
  "RSA-SHA1": { "sign": "rsa", "hash": "sha1", "id": "3021300906052b0e03021a05000414" },
  "ecdsa-with-SHA1": { "sign": "ecdsa", "hash": "sha1", "id": "" },
  sha256: sha256$3,
  sha224: sha224$2,
  sha384: sha384$2,
  sha512: sha512$2,
  "DSA-SHA": { "sign": "dsa", "hash": "sha1", "id": "" },
  "DSA-SHA1": { "sign": "dsa", "hash": "sha1", "id": "" },
  DSA,
  "DSA-WITH-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" },
  "DSA-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" },
  "DSA-WITH-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" },
  "DSA-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" },
  "DSA-WITH-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" },
  "DSA-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" },
  "DSA-WITH-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" },
  "DSA-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" },
  "DSA-RIPEMD160": { "sign": "dsa", "hash": "rmd160", "id": "" },
  ripemd160WithRSA,
  "RSA-RIPEMD160": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" },
  md5WithRSAEncryption,
  "RSA-MD5": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" }
};
var algos;
var hasRequiredAlgos;
function requireAlgos() {
  if (hasRequiredAlgos) return algos;
  hasRequiredAlgos = 1;
  algos = require$$6;
  return algos;
}
var browser$c = {};
var precondition;
var hasRequiredPrecondition;
function requirePrecondition() {
  if (hasRequiredPrecondition) return precondition;
  hasRequiredPrecondition = 1;
  var $isFinite = isFinite;
  var MAX_ALLOC = Math.pow(2, 30) - 1;
  precondition = function(iterations, keylen) {
    if (typeof iterations !== "number") {
      throw new TypeError("Iterations not a number");
    }
    if (iterations < 0 || !$isFinite(iterations)) {
      throw new TypeError("Bad iterations");
    }
    if (typeof keylen !== "number") {
      throw new TypeError("Key length not a number");
    }
    if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) {
      throw new TypeError("Bad key length");
    }
  };
  return precondition;
}
var defaultEncoding_1;
var hasRequiredDefaultEncoding;
function requireDefaultEncoding() {
  if (hasRequiredDefaultEncoding) return defaultEncoding_1;
  hasRequiredDefaultEncoding = 1;
  var defaultEncoding;
  if (commonjsGlobal$1.process && commonjsGlobal$1.process.browser) {
    defaultEncoding = "utf-8";
  } else if (commonjsGlobal$1.process && commonjsGlobal$1.process.version) {
    var pVersionMajor = parseInt(process.version.split(".")[0].slice(1), 10);
    defaultEncoding = pVersionMajor >= 6 ? "utf-8" : "binary";
  } else {
    defaultEncoding = "utf-8";
  }
  defaultEncoding_1 = defaultEncoding;
  return defaultEncoding_1;
}
var toBuffer_1;
var hasRequiredToBuffer;
function requireToBuffer() {
  if (hasRequiredToBuffer) return toBuffer_1;
  hasRequiredToBuffer = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var toBuffer2 = /* @__PURE__ */ requireToBuffer$2();
  var useUint8Array = typeof Uint8Array !== "undefined";
  var useArrayBuffer = useUint8Array && typeof ArrayBuffer !== "undefined";
  var isView = useArrayBuffer && ArrayBuffer.isView;
  toBuffer_1 = function(thing, encoding, name) {
    if (typeof thing === "string" || Buffer2.isBuffer(thing) || useUint8Array && thing instanceof Uint8Array || isView && isView(thing)) {
      return toBuffer2(thing, encoding);
    }
    throw new TypeError(name + " must be a string, a Buffer, a Uint8Array, or a DataView");
  };
  return toBuffer_1;
}
var syncBrowser;
var hasRequiredSyncBrowser;
function requireSyncBrowser() {
  if (hasRequiredSyncBrowser) return syncBrowser;
  hasRequiredSyncBrowser = 1;
  var md52 = requireMd5$1();
  var RIPEMD160 = requireRipemd160$1();
  var sha2 = requireSha_js();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var checkParameters = requirePrecondition();
  var defaultEncoding = requireDefaultEncoding();
  var toBuffer2 = requireToBuffer();
  var ZEROS = Buffer2.alloc(128);
  var sizes = {
    __proto__: null,
    md5: 16,
    sha1: 20,
    sha224: 28,
    sha256: 32,
    sha384: 48,
    sha512: 64,
    "sha512-256": 32,
    ripemd160: 20,
    rmd160: 20
  };
  var mapping = {
    __proto__: null,
    "sha-1": "sha1",
    "sha-224": "sha224",
    "sha-256": "sha256",
    "sha-384": "sha384",
    "sha-512": "sha512",
    "ripemd-160": "ripemd160"
  };
  function rmd160Func(data2) {
    return new RIPEMD160().update(data2).digest();
  }
  function getDigest(alg) {
    function shaFunc(data2) {
      return sha2(alg).update(data2).digest();
    }
    if (alg === "rmd160" || alg === "ripemd160") {
      return rmd160Func;
    }
    if (alg === "md5") {
      return md52;
    }
    return shaFunc;
  }
  function Hmac(alg, key2, saltLen) {
    var hash2 = getDigest(alg);
    var blocksize = alg === "sha512" || alg === "sha384" ? 128 : 64;
    if (key2.length > blocksize) {
      key2 = hash2(key2);
    } else if (key2.length < blocksize) {
      key2 = Buffer2.concat([key2, ZEROS], blocksize);
    }
    var ipad = Buffer2.allocUnsafe(blocksize + sizes[alg]);
    var opad = Buffer2.allocUnsafe(blocksize + sizes[alg]);
    for (var i2 = 0; i2 < blocksize; i2++) {
      ipad[i2] = key2[i2] ^ 54;
      opad[i2] = key2[i2] ^ 92;
    }
    var ipad1 = Buffer2.allocUnsafe(blocksize + saltLen + 4);
    ipad.copy(ipad1, 0, 0, blocksize);
    this.ipad1 = ipad1;
    this.ipad2 = ipad;
    this.opad = opad;
    this.alg = alg;
    this.blocksize = blocksize;
    this.hash = hash2;
    this.size = sizes[alg];
  }
  Hmac.prototype.run = function(data2, ipad) {
    data2.copy(ipad, this.blocksize);
    var h2 = this.hash(ipad);
    h2.copy(this.opad, this.blocksize);
    return this.hash(this.opad);
  };
  function pbkdf22(password, salt, iterations, keylen, digest) {
    checkParameters(iterations, keylen);
    password = toBuffer2(password, defaultEncoding, "Password");
    salt = toBuffer2(salt, defaultEncoding, "Salt");
    var lowerDigest = (digest || "sha1").toLowerCase();
    var mappedDigest = mapping[lowerDigest] || lowerDigest;
    var size = sizes[mappedDigest];
    if (typeof size !== "number" || !size) {
      throw new TypeError("Digest algorithm not supported: " + digest);
    }
    var hmac2 = new Hmac(mappedDigest, password, salt.length);
    var DK = Buffer2.allocUnsafe(keylen);
    var block1 = Buffer2.allocUnsafe(salt.length + 4);
    salt.copy(block1, 0, 0, salt.length);
    var destPos = 0;
    var hLen = size;
    var l2 = Math.ceil(keylen / hLen);
    for (var i2 = 1; i2 <= l2; i2++) {
      block1.writeUInt32BE(i2, salt.length);
      var T2 = hmac2.run(block1, hmac2.ipad1);
      var U = T2;
      for (var j = 1; j < iterations; j++) {
        U = hmac2.run(U, hmac2.ipad2);
        for (var k2 = 0; k2 < hLen; k2++) {
          T2[k2] ^= U[k2];
        }
      }
      T2.copy(DK, destPos);
      destPos += hLen;
    }
    return DK;
  }
  syncBrowser = pbkdf22;
  return syncBrowser;
}
var async$1;
var hasRequiredAsync$1;
function requireAsync$1() {
  if (hasRequiredAsync$1) return async$1;
  hasRequiredAsync$1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var checkParameters = requirePrecondition();
  var defaultEncoding = requireDefaultEncoding();
  var sync = requireSyncBrowser();
  var toBuffer2 = requireToBuffer();
  var ZERO_BUF;
  var subtle = commonjsGlobal$1.crypto && commonjsGlobal$1.crypto.subtle;
  var toBrowser = {
    sha: "SHA-1",
    "sha-1": "SHA-1",
    sha1: "SHA-1",
    sha256: "SHA-256",
    "sha-256": "SHA-256",
    sha384: "SHA-384",
    "sha-384": "SHA-384",
    "sha-512": "SHA-512",
    sha512: "SHA-512"
  };
  var checks = [];
  var nextTick;
  function getNextTick() {
    if (nextTick) {
      return nextTick;
    }
    if (commonjsGlobal$1.process && commonjsGlobal$1.process.nextTick) {
      nextTick = commonjsGlobal$1.process.nextTick;
    } else if (commonjsGlobal$1.queueMicrotask) {
      nextTick = commonjsGlobal$1.queueMicrotask;
    } else if (commonjsGlobal$1.setImmediate) {
      nextTick = commonjsGlobal$1.setImmediate;
    } else {
      nextTick = commonjsGlobal$1.setTimeout;
    }
    return nextTick;
  }
  function browserPbkdf2(password, salt, iterations, length, algo) {
    return subtle.importKey("raw", password, { name: "PBKDF2" }, false, ["deriveBits"]).then(function(key2) {
      return subtle.deriveBits({
        name: "PBKDF2",
        salt,
        iterations,
        hash: {
          name: algo
        }
      }, key2, length << 3);
    }).then(function(res) {
      return Buffer2.from(res);
    });
  }
  function checkNative(algo) {
    if (commonjsGlobal$1.process && !commonjsGlobal$1.process.browser) {
      return Promise.resolve(false);
    }
    if (!subtle || !subtle.importKey || !subtle.deriveBits) {
      return Promise.resolve(false);
    }
    if (checks[algo] !== void 0) {
      return checks[algo];
    }
    ZERO_BUF = ZERO_BUF || Buffer2.alloc(8);
    var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(
      function() {
        return true;
      },
      function() {
        return false;
      }
    );
    checks[algo] = prom;
    return prom;
  }
  function resolvePromise(promise, callback) {
    promise.then(function(out) {
      getNextTick()(function() {
        callback(null, out);
      });
    }, function(e4) {
      getNextTick()(function() {
        callback(e4);
      });
    });
  }
  async$1 = function(password, salt, iterations, keylen, digest, callback) {
    if (typeof digest === "function") {
      callback = digest;
      digest = void 0;
    }
    checkParameters(iterations, keylen);
    password = toBuffer2(password, defaultEncoding, "Password");
    salt = toBuffer2(salt, defaultEncoding, "Salt");
    if (typeof callback !== "function") {
      throw new Error("No callback provided to pbkdf2");
    }
    digest = digest || "sha1";
    var algo = toBrowser[digest.toLowerCase()];
    if (!algo || typeof commonjsGlobal$1.Promise !== "function") {
      getNextTick()(function() {
        var out;
        try {
          out = sync(password, salt, iterations, keylen, digest);
        } catch (e4) {
          callback(e4);
          return;
        }
        callback(null, out);
      });
      return;
    }
    resolvePromise(checkNative(algo).then(function(resp) {
      if (resp) {
        return browserPbkdf2(password, salt, iterations, keylen, algo);
      }
      return sync(password, salt, iterations, keylen, digest);
    }), callback);
  };
  return async$1;
}
var hasRequiredBrowser$a;
function requireBrowser$a() {
  if (hasRequiredBrowser$a) return browser$c;
  hasRequiredBrowser$a = 1;
  browser$c.pbkdf2 = requireAsync$1();
  browser$c.pbkdf2Sync = requireSyncBrowser();
  return browser$c;
}
var browser$b = {};
var des$1 = {};
var utils$4 = {};
var hasRequiredUtils$4;
function requireUtils$4() {
  if (hasRequiredUtils$4) return utils$4;
  hasRequiredUtils$4 = 1;
  utils$4.readUInt32BE = function readUInt32BE(bytes, off) {
    var res = bytes[0 + off] << 24 | bytes[1 + off] << 16 | bytes[2 + off] << 8 | bytes[3 + off];
    return res >>> 0;
  };
  utils$4.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
    bytes[0 + off] = value >>> 24;
    bytes[1 + off] = value >>> 16 & 255;
    bytes[2 + off] = value >>> 8 & 255;
    bytes[3 + off] = value & 255;
  };
  utils$4.ip = function ip(inL, inR, out, off) {
    var outL = 0;
    var outR = 0;
    for (var i2 = 6; i2 >= 0; i2 -= 2) {
      for (var j = 0; j <= 24; j += 8) {
        outL <<= 1;
        outL |= inR >>> j + i2 & 1;
      }
      for (var j = 0; j <= 24; j += 8) {
        outL <<= 1;
        outL |= inL >>> j + i2 & 1;
      }
    }
    for (var i2 = 6; i2 >= 0; i2 -= 2) {
      for (var j = 1; j <= 25; j += 8) {
        outR <<= 1;
        outR |= inR >>> j + i2 & 1;
      }
      for (var j = 1; j <= 25; j += 8) {
        outR <<= 1;
        outR |= inL >>> j + i2 & 1;
      }
    }
    out[off + 0] = outL >>> 0;
    out[off + 1] = outR >>> 0;
  };
  utils$4.rip = function rip(inL, inR, out, off) {
    var outL = 0;
    var outR = 0;
    for (var i2 = 0; i2 < 4; i2++) {
      for (var j = 24; j >= 0; j -= 8) {
        outL <<= 1;
        outL |= inR >>> j + i2 & 1;
        outL <<= 1;
        outL |= inL >>> j + i2 & 1;
      }
    }
    for (var i2 = 4; i2 < 8; i2++) {
      for (var j = 24; j >= 0; j -= 8) {
        outR <<= 1;
        outR |= inR >>> j + i2 & 1;
        outR <<= 1;
        outR |= inL >>> j + i2 & 1;
      }
    }
    out[off + 0] = outL >>> 0;
    out[off + 1] = outR >>> 0;
  };
  utils$4.pc1 = function pc1(inL, inR, out, off) {
    var outL = 0;
    var outR = 0;
    for (var i2 = 7; i2 >= 5; i2--) {
      for (var j = 0; j <= 24; j += 8) {
        outL <<= 1;
        outL |= inR >> j + i2 & 1;
      }
      for (var j = 0; j <= 24; j += 8) {
        outL <<= 1;
        outL |= inL >> j + i2 & 1;
      }
    }
    for (var j = 0; j <= 24; j += 8) {
      outL <<= 1;
      outL |= inR >> j + i2 & 1;
    }
    for (var i2 = 1; i2 <= 3; i2++) {
      for (var j = 0; j <= 24; j += 8) {
        outR <<= 1;
        outR |= inR >> j + i2 & 1;
      }
      for (var j = 0; j <= 24; j += 8) {
        outR <<= 1;
        outR |= inL >> j + i2 & 1;
      }
    }
    for (var j = 0; j <= 24; j += 8) {
      outR <<= 1;
      outR |= inL >> j + i2 & 1;
    }
    out[off + 0] = outL >>> 0;
    out[off + 1] = outR >>> 0;
  };
  utils$4.r28shl = function r28shl(num, shift) {
    return num << shift & 268435455 | num >>> 28 - shift;
  };
  var pc2table = [
    // inL => outL
    14,
    11,
    17,
    4,
    27,
    23,
    25,
    0,
    13,
    22,
    7,
    18,
    5,
    9,
    16,
    24,
    2,
    20,
    12,
    21,
    1,
    8,
    15,
    26,
    // inR => outR
    15,
    4,
    25,
    19,
    9,
    1,
    26,
    16,
    5,
    11,
    23,
    8,
    12,
    7,
    17,
    0,
    22,
    3,
    10,
    14,
    6,
    20,
    27,
    24
  ];
  utils$4.pc2 = function pc2(inL, inR, out, off) {
    var outL = 0;
    var outR = 0;
    var len = pc2table.length >>> 1;
    for (var i2 = 0; i2 < len; i2++) {
      outL <<= 1;
      outL |= inL >>> pc2table[i2] & 1;
    }
    for (var i2 = len; i2 < pc2table.length; i2++) {
      outR <<= 1;
      outR |= inR >>> pc2table[i2] & 1;
    }
    out[off + 0] = outL >>> 0;
    out[off + 1] = outR >>> 0;
  };
  utils$4.expand = function expand(r2, out, off) {
    var outL = 0;
    var outR = 0;
    outL = (r2 & 1) << 5 | r2 >>> 27;
    for (var i2 = 23; i2 >= 15; i2 -= 4) {
      outL <<= 6;
      outL |= r2 >>> i2 & 63;
    }
    for (var i2 = 11; i2 >= 3; i2 -= 4) {
      outR |= r2 >>> i2 & 63;
      outR <<= 6;
    }
    outR |= (r2 & 31) << 1 | r2 >>> 31;
    out[off + 0] = outL >>> 0;
    out[off + 1] = outR >>> 0;
  };
  var sTable = [
    14,
    0,
    4,
    15,
    13,
    7,
    1,
    4,
    2,
    14,
    15,
    2,
    11,
    13,
    8,
    1,
    3,
    10,
    10,
    6,
    6,
    12,
    12,
    11,
    5,
    9,
    9,
    5,
    0,
    3,
    7,
    8,
    4,
    15,
    1,
    12,
    14,
    8,
    8,
    2,
    13,
    4,
    6,
    9,
    2,
    1,
    11,
    7,
    15,
    5,
    12,
    11,
    9,
    3,
    7,
    14,
    3,
    10,
    10,
    0,
    5,
    6,
    0,
    13,
    15,
    3,
    1,
    13,
    8,
    4,
    14,
    7,
    6,
    15,
    11,
    2,
    3,
    8,
    4,
    14,
    9,
    12,
    7,
    0,
    2,
    1,
    13,
    10,
    12,
    6,
    0,
    9,
    5,
    11,
    10,
    5,
    0,
    13,
    14,
    8,
    7,
    10,
    11,
    1,
    10,
    3,
    4,
    15,
    13,
    4,
    1,
    2,
    5,
    11,
    8,
    6,
    12,
    7,
    6,
    12,
    9,
    0,
    3,
    5,
    2,
    14,
    15,
    9,
    10,
    13,
    0,
    7,
    9,
    0,
    14,
    9,
    6,
    3,
    3,
    4,
    15,
    6,
    5,
    10,
    1,
    2,
    13,
    8,
    12,
    5,
    7,
    14,
    11,
    12,
    4,
    11,
    2,
    15,
    8,
    1,
    13,
    1,
    6,
    10,
    4,
    13,
    9,
    0,
    8,
    6,
    15,
    9,
    3,
    8,
    0,
    7,
    11,
    4,
    1,
    15,
    2,
    14,
    12,
    3,
    5,
    11,
    10,
    5,
    14,
    2,
    7,
    12,
    7,
    13,
    13,
    8,
    14,
    11,
    3,
    5,
    0,
    6,
    6,
    15,
    9,
    0,
    10,
    3,
    1,
    4,
    2,
    7,
    8,
    2,
    5,
    12,
    11,
    1,
    12,
    10,
    4,
    14,
    15,
    9,
    10,
    3,
    6,
    15,
    9,
    0,
    0,
    6,
    12,
    10,
    11,
    1,
    7,
    13,
    13,
    8,
    15,
    9,
    1,
    4,
    3,
    5,
    14,
    11,
    5,
    12,
    2,
    7,
    8,
    2,
    4,
    14,
    2,
    14,
    12,
    11,
    4,
    2,
    1,
    12,
    7,
    4,
    10,
    7,
    11,
    13,
    6,
    1,
    8,
    5,
    5,
    0,
    3,
    15,
    15,
    10,
    13,
    3,
    0,
    9,
    14,
    8,
    9,
    6,
    4,
    11,
    2,
    8,
    1,
    12,
    11,
    7,
    10,
    1,
    13,
    14,
    7,
    2,
    8,
    13,
    15,
    6,
    9,
    15,
    12,
    0,
    5,
    9,
    6,
    10,
    3,
    4,
    0,
    5,
    14,
    3,
    12,
    10,
    1,
    15,
    10,
    4,
    15,
    2,
    9,
    7,
    2,
    12,
    6,
    9,
    8,
    5,
    0,
    6,
    13,
    1,
    3,
    13,
    4,
    14,
    14,
    0,
    7,
    11,
    5,
    3,
    11,
    8,
    9,
    4,
    14,
    3,
    15,
    2,
    5,
    12,
    2,
    9,
    8,
    5,
    12,
    15,
    3,
    10,
    7,
    11,
    0,
    14,
    4,
    1,
    10,
    7,
    1,
    6,
    13,
    0,
    11,
    8,
    6,
    13,
    4,
    13,
    11,
    0,
    2,
    11,
    14,
    7,
    15,
    4,
    0,
    9,
    8,
    1,
    13,
    10,
    3,
    14,
    12,
    3,
    9,
    5,
    7,
    12,
    5,
    2,
    10,
    15,
    6,
    8,
    1,
    6,
    1,
    6,
    4,
    11,
    11,
    13,
    13,
    8,
    12,
    1,
    3,
    4,
    7,
    10,
    14,
    7,
    10,
    9,
    15,
    5,
    6,
    0,
    8,
    15,
    0,
    14,
    5,
    2,
    9,
    3,
    2,
    12,
    13,
    1,
    2,
    15,
    8,
    13,
    4,
    8,
    6,
    10,
    15,
    3,
    11,
    7,
    1,
    4,
    10,
    12,
    9,
    5,
    3,
    6,
    14,
    11,
    5,
    0,
    0,
    14,
    12,
    9,
    7,
    2,
    7,
    2,
    11,
    1,
    4,
    14,
    1,
    7,
    9,
    4,
    12,
    10,
    14,
    8,
    2,
    13,
    0,
    15,
    6,
    12,
    10,
    9,
    13,
    0,
    15,
    3,
    3,
    5,
    5,
    6,
    8,
    11
  ];
  utils$4.substitute = function substitute(inL, inR) {
    var out = 0;
    for (var i2 = 0; i2 < 4; i2++) {
      var b2 = inL >>> 18 - i2 * 6 & 63;
      var sb = sTable[i2 * 64 + b2];
      out <<= 4;
      out |= sb;
    }
    for (var i2 = 0; i2 < 4; i2++) {
      var b2 = inR >>> 18 - i2 * 6 & 63;
      var sb = sTable[4 * 64 + i2 * 64 + b2];
      out <<= 4;
      out |= sb;
    }
    return out >>> 0;
  };
  var permuteTable = [
    16,
    25,
    12,
    11,
    3,
    20,
    4,
    15,
    31,
    17,
    9,
    6,
    27,
    14,
    1,
    22,
    30,
    24,
    8,
    18,
    0,
    5,
    29,
    23,
    13,
    19,
    2,
    26,
    10,
    21,
    28,
    7
  ];
  utils$4.permute = function permute(num) {
    var out = 0;
    for (var i2 = 0; i2 < permuteTable.length; i2++) {
      out <<= 1;
      out |= num >>> permuteTable[i2] & 1;
    }
    return out >>> 0;
  };
  utils$4.padSplit = function padSplit(num, size, group) {
    var str = num.toString(2);
    while (str.length < size)
      str = "0" + str;
    var out = [];
    for (var i2 = 0; i2 < size; i2 += group)
      out.push(str.slice(i2, i2 + group));
    return out.join(" ");
  };
  return utils$4;
}
var minimalisticAssert;
var hasRequiredMinimalisticAssert;
function requireMinimalisticAssert() {
  if (hasRequiredMinimalisticAssert) return minimalisticAssert;
  hasRequiredMinimalisticAssert = 1;
  minimalisticAssert = assert;
  function assert(val, msg) {
    if (!val)
      throw new Error(msg || "Assertion failed");
  }
  assert.equal = function assertEqual(l2, r2, msg) {
    if (l2 != r2)
      throw new Error(msg || "Assertion failed: " + l2 + " != " + r2);
  };
  return minimalisticAssert;
}
var cipher;
var hasRequiredCipher;
function requireCipher() {
  if (hasRequiredCipher) return cipher;
  hasRequiredCipher = 1;
  var assert = requireMinimalisticAssert();
  function Cipher(options2) {
    this.options = options2;
    this.type = this.options.type;
    this.blockSize = 8;
    this._init();
    this.buffer = new Array(this.blockSize);
    this.bufferOff = 0;
    this.padding = options2.padding !== false;
  }
  cipher = Cipher;
  Cipher.prototype._init = function _init() {
  };
  Cipher.prototype.update = function update(data2) {
    if (data2.length === 0)
      return [];
    if (this.type === "decrypt")
      return this._updateDecrypt(data2);
    else
      return this._updateEncrypt(data2);
  };
  Cipher.prototype._buffer = function _buffer(data2, off) {
    var min2 = Math.min(this.buffer.length - this.bufferOff, data2.length - off);
    for (var i2 = 0; i2 < min2; i2++)
      this.buffer[this.bufferOff + i2] = data2[off + i2];
    this.bufferOff += min2;
    return min2;
  };
  Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
    this._update(this.buffer, 0, out, off);
    this.bufferOff = 0;
    return this.blockSize;
  };
  Cipher.prototype._updateEncrypt = function _updateEncrypt(data2) {
    var inputOff = 0;
    var outputOff = 0;
    var count = (this.bufferOff + data2.length) / this.blockSize | 0;
    var out = new Array(count * this.blockSize);
    if (this.bufferOff !== 0) {
      inputOff += this._buffer(data2, inputOff);
      if (this.bufferOff === this.buffer.length)
        outputOff += this._flushBuffer(out, outputOff);
    }
    var max2 = data2.length - (data2.length - inputOff) % this.blockSize;
    for (; inputOff < max2; inputOff += this.blockSize) {
      this._update(data2, inputOff, out, outputOff);
      outputOff += this.blockSize;
    }
    for (; inputOff < data2.length; inputOff++, this.bufferOff++)
      this.buffer[this.bufferOff] = data2[inputOff];
    return out;
  };
  Cipher.prototype._updateDecrypt = function _updateDecrypt(data2) {
    var inputOff = 0;
    var outputOff = 0;
    var count = Math.ceil((this.bufferOff + data2.length) / this.blockSize) - 1;
    var out = new Array(count * this.blockSize);
    for (; count > 0; count--) {
      inputOff += this._buffer(data2, inputOff);
      outputOff += this._flushBuffer(out, outputOff);
    }
    inputOff += this._buffer(data2, inputOff);
    return out;
  };
  Cipher.prototype.final = function final(buffer2) {
    var first;
    if (buffer2)
      first = this.update(buffer2);
    var last;
    if (this.type === "encrypt")
      last = this._finalEncrypt();
    else
      last = this._finalDecrypt();
    if (first)
      return first.concat(last);
    else
      return last;
  };
  Cipher.prototype._pad = function _pad(buffer2, off) {
    if (off === 0)
      return false;
    while (off < buffer2.length)
      buffer2[off++] = 0;
    return true;
  };
  Cipher.prototype._finalEncrypt = function _finalEncrypt() {
    if (!this._pad(this.buffer, this.bufferOff))
      return [];
    var out = new Array(this.blockSize);
    this._update(this.buffer, 0, out, 0);
    return out;
  };
  Cipher.prototype._unpad = function _unpad(buffer2) {
    return buffer2;
  };
  Cipher.prototype._finalDecrypt = function _finalDecrypt() {
    assert.equal(this.bufferOff, this.blockSize, "Not enough data to decrypt");
    var out = new Array(this.blockSize);
    this._flushBuffer(out, 0);
    return this._unpad(out);
  };
  return cipher;
}
var des;
var hasRequiredDes$1;
function requireDes$1() {
  if (hasRequiredDes$1) return des;
  hasRequiredDes$1 = 1;
  var assert = requireMinimalisticAssert();
  var inherits = requireInherits_browser();
  var utils2 = requireUtils$4();
  var Cipher = requireCipher();
  function DESState() {
    this.tmp = new Array(2);
    this.keys = null;
  }
  function DES(options2) {
    Cipher.call(this, options2);
    var state = new DESState();
    this._desState = state;
    this.deriveKeys(state, options2.key);
  }
  inherits(DES, Cipher);
  des = DES;
  DES.create = function create2(options2) {
    return new DES(options2);
  };
  var shiftTable = [
    1,
    1,
    2,
    2,
    2,
    2,
    2,
    2,
    1,
    2,
    2,
    2,
    2,
    2,
    2,
    1
  ];
  DES.prototype.deriveKeys = function deriveKeys(state, key2) {
    state.keys = new Array(16 * 2);
    assert.equal(key2.length, this.blockSize, "Invalid key length");
    var kL = utils2.readUInt32BE(key2, 0);
    var kR = utils2.readUInt32BE(key2, 4);
    utils2.pc1(kL, kR, state.tmp, 0);
    kL = state.tmp[0];
    kR = state.tmp[1];
    for (var i2 = 0; i2 < state.keys.length; i2 += 2) {
      var shift = shiftTable[i2 >>> 1];
      kL = utils2.r28shl(kL, shift);
      kR = utils2.r28shl(kR, shift);
      utils2.pc2(kL, kR, state.keys, i2);
    }
  };
  DES.prototype._update = function _update(inp, inOff, out, outOff) {
    var state = this._desState;
    var l2 = utils2.readUInt32BE(inp, inOff);
    var r2 = utils2.readUInt32BE(inp, inOff + 4);
    utils2.ip(l2, r2, state.tmp, 0);
    l2 = state.tmp[0];
    r2 = state.tmp[1];
    if (this.type === "encrypt")
      this._encrypt(state, l2, r2, state.tmp, 0);
    else
      this._decrypt(state, l2, r2, state.tmp, 0);
    l2 = state.tmp[0];
    r2 = state.tmp[1];
    utils2.writeUInt32BE(out, l2, outOff);
    utils2.writeUInt32BE(out, r2, outOff + 4);
  };
  DES.prototype._pad = function _pad(buffer2, off) {
    if (this.padding === false) {
      return false;
    }
    var value = buffer2.length - off;
    for (var i2 = off; i2 < buffer2.length; i2++)
      buffer2[i2] = value;
    return true;
  };
  DES.prototype._unpad = function _unpad(buffer2) {
    if (this.padding === false) {
      return buffer2;
    }
    var pad = buffer2[buffer2.length - 1];
    for (var i2 = buffer2.length - pad; i2 < buffer2.length; i2++)
      assert.equal(buffer2[i2], pad);
    return buffer2.slice(0, buffer2.length - pad);
  };
  DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
    var l2 = lStart;
    var r2 = rStart;
    for (var i2 = 0; i2 < state.keys.length; i2 += 2) {
      var keyL = state.keys[i2];
      var keyR = state.keys[i2 + 1];
      utils2.expand(r2, state.tmp, 0);
      keyL ^= state.tmp[0];
      keyR ^= state.tmp[1];
      var s2 = utils2.substitute(keyL, keyR);
      var f2 = utils2.permute(s2);
      var t2 = r2;
      r2 = (l2 ^ f2) >>> 0;
      l2 = t2;
    }
    utils2.rip(r2, l2, out, off);
  };
  DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
    var l2 = rStart;
    var r2 = lStart;
    for (var i2 = state.keys.length - 2; i2 >= 0; i2 -= 2) {
      var keyL = state.keys[i2];
      var keyR = state.keys[i2 + 1];
      utils2.expand(l2, state.tmp, 0);
      keyL ^= state.tmp[0];
      keyR ^= state.tmp[1];
      var s2 = utils2.substitute(keyL, keyR);
      var f2 = utils2.permute(s2);
      var t2 = l2;
      l2 = (r2 ^ f2) >>> 0;
      r2 = t2;
    }
    utils2.rip(l2, r2, out, off);
  };
  return des;
}
var cbc$1 = {};
var hasRequiredCbc$1;
function requireCbc$1() {
  if (hasRequiredCbc$1) return cbc$1;
  hasRequiredCbc$1 = 1;
  var assert = requireMinimalisticAssert();
  var inherits = requireInherits_browser();
  var proto = {};
  function CBCState(iv) {
    assert.equal(iv.length, 8, "Invalid IV length");
    this.iv = new Array(8);
    for (var i2 = 0; i2 < this.iv.length; i2++)
      this.iv[i2] = iv[i2];
  }
  function instantiate(Base) {
    function CBC(options2) {
      Base.call(this, options2);
      this._cbcInit();
    }
    inherits(CBC, Base);
    var keys = Object.keys(proto);
    for (var i2 = 0; i2 < keys.length; i2++) {
      var key2 = keys[i2];
      CBC.prototype[key2] = proto[key2];
    }
    CBC.create = function create2(options2) {
      return new CBC(options2);
    };
    return CBC;
  }
  cbc$1.instantiate = instantiate;
  proto._cbcInit = function _cbcInit() {
    var state = new CBCState(this.options.iv);
    this._cbcState = state;
  };
  proto._update = function _update(inp, inOff, out, outOff) {
    var state = this._cbcState;
    var superProto = this.constructor.super_.prototype;
    var iv = state.iv;
    if (this.type === "encrypt") {
      for (var i2 = 0; i2 < this.blockSize; i2++)
        iv[i2] ^= inp[inOff + i2];
      superProto._update.call(this, iv, 0, out, outOff);
      for (var i2 = 0; i2 < this.blockSize; i2++)
        iv[i2] = out[outOff + i2];
    } else {
      superProto._update.call(this, inp, inOff, out, outOff);
      for (var i2 = 0; i2 < this.blockSize; i2++)
        out[outOff + i2] ^= iv[i2];
      for (var i2 = 0; i2 < this.blockSize; i2++)
        iv[i2] = inp[inOff + i2];
    }
  };
  return cbc$1;
}
var ede;
var hasRequiredEde;
function requireEde() {
  if (hasRequiredEde) return ede;
  hasRequiredEde = 1;
  var assert = requireMinimalisticAssert();
  var inherits = requireInherits_browser();
  var Cipher = requireCipher();
  var DES = requireDes$1();
  function EDEState(type2, key2) {
    assert.equal(key2.length, 24, "Invalid key length");
    var k1 = key2.slice(0, 8);
    var k2 = key2.slice(8, 16);
    var k3 = key2.slice(16, 24);
    if (type2 === "encrypt") {
      this.ciphers = [
        DES.create({ type: "encrypt", key: k1 }),
        DES.create({ type: "decrypt", key: k2 }),
        DES.create({ type: "encrypt", key: k3 })
      ];
    } else {
      this.ciphers = [
        DES.create({ type: "decrypt", key: k3 }),
        DES.create({ type: "encrypt", key: k2 }),
        DES.create({ type: "decrypt", key: k1 })
      ];
    }
  }
  function EDE(options2) {
    Cipher.call(this, options2);
    var state = new EDEState(this.type, this.options.key);
    this._edeState = state;
  }
  inherits(EDE, Cipher);
  ede = EDE;
  EDE.create = function create2(options2) {
    return new EDE(options2);
  };
  EDE.prototype._update = function _update(inp, inOff, out, outOff) {
    var state = this._edeState;
    state.ciphers[0]._update(inp, inOff, out, outOff);
    state.ciphers[1]._update(out, outOff, out, outOff);
    state.ciphers[2]._update(out, outOff, out, outOff);
  };
  EDE.prototype._pad = DES.prototype._pad;
  EDE.prototype._unpad = DES.prototype._unpad;
  return ede;
}
var hasRequiredDes;
function requireDes() {
  if (hasRequiredDes) return des$1;
  hasRequiredDes = 1;
  des$1.utils = requireUtils$4();
  des$1.Cipher = requireCipher();
  des$1.DES = requireDes$1();
  des$1.CBC = requireCbc$1();
  des$1.EDE = requireEde();
  return des$1;
}
var browserifyDes;
var hasRequiredBrowserifyDes;
function requireBrowserifyDes() {
  if (hasRequiredBrowserifyDes) return browserifyDes;
  hasRequiredBrowserifyDes = 1;
  var CipherBase = requireCipherBase();
  var des2 = requireDes();
  var inherits = requireInherits_browser();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var modes2 = {
    "des-ede3-cbc": des2.CBC.instantiate(des2.EDE),
    "des-ede3": des2.EDE,
    "des-ede-cbc": des2.CBC.instantiate(des2.EDE),
    "des-ede": des2.EDE,
    "des-cbc": des2.CBC.instantiate(des2.DES),
    "des-ecb": des2.DES
  };
  modes2.des = modes2["des-cbc"];
  modes2.des3 = modes2["des-ede3-cbc"];
  browserifyDes = DES;
  inherits(DES, CipherBase);
  function DES(opts) {
    CipherBase.call(this);
    var modeName = opts.mode.toLowerCase();
    var mode = modes2[modeName];
    var type2;
    if (opts.decrypt) {
      type2 = "decrypt";
    } else {
      type2 = "encrypt";
    }
    var key2 = opts.key;
    if (!Buffer2.isBuffer(key2)) {
      key2 = Buffer2.from(key2);
    }
    if (modeName === "des-ede" || modeName === "des-ede-cbc") {
      key2 = Buffer2.concat([key2, key2.slice(0, 8)]);
    }
    var iv = opts.iv;
    if (!Buffer2.isBuffer(iv)) {
      iv = Buffer2.from(iv);
    }
    this._des = mode.create({
      key: key2,
      iv,
      type: type2
    });
  }
  DES.prototype._update = function(data2) {
    return Buffer2.from(this._des.update(data2));
  };
  DES.prototype._final = function() {
    return Buffer2.from(this._des.final());
  };
  return browserifyDes;
}
var browser$a = {};
var encrypter = {};
var ecb = {};
var hasRequiredEcb;
function requireEcb() {
  if (hasRequiredEcb) return ecb;
  hasRequiredEcb = 1;
  ecb.encrypt = function(self2, block) {
    return self2._cipher.encryptBlock(block);
  };
  ecb.decrypt = function(self2, block) {
    return self2._cipher.decryptBlock(block);
  };
  return ecb;
}
var cbc = {};
var bufferXor;
var hasRequiredBufferXor;
function requireBufferXor() {
  if (hasRequiredBufferXor) return bufferXor;
  hasRequiredBufferXor = 1;
  bufferXor = function xor2(a2, b2) {
    var length = Math.min(a2.length, b2.length);
    var buffer2 = new Buffer(length);
    for (var i2 = 0; i2 < length; ++i2) {
      buffer2[i2] = a2[i2] ^ b2[i2];
    }
    return buffer2;
  };
  return bufferXor;
}
var hasRequiredCbc;
function requireCbc() {
  if (hasRequiredCbc) return cbc;
  hasRequiredCbc = 1;
  var xor2 = requireBufferXor();
  cbc.encrypt = function(self2, block) {
    var data2 = xor2(block, self2._prev);
    self2._prev = self2._cipher.encryptBlock(data2);
    return self2._prev;
  };
  cbc.decrypt = function(self2, block) {
    var pad = self2._prev;
    self2._prev = block;
    var out = self2._cipher.decryptBlock(block);
    return xor2(out, pad);
  };
  return cbc;
}
var cfb = {};
var hasRequiredCfb;
function requireCfb() {
  if (hasRequiredCfb) return cfb;
  hasRequiredCfb = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var xor2 = requireBufferXor();
  function encryptStart(self2, data2, decrypt2) {
    var len = data2.length;
    var out = xor2(data2, self2._cache);
    self2._cache = self2._cache.slice(len);
    self2._prev = Buffer2.concat([self2._prev, decrypt2 ? data2 : out]);
    return out;
  }
  cfb.encrypt = function(self2, data2, decrypt2) {
    var out = Buffer2.allocUnsafe(0);
    var len;
    while (data2.length) {
      if (self2._cache.length === 0) {
        self2._cache = self2._cipher.encryptBlock(self2._prev);
        self2._prev = Buffer2.allocUnsafe(0);
      }
      if (self2._cache.length <= data2.length) {
        len = self2._cache.length;
        out = Buffer2.concat([out, encryptStart(self2, data2.slice(0, len), decrypt2)]);
        data2 = data2.slice(len);
      } else {
        out = Buffer2.concat([out, encryptStart(self2, data2, decrypt2)]);
        break;
      }
    }
    return out;
  };
  return cfb;
}
var cfb8 = {};
var hasRequiredCfb8;
function requireCfb8() {
  if (hasRequiredCfb8) return cfb8;
  hasRequiredCfb8 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function encryptByte(self2, byteParam, decrypt2) {
    var pad = self2._cipher.encryptBlock(self2._prev);
    var out = pad[0] ^ byteParam;
    self2._prev = Buffer2.concat([
      self2._prev.slice(1),
      Buffer2.from([decrypt2 ? byteParam : out])
    ]);
    return out;
  }
  cfb8.encrypt = function(self2, chunk, decrypt2) {
    var len = chunk.length;
    var out = Buffer2.allocUnsafe(len);
    var i2 = -1;
    while (++i2 < len) {
      out[i2] = encryptByte(self2, chunk[i2], decrypt2);
    }
    return out;
  };
  return cfb8;
}
var cfb1 = {};
var hasRequiredCfb1;
function requireCfb1() {
  if (hasRequiredCfb1) return cfb1;
  hasRequiredCfb1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function encryptByte(self2, byteParam, decrypt2) {
    var pad;
    var i2 = -1;
    var len = 8;
    var out = 0;
    var bit, value;
    while (++i2 < len) {
      pad = self2._cipher.encryptBlock(self2._prev);
      bit = byteParam & 1 << 7 - i2 ? 128 : 0;
      value = pad[0] ^ bit;
      out += (value & 128) >> i2 % 8;
      self2._prev = shiftIn(self2._prev, decrypt2 ? bit : value);
    }
    return out;
  }
  function shiftIn(buffer2, value) {
    var len = buffer2.length;
    var i2 = -1;
    var out = Buffer2.allocUnsafe(buffer2.length);
    buffer2 = Buffer2.concat([buffer2, Buffer2.from([value])]);
    while (++i2 < len) {
      out[i2] = buffer2[i2] << 1 | buffer2[i2 + 1] >> 7;
    }
    return out;
  }
  cfb1.encrypt = function(self2, chunk, decrypt2) {
    var len = chunk.length;
    var out = Buffer2.allocUnsafe(len);
    var i2 = -1;
    while (++i2 < len) {
      out[i2] = encryptByte(self2, chunk[i2], decrypt2);
    }
    return out;
  };
  return cfb1;
}
var ofb = {};
var hasRequiredOfb;
function requireOfb() {
  if (hasRequiredOfb) return ofb;
  hasRequiredOfb = 1;
  var xor2 = requireBufferXor();
  function getBlock(self2) {
    self2._prev = self2._cipher.encryptBlock(self2._prev);
    return self2._prev;
  }
  ofb.encrypt = function(self2, chunk) {
    while (self2._cache.length < chunk.length) {
      self2._cache = Buffer.concat([self2._cache, getBlock(self2)]);
    }
    var pad = self2._cache.slice(0, chunk.length);
    self2._cache = self2._cache.slice(chunk.length);
    return xor2(chunk, pad);
  };
  return ofb;
}
var ctr = {};
var incr32_1;
var hasRequiredIncr32;
function requireIncr32() {
  if (hasRequiredIncr32) return incr32_1;
  hasRequiredIncr32 = 1;
  function incr32(iv) {
    var len = iv.length;
    var item;
    while (len--) {
      item = iv.readUInt8(len);
      if (item === 255) {
        iv.writeUInt8(0, len);
      } else {
        item++;
        iv.writeUInt8(item, len);
        break;
      }
    }
  }
  incr32_1 = incr32;
  return incr32_1;
}
var hasRequiredCtr;
function requireCtr() {
  if (hasRequiredCtr) return ctr;
  hasRequiredCtr = 1;
  var xor2 = requireBufferXor();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var incr32 = requireIncr32();
  function getBlock(self2) {
    var out = self2._cipher.encryptBlockRaw(self2._prev);
    incr32(self2._prev);
    return out;
  }
  var blockSize = 16;
  ctr.encrypt = function(self2, chunk) {
    var chunkNum = Math.ceil(chunk.length / blockSize);
    var start = self2._cache.length;
    self2._cache = Buffer2.concat([
      self2._cache,
      Buffer2.allocUnsafe(chunkNum * blockSize)
    ]);
    for (var i2 = 0; i2 < chunkNum; i2++) {
      var out = getBlock(self2);
      var offset = start + i2 * blockSize;
      self2._cache.writeUInt32BE(out[0], offset + 0);
      self2._cache.writeUInt32BE(out[1], offset + 4);
      self2._cache.writeUInt32BE(out[2], offset + 8);
      self2._cache.writeUInt32BE(out[3], offset + 12);
    }
    var pad = self2._cache.slice(0, chunk.length);
    self2._cache = self2._cache.slice(chunk.length);
    return xor2(chunk, pad);
  };
  return ctr;
}
const aes128 = { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" };
const aes192 = { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" };
const aes256 = { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" };
const require$$2$1 = {
  "aes-128-ecb": { "cipher": "AES", "key": 128, "iv": 0, "mode": "ECB", "type": "block" },
  "aes-192-ecb": { "cipher": "AES", "key": 192, "iv": 0, "mode": "ECB", "type": "block" },
  "aes-256-ecb": { "cipher": "AES", "key": 256, "iv": 0, "mode": "ECB", "type": "block" },
  "aes-128-cbc": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" },
  "aes-192-cbc": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" },
  "aes-256-cbc": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" },
  aes128,
  aes192,
  aes256,
  "aes-128-cfb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB", "type": "stream" },
  "aes-192-cfb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB", "type": "stream" },
  "aes-256-cfb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB", "type": "stream" },
  "aes-128-cfb8": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB8", "type": "stream" },
  "aes-192-cfb8": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB8", "type": "stream" },
  "aes-256-cfb8": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB8", "type": "stream" },
  "aes-128-cfb1": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB1", "type": "stream" },
  "aes-192-cfb1": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB1", "type": "stream" },
  "aes-256-cfb1": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB1", "type": "stream" },
  "aes-128-ofb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "OFB", "type": "stream" },
  "aes-192-ofb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "OFB", "type": "stream" },
  "aes-256-ofb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "OFB", "type": "stream" },
  "aes-128-ctr": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CTR", "type": "stream" },
  "aes-192-ctr": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CTR", "type": "stream" },
  "aes-256-ctr": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CTR", "type": "stream" },
  "aes-128-gcm": { "cipher": "AES", "key": 128, "iv": 12, "mode": "GCM", "type": "auth" },
  "aes-192-gcm": { "cipher": "AES", "key": 192, "iv": 12, "mode": "GCM", "type": "auth" },
  "aes-256-gcm": { "cipher": "AES", "key": 256, "iv": 12, "mode": "GCM", "type": "auth" }
};
var modes_1;
var hasRequiredModes$1;
function requireModes$1() {
  if (hasRequiredModes$1) return modes_1;
  hasRequiredModes$1 = 1;
  var modeModules = {
    ECB: requireEcb(),
    CBC: requireCbc(),
    CFB: requireCfb(),
    CFB8: requireCfb8(),
    CFB1: requireCfb1(),
    OFB: requireOfb(),
    CTR: requireCtr(),
    GCM: requireCtr()
  };
  var modes2 = require$$2$1;
  for (var key2 in modes2) {
    modes2[key2].module = modeModules[modes2[key2].mode];
  }
  modes_1 = modes2;
  return modes_1;
}
var aes$2 = {};
var hasRequiredAes$1;
function requireAes$1() {
  if (hasRequiredAes$1) return aes$2;
  hasRequiredAes$1 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function asUInt32Array(buf) {
    if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
    var len = buf.length / 4 | 0;
    var out = new Array(len);
    for (var i2 = 0; i2 < len; i2++) {
      out[i2] = buf.readUInt32BE(i2 * 4);
    }
    return out;
  }
  function scrubVec(v2) {
    for (var i2 = 0; i2 < v2.length; v2++) {
      v2[i2] = 0;
    }
  }
  function cryptBlock(M2, keySchedule, SUB_MIX, SBOX, nRounds) {
    var SUB_MIX0 = SUB_MIX[0];
    var SUB_MIX1 = SUB_MIX[1];
    var SUB_MIX2 = SUB_MIX[2];
    var SUB_MIX3 = SUB_MIX[3];
    var s0 = M2[0] ^ keySchedule[0];
    var s1 = M2[1] ^ keySchedule[1];
    var s2 = M2[2] ^ keySchedule[2];
    var s3 = M2[3] ^ keySchedule[3];
    var t0, t1, t2, t3;
    var ksRow = 4;
    for (var round2 = 1; round2 < nRounds; round2++) {
      t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[s1 >>> 16 & 255] ^ SUB_MIX2[s2 >>> 8 & 255] ^ SUB_MIX3[s3 & 255] ^ keySchedule[ksRow++];
      t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[s2 >>> 16 & 255] ^ SUB_MIX2[s3 >>> 8 & 255] ^ SUB_MIX3[s0 & 255] ^ keySchedule[ksRow++];
      t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[s3 >>> 16 & 255] ^ SUB_MIX2[s0 >>> 8 & 255] ^ SUB_MIX3[s1 & 255] ^ keySchedule[ksRow++];
      t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[s0 >>> 16 & 255] ^ SUB_MIX2[s1 >>> 8 & 255] ^ SUB_MIX3[s2 & 255] ^ keySchedule[ksRow++];
      s0 = t0;
      s1 = t1;
      s2 = t2;
      s3 = t3;
    }
    t0 = (SBOX[s0 >>> 24] << 24 | SBOX[s1 >>> 16 & 255] << 16 | SBOX[s2 >>> 8 & 255] << 8 | SBOX[s3 & 255]) ^ keySchedule[ksRow++];
    t1 = (SBOX[s1 >>> 24] << 24 | SBOX[s2 >>> 16 & 255] << 16 | SBOX[s3 >>> 8 & 255] << 8 | SBOX[s0 & 255]) ^ keySchedule[ksRow++];
    t2 = (SBOX[s2 >>> 24] << 24 | SBOX[s3 >>> 16 & 255] << 16 | SBOX[s0 >>> 8 & 255] << 8 | SBOX[s1 & 255]) ^ keySchedule[ksRow++];
    t3 = (SBOX[s3 >>> 24] << 24 | SBOX[s0 >>> 16 & 255] << 16 | SBOX[s1 >>> 8 & 255] << 8 | SBOX[s2 & 255]) ^ keySchedule[ksRow++];
    t0 = t0 >>> 0;
    t1 = t1 >>> 0;
    t2 = t2 >>> 0;
    t3 = t3 >>> 0;
    return [t0, t1, t2, t3];
  }
  var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
  var G2 = function() {
    var d = new Array(256);
    for (var j = 0; j < 256; j++) {
      if (j < 128) {
        d[j] = j << 1;
      } else {
        d[j] = j << 1 ^ 283;
      }
    }
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX = [[], [], [], []];
    var INV_SUB_MIX = [[], [], [], []];
    var x2 = 0;
    var xi = 0;
    for (var i2 = 0; i2 < 256; ++i2) {
      var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
      sx = sx >>> 8 ^ sx & 255 ^ 99;
      SBOX[x2] = sx;
      INV_SBOX[sx] = x2;
      var x22 = d[x2];
      var x4 = d[x22];
      var x8 = d[x4];
      var t2 = d[sx] * 257 ^ sx * 16843008;
      SUB_MIX[0][x2] = t2 << 24 | t2 >>> 8;
      SUB_MIX[1][x2] = t2 << 16 | t2 >>> 16;
      SUB_MIX[2][x2] = t2 << 8 | t2 >>> 24;
      SUB_MIX[3][x2] = t2;
      t2 = x8 * 16843009 ^ x4 * 65537 ^ x22 * 257 ^ x2 * 16843008;
      INV_SUB_MIX[0][sx] = t2 << 24 | t2 >>> 8;
      INV_SUB_MIX[1][sx] = t2 << 16 | t2 >>> 16;
      INV_SUB_MIX[2][sx] = t2 << 8 | t2 >>> 24;
      INV_SUB_MIX[3][sx] = t2;
      if (x2 === 0) {
        x2 = xi = 1;
      } else {
        x2 = x22 ^ d[d[d[x8 ^ x22]]];
        xi ^= d[d[xi]];
      }
    }
    return {
      SBOX,
      INV_SBOX,
      SUB_MIX,
      INV_SUB_MIX
    };
  }();
  function AES(key2) {
    this._key = asUInt32Array(key2);
    this._reset();
  }
  AES.blockSize = 4 * 4;
  AES.keySize = 256 / 8;
  AES.prototype.blockSize = AES.blockSize;
  AES.prototype.keySize = AES.keySize;
  AES.prototype._reset = function() {
    var keyWords = this._key;
    var keySize = keyWords.length;
    var nRounds = keySize + 6;
    var ksRows = (nRounds + 1) * 4;
    var keySchedule = [];
    for (var k2 = 0; k2 < keySize; k2++) {
      keySchedule[k2] = keyWords[k2];
    }
    for (k2 = keySize; k2 < ksRows; k2++) {
      var t2 = keySchedule[k2 - 1];
      if (k2 % keySize === 0) {
        t2 = t2 << 8 | t2 >>> 24;
        t2 = G2.SBOX[t2 >>> 24] << 24 | G2.SBOX[t2 >>> 16 & 255] << 16 | G2.SBOX[t2 >>> 8 & 255] << 8 | G2.SBOX[t2 & 255];
        t2 ^= RCON[k2 / keySize | 0] << 24;
      } else if (keySize > 6 && k2 % keySize === 4) {
        t2 = G2.SBOX[t2 >>> 24] << 24 | G2.SBOX[t2 >>> 16 & 255] << 16 | G2.SBOX[t2 >>> 8 & 255] << 8 | G2.SBOX[t2 & 255];
      }
      keySchedule[k2] = keySchedule[k2 - keySize] ^ t2;
    }
    var invKeySchedule = [];
    for (var ik = 0; ik < ksRows; ik++) {
      var ksR = ksRows - ik;
      var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)];
      if (ik < 4 || ksR <= 4) {
        invKeySchedule[ik] = tt;
      } else {
        invKeySchedule[ik] = G2.INV_SUB_MIX[0][G2.SBOX[tt >>> 24]] ^ G2.INV_SUB_MIX[1][G2.SBOX[tt >>> 16 & 255]] ^ G2.INV_SUB_MIX[2][G2.SBOX[tt >>> 8 & 255]] ^ G2.INV_SUB_MIX[3][G2.SBOX[tt & 255]];
      }
    }
    this._nRounds = nRounds;
    this._keySchedule = keySchedule;
    this._invKeySchedule = invKeySchedule;
  };
  AES.prototype.encryptBlockRaw = function(M2) {
    M2 = asUInt32Array(M2);
    return cryptBlock(M2, this._keySchedule, G2.SUB_MIX, G2.SBOX, this._nRounds);
  };
  AES.prototype.encryptBlock = function(M2) {
    var out = this.encryptBlockRaw(M2);
    var buf = Buffer2.allocUnsafe(16);
    buf.writeUInt32BE(out[0], 0);
    buf.writeUInt32BE(out[1], 4);
    buf.writeUInt32BE(out[2], 8);
    buf.writeUInt32BE(out[3], 12);
    return buf;
  };
  AES.prototype.decryptBlock = function(M2) {
    M2 = asUInt32Array(M2);
    var m1 = M2[1];
    M2[1] = M2[3];
    M2[3] = m1;
    var out = cryptBlock(M2, this._invKeySchedule, G2.INV_SUB_MIX, G2.INV_SBOX, this._nRounds);
    var buf = Buffer2.allocUnsafe(16);
    buf.writeUInt32BE(out[0], 0);
    buf.writeUInt32BE(out[3], 4);
    buf.writeUInt32BE(out[2], 8);
    buf.writeUInt32BE(out[1], 12);
    return buf;
  };
  AES.prototype.scrub = function() {
    scrubVec(this._keySchedule);
    scrubVec(this._invKeySchedule);
    scrubVec(this._key);
  };
  aes$2.AES = AES;
  return aes$2;
}
var ghash;
var hasRequiredGhash;
function requireGhash() {
  if (hasRequiredGhash) return ghash;
  hasRequiredGhash = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var ZEROES = Buffer2.alloc(16, 0);
  function toArray(buf) {
    return [
      buf.readUInt32BE(0),
      buf.readUInt32BE(4),
      buf.readUInt32BE(8),
      buf.readUInt32BE(12)
    ];
  }
  function fromArray(out) {
    var buf = Buffer2.allocUnsafe(16);
    buf.writeUInt32BE(out[0] >>> 0, 0);
    buf.writeUInt32BE(out[1] >>> 0, 4);
    buf.writeUInt32BE(out[2] >>> 0, 8);
    buf.writeUInt32BE(out[3] >>> 0, 12);
    return buf;
  }
  function GHASH(key2) {
    this.h = key2;
    this.state = Buffer2.alloc(16, 0);
    this.cache = Buffer2.allocUnsafe(0);
  }
  GHASH.prototype.ghash = function(block) {
    var i2 = -1;
    while (++i2 < block.length) {
      this.state[i2] ^= block[i2];
    }
    this._multiply();
  };
  GHASH.prototype._multiply = function() {
    var Vi = toArray(this.h);
    var Zi = [0, 0, 0, 0];
    var j, xi, lsbVi;
    var i2 = -1;
    while (++i2 < 128) {
      xi = (this.state[~~(i2 / 8)] & 1 << 7 - i2 % 8) !== 0;
      if (xi) {
        Zi[0] ^= Vi[0];
        Zi[1] ^= Vi[1];
        Zi[2] ^= Vi[2];
        Zi[3] ^= Vi[3];
      }
      lsbVi = (Vi[3] & 1) !== 0;
      for (j = 3; j > 0; j--) {
        Vi[j] = Vi[j] >>> 1 | (Vi[j - 1] & 1) << 31;
      }
      Vi[0] = Vi[0] >>> 1;
      if (lsbVi) {
        Vi[0] = Vi[0] ^ 225 << 24;
      }
    }
    this.state = fromArray(Zi);
  };
  GHASH.prototype.update = function(buf) {
    this.cache = Buffer2.concat([this.cache, buf]);
    var chunk;
    while (this.cache.length >= 16) {
      chunk = this.cache.slice(0, 16);
      this.cache = this.cache.slice(16);
      this.ghash(chunk);
    }
  };
  GHASH.prototype.final = function(abl, bl) {
    if (this.cache.length) {
      this.ghash(Buffer2.concat([this.cache, ZEROES], 16));
    }
    this.ghash(fromArray([0, abl, 0, bl]));
    return this.state;
  };
  ghash = GHASH;
  return ghash;
}
var authCipher;
var hasRequiredAuthCipher;
function requireAuthCipher() {
  if (hasRequiredAuthCipher) return authCipher;
  hasRequiredAuthCipher = 1;
  var aes2 = requireAes$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var Transform = requireCipherBase();
  var inherits = requireInherits_browser();
  var GHASH = requireGhash();
  var xor2 = requireBufferXor();
  var incr32 = requireIncr32();
  function xorTest(a2, b2) {
    var out = 0;
    if (a2.length !== b2.length) out++;
    var len = Math.min(a2.length, b2.length);
    for (var i2 = 0; i2 < len; ++i2) {
      out += a2[i2] ^ b2[i2];
    }
    return out;
  }
  function calcIv(self2, iv, ck) {
    if (iv.length === 12) {
      self2._finID = Buffer2.concat([iv, Buffer2.from([0, 0, 0, 1])]);
      return Buffer2.concat([iv, Buffer2.from([0, 0, 0, 2])]);
    }
    var ghash2 = new GHASH(ck);
    var len = iv.length;
    var toPad = len % 16;
    ghash2.update(iv);
    if (toPad) {
      toPad = 16 - toPad;
      ghash2.update(Buffer2.alloc(toPad, 0));
    }
    ghash2.update(Buffer2.alloc(8, 0));
    var ivBits = len * 8;
    var tail = Buffer2.alloc(8);
    tail.writeUIntBE(ivBits, 0, 8);
    ghash2.update(tail);
    self2._finID = ghash2.state;
    var out = Buffer2.from(self2._finID);
    incr32(out);
    return out;
  }
  function StreamCipher(mode, key2, iv, decrypt2) {
    Transform.call(this);
    var h2 = Buffer2.alloc(4, 0);
    this._cipher = new aes2.AES(key2);
    var ck = this._cipher.encryptBlock(h2);
    this._ghash = new GHASH(ck);
    iv = calcIv(this, iv, ck);
    this._prev = Buffer2.from(iv);
    this._cache = Buffer2.allocUnsafe(0);
    this._secCache = Buffer2.allocUnsafe(0);
    this._decrypt = decrypt2;
    this._alen = 0;
    this._len = 0;
    this._mode = mode;
    this._authTag = null;
    this._called = false;
  }
  inherits(StreamCipher, Transform);
  StreamCipher.prototype._update = function(chunk) {
    if (!this._called && this._alen) {
      var rump = 16 - this._alen % 16;
      if (rump < 16) {
        rump = Buffer2.alloc(rump, 0);
        this._ghash.update(rump);
      }
    }
    this._called = true;
    var out = this._mode.encrypt(this, chunk);
    if (this._decrypt) {
      this._ghash.update(chunk);
    } else {
      this._ghash.update(out);
    }
    this._len += chunk.length;
    return out;
  };
  StreamCipher.prototype._final = function() {
    if (this._decrypt && !this._authTag) throw new Error("Unsupported state or unable to authenticate data");
    var tag = xor2(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID));
    if (this._decrypt && xorTest(tag, this._authTag)) throw new Error("Unsupported state or unable to authenticate data");
    this._authTag = tag;
    this._cipher.scrub();
  };
  StreamCipher.prototype.getAuthTag = function getAuthTag() {
    if (this._decrypt || !Buffer2.isBuffer(this._authTag)) throw new Error("Attempting to get auth tag in unsupported state");
    return this._authTag;
  };
  StreamCipher.prototype.setAuthTag = function setAuthTag(tag) {
    if (!this._decrypt) throw new Error("Attempting to set auth tag in unsupported state");
    this._authTag = tag;
  };
  StreamCipher.prototype.setAAD = function setAAD(buf) {
    if (this._called) throw new Error("Attempting to set AAD in unsupported state");
    this._ghash.update(buf);
    this._alen += buf.length;
  };
  authCipher = StreamCipher;
  return authCipher;
}
var streamCipher;
var hasRequiredStreamCipher;
function requireStreamCipher() {
  if (hasRequiredStreamCipher) return streamCipher;
  hasRequiredStreamCipher = 1;
  var aes2 = requireAes$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var Transform = requireCipherBase();
  var inherits = requireInherits_browser();
  function StreamCipher(mode, key2, iv, decrypt2) {
    Transform.call(this);
    this._cipher = new aes2.AES(key2);
    this._prev = Buffer2.from(iv);
    this._cache = Buffer2.allocUnsafe(0);
    this._secCache = Buffer2.allocUnsafe(0);
    this._decrypt = decrypt2;
    this._mode = mode;
  }
  inherits(StreamCipher, Transform);
  StreamCipher.prototype._update = function(chunk) {
    return this._mode.encrypt(this, chunk, this._decrypt);
  };
  StreamCipher.prototype._final = function() {
    this._cipher.scrub();
  };
  streamCipher = StreamCipher;
  return streamCipher;
}
var evp_bytestokey;
var hasRequiredEvp_bytestokey;
function requireEvp_bytestokey() {
  if (hasRequiredEvp_bytestokey) return evp_bytestokey;
  hasRequiredEvp_bytestokey = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var MD5 = requireMd5_js();
  function EVP_BytesToKey(password, salt, keyBits, ivLen) {
    if (!Buffer2.isBuffer(password)) password = Buffer2.from(password, "binary");
    if (salt) {
      if (!Buffer2.isBuffer(salt)) salt = Buffer2.from(salt, "binary");
      if (salt.length !== 8) throw new RangeError("salt should be Buffer with 8 byte length");
    }
    var keyLen = keyBits / 8;
    var key2 = Buffer2.alloc(keyLen);
    var iv = Buffer2.alloc(ivLen || 0);
    var tmp = Buffer2.alloc(0);
    while (keyLen > 0 || ivLen > 0) {
      var hash2 = new MD5();
      hash2.update(tmp);
      hash2.update(password);
      if (salt) hash2.update(salt);
      tmp = hash2.digest();
      var used = 0;
      if (keyLen > 0) {
        var keyStart = key2.length - keyLen;
        used = Math.min(keyLen, tmp.length);
        tmp.copy(key2, keyStart, 0, used);
        keyLen -= used;
      }
      if (used < tmp.length && ivLen > 0) {
        var ivStart = iv.length - ivLen;
        var length = Math.min(ivLen, tmp.length - used);
        tmp.copy(iv, ivStart, used, used + length);
        ivLen -= length;
      }
    }
    tmp.fill(0);
    return { key: key2, iv };
  }
  evp_bytestokey = EVP_BytesToKey;
  return evp_bytestokey;
}
var hasRequiredEncrypter;
function requireEncrypter() {
  if (hasRequiredEncrypter) return encrypter;
  hasRequiredEncrypter = 1;
  var MODES = requireModes$1();
  var AuthCipher = requireAuthCipher();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var StreamCipher = requireStreamCipher();
  var Transform = requireCipherBase();
  var aes2 = requireAes$1();
  var ebtk = requireEvp_bytestokey();
  var inherits = requireInherits_browser();
  function Cipher(mode, key2, iv) {
    Transform.call(this);
    this._cache = new Splitter();
    this._cipher = new aes2.AES(key2);
    this._prev = Buffer2.from(iv);
    this._mode = mode;
    this._autopadding = true;
  }
  inherits(Cipher, Transform);
  Cipher.prototype._update = function(data2) {
    this._cache.add(data2);
    var chunk;
    var thing;
    var out = [];
    while (chunk = this._cache.get()) {
      thing = this._mode.encrypt(this, chunk);
      out.push(thing);
    }
    return Buffer2.concat(out);
  };
  var PADDING = Buffer2.alloc(16, 16);
  Cipher.prototype._final = function() {
    var chunk = this._cache.flush();
    if (this._autopadding) {
      chunk = this._mode.encrypt(this, chunk);
      this._cipher.scrub();
      return chunk;
    }
    if (!chunk.equals(PADDING)) {
      this._cipher.scrub();
      throw new Error("data not multiple of block length");
    }
  };
  Cipher.prototype.setAutoPadding = function(setTo) {
    this._autopadding = !!setTo;
    return this;
  };
  function Splitter() {
    this.cache = Buffer2.allocUnsafe(0);
  }
  Splitter.prototype.add = function(data2) {
    this.cache = Buffer2.concat([this.cache, data2]);
  };
  Splitter.prototype.get = function() {
    if (this.cache.length > 15) {
      var out = this.cache.slice(0, 16);
      this.cache = this.cache.slice(16);
      return out;
    }
    return null;
  };
  Splitter.prototype.flush = function() {
    var len = 16 - this.cache.length;
    var padBuff = Buffer2.allocUnsafe(len);
    var i2 = -1;
    while (++i2 < len) {
      padBuff.writeUInt8(len, i2);
    }
    return Buffer2.concat([this.cache, padBuff]);
  };
  function createCipheriv(suite, password, iv) {
    var config = MODES[suite.toLowerCase()];
    if (!config) throw new TypeError("invalid suite type");
    if (typeof password === "string") password = Buffer2.from(password);
    if (password.length !== config.key / 8) throw new TypeError("invalid key length " + password.length);
    if (typeof iv === "string") iv = Buffer2.from(iv);
    if (config.mode !== "GCM" && iv.length !== config.iv) throw new TypeError("invalid iv length " + iv.length);
    if (config.type === "stream") {
      return new StreamCipher(config.module, password, iv);
    } else if (config.type === "auth") {
      return new AuthCipher(config.module, password, iv);
    }
    return new Cipher(config.module, password, iv);
  }
  function createCipher(suite, password) {
    var config = MODES[suite.toLowerCase()];
    if (!config) throw new TypeError("invalid suite type");
    var keys = ebtk(password, false, config.key, config.iv);
    return createCipheriv(suite, keys.key, keys.iv);
  }
  encrypter.createCipheriv = createCipheriv;
  encrypter.createCipher = createCipher;
  return encrypter;
}
var decrypter = {};
var hasRequiredDecrypter;
function requireDecrypter() {
  if (hasRequiredDecrypter) return decrypter;
  hasRequiredDecrypter = 1;
  var AuthCipher = requireAuthCipher();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var MODES = requireModes$1();
  var StreamCipher = requireStreamCipher();
  var Transform = requireCipherBase();
  var aes2 = requireAes$1();
  var ebtk = requireEvp_bytestokey();
  var inherits = requireInherits_browser();
  function Decipher(mode, key2, iv) {
    Transform.call(this);
    this._cache = new Splitter();
    this._last = void 0;
    this._cipher = new aes2.AES(key2);
    this._prev = Buffer2.from(iv);
    this._mode = mode;
    this._autopadding = true;
  }
  inherits(Decipher, Transform);
  Decipher.prototype._update = function(data2) {
    this._cache.add(data2);
    var chunk;
    var thing;
    var out = [];
    while (chunk = this._cache.get(this._autopadding)) {
      thing = this._mode.decrypt(this, chunk);
      out.push(thing);
    }
    return Buffer2.concat(out);
  };
  Decipher.prototype._final = function() {
    var chunk = this._cache.flush();
    if (this._autopadding) {
      return unpad(this._mode.decrypt(this, chunk));
    } else if (chunk) {
      throw new Error("data not multiple of block length");
    }
  };
  Decipher.prototype.setAutoPadding = function(setTo) {
    this._autopadding = !!setTo;
    return this;
  };
  function Splitter() {
    this.cache = Buffer2.allocUnsafe(0);
  }
  Splitter.prototype.add = function(data2) {
    this.cache = Buffer2.concat([this.cache, data2]);
  };
  Splitter.prototype.get = function(autoPadding) {
    var out;
    if (autoPadding) {
      if (this.cache.length > 16) {
        out = this.cache.slice(0, 16);
        this.cache = this.cache.slice(16);
        return out;
      }
    } else {
      if (this.cache.length >= 16) {
        out = this.cache.slice(0, 16);
        this.cache = this.cache.slice(16);
        return out;
      }
    }
    return null;
  };
  Splitter.prototype.flush = function() {
    if (this.cache.length) return this.cache;
  };
  function unpad(last) {
    var padded = last[15];
    if (padded < 1 || padded > 16) {
      throw new Error("unable to decrypt data");
    }
    var i2 = -1;
    while (++i2 < padded) {
      if (last[i2 + (16 - padded)] !== padded) {
        throw new Error("unable to decrypt data");
      }
    }
    if (padded === 16) return;
    return last.slice(0, 16 - padded);
  }
  function createDecipheriv(suite, password, iv) {
    var config = MODES[suite.toLowerCase()];
    if (!config) throw new TypeError("invalid suite type");
    if (typeof iv === "string") iv = Buffer2.from(iv);
    if (config.mode !== "GCM" && iv.length !== config.iv) throw new TypeError("invalid iv length " + iv.length);
    if (typeof password === "string") password = Buffer2.from(password);
    if (password.length !== config.key / 8) throw new TypeError("invalid key length " + password.length);
    if (config.type === "stream") {
      return new StreamCipher(config.module, password, iv, true);
    } else if (config.type === "auth") {
      return new AuthCipher(config.module, password, iv, true);
    }
    return new Decipher(config.module, password, iv);
  }
  function createDecipher(suite, password) {
    var config = MODES[suite.toLowerCase()];
    if (!config) throw new TypeError("invalid suite type");
    var keys = ebtk(password, false, config.key, config.iv);
    return createDecipheriv(suite, keys.key, keys.iv);
  }
  decrypter.createDecipher = createDecipher;
  decrypter.createDecipheriv = createDecipheriv;
  return decrypter;
}
var hasRequiredBrowser$9;
function requireBrowser$9() {
  if (hasRequiredBrowser$9) return browser$a;
  hasRequiredBrowser$9 = 1;
  var ciphers = requireEncrypter();
  var deciphers = requireDecrypter();
  var modes2 = require$$2$1;
  function getCiphers() {
    return Object.keys(modes2);
  }
  browser$a.createCipher = browser$a.Cipher = ciphers.createCipher;
  browser$a.createCipheriv = browser$a.Cipheriv = ciphers.createCipheriv;
  browser$a.createDecipher = browser$a.Decipher = deciphers.createDecipher;
  browser$a.createDecipheriv = browser$a.Decipheriv = deciphers.createDecipheriv;
  browser$a.listCiphers = browser$a.getCiphers = getCiphers;
  return browser$a;
}
var modes = {};
var hasRequiredModes;
function requireModes() {
  if (hasRequiredModes) return modes;
  hasRequiredModes = 1;
  (function(exports) {
    exports["des-ecb"] = {
      key: 8,
      iv: 0
    };
    exports["des-cbc"] = exports.des = {
      key: 8,
      iv: 8
    };
    exports["des-ede3-cbc"] = exports.des3 = {
      key: 24,
      iv: 8
    };
    exports["des-ede3"] = {
      key: 24,
      iv: 0
    };
    exports["des-ede-cbc"] = {
      key: 16,
      iv: 8
    };
    exports["des-ede"] = {
      key: 16,
      iv: 0
    };
  })(modes);
  return modes;
}
var hasRequiredBrowser$8;
function requireBrowser$8() {
  if (hasRequiredBrowser$8) return browser$b;
  hasRequiredBrowser$8 = 1;
  var DES = requireBrowserifyDes();
  var aes2 = requireBrowser$9();
  var aesModes = requireModes$1();
  var desModes = requireModes();
  var ebtk = requireEvp_bytestokey();
  function createCipher(suite, password) {
    suite = suite.toLowerCase();
    var keyLen, ivLen;
    if (aesModes[suite]) {
      keyLen = aesModes[suite].key;
      ivLen = aesModes[suite].iv;
    } else if (desModes[suite]) {
      keyLen = desModes[suite].key * 8;
      ivLen = desModes[suite].iv;
    } else {
      throw new TypeError("invalid suite type");
    }
    var keys = ebtk(password, false, keyLen, ivLen);
    return createCipheriv(suite, keys.key, keys.iv);
  }
  function createDecipher(suite, password) {
    suite = suite.toLowerCase();
    var keyLen, ivLen;
    if (aesModes[suite]) {
      keyLen = aesModes[suite].key;
      ivLen = aesModes[suite].iv;
    } else if (desModes[suite]) {
      keyLen = desModes[suite].key * 8;
      ivLen = desModes[suite].iv;
    } else {
      throw new TypeError("invalid suite type");
    }
    var keys = ebtk(password, false, keyLen, ivLen);
    return createDecipheriv(suite, keys.key, keys.iv);
  }
  function createCipheriv(suite, key2, iv) {
    suite = suite.toLowerCase();
    if (aesModes[suite]) return aes2.createCipheriv(suite, key2, iv);
    if (desModes[suite]) return new DES({ key: key2, iv, mode: suite });
    throw new TypeError("invalid suite type");
  }
  function createDecipheriv(suite, key2, iv) {
    suite = suite.toLowerCase();
    if (aesModes[suite]) return aes2.createDecipheriv(suite, key2, iv);
    if (desModes[suite]) return new DES({ key: key2, iv, mode: suite, decrypt: true });
    throw new TypeError("invalid suite type");
  }
  function getCiphers() {
    return Object.keys(desModes).concat(aes2.getCiphers());
  }
  browser$b.createCipher = browser$b.Cipher = createCipher;
  browser$b.createCipheriv = browser$b.Cipheriv = createCipheriv;
  browser$b.createDecipher = browser$b.Decipher = createDecipher;
  browser$b.createDecipheriv = browser$b.Decipheriv = createDecipheriv;
  browser$b.listCiphers = browser$b.getCiphers = getCiphers;
  return browser$b;
}
var browser$9 = {};
var bn$3 = { exports: {} };
var bn$2 = bn$3.exports;
var hasRequiredBn$1;
function requireBn$1() {
  if (hasRequiredBn$1) return bn$3.exports;
  hasRequiredBn$1 = 1;
  (function(module2) {
    (function(module3, exports) {
      function assert(val, msg) {
        if (!val) throw new Error(msg || "Assertion failed");
      }
      function inherits(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {
        };
        TempCtor.prototype = superCtor.prototype;
        ctor.prototype = new TempCtor();
        ctor.prototype.constructor = ctor;
      }
      function BN(number, base2, endian) {
        if (BN.isBN(number)) {
          return number;
        }
        this.negative = 0;
        this.words = null;
        this.length = 0;
        this.red = null;
        if (number !== null) {
          if (base2 === "le" || base2 === "be") {
            endian = base2;
            base2 = 10;
          }
          this._init(number || 0, base2 || 10, endian || "be");
        }
      }
      if (typeof module3 === "object") {
        module3.exports = BN;
      } else {
        exports.BN = BN;
      }
      BN.BN = BN;
      BN.wordSize = 26;
      var Buffer2;
      try {
        if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") {
          Buffer2 = window.Buffer;
        } else {
          Buffer2 = require$$0$2.Buffer;
        }
      } catch (e4) {
      }
      BN.isBN = function isBN(num) {
        if (num instanceof BN) {
          return true;
        }
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      };
      BN.max = function max2(left, right) {
        if (left.cmp(right) > 0) return left;
        return right;
      };
      BN.min = function min2(left, right) {
        if (left.cmp(right) < 0) return left;
        return right;
      };
      BN.prototype._init = function init2(number, base2, endian) {
        if (typeof number === "number") {
          return this._initNumber(number, base2, endian);
        }
        if (typeof number === "object") {
          return this._initArray(number, base2, endian);
        }
        if (base2 === "hex") {
          base2 = 16;
        }
        assert(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36);
        number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-") {
          start++;
          this.negative = 1;
        }
        if (start < number.length) {
          if (base2 === 16) {
            this._parseHex(number, start, endian);
          } else {
            this._parseBase(number, base2, start);
            if (endian === "le") {
              this._initArray(this.toArray(), base2, endian);
            }
          }
        }
      };
      BN.prototype._initNumber = function _initNumber(number, base2, endian) {
        if (number < 0) {
          this.negative = 1;
          number = -number;
        }
        if (number < 67108864) {
          this.words = [number & 67108863];
          this.length = 1;
        } else if (number < 4503599627370496) {
          this.words = [
            number & 67108863,
            number / 67108864 & 67108863
          ];
          this.length = 2;
        } else {
          assert(number < 9007199254740992);
          this.words = [
            number & 67108863,
            number / 67108864 & 67108863,
            1
          ];
          this.length = 3;
        }
        if (endian !== "le") return;
        this._initArray(this.toArray(), base2, endian);
      };
      BN.prototype._initArray = function _initArray(number, base2, endian) {
        assert(typeof number.length === "number");
        if (number.length <= 0) {
          this.words = [0];
          this.length = 1;
          return this;
        }
        this.length = Math.ceil(number.length / 3);
        this.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          this.words[i2] = 0;
        }
        var j, w;
        var off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0; i2 >= 0; i2 -= 3) {
            w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16;
            this.words[j] |= w << off & 67108863;
            this.words[j + 1] = w >>> 26 - off & 67108863;
            off += 24;
            if (off >= 26) {
              off -= 26;
              j++;
            }
          }
        } else if (endian === "le") {
          for (i2 = 0, j = 0; i2 < number.length; i2 += 3) {
            w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16;
            this.words[j] |= w << off & 67108863;
            this.words[j + 1] = w >>> 26 - off & 67108863;
            off += 24;
            if (off >= 26) {
              off -= 26;
              j++;
            }
          }
        }
        return this.strip();
      };
      function parseHex4Bits(string, index2) {
        var c2 = string.charCodeAt(index2);
        if (c2 >= 65 && c2 <= 70) {
          return c2 - 55;
        } else if (c2 >= 97 && c2 <= 102) {
          return c2 - 87;
        } else {
          return c2 - 48 & 15;
        }
      }
      function parseHexByte(string, lowerBound, index2) {
        var r2 = parseHex4Bits(string, index2);
        if (index2 - 1 >= lowerBound) {
          r2 |= parseHex4Bits(string, index2 - 1) << 4;
        }
        return r2;
      }
      BN.prototype._parseHex = function _parseHex(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6);
        this.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          this.words[i2] = 0;
        }
        var off = 0;
        var j = 0;
        var w;
        if (endian === "be") {
          for (i2 = number.length - 1; i2 >= start; i2 -= 2) {
            w = parseHexByte(number, start, i2) << off;
            this.words[j] |= w & 67108863;
            if (off >= 18) {
              off -= 18;
              j += 1;
              this.words[j] |= w >>> 26;
            } else {
              off += 8;
            }
          }
        } else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start; i2 < number.length; i2 += 2) {
            w = parseHexByte(number, start, i2) << off;
            this.words[j] |= w & 67108863;
            if (off >= 18) {
              off -= 18;
              j += 1;
              this.words[j] |= w >>> 26;
            } else {
              off += 8;
            }
          }
        }
        this.strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0;
        var len = Math.min(str.length, end);
        for (var i2 = start; i2 < len; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          r2 *= mul;
          if (c2 >= 49) {
            r2 += c2 - 49 + 10;
          } else if (c2 >= 17) {
            r2 += c2 - 17 + 10;
          } else {
            r2 += c2;
          }
        }
        return r2;
      }
      BN.prototype._parseBase = function _parseBase(number, base2, start) {
        this.words = [0];
        this.length = 1;
        for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) {
          limbLen++;
        }
        limbLen--;
        limbPow = limbPow / base2 | 0;
        var total = number.length - start;
        var mod = total % limbLen;
        var end = Math.min(total, total - mod) + start;
        var word = 0;
        for (var i2 = start; i2 < end; i2 += limbLen) {
          word = parseBase(number, i2, i2 + limbLen, base2);
          this.imuln(limbPow);
          if (this.words[0] + word < 67108864) {
            this.words[0] += word;
          } else {
            this._iaddn(word);
          }
        }
        if (mod !== 0) {
          var pow2 = 1;
          word = parseBase(number, i2, number.length, base2);
          for (i2 = 0; i2 < mod; i2++) {
            pow2 *= base2;
          }
          this.imuln(pow2);
          if (this.words[0] + word < 67108864) {
            this.words[0] += word;
          } else {
            this._iaddn(word);
          }
        }
        this.strip();
      };
      BN.prototype.copy = function copy2(dest) {
        dest.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          dest.words[i2] = this.words[i2];
        }
        dest.length = this.length;
        dest.negative = this.negative;
        dest.red = this.red;
      };
      BN.prototype.clone = function clone2() {
        var r2 = new BN(null);
        this.copy(r2);
        return r2;
      };
      BN.prototype._expand = function _expand(size) {
        while (this.length < size) {
          this.words[this.length++] = 0;
        }
        return this;
      };
      BN.prototype.strip = function strip() {
        while (this.length > 1 && this.words[this.length - 1] === 0) {
          this.length--;
        }
        return this._normSign();
      };
      BN.prototype._normSign = function _normSign() {
        if (this.length === 1 && this.words[0] === 0) {
          this.negative = 0;
        }
        return this;
      };
      BN.prototype.inspect = function inspect() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      };
      var zeros = [
        "",
        "0",
        "00",
        "000",
        "0000",
        "00000",
        "000000",
        "0000000",
        "00000000",
        "000000000",
        "0000000000",
        "00000000000",
        "000000000000",
        "0000000000000",
        "00000000000000",
        "000000000000000",
        "0000000000000000",
        "00000000000000000",
        "000000000000000000",
        "0000000000000000000",
        "00000000000000000000",
        "000000000000000000000",
        "0000000000000000000000",
        "00000000000000000000000",
        "000000000000000000000000",
        "0000000000000000000000000"
      ];
      var groupSizes = [
        0,
        0,
        25,
        16,
        12,
        11,
        10,
        9,
        8,
        8,
        7,
        7,
        7,
        7,
        6,
        6,
        6,
        6,
        6,
        6,
        6,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5
      ];
      var groupBases = [
        0,
        0,
        33554432,
        43046721,
        16777216,
        48828125,
        60466176,
        40353607,
        16777216,
        43046721,
        1e7,
        19487171,
        35831808,
        62748517,
        7529536,
        11390625,
        16777216,
        24137569,
        34012224,
        47045881,
        64e6,
        4084101,
        5153632,
        6436343,
        7962624,
        9765625,
        11881376,
        14348907,
        17210368,
        20511149,
        243e5,
        28629151,
        33554432,
        39135393,
        45435424,
        52521875,
        60466176
      ];
      BN.prototype.toString = function toString2(base2, padding) {
        base2 = base2 || 10;
        padding = padding | 0 || 1;
        var out;
        if (base2 === 16 || base2 === "hex") {
          out = "";
          var off = 0;
          var carry = 0;
          for (var i2 = 0; i2 < this.length; i2++) {
            var w = this.words[i2];
            var word = ((w << off | carry) & 16777215).toString(16);
            carry = w >>> 24 - off & 16777215;
            off += 2;
            if (off >= 26) {
              off -= 26;
              i2--;
            }
            if (carry !== 0 || i2 !== this.length - 1) {
              out = zeros[6 - word.length] + word + out;
            } else {
              out = word + out;
            }
          }
          if (carry !== 0) {
            out = carry.toString(16) + out;
          }
          while (out.length % padding !== 0) {
            out = "0" + out;
          }
          if (this.negative !== 0) {
            out = "-" + out;
          }
          return out;
        }
        if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) {
          var groupSize = groupSizes[base2];
          var groupBase = groupBases[base2];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modn(groupBase).toString(base2);
            c2 = c2.idivn(groupBase);
            if (!c2.isZero()) {
              out = zeros[groupSize - r2.length] + r2 + out;
            } else {
              out = r2 + out;
            }
          }
          if (this.isZero()) {
            out = "0" + out;
          }
          while (out.length % padding !== 0) {
            out = "0" + out;
          }
          if (this.negative !== 0) {
            out = "-" + out;
          }
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      };
      BN.prototype.toNumber = function toNumber() {
        var ret = this.words[0];
        if (this.length === 2) {
          ret += this.words[1] * 67108864;
        } else if (this.length === 3 && this.words[2] === 1) {
          ret += 4503599627370496 + this.words[1] * 67108864;
        } else if (this.length > 2) {
          assert(false, "Number can only safely store up to 53 bits");
        }
        return this.negative !== 0 ? -ret : ret;
      };
      BN.prototype.toJSON = function toJSON() {
        return this.toString(16);
      };
      BN.prototype.toBuffer = function toBuffer2(endian, length) {
        assert(typeof Buffer2 !== "undefined");
        return this.toArrayLike(Buffer2, endian, length);
      };
      BN.prototype.toArray = function toArray(endian, length) {
        return this.toArrayLike(Array, endian, length);
      };
      BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
        var byteLength2 = this.byteLength();
        var reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length");
        assert(reqLength > 0, "Requested array length <= 0");
        this.strip();
        var littleEndian = endian === "le";
        var res = new ArrayType(reqLength);
        var b2, i2;
        var q = this.clone();
        if (!littleEndian) {
          for (i2 = 0; i2 < reqLength - byteLength2; i2++) {
            res[i2] = 0;
          }
          for (i2 = 0; !q.isZero(); i2++) {
            b2 = q.andln(255);
            q.iushrn(8);
            res[reqLength - i2 - 1] = b2;
          }
        } else {
          for (i2 = 0; !q.isZero(); i2++) {
            b2 = q.andln(255);
            q.iushrn(8);
            res[i2] = b2;
          }
          for (; i2 < reqLength; i2++) {
            res[i2] = 0;
          }
        }
        return res;
      };
      if (Math.clz32) {
        BN.prototype._countBits = function _countBits(w) {
          return 32 - Math.clz32(w);
        };
      } else {
        BN.prototype._countBits = function _countBits(w) {
          var t2 = w;
          var r2 = 0;
          if (t2 >= 4096) {
            r2 += 13;
            t2 >>>= 13;
          }
          if (t2 >= 64) {
            r2 += 7;
            t2 >>>= 7;
          }
          if (t2 >= 8) {
            r2 += 4;
            t2 >>>= 4;
          }
          if (t2 >= 2) {
            r2 += 2;
            t2 >>>= 2;
          }
          return r2 + t2;
        };
      }
      BN.prototype._zeroBits = function _zeroBits(w) {
        if (w === 0) return 26;
        var t2 = w;
        var r2 = 0;
        if ((t2 & 8191) === 0) {
          r2 += 13;
          t2 >>>= 13;
        }
        if ((t2 & 127) === 0) {
          r2 += 7;
          t2 >>>= 7;
        }
        if ((t2 & 15) === 0) {
          r2 += 4;
          t2 >>>= 4;
        }
        if ((t2 & 3) === 0) {
          r2 += 2;
          t2 >>>= 2;
        }
        if ((t2 & 1) === 0) {
          r2++;
        }
        return r2;
      };
      BN.prototype.bitLength = function bitLength() {
        var w = this.words[this.length - 1];
        var hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = new Array(num.bitLength());
        for (var bit = 0; bit < w.length; bit++) {
          var off = bit / 26 | 0;
          var wbit = bit % 26;
          w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
        }
        return w;
      }
      BN.prototype.zeroBits = function zeroBits() {
        if (this.isZero()) return 0;
        var r2 = 0;
        for (var i2 = 0; i2 < this.length; i2++) {
          var b2 = this._zeroBits(this.words[i2]);
          r2 += b2;
          if (b2 !== 26) break;
        }
        return r2;
      };
      BN.prototype.byteLength = function byteLength2() {
        return Math.ceil(this.bitLength() / 8);
      };
      BN.prototype.toTwos = function toTwos(width) {
        if (this.negative !== 0) {
          return this.abs().inotn(width).iaddn(1);
        }
        return this.clone();
      };
      BN.prototype.fromTwos = function fromTwos(width) {
        if (this.testn(width - 1)) {
          return this.notn(width).iaddn(1).ineg();
        }
        return this.clone();
      };
      BN.prototype.isNeg = function isNeg() {
        return this.negative !== 0;
      };
      BN.prototype.neg = function neg() {
        return this.clone().ineg();
      };
      BN.prototype.ineg = function ineg() {
        if (!this.isZero()) {
          this.negative ^= 1;
        }
        return this;
      };
      BN.prototype.iuor = function iuor(num) {
        while (this.length < num.length) {
          this.words[this.length++] = 0;
        }
        for (var i2 = 0; i2 < num.length; i2++) {
          this.words[i2] = this.words[i2] | num.words[i2];
        }
        return this.strip();
      };
      BN.prototype.ior = function ior(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuor(num);
      };
      BN.prototype.or = function or2(num) {
        if (this.length > num.length) return this.clone().ior(num);
        return num.clone().ior(this);
      };
      BN.prototype.uor = function uor(num) {
        if (this.length > num.length) return this.clone().iuor(num);
        return num.clone().iuor(this);
      };
      BN.prototype.iuand = function iuand(num) {
        var b2;
        if (this.length > num.length) {
          b2 = num;
        } else {
          b2 = this;
        }
        for (var i2 = 0; i2 < b2.length; i2++) {
          this.words[i2] = this.words[i2] & num.words[i2];
        }
        this.length = b2.length;
        return this.strip();
      };
      BN.prototype.iand = function iand(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuand(num);
      };
      BN.prototype.and = function and2(num) {
        if (this.length > num.length) return this.clone().iand(num);
        return num.clone().iand(this);
      };
      BN.prototype.uand = function uand(num) {
        if (this.length > num.length) return this.clone().iuand(num);
        return num.clone().iuand(this);
      };
      BN.prototype.iuxor = function iuxor(num) {
        var a2;
        var b2;
        if (this.length > num.length) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        for (var i2 = 0; i2 < b2.length; i2++) {
          this.words[i2] = a2.words[i2] ^ b2.words[i2];
        }
        if (this !== a2) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        this.length = a2.length;
        return this.strip();
      };
      BN.prototype.ixor = function ixor(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuxor(num);
      };
      BN.prototype.xor = function xor2(num) {
        if (this.length > num.length) return this.clone().ixor(num);
        return num.clone().ixor(this);
      };
      BN.prototype.uxor = function uxor(num) {
        if (this.length > num.length) return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      };
      BN.prototype.inotn = function inotn(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0;
        var bitsLeft = width % 26;
        this._expand(bytesNeeded);
        if (bitsLeft > 0) {
          bytesNeeded--;
        }
        for (var i2 = 0; i2 < bytesNeeded; i2++) {
          this.words[i2] = ~this.words[i2] & 67108863;
        }
        if (bitsLeft > 0) {
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        }
        return this.strip();
      };
      BN.prototype.notn = function notn(width) {
        return this.clone().inotn(width);
      };
      BN.prototype.setn = function setn(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0;
        var wbit = bit % 26;
        this._expand(off + 1);
        if (val) {
          this.words[off] = this.words[off] | 1 << wbit;
        } else {
          this.words[off] = this.words[off] & ~(1 << wbit);
        }
        return this.strip();
      };
      BN.prototype.iadd = function iadd(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0) {
          this.negative = 0;
          r2 = this.isub(num);
          this.negative ^= 1;
          return this._normSign();
        } else if (this.negative === 0 && num.negative !== 0) {
          num.negative = 0;
          r2 = this.isub(num);
          num.negative = 1;
          return r2._normSign();
        }
        var a2, b2;
        if (this.length > num.length) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        var carry = 0;
        for (var i2 = 0; i2 < b2.length; i2++) {
          r2 = (a2.words[i2] | 0) + (b2.words[i2] | 0) + carry;
          this.words[i2] = r2 & 67108863;
          carry = r2 >>> 26;
        }
        for (; carry !== 0 && i2 < a2.length; i2++) {
          r2 = (a2.words[i2] | 0) + carry;
          this.words[i2] = r2 & 67108863;
          carry = r2 >>> 26;
        }
        this.length = a2.length;
        if (carry !== 0) {
          this.words[this.length] = carry;
          this.length++;
        } else if (a2 !== this) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        return this;
      };
      BN.prototype.add = function add2(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0) {
          num.negative = 0;
          res = this.sub(num);
          num.negative ^= 1;
          return res;
        } else if (num.negative === 0 && this.negative !== 0) {
          this.negative = 0;
          res = num.sub(this);
          this.negative = 1;
          return res;
        }
        if (this.length > num.length) return this.clone().iadd(num);
        return num.clone().iadd(this);
      };
      BN.prototype.isub = function isub(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          num.negative = 1;
          return r2._normSign();
        } else if (this.negative !== 0) {
          this.negative = 0;
          this.iadd(num);
          this.negative = 1;
          return this._normSign();
        }
        var cmp = this.cmp(num);
        if (cmp === 0) {
          this.negative = 0;
          this.length = 1;
          this.words[0] = 0;
          return this;
        }
        var a2, b2;
        if (cmp > 0) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        var carry = 0;
        for (var i2 = 0; i2 < b2.length; i2++) {
          r2 = (a2.words[i2] | 0) - (b2.words[i2] | 0) + carry;
          carry = r2 >> 26;
          this.words[i2] = r2 & 67108863;
        }
        for (; carry !== 0 && i2 < a2.length; i2++) {
          r2 = (a2.words[i2] | 0) + carry;
          carry = r2 >> 26;
          this.words[i2] = r2 & 67108863;
        }
        if (carry === 0 && i2 < a2.length && a2 !== this) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        this.length = Math.max(this.length, i2);
        if (a2 !== this) {
          this.negative = 1;
        }
        return this.strip();
      };
      BN.prototype.sub = function sub(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len = self2.length + num.length | 0;
        out.length = len;
        len = len - 1 | 0;
        var a2 = self2.words[0] | 0;
        var b2 = num.words[0] | 0;
        var r2 = a2 * b2;
        var lo = r2 & 67108863;
        var carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k2 = 1; k2 < len; k2++) {
          var ncarry = carry >>> 26;
          var rword = carry & 67108863;
          var maxJ = Math.min(k2, num.length - 1);
          for (var j = Math.max(0, k2 - self2.length + 1); j <= maxJ; j++) {
            var i2 = k2 - j | 0;
            a2 = self2.words[i2] | 0;
            b2 = num.words[j] | 0;
            r2 = a2 * b2 + rword;
            ncarry += r2 / 67108864 | 0;
            rword = r2 & 67108863;
          }
          out.words[k2] = rword | 0;
          carry = ncarry | 0;
        }
        if (carry !== 0) {
          out.words[k2] = carry | 0;
        } else {
          out.length--;
        }
        return out.strip();
      }
      var comb10MulTo = function comb10MulTo2(self2, num, out) {
        var a2 = self2.words;
        var b2 = num.words;
        var o2 = out.words;
        var c2 = 0;
        var lo;
        var mid;
        var hi;
        var a0 = a2[0] | 0;
        var al0 = a0 & 8191;
        var ah0 = a0 >>> 13;
        var a1 = a2[1] | 0;
        var al1 = a1 & 8191;
        var ah1 = a1 >>> 13;
        var a22 = a2[2] | 0;
        var al2 = a22 & 8191;
        var ah2 = a22 >>> 13;
        var a3 = a2[3] | 0;
        var al3 = a3 & 8191;
        var ah3 = a3 >>> 13;
        var a4 = a2[4] | 0;
        var al4 = a4 & 8191;
        var ah4 = a4 >>> 13;
        var a5 = a2[5] | 0;
        var al5 = a5 & 8191;
        var ah5 = a5 >>> 13;
        var a6 = a2[6] | 0;
        var al6 = a6 & 8191;
        var ah6 = a6 >>> 13;
        var a7 = a2[7] | 0;
        var al7 = a7 & 8191;
        var ah7 = a7 >>> 13;
        var a8 = a2[8] | 0;
        var al8 = a8 & 8191;
        var ah8 = a8 >>> 13;
        var a9 = a2[9] | 0;
        var al9 = a9 & 8191;
        var ah9 = a9 >>> 13;
        var b0 = b2[0] | 0;
        var bl0 = b0 & 8191;
        var bh0 = b0 >>> 13;
        var b1 = b2[1] | 0;
        var bl1 = b1 & 8191;
        var bh1 = b1 >>> 13;
        var b22 = b2[2] | 0;
        var bl2 = b22 & 8191;
        var bh2 = b22 >>> 13;
        var b3 = b2[3] | 0;
        var bl3 = b3 & 8191;
        var bh3 = b3 >>> 13;
        var b4 = b2[4] | 0;
        var bl4 = b4 & 8191;
        var bh4 = b4 >>> 13;
        var b5 = b2[5] | 0;
        var bl5 = b5 & 8191;
        var bh5 = b5 >>> 13;
        var b6 = b2[6] | 0;
        var bl6 = b6 & 8191;
        var bh6 = b6 >>> 13;
        var b7 = b2[7] | 0;
        var bl7 = b7 & 8191;
        var bh7 = b7 >>> 13;
        var b8 = b2[8] | 0;
        var bl8 = b8 & 8191;
        var bh8 = b8 >>> 13;
        var b9 = b2[9] | 0;
        var bl9 = b9 & 8191;
        var bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative;
        out.length = 19;
        lo = Math.imul(al0, bl0);
        mid = Math.imul(al0, bh0);
        mid = mid + Math.imul(ah0, bl0) | 0;
        hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
        w0 &= 67108863;
        lo = Math.imul(al1, bl0);
        mid = Math.imul(al1, bh0);
        mid = mid + Math.imul(ah1, bl0) | 0;
        hi = Math.imul(ah1, bh0);
        lo = lo + Math.imul(al0, bl1) | 0;
        mid = mid + Math.imul(al0, bh1) | 0;
        mid = mid + Math.imul(ah0, bl1) | 0;
        hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
        w1 &= 67108863;
        lo = Math.imul(al2, bl0);
        mid = Math.imul(al2, bh0);
        mid = mid + Math.imul(ah2, bl0) | 0;
        hi = Math.imul(ah2, bh0);
        lo = lo + Math.imul(al1, bl1) | 0;
        mid = mid + Math.imul(al1, bh1) | 0;
        mid = mid + Math.imul(ah1, bl1) | 0;
        hi = hi + Math.imul(ah1, bh1) | 0;
        lo = lo + Math.imul(al0, bl2) | 0;
        mid = mid + Math.imul(al0, bh2) | 0;
        mid = mid + Math.imul(ah0, bl2) | 0;
        hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
        w2 &= 67108863;
        lo = Math.imul(al3, bl0);
        mid = Math.imul(al3, bh0);
        mid = mid + Math.imul(ah3, bl0) | 0;
        hi = Math.imul(ah3, bh0);
        lo = lo + Math.imul(al2, bl1) | 0;
        mid = mid + Math.imul(al2, bh1) | 0;
        mid = mid + Math.imul(ah2, bl1) | 0;
        hi = hi + Math.imul(ah2, bh1) | 0;
        lo = lo + Math.imul(al1, bl2) | 0;
        mid = mid + Math.imul(al1, bh2) | 0;
        mid = mid + Math.imul(ah1, bl2) | 0;
        hi = hi + Math.imul(ah1, bh2) | 0;
        lo = lo + Math.imul(al0, bl3) | 0;
        mid = mid + Math.imul(al0, bh3) | 0;
        mid = mid + Math.imul(ah0, bl3) | 0;
        hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
        w3 &= 67108863;
        lo = Math.imul(al4, bl0);
        mid = Math.imul(al4, bh0);
        mid = mid + Math.imul(ah4, bl0) | 0;
        hi = Math.imul(ah4, bh0);
        lo = lo + Math.imul(al3, bl1) | 0;
        mid = mid + Math.imul(al3, bh1) | 0;
        mid = mid + Math.imul(ah3, bl1) | 0;
        hi = hi + Math.imul(ah3, bh1) | 0;
        lo = lo + Math.imul(al2, bl2) | 0;
        mid = mid + Math.imul(al2, bh2) | 0;
        mid = mid + Math.imul(ah2, bl2) | 0;
        hi = hi + Math.imul(ah2, bh2) | 0;
        lo = lo + Math.imul(al1, bl3) | 0;
        mid = mid + Math.imul(al1, bh3) | 0;
        mid = mid + Math.imul(ah1, bl3) | 0;
        hi = hi + Math.imul(ah1, bh3) | 0;
        lo = lo + Math.imul(al0, bl4) | 0;
        mid = mid + Math.imul(al0, bh4) | 0;
        mid = mid + Math.imul(ah0, bl4) | 0;
        hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
        w4 &= 67108863;
        lo = Math.imul(al5, bl0);
        mid = Math.imul(al5, bh0);
        mid = mid + Math.imul(ah5, bl0) | 0;
        hi = Math.imul(ah5, bh0);
        lo = lo + Math.imul(al4, bl1) | 0;
        mid = mid + Math.imul(al4, bh1) | 0;
        mid = mid + Math.imul(ah4, bl1) | 0;
        hi = hi + Math.imul(ah4, bh1) | 0;
        lo = lo + Math.imul(al3, bl2) | 0;
        mid = mid + Math.imul(al3, bh2) | 0;
        mid = mid + Math.imul(ah3, bl2) | 0;
        hi = hi + Math.imul(ah3, bh2) | 0;
        lo = lo + Math.imul(al2, bl3) | 0;
        mid = mid + Math.imul(al2, bh3) | 0;
        mid = mid + Math.imul(ah2, bl3) | 0;
        hi = hi + Math.imul(ah2, bh3) | 0;
        lo = lo + Math.imul(al1, bl4) | 0;
        mid = mid + Math.imul(al1, bh4) | 0;
        mid = mid + Math.imul(ah1, bl4) | 0;
        hi = hi + Math.imul(ah1, bh4) | 0;
        lo = lo + Math.imul(al0, bl5) | 0;
        mid = mid + Math.imul(al0, bh5) | 0;
        mid = mid + Math.imul(ah0, bl5) | 0;
        hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
        w5 &= 67108863;
        lo = Math.imul(al6, bl0);
        mid = Math.imul(al6, bh0);
        mid = mid + Math.imul(ah6, bl0) | 0;
        hi = Math.imul(ah6, bh0);
        lo = lo + Math.imul(al5, bl1) | 0;
        mid = mid + Math.imul(al5, bh1) | 0;
        mid = mid + Math.imul(ah5, bl1) | 0;
        hi = hi + Math.imul(ah5, bh1) | 0;
        lo = lo + Math.imul(al4, bl2) | 0;
        mid = mid + Math.imul(al4, bh2) | 0;
        mid = mid + Math.imul(ah4, bl2) | 0;
        hi = hi + Math.imul(ah4, bh2) | 0;
        lo = lo + Math.imul(al3, bl3) | 0;
        mid = mid + Math.imul(al3, bh3) | 0;
        mid = mid + Math.imul(ah3, bl3) | 0;
        hi = hi + Math.imul(ah3, bh3) | 0;
        lo = lo + Math.imul(al2, bl4) | 0;
        mid = mid + Math.imul(al2, bh4) | 0;
        mid = mid + Math.imul(ah2, bl4) | 0;
        hi = hi + Math.imul(ah2, bh4) | 0;
        lo = lo + Math.imul(al1, bl5) | 0;
        mid = mid + Math.imul(al1, bh5) | 0;
        mid = mid + Math.imul(ah1, bl5) | 0;
        hi = hi + Math.imul(ah1, bh5) | 0;
        lo = lo + Math.imul(al0, bl6) | 0;
        mid = mid + Math.imul(al0, bh6) | 0;
        mid = mid + Math.imul(ah0, bl6) | 0;
        hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
        w6 &= 67108863;
        lo = Math.imul(al7, bl0);
        mid = Math.imul(al7, bh0);
        mid = mid + Math.imul(ah7, bl0) | 0;
        hi = Math.imul(ah7, bh0);
        lo = lo + Math.imul(al6, bl1) | 0;
        mid = mid + Math.imul(al6, bh1) | 0;
        mid = mid + Math.imul(ah6, bl1) | 0;
        hi = hi + Math.imul(ah6, bh1) | 0;
        lo = lo + Math.imul(al5, bl2) | 0;
        mid = mid + Math.imul(al5, bh2) | 0;
        mid = mid + Math.imul(ah5, bl2) | 0;
        hi = hi + Math.imul(ah5, bh2) | 0;
        lo = lo + Math.imul(al4, bl3) | 0;
        mid = mid + Math.imul(al4, bh3) | 0;
        mid = mid + Math.imul(ah4, bl3) | 0;
        hi = hi + Math.imul(ah4, bh3) | 0;
        lo = lo + Math.imul(al3, bl4) | 0;
        mid = mid + Math.imul(al3, bh4) | 0;
        mid = mid + Math.imul(ah3, bl4) | 0;
        hi = hi + Math.imul(ah3, bh4) | 0;
        lo = lo + Math.imul(al2, bl5) | 0;
        mid = mid + Math.imul(al2, bh5) | 0;
        mid = mid + Math.imul(ah2, bl5) | 0;
        hi = hi + Math.imul(ah2, bh5) | 0;
        lo = lo + Math.imul(al1, bl6) | 0;
        mid = mid + Math.imul(al1, bh6) | 0;
        mid = mid + Math.imul(ah1, bl6) | 0;
        hi = hi + Math.imul(ah1, bh6) | 0;
        lo = lo + Math.imul(al0, bl7) | 0;
        mid = mid + Math.imul(al0, bh7) | 0;
        mid = mid + Math.imul(ah0, bl7) | 0;
        hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
        w7 &= 67108863;
        lo = Math.imul(al8, bl0);
        mid = Math.imul(al8, bh0);
        mid = mid + Math.imul(ah8, bl0) | 0;
        hi = Math.imul(ah8, bh0);
        lo = lo + Math.imul(al7, bl1) | 0;
        mid = mid + Math.imul(al7, bh1) | 0;
        mid = mid + Math.imul(ah7, bl1) | 0;
        hi = hi + Math.imul(ah7, bh1) | 0;
        lo = lo + Math.imul(al6, bl2) | 0;
        mid = mid + Math.imul(al6, bh2) | 0;
        mid = mid + Math.imul(ah6, bl2) | 0;
        hi = hi + Math.imul(ah6, bh2) | 0;
        lo = lo + Math.imul(al5, bl3) | 0;
        mid = mid + Math.imul(al5, bh3) | 0;
        mid = mid + Math.imul(ah5, bl3) | 0;
        hi = hi + Math.imul(ah5, bh3) | 0;
        lo = lo + Math.imul(al4, bl4) | 0;
        mid = mid + Math.imul(al4, bh4) | 0;
        mid = mid + Math.imul(ah4, bl4) | 0;
        hi = hi + Math.imul(ah4, bh4) | 0;
        lo = lo + Math.imul(al3, bl5) | 0;
        mid = mid + Math.imul(al3, bh5) | 0;
        mid = mid + Math.imul(ah3, bl5) | 0;
        hi = hi + Math.imul(ah3, bh5) | 0;
        lo = lo + Math.imul(al2, bl6) | 0;
        mid = mid + Math.imul(al2, bh6) | 0;
        mid = mid + Math.imul(ah2, bl6) | 0;
        hi = hi + Math.imul(ah2, bh6) | 0;
        lo = lo + Math.imul(al1, bl7) | 0;
        mid = mid + Math.imul(al1, bh7) | 0;
        mid = mid + Math.imul(ah1, bl7) | 0;
        hi = hi + Math.imul(ah1, bh7) | 0;
        lo = lo + Math.imul(al0, bl8) | 0;
        mid = mid + Math.imul(al0, bh8) | 0;
        mid = mid + Math.imul(ah0, bl8) | 0;
        hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
        w8 &= 67108863;
        lo = Math.imul(al9, bl0);
        mid = Math.imul(al9, bh0);
        mid = mid + Math.imul(ah9, bl0) | 0;
        hi = Math.imul(ah9, bh0);
        lo = lo + Math.imul(al8, bl1) | 0;
        mid = mid + Math.imul(al8, bh1) | 0;
        mid = mid + Math.imul(ah8, bl1) | 0;
        hi = hi + Math.imul(ah8, bh1) | 0;
        lo = lo + Math.imul(al7, bl2) | 0;
        mid = mid + Math.imul(al7, bh2) | 0;
        mid = mid + Math.imul(ah7, bl2) | 0;
        hi = hi + Math.imul(ah7, bh2) | 0;
        lo = lo + Math.imul(al6, bl3) | 0;
        mid = mid + Math.imul(al6, bh3) | 0;
        mid = mid + Math.imul(ah6, bl3) | 0;
        hi = hi + Math.imul(ah6, bh3) | 0;
        lo = lo + Math.imul(al5, bl4) | 0;
        mid = mid + Math.imul(al5, bh4) | 0;
        mid = mid + Math.imul(ah5, bl4) | 0;
        hi = hi + Math.imul(ah5, bh4) | 0;
        lo = lo + Math.imul(al4, bl5) | 0;
        mid = mid + Math.imul(al4, bh5) | 0;
        mid = mid + Math.imul(ah4, bl5) | 0;
        hi = hi + Math.imul(ah4, bh5) | 0;
        lo = lo + Math.imul(al3, bl6) | 0;
        mid = mid + Math.imul(al3, bh6) | 0;
        mid = mid + Math.imul(ah3, bl6) | 0;
        hi = hi + Math.imul(ah3, bh6) | 0;
        lo = lo + Math.imul(al2, bl7) | 0;
        mid = mid + Math.imul(al2, bh7) | 0;
        mid = mid + Math.imul(ah2, bl7) | 0;
        hi = hi + Math.imul(ah2, bh7) | 0;
        lo = lo + Math.imul(al1, bl8) | 0;
        mid = mid + Math.imul(al1, bh8) | 0;
        mid = mid + Math.imul(ah1, bl8) | 0;
        hi = hi + Math.imul(ah1, bh8) | 0;
        lo = lo + Math.imul(al0, bl9) | 0;
        mid = mid + Math.imul(al0, bh9) | 0;
        mid = mid + Math.imul(ah0, bl9) | 0;
        hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
        w9 &= 67108863;
        lo = Math.imul(al9, bl1);
        mid = Math.imul(al9, bh1);
        mid = mid + Math.imul(ah9, bl1) | 0;
        hi = Math.imul(ah9, bh1);
        lo = lo + Math.imul(al8, bl2) | 0;
        mid = mid + Math.imul(al8, bh2) | 0;
        mid = mid + Math.imul(ah8, bl2) | 0;
        hi = hi + Math.imul(ah8, bh2) | 0;
        lo = lo + Math.imul(al7, bl3) | 0;
        mid = mid + Math.imul(al7, bh3) | 0;
        mid = mid + Math.imul(ah7, bl3) | 0;
        hi = hi + Math.imul(ah7, bh3) | 0;
        lo = lo + Math.imul(al6, bl4) | 0;
        mid = mid + Math.imul(al6, bh4) | 0;
        mid = mid + Math.imul(ah6, bl4) | 0;
        hi = hi + Math.imul(ah6, bh4) | 0;
        lo = lo + Math.imul(al5, bl5) | 0;
        mid = mid + Math.imul(al5, bh5) | 0;
        mid = mid + Math.imul(ah5, bl5) | 0;
        hi = hi + Math.imul(ah5, bh5) | 0;
        lo = lo + Math.imul(al4, bl6) | 0;
        mid = mid + Math.imul(al4, bh6) | 0;
        mid = mid + Math.imul(ah4, bl6) | 0;
        hi = hi + Math.imul(ah4, bh6) | 0;
        lo = lo + Math.imul(al3, bl7) | 0;
        mid = mid + Math.imul(al3, bh7) | 0;
        mid = mid + Math.imul(ah3, bl7) | 0;
        hi = hi + Math.imul(ah3, bh7) | 0;
        lo = lo + Math.imul(al2, bl8) | 0;
        mid = mid + Math.imul(al2, bh8) | 0;
        mid = mid + Math.imul(ah2, bl8) | 0;
        hi = hi + Math.imul(ah2, bh8) | 0;
        lo = lo + Math.imul(al1, bl9) | 0;
        mid = mid + Math.imul(al1, bh9) | 0;
        mid = mid + Math.imul(ah1, bl9) | 0;
        hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
        w10 &= 67108863;
        lo = Math.imul(al9, bl2);
        mid = Math.imul(al9, bh2);
        mid = mid + Math.imul(ah9, bl2) | 0;
        hi = Math.imul(ah9, bh2);
        lo = lo + Math.imul(al8, bl3) | 0;
        mid = mid + Math.imul(al8, bh3) | 0;
        mid = mid + Math.imul(ah8, bl3) | 0;
        hi = hi + Math.imul(ah8, bh3) | 0;
        lo = lo + Math.imul(al7, bl4) | 0;
        mid = mid + Math.imul(al7, bh4) | 0;
        mid = mid + Math.imul(ah7, bl4) | 0;
        hi = hi + Math.imul(ah7, bh4) | 0;
        lo = lo + Math.imul(al6, bl5) | 0;
        mid = mid + Math.imul(al6, bh5) | 0;
        mid = mid + Math.imul(ah6, bl5) | 0;
        hi = hi + Math.imul(ah6, bh5) | 0;
        lo = lo + Math.imul(al5, bl6) | 0;
        mid = mid + Math.imul(al5, bh6) | 0;
        mid = mid + Math.imul(ah5, bl6) | 0;
        hi = hi + Math.imul(ah5, bh6) | 0;
        lo = lo + Math.imul(al4, bl7) | 0;
        mid = mid + Math.imul(al4, bh7) | 0;
        mid = mid + Math.imul(ah4, bl7) | 0;
        hi = hi + Math.imul(ah4, bh7) | 0;
        lo = lo + Math.imul(al3, bl8) | 0;
        mid = mid + Math.imul(al3, bh8) | 0;
        mid = mid + Math.imul(ah3, bl8) | 0;
        hi = hi + Math.imul(ah3, bh8) | 0;
        lo = lo + Math.imul(al2, bl9) | 0;
        mid = mid + Math.imul(al2, bh9) | 0;
        mid = mid + Math.imul(ah2, bl9) | 0;
        hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
        w11 &= 67108863;
        lo = Math.imul(al9, bl3);
        mid = Math.imul(al9, bh3);
        mid = mid + Math.imul(ah9, bl3) | 0;
        hi = Math.imul(ah9, bh3);
        lo = lo + Math.imul(al8, bl4) | 0;
        mid = mid + Math.imul(al8, bh4) | 0;
        mid = mid + Math.imul(ah8, bl4) | 0;
        hi = hi + Math.imul(ah8, bh4) | 0;
        lo = lo + Math.imul(al7, bl5) | 0;
        mid = mid + Math.imul(al7, bh5) | 0;
        mid = mid + Math.imul(ah7, bl5) | 0;
        hi = hi + Math.imul(ah7, bh5) | 0;
        lo = lo + Math.imul(al6, bl6) | 0;
        mid = mid + Math.imul(al6, bh6) | 0;
        mid = mid + Math.imul(ah6, bl6) | 0;
        hi = hi + Math.imul(ah6, bh6) | 0;
        lo = lo + Math.imul(al5, bl7) | 0;
        mid = mid + Math.imul(al5, bh7) | 0;
        mid = mid + Math.imul(ah5, bl7) | 0;
        hi = hi + Math.imul(ah5, bh7) | 0;
        lo = lo + Math.imul(al4, bl8) | 0;
        mid = mid + Math.imul(al4, bh8) | 0;
        mid = mid + Math.imul(ah4, bl8) | 0;
        hi = hi + Math.imul(ah4, bh8) | 0;
        lo = lo + Math.imul(al3, bl9) | 0;
        mid = mid + Math.imul(al3, bh9) | 0;
        mid = mid + Math.imul(ah3, bl9) | 0;
        hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
        w12 &= 67108863;
        lo = Math.imul(al9, bl4);
        mid = Math.imul(al9, bh4);
        mid = mid + Math.imul(ah9, bl4) | 0;
        hi = Math.imul(ah9, bh4);
        lo = lo + Math.imul(al8, bl5) | 0;
        mid = mid + Math.imul(al8, bh5) | 0;
        mid = mid + Math.imul(ah8, bl5) | 0;
        hi = hi + Math.imul(ah8, bh5) | 0;
        lo = lo + Math.imul(al7, bl6) | 0;
        mid = mid + Math.imul(al7, bh6) | 0;
        mid = mid + Math.imul(ah7, bl6) | 0;
        hi = hi + Math.imul(ah7, bh6) | 0;
        lo = lo + Math.imul(al6, bl7) | 0;
        mid = mid + Math.imul(al6, bh7) | 0;
        mid = mid + Math.imul(ah6, bl7) | 0;
        hi = hi + Math.imul(ah6, bh7) | 0;
        lo = lo + Math.imul(al5, bl8) | 0;
        mid = mid + Math.imul(al5, bh8) | 0;
        mid = mid + Math.imul(ah5, bl8) | 0;
        hi = hi + Math.imul(ah5, bh8) | 0;
        lo = lo + Math.imul(al4, bl9) | 0;
        mid = mid + Math.imul(al4, bh9) | 0;
        mid = mid + Math.imul(ah4, bl9) | 0;
        hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
        w13 &= 67108863;
        lo = Math.imul(al9, bl5);
        mid = Math.imul(al9, bh5);
        mid = mid + Math.imul(ah9, bl5) | 0;
        hi = Math.imul(ah9, bh5);
        lo = lo + Math.imul(al8, bl6) | 0;
        mid = mid + Math.imul(al8, bh6) | 0;
        mid = mid + Math.imul(ah8, bl6) | 0;
        hi = hi + Math.imul(ah8, bh6) | 0;
        lo = lo + Math.imul(al7, bl7) | 0;
        mid = mid + Math.imul(al7, bh7) | 0;
        mid = mid + Math.imul(ah7, bl7) | 0;
        hi = hi + Math.imul(ah7, bh7) | 0;
        lo = lo + Math.imul(al6, bl8) | 0;
        mid = mid + Math.imul(al6, bh8) | 0;
        mid = mid + Math.imul(ah6, bl8) | 0;
        hi = hi + Math.imul(ah6, bh8) | 0;
        lo = lo + Math.imul(al5, bl9) | 0;
        mid = mid + Math.imul(al5, bh9) | 0;
        mid = mid + Math.imul(ah5, bl9) | 0;
        hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
        w14 &= 67108863;
        lo = Math.imul(al9, bl6);
        mid = Math.imul(al9, bh6);
        mid = mid + Math.imul(ah9, bl6) | 0;
        hi = Math.imul(ah9, bh6);
        lo = lo + Math.imul(al8, bl7) | 0;
        mid = mid + Math.imul(al8, bh7) | 0;
        mid = mid + Math.imul(ah8, bl7) | 0;
        hi = hi + Math.imul(ah8, bh7) | 0;
        lo = lo + Math.imul(al7, bl8) | 0;
        mid = mid + Math.imul(al7, bh8) | 0;
        mid = mid + Math.imul(ah7, bl8) | 0;
        hi = hi + Math.imul(ah7, bh8) | 0;
        lo = lo + Math.imul(al6, bl9) | 0;
        mid = mid + Math.imul(al6, bh9) | 0;
        mid = mid + Math.imul(ah6, bl9) | 0;
        hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
        w15 &= 67108863;
        lo = Math.imul(al9, bl7);
        mid = Math.imul(al9, bh7);
        mid = mid + Math.imul(ah9, bl7) | 0;
        hi = Math.imul(ah9, bh7);
        lo = lo + Math.imul(al8, bl8) | 0;
        mid = mid + Math.imul(al8, bh8) | 0;
        mid = mid + Math.imul(ah8, bl8) | 0;
        hi = hi + Math.imul(ah8, bh8) | 0;
        lo = lo + Math.imul(al7, bl9) | 0;
        mid = mid + Math.imul(al7, bh9) | 0;
        mid = mid + Math.imul(ah7, bl9) | 0;
        hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
        w16 &= 67108863;
        lo = Math.imul(al9, bl8);
        mid = Math.imul(al9, bh8);
        mid = mid + Math.imul(ah9, bl8) | 0;
        hi = Math.imul(ah9, bh8);
        lo = lo + Math.imul(al8, bl9) | 0;
        mid = mid + Math.imul(al8, bh9) | 0;
        mid = mid + Math.imul(ah8, bl9) | 0;
        hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
        w17 &= 67108863;
        lo = Math.imul(al9, bl9);
        mid = Math.imul(al9, bh9);
        mid = mid + Math.imul(ah9, bl9) | 0;
        hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
        w18 &= 67108863;
        o2[0] = w0;
        o2[1] = w1;
        o2[2] = w2;
        o2[3] = w3;
        o2[4] = w4;
        o2[5] = w5;
        o2[6] = w6;
        o2[7] = w7;
        o2[8] = w8;
        o2[9] = w9;
        o2[10] = w10;
        o2[11] = w11;
        o2[12] = w12;
        o2[13] = w13;
        o2[14] = w14;
        o2[15] = w15;
        o2[16] = w16;
        o2[17] = w17;
        o2[18] = w18;
        if (c2 !== 0) {
          o2[19] = c2;
          out.length++;
        }
        return out;
      };
      if (!Math.imul) {
        comb10MulTo = smallMulTo;
      }
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        out.length = self2.length + num.length;
        var carry = 0;
        var hncarry = 0;
        for (var k2 = 0; k2 < out.length - 1; k2++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863;
          var maxJ = Math.min(k2, num.length - 1);
          for (var j = Math.max(0, k2 - self2.length + 1); j <= maxJ; j++) {
            var i2 = k2 - j;
            var a2 = self2.words[i2] | 0;
            var b2 = num.words[j] | 0;
            var r2 = a2 * b2;
            var lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0;
            lo = lo + rword | 0;
            rword = lo & 67108863;
            ncarry = ncarry + (lo >>> 26) | 0;
            hncarry += ncarry >>> 26;
            ncarry &= 67108863;
          }
          out.words[k2] = rword;
          carry = ncarry;
          ncarry = hncarry;
        }
        if (carry !== 0) {
          out.words[k2] = carry;
        } else {
          out.length--;
        }
        return out.strip();
      }
      function jumboMulTo(self2, num, out) {
        var fftm = new FFTM();
        return fftm.mulp(self2, num, out);
      }
      BN.prototype.mulTo = function mulTo(num, out) {
        var res;
        var len = this.length + num.length;
        if (this.length === 10 && num.length === 10) {
          res = comb10MulTo(this, num, out);
        } else if (len < 63) {
          res = smallMulTo(this, num, out);
        } else if (len < 1024) {
          res = bigMulTo(this, num, out);
        } else {
          res = jumboMulTo(this, num, out);
        }
        return res;
      };
      function FFTM(x2, y2) {
        this.x = x2;
        this.y = y2;
      }
      FFTM.prototype.makeRBT = function makeRBT(N2) {
        var t2 = new Array(N2);
        var l2 = BN.prototype._countBits(N2) - 1;
        for (var i2 = 0; i2 < N2; i2++) {
          t2[i2] = this.revBin(i2, l2, N2);
        }
        return t2;
      };
      FFTM.prototype.revBin = function revBin(x2, l2, N2) {
        if (x2 === 0 || x2 === N2 - 1) return x2;
        var rb = 0;
        for (var i2 = 0; i2 < l2; i2++) {
          rb |= (x2 & 1) << l2 - i2 - 1;
          x2 >>= 1;
        }
        return rb;
      };
      FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N2) {
        for (var i2 = 0; i2 < N2; i2++) {
          rtws[i2] = rws[rbt[i2]];
          itws[i2] = iws[rbt[i2]];
        }
      };
      FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N2, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N2);
        for (var s2 = 1; s2 < N2; s2 <<= 1) {
          var l2 = s2 << 1;
          var rtwdf = Math.cos(2 * Math.PI / l2);
          var itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0; p2 < N2; p2 += l2) {
            var rtwdf_ = rtwdf;
            var itwdf_ = itwdf;
            for (var j = 0; j < s2; j++) {
              var re = rtws[p2 + j];
              var ie = itws[p2 + j];
              var ro = rtws[p2 + j + s2];
              var io = itws[p2 + j + s2];
              var rx = rtwdf_ * ro - itwdf_ * io;
              io = rtwdf_ * io + itwdf_ * ro;
              ro = rx;
              rtws[p2 + j] = re + ro;
              itws[p2 + j] = ie + io;
              rtws[p2 + j + s2] = re - ro;
              itws[p2 + j + s2] = ie - io;
              if (j !== l2) {
                rx = rtwdf * rtwdf_ - itwdf * itwdf_;
                itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
                rtwdf_ = rx;
              }
            }
          }
        }
      };
      FFTM.prototype.guessLen13b = function guessLen13b(n2, m) {
        var N2 = Math.max(m, n2) | 1;
        var odd = N2 & 1;
        var i2 = 0;
        for (N2 = N2 / 2 | 0; N2; N2 = N2 >>> 1) {
          i2++;
        }
        return 1 << i2 + 1 + odd;
      };
      FFTM.prototype.conjugate = function conjugate(rws, iws, N2) {
        if (N2 <= 1) return;
        for (var i2 = 0; i2 < N2 / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N2 - i2 - 1];
          rws[N2 - i2 - 1] = t2;
          t2 = iws[i2];
          iws[i2] = -iws[N2 - i2 - 1];
          iws[N2 - i2 - 1] = -t2;
        }
      };
      FFTM.prototype.normalize13b = function normalize13b(ws, N2) {
        var carry = 0;
        for (var i2 = 0; i2 < N2 / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N2) * 8192 + Math.round(ws[2 * i2] / N2) + carry;
          ws[i2] = w & 67108863;
          if (w < 67108864) {
            carry = 0;
          } else {
            carry = w / 67108864 | 0;
          }
        }
        return ws;
      };
      FFTM.prototype.convert13b = function convert13b(ws, len, rws, N2) {
        var carry = 0;
        for (var i2 = 0; i2 < len; i2++) {
          carry = carry + (ws[i2] | 0);
          rws[2 * i2] = carry & 8191;
          carry = carry >>> 13;
          rws[2 * i2 + 1] = carry & 8191;
          carry = carry >>> 13;
        }
        for (i2 = 2 * len; i2 < N2; ++i2) {
          rws[i2] = 0;
        }
        assert(carry === 0);
        assert((carry & -8192) === 0);
      };
      FFTM.prototype.stub = function stub(N2) {
        var ph = new Array(N2);
        for (var i2 = 0; i2 < N2; i2++) {
          ph[i2] = 0;
        }
        return ph;
      };
      FFTM.prototype.mulp = function mulp(x2, y2, out) {
        var N2 = 2 * this.guessLen13b(x2.length, y2.length);
        var rbt = this.makeRBT(N2);
        var _2 = this.stub(N2);
        var rws = new Array(N2);
        var rwst = new Array(N2);
        var iwst = new Array(N2);
        var nrws = new Array(N2);
        var nrwst = new Array(N2);
        var niwst = new Array(N2);
        var rmws = out.words;
        rmws.length = N2;
        this.convert13b(x2.words, x2.length, rws, N2);
        this.convert13b(y2.words, y2.length, nrws, N2);
        this.transform(rws, _2, rwst, iwst, N2, rbt);
        this.transform(nrws, _2, nrwst, niwst, N2, rbt);
        for (var i2 = 0; i2 < N2; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2];
          rwst[i2] = rx;
        }
        this.conjugate(rwst, iwst, N2);
        this.transform(rwst, iwst, rmws, _2, N2, rbt);
        this.conjugate(rmws, _2, N2);
        this.normalize13b(rmws, N2);
        out.negative = x2.negative ^ y2.negative;
        out.length = x2.length + y2.length;
        return out.strip();
      };
      BN.prototype.mul = function mul(num) {
        var out = new BN(null);
        out.words = new Array(this.length + num.length);
        return this.mulTo(num, out);
      };
      BN.prototype.mulf = function mulf(num) {
        var out = new BN(null);
        out.words = new Array(this.length + num.length);
        return jumboMulTo(this, num, out);
      };
      BN.prototype.imul = function imul(num) {
        return this.clone().mulTo(num, this);
      };
      BN.prototype.imuln = function imuln(num) {
        assert(typeof num === "number");
        assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0; i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num;
          var lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26;
          carry += w / 67108864 | 0;
          carry += lo >>> 26;
          this.words[i2] = lo & 67108863;
        }
        if (carry !== 0) {
          this.words[i2] = carry;
          this.length++;
        }
        this.length = num === 0 ? 1 : this.length;
        return this;
      };
      BN.prototype.muln = function muln(num) {
        return this.clone().imuln(num);
      };
      BN.prototype.sqr = function sqr() {
        return this.mul(this);
      };
      BN.prototype.isqr = function isqr() {
        return this.imul(this.clone());
      };
      BN.prototype.pow = function pow2(num) {
        var w = toBitArray(num);
        if (w.length === 0) return new BN(1);
        var res = this;
        for (var i2 = 0; i2 < w.length; i2++, res = res.sqr()) {
          if (w[i2] !== 0) break;
        }
        if (++i2 < w.length) {
          for (var q = res.sqr(); i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0) continue;
            res = res.mul(q);
          }
        }
        return res;
      };
      BN.prototype.iushln = function iushln(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26;
        var s2 = (bits - r2) / 26;
        var carryMask = 67108863 >>> 26 - r2 << 26 - r2;
        var i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0; i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask;
            var c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry;
            carry = newCarry >>> 26 - r2;
          }
          if (carry) {
            this.words[i2] = carry;
            this.length++;
          }
        }
        if (s2 !== 0) {
          for (i2 = this.length - 1; i2 >= 0; i2--) {
            this.words[i2 + s2] = this.words[i2];
          }
          for (i2 = 0; i2 < s2; i2++) {
            this.words[i2] = 0;
          }
          this.length += s2;
        }
        return this.strip();
      };
      BN.prototype.ishln = function ishln(bits) {
        assert(this.negative === 0);
        return this.iushln(bits);
      };
      BN.prototype.iushrn = function iushrn(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h2;
        if (hint) {
          h2 = (hint - hint % 26) / 26;
        } else {
          h2 = 0;
        }
        var r2 = bits % 26;
        var s2 = Math.min((bits - r2) / 26, this.length);
        var mask = 67108863 ^ 67108863 >>> r2 << r2;
        var maskedWords = extended;
        h2 -= s2;
        h2 = Math.max(0, h2);
        if (maskedWords) {
          for (var i2 = 0; i2 < s2; i2++) {
            maskedWords.words[i2] = this.words[i2];
          }
          maskedWords.length = s2;
        }
        if (s2 === 0) ;
        else if (this.length > s2) {
          this.length -= s2;
          for (i2 = 0; i2 < this.length; i2++) {
            this.words[i2] = this.words[i2 + s2];
          }
        } else {
          this.words[0] = 0;
          this.length = 1;
        }
        var carry = 0;
        for (i2 = this.length - 1; i2 >= 0 && (carry !== 0 || i2 >= h2); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2;
          carry = word & mask;
        }
        if (maskedWords && carry !== 0) {
          maskedWords.words[maskedWords.length++] = carry;
        }
        if (this.length === 0) {
          this.words[0] = 0;
          this.length = 1;
        }
        return this.strip();
      };
      BN.prototype.ishrn = function ishrn(bits, hint, extended) {
        assert(this.negative === 0);
        return this.iushrn(bits, hint, extended);
      };
      BN.prototype.shln = function shln(bits) {
        return this.clone().ishln(bits);
      };
      BN.prototype.ushln = function ushln(bits) {
        return this.clone().iushln(bits);
      };
      BN.prototype.shrn = function shrn(bits) {
        return this.clone().ishrn(bits);
      };
      BN.prototype.ushrn = function ushrn(bits) {
        return this.clone().iushrn(bits);
      };
      BN.prototype.testn = function testn(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26;
        var s2 = (bit - r2) / 26;
        var q = 1 << r2;
        if (this.length <= s2) return false;
        var w = this.words[s2];
        return !!(w & q);
      };
      BN.prototype.imaskn = function imaskn(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26;
        var s2 = (bits - r2) / 26;
        assert(this.negative === 0, "imaskn works only with positive numbers");
        if (this.length <= s2) {
          return this;
        }
        if (r2 !== 0) {
          s2++;
        }
        this.length = Math.min(s2, this.length);
        if (r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this.strip();
      };
      BN.prototype.maskn = function maskn(bits) {
        return this.clone().imaskn(bits);
      };
      BN.prototype.iaddn = function iaddn(num) {
        assert(typeof num === "number");
        assert(num < 67108864);
        if (num < 0) return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) < num) {
            this.words[0] = num - (this.words[0] | 0);
            this.negative = 0;
            return this;
          }
          this.negative = 0;
          this.isubn(num);
          this.negative = 1;
          return this;
        }
        return this._iaddn(num);
      };
      BN.prototype._iaddn = function _iaddn(num) {
        this.words[0] += num;
        for (var i2 = 0; i2 < this.length && this.words[i2] >= 67108864; i2++) {
          this.words[i2] -= 67108864;
          if (i2 === this.length - 1) {
            this.words[i2 + 1] = 1;
          } else {
            this.words[i2 + 1]++;
          }
        }
        this.length = Math.max(this.length, i2 + 1);
        return this;
      };
      BN.prototype.isubn = function isubn(num) {
        assert(typeof num === "number");
        assert(num < 67108864);
        if (num < 0) return this.iaddn(-num);
        if (this.negative !== 0) {
          this.negative = 0;
          this.iaddn(num);
          this.negative = 1;
          return this;
        }
        this.words[0] -= num;
        if (this.length === 1 && this.words[0] < 0) {
          this.words[0] = -this.words[0];
          this.negative = 1;
        } else {
          for (var i2 = 0; i2 < this.length && this.words[i2] < 0; i2++) {
            this.words[i2] += 67108864;
            this.words[i2 + 1] -= 1;
          }
        }
        return this.strip();
      };
      BN.prototype.addn = function addn(num) {
        return this.clone().iaddn(num);
      };
      BN.prototype.subn = function subn(num) {
        return this.clone().isubn(num);
      };
      BN.prototype.iabs = function iabs() {
        this.negative = 0;
        return this;
      };
      BN.prototype.abs = function abs2() {
        return this.clone().iabs();
      };
      BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
        var len = num.length + shift;
        var i2;
        this._expand(len);
        var w;
        var carry = 0;
        for (i2 = 0; i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863;
          carry = (w >> 26) - (right / 67108864 | 0);
          this.words[i2 + shift] = w & 67108863;
        }
        for (; i2 < this.length - shift; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          carry = w >> 26;
          this.words[i2 + shift] = w & 67108863;
        }
        if (carry === 0) return this.strip();
        assert(carry === -1);
        carry = 0;
        for (i2 = 0; i2 < this.length; i2++) {
          w = -(this.words[i2] | 0) + carry;
          carry = w >> 26;
          this.words[i2] = w & 67108863;
        }
        this.negative = 1;
        return this.strip();
      };
      BN.prototype._wordDiv = function _wordDiv(num, mode) {
        var shift = this.length - num.length;
        var a2 = this.clone();
        var b2 = num;
        var bhi = b2.words[b2.length - 1] | 0;
        var bhiBits = this._countBits(bhi);
        shift = 26 - bhiBits;
        if (shift !== 0) {
          b2 = b2.ushln(shift);
          a2.iushln(shift);
          bhi = b2.words[b2.length - 1] | 0;
        }
        var m = a2.length - b2.length;
        var q;
        if (mode !== "mod") {
          q = new BN(null);
          q.length = m + 1;
          q.words = new Array(q.length);
          for (var i2 = 0; i2 < q.length; i2++) {
            q.words[i2] = 0;
          }
        }
        var diff = a2.clone()._ishlnsubmul(b2, 1, m);
        if (diff.negative === 0) {
          a2 = diff;
          if (q) {
            q.words[m] = 1;
          }
        }
        for (var j = m - 1; j >= 0; j--) {
          var qj = (a2.words[b2.length + j] | 0) * 67108864 + (a2.words[b2.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863);
          a2._ishlnsubmul(b2, qj, j);
          while (a2.negative !== 0) {
            qj--;
            a2.negative = 0;
            a2._ishlnsubmul(b2, 1, j);
            if (!a2.isZero()) {
              a2.negative ^= 1;
            }
          }
          if (q) {
            q.words[j] = qj;
          }
        }
        if (q) {
          q.strip();
        }
        a2.strip();
        if (mode !== "div" && shift !== 0) {
          a2.iushrn(shift);
        }
        return {
          div: q || null,
          mod: a2
        };
      };
      BN.prototype.divmod = function divmod(num, mode, positive) {
        assert(!num.isZero());
        if (this.isZero()) {
          return {
            div: new BN(0),
            mod: new BN(0)
          };
        }
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          res = this.neg().divmod(num, mode);
          if (mode !== "mod") {
            div = res.div.neg();
          }
          if (mode !== "div") {
            mod = res.mod.neg();
            if (positive && mod.negative !== 0) {
              mod.iadd(num);
            }
          }
          return {
            div,
            mod
          };
        }
        if (this.negative === 0 && num.negative !== 0) {
          res = this.divmod(num.neg(), mode);
          if (mode !== "mod") {
            div = res.div.neg();
          }
          return {
            div,
            mod: res.mod
          };
        }
        if ((this.negative & num.negative) !== 0) {
          res = this.neg().divmod(num.neg(), mode);
          if (mode !== "div") {
            mod = res.mod.neg();
            if (positive && mod.negative !== 0) {
              mod.isub(num);
            }
          }
          return {
            div: res.div,
            mod
          };
        }
        if (num.length > this.length || this.cmp(num) < 0) {
          return {
            div: new BN(0),
            mod: this
          };
        }
        if (num.length === 1) {
          if (mode === "div") {
            return {
              div: this.divn(num.words[0]),
              mod: null
            };
          }
          if (mode === "mod") {
            return {
              div: null,
              mod: new BN(this.modn(num.words[0]))
            };
          }
          return {
            div: this.divn(num.words[0]),
            mod: new BN(this.modn(num.words[0]))
          };
        }
        return this._wordDiv(num, mode);
      };
      BN.prototype.div = function div(num) {
        return this.divmod(num, "div", false).div;
      };
      BN.prototype.mod = function mod(num) {
        return this.divmod(num, "mod", false).mod;
      };
      BN.prototype.umod = function umod(num) {
        return this.divmod(num, "mod", true).mod;
      };
      BN.prototype.divRound = function divRound(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero()) return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
        var half = num.ushrn(1);
        var r2 = num.andln(1);
        var cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      };
      BN.prototype.modn = function modn(num) {
        assert(num <= 67108863);
        var p2 = (1 << 26) % num;
        var acc = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        }
        return acc;
      };
      BN.prototype.idivn = function idivn(num) {
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0;
          carry = w % num;
        }
        return this.strip();
      };
      BN.prototype.divn = function divn(num) {
        return this.clone().idivn(num);
      };
      BN.prototype.egcd = function egcd(p2) {
        assert(p2.negative === 0);
        assert(!p2.isZero());
        var x2 = this;
        var y2 = p2.clone();
        if (x2.negative !== 0) {
          x2 = x2.umod(p2);
        } else {
          x2 = x2.clone();
        }
        var A2 = new BN(1);
        var B2 = new BN(0);
        var C2 = new BN(0);
        var D = new BN(1);
        var g = 0;
        while (x2.isEven() && y2.isEven()) {
          x2.iushrn(1);
          y2.iushrn(1);
          ++g;
        }
        var yp = y2.clone();
        var xp = x2.clone();
        while (!x2.isZero()) {
          for (var i2 = 0, im = 1; (x2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1) ;
          if (i2 > 0) {
            x2.iushrn(i2);
            while (i2-- > 0) {
              if (A2.isOdd() || B2.isOdd()) {
                A2.iadd(yp);
                B2.isub(xp);
              }
              A2.iushrn(1);
              B2.iushrn(1);
            }
          }
          for (var j = 0, jm = 1; (y2.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
          if (j > 0) {
            y2.iushrn(j);
            while (j-- > 0) {
              if (C2.isOdd() || D.isOdd()) {
                C2.iadd(yp);
                D.isub(xp);
              }
              C2.iushrn(1);
              D.iushrn(1);
            }
          }
          if (x2.cmp(y2) >= 0) {
            x2.isub(y2);
            A2.isub(C2);
            B2.isub(D);
          } else {
            y2.isub(x2);
            C2.isub(A2);
            D.isub(B2);
          }
        }
        return {
          a: C2,
          b: D,
          gcd: y2.iushln(g)
        };
      };
      BN.prototype._invmp = function _invmp(p2) {
        assert(p2.negative === 0);
        assert(!p2.isZero());
        var a2 = this;
        var b2 = p2.clone();
        if (a2.negative !== 0) {
          a2 = a2.umod(p2);
        } else {
          a2 = a2.clone();
        }
        var x1 = new BN(1);
        var x2 = new BN(0);
        var delta = b2.clone();
        while (a2.cmpn(1) > 0 && b2.cmpn(1) > 0) {
          for (var i2 = 0, im = 1; (a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1) ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd()) {
                x1.iadd(delta);
              }
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1; (b2.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
          if (j > 0) {
            b2.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd()) {
                x2.iadd(delta);
              }
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b2) >= 0) {
            a2.isub(b2);
            x1.isub(x2);
          } else {
            b2.isub(a2);
            x2.isub(x1);
          }
        }
        var res;
        if (a2.cmpn(1) === 0) {
          res = x1;
        } else {
          res = x2;
        }
        if (res.cmpn(0) < 0) {
          res.iadd(p2);
        }
        return res;
      };
      BN.prototype.gcd = function gcd(num) {
        if (this.isZero()) return num.abs();
        if (num.isZero()) return this.abs();
        var a2 = this.clone();
        var b2 = num.clone();
        a2.negative = 0;
        b2.negative = 0;
        for (var shift = 0; a2.isEven() && b2.isEven(); shift++) {
          a2.iushrn(1);
          b2.iushrn(1);
        }
        do {
          while (a2.isEven()) {
            a2.iushrn(1);
          }
          while (b2.isEven()) {
            b2.iushrn(1);
          }
          var r2 = a2.cmp(b2);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b2;
            b2 = t2;
          } else if (r2 === 0 || b2.cmpn(1) === 0) {
            break;
          }
          a2.isub(b2);
        } while (true);
        return b2.iushln(shift);
      };
      BN.prototype.invm = function invm(num) {
        return this.egcd(num).a.umod(num);
      };
      BN.prototype.isEven = function isEven() {
        return (this.words[0] & 1) === 0;
      };
      BN.prototype.isOdd = function isOdd() {
        return (this.words[0] & 1) === 1;
      };
      BN.prototype.andln = function andln(num) {
        return this.words[0] & num;
      };
      BN.prototype.bincn = function bincn(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26;
        var s2 = (bit - r2) / 26;
        var q = 1 << r2;
        if (this.length <= s2) {
          this._expand(s2 + 1);
          this.words[s2] |= q;
          return this;
        }
        var carry = q;
        for (var i2 = s2; carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry;
          carry = w >>> 26;
          w &= 67108863;
          this.words[i2] = w;
        }
        if (carry !== 0) {
          this.words[i2] = carry;
          this.length++;
        }
        return this;
      };
      BN.prototype.isZero = function isZero() {
        return this.length === 1 && this.words[0] === 0;
      };
      BN.prototype.cmpn = function cmpn(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative) return -1;
        if (this.negative === 0 && negative) return 1;
        this.strip();
        var res;
        if (this.length > 1) {
          res = 1;
        } else {
          if (negative) {
            num = -num;
          }
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0) return -res | 0;
        return res;
      };
      BN.prototype.cmp = function cmp(num) {
        if (this.negative !== 0 && num.negative === 0) return -1;
        if (this.negative === 0 && num.negative !== 0) return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0) return -res | 0;
        return res;
      };
      BN.prototype.ucmp = function ucmp(num) {
        if (this.length > num.length) return 1;
        if (this.length < num.length) return -1;
        var res = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0;
          var b2 = num.words[i2] | 0;
          if (a2 === b2) continue;
          if (a2 < b2) {
            res = -1;
          } else if (a2 > b2) {
            res = 1;
          }
          break;
        }
        return res;
      };
      BN.prototype.gtn = function gtn(num) {
        return this.cmpn(num) === 1;
      };
      BN.prototype.gt = function gt(num) {
        return this.cmp(num) === 1;
      };
      BN.prototype.gten = function gten(num) {
        return this.cmpn(num) >= 0;
      };
      BN.prototype.gte = function gte(num) {
        return this.cmp(num) >= 0;
      };
      BN.prototype.ltn = function ltn(num) {
        return this.cmpn(num) === -1;
      };
      BN.prototype.lt = function lt(num) {
        return this.cmp(num) === -1;
      };
      BN.prototype.lten = function lten(num) {
        return this.cmpn(num) <= 0;
      };
      BN.prototype.lte = function lte(num) {
        return this.cmp(num) <= 0;
      };
      BN.prototype.eqn = function eqn(num) {
        return this.cmpn(num) === 0;
      };
      BN.prototype.eq = function eq(num) {
        return this.cmp(num) === 0;
      };
      BN.red = function red(num) {
        return new Red(num);
      };
      BN.prototype.toRed = function toRed(ctx) {
        assert(!this.red, "Already a number in reduction context");
        assert(this.negative === 0, "red works only with positives");
        return ctx.convertTo(this)._forceRed(ctx);
      };
      BN.prototype.fromRed = function fromRed() {
        assert(this.red, "fromRed works only with numbers in reduction context");
        return this.red.convertFrom(this);
      };
      BN.prototype._forceRed = function _forceRed(ctx) {
        this.red = ctx;
        return this;
      };
      BN.prototype.forceRed = function forceRed(ctx) {
        assert(!this.red, "Already a number in reduction context");
        return this._forceRed(ctx);
      };
      BN.prototype.redAdd = function redAdd(num) {
        assert(this.red, "redAdd works only with red numbers");
        return this.red.add(this, num);
      };
      BN.prototype.redIAdd = function redIAdd(num) {
        assert(this.red, "redIAdd works only with red numbers");
        return this.red.iadd(this, num);
      };
      BN.prototype.redSub = function redSub(num) {
        assert(this.red, "redSub works only with red numbers");
        return this.red.sub(this, num);
      };
      BN.prototype.redISub = function redISub(num) {
        assert(this.red, "redISub works only with red numbers");
        return this.red.isub(this, num);
      };
      BN.prototype.redShl = function redShl(num) {
        assert(this.red, "redShl works only with red numbers");
        return this.red.shl(this, num);
      };
      BN.prototype.redMul = function redMul(num) {
        assert(this.red, "redMul works only with red numbers");
        this.red._verify2(this, num);
        return this.red.mul(this, num);
      };
      BN.prototype.redIMul = function redIMul(num) {
        assert(this.red, "redMul works only with red numbers");
        this.red._verify2(this, num);
        return this.red.imul(this, num);
      };
      BN.prototype.redSqr = function redSqr() {
        assert(this.red, "redSqr works only with red numbers");
        this.red._verify1(this);
        return this.red.sqr(this);
      };
      BN.prototype.redISqr = function redISqr() {
        assert(this.red, "redISqr works only with red numbers");
        this.red._verify1(this);
        return this.red.isqr(this);
      };
      BN.prototype.redSqrt = function redSqrt() {
        assert(this.red, "redSqrt works only with red numbers");
        this.red._verify1(this);
        return this.red.sqrt(this);
      };
      BN.prototype.redInvm = function redInvm() {
        assert(this.red, "redInvm works only with red numbers");
        this.red._verify1(this);
        return this.red.invm(this);
      };
      BN.prototype.redNeg = function redNeg() {
        assert(this.red, "redNeg works only with red numbers");
        this.red._verify1(this);
        return this.red.neg(this);
      };
      BN.prototype.redPow = function redPow(num) {
        assert(this.red && !num.red, "redPow(normalNum)");
        this.red._verify1(this);
        return this.red.pow(this, num);
      };
      var primes = {
        k256: null,
        p224: null,
        p192: null,
        p25519: null
      };
      function MPrime(name, p2) {
        this.name = name;
        this.p = new BN(p2, 16);
        this.n = this.p.bitLength();
        this.k = new BN(1).iushln(this.n).isub(this.p);
        this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function _tmp() {
        var tmp = new BN(null);
        tmp.words = new Array(Math.ceil(this.n / 13));
        return tmp;
      };
      MPrime.prototype.ireduce = function ireduce(num) {
        var r2 = num;
        var rlen;
        do {
          this.split(r2, this.tmp);
          r2 = this.imulK(r2);
          r2 = r2.iadd(this.tmp);
          rlen = r2.bitLength();
        } while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0) {
          r2.words[0] = 0;
          r2.length = 1;
        } else if (cmp > 0) {
          r2.isub(this.p);
        } else {
          if (r2.strip !== void 0) {
            r2.strip();
          } else {
            r2._strip();
          }
        }
        return r2;
      };
      MPrime.prototype.split = function split(input, out) {
        input.iushrn(this.n, 0, out);
      };
      MPrime.prototype.imulK = function imulK(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(
          this,
          "k256",
          "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"
        );
      }
      inherits(K256, MPrime);
      K256.prototype.split = function split(input, output) {
        var mask = 4194303;
        var outLen = Math.min(input.length, 9);
        for (var i2 = 0; i2 < outLen; i2++) {
          output.words[i2] = input.words[i2];
        }
        output.length = outLen;
        if (input.length <= 9) {
          input.words[0] = 0;
          input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10; i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22;
          prev = next;
        }
        prev >>>= 22;
        input.words[i2 - 10] = prev;
        if (prev === 0 && input.length > 10) {
          input.length -= 10;
        } else {
          input.length -= 9;
        }
      };
      K256.prototype.imulK = function imulK(num) {
        num.words[num.length] = 0;
        num.words[num.length + 1] = 0;
        num.length += 2;
        var lo = 0;
        for (var i2 = 0; i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977;
          num.words[i2] = lo & 67108863;
          lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          num.length--;
          if (num.words[num.length - 1] === 0) {
            num.length--;
          }
        }
        return num;
      };
      function P224() {
        MPrime.call(
          this,
          "p224",
          "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"
        );
      }
      inherits(P224, MPrime);
      function P192() {
        MPrime.call(
          this,
          "p192",
          "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"
        );
      }
      inherits(P192, MPrime);
      function P25519() {
        MPrime.call(
          this,
          "25519",
          "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"
        );
      }
      inherits(P25519, MPrime);
      P25519.prototype.imulK = function imulK(num) {
        var carry = 0;
        for (var i2 = 0; i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry;
          var lo = hi & 67108863;
          hi >>>= 26;
          num.words[i2] = lo;
          carry = hi;
        }
        if (carry !== 0) {
          num.words[num.length++] = carry;
        }
        return num;
      };
      BN._prime = function prime(name) {
        if (primes[name]) return primes[name];
        var prime2;
        if (name === "k256") {
          prime2 = new K256();
        } else if (name === "p224") {
          prime2 = new P224();
        } else if (name === "p192") {
          prime2 = new P192();
        } else if (name === "p25519") {
          prime2 = new P25519();
        } else {
          throw new Error("Unknown prime " + name);
        }
        primes[name] = prime2;
        return prime2;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p;
          this.prime = prime;
        } else {
          assert(m.gtn(1), "modulus must be greater than 1");
          this.m = m;
          this.prime = null;
        }
      }
      Red.prototype._verify1 = function _verify1(a2) {
        assert(a2.negative === 0, "red works only with positives");
        assert(a2.red, "red works only with red numbers");
      };
      Red.prototype._verify2 = function _verify2(a2, b2) {
        assert((a2.negative | b2.negative) === 0, "red works only with positives");
        assert(
          a2.red && a2.red === b2.red,
          "red works only with red numbers"
        );
      };
      Red.prototype.imod = function imod(a2) {
        if (this.prime) return this.prime.ireduce(a2)._forceRed(this);
        return a2.umod(this.m)._forceRed(this);
      };
      Red.prototype.neg = function neg(a2) {
        if (a2.isZero()) {
          return a2.clone();
        }
        return this.m.sub(a2)._forceRed(this);
      };
      Red.prototype.add = function add2(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.add(b2);
        if (res.cmp(this.m) >= 0) {
          res.isub(this.m);
        }
        return res._forceRed(this);
      };
      Red.prototype.iadd = function iadd(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.iadd(b2);
        if (res.cmp(this.m) >= 0) {
          res.isub(this.m);
        }
        return res;
      };
      Red.prototype.sub = function sub(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.sub(b2);
        if (res.cmpn(0) < 0) {
          res.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Red.prototype.isub = function isub(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.isub(b2);
        if (res.cmpn(0) < 0) {
          res.iadd(this.m);
        }
        return res;
      };
      Red.prototype.shl = function shl(a2, num) {
        this._verify1(a2);
        return this.imod(a2.ushln(num));
      };
      Red.prototype.imul = function imul(a2, b2) {
        this._verify2(a2, b2);
        return this.imod(a2.imul(b2));
      };
      Red.prototype.mul = function mul(a2, b2) {
        this._verify2(a2, b2);
        return this.imod(a2.mul(b2));
      };
      Red.prototype.isqr = function isqr(a2) {
        return this.imul(a2, a2.clone());
      };
      Red.prototype.sqr = function sqr(a2) {
        return this.mul(a2, a2);
      };
      Red.prototype.sqrt = function sqrt(a2) {
        if (a2.isZero()) return a2.clone();
        var mod3 = this.m.andln(3);
        assert(mod3 % 2 === 1);
        if (mod3 === 3) {
          var pow2 = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow2);
        }
        var q = this.m.subn(1);
        var s2 = 0;
        while (!q.isZero() && q.andln(1) === 0) {
          s2++;
          q.iushrn(1);
        }
        assert(!q.isZero());
        var one = new BN(1).toRed(this);
        var nOne = one.redNeg();
        var lpow = this.m.subn(1).iushrn(1);
        var z2 = this.m.bitLength();
        z2 = new BN(2 * z2 * z2).toRed(this);
        while (this.pow(z2, lpow).cmp(nOne) !== 0) {
          z2.redIAdd(nOne);
        }
        var c2 = this.pow(z2, q);
        var r2 = this.pow(a2, q.addn(1).iushrn(1));
        var t2 = this.pow(a2, q);
        var m = s2;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0; tmp.cmp(one) !== 0; i2++) {
            tmp = tmp.redSqr();
          }
          assert(i2 < m);
          var b2 = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b2);
          c2 = b2.redSqr();
          t2 = t2.redMul(c2);
          m = i2;
        }
        return r2;
      };
      Red.prototype.invm = function invm(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0) {
          inv.negative = 0;
          return this.imod(inv).redNeg();
        } else {
          return this.imod(inv);
        }
      };
      Red.prototype.pow = function pow2(a2, num) {
        if (num.isZero()) return new BN(1).toRed(this);
        if (num.cmpn(1) === 0) return a2.clone();
        var windowSize = 4;
        var wnd = new Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this);
        wnd[1] = a2;
        for (var i2 = 2; i2 < wnd.length; i2++) {
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        }
        var res = wnd[0];
        var current = 0;
        var currentLen = 0;
        var start = num.bitLength() % 26;
        if (start === 0) {
          start = 26;
        }
        for (i2 = num.length - 1; i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1; j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0]) {
              res = this.sqr(res);
            }
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            current <<= 1;
            current |= bit;
            currentLen++;
            if (currentLen !== windowSize && (i2 !== 0 || j !== 0)) continue;
            res = this.mul(res, wnd[current]);
            currentLen = 0;
            current = 0;
          }
          start = 26;
        }
        return res;
      };
      Red.prototype.convertTo = function convertTo(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      };
      Red.prototype.convertFrom = function convertFrom(num) {
        var res = num.clone();
        res.red = null;
        return res;
      };
      BN.mont = function mont2(num) {
        return new Mont(num);
      };
      function Mont(m) {
        Red.call(this, m);
        this.shift = this.m.bitLength();
        if (this.shift % 26 !== 0) {
          this.shift += 26 - this.shift % 26;
        }
        this.r = new BN(1).iushln(this.shift);
        this.r2 = this.imod(this.r.sqr());
        this.rinv = this.r._invmp(this.m);
        this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
        this.minv = this.minv.umod(this.r);
        this.minv = this.r.sub(this.minv);
      }
      inherits(Mont, Red);
      Mont.prototype.convertTo = function convertTo(num) {
        return this.imod(num.ushln(this.shift));
      };
      Mont.prototype.convertFrom = function convertFrom(num) {
        var r2 = this.imod(num.mul(this.rinv));
        r2.red = null;
        return r2;
      };
      Mont.prototype.imul = function imul(a2, b2) {
        if (a2.isZero() || b2.isZero()) {
          a2.words[0] = 0;
          a2.length = 1;
          return a2;
        }
        var t2 = a2.imul(b2);
        var c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
        var u2 = t2.isub(c2).iushrn(this.shift);
        var res = u2;
        if (u2.cmp(this.m) >= 0) {
          res = u2.isub(this.m);
        } else if (u2.cmpn(0) < 0) {
          res = u2.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Mont.prototype.mul = function mul(a2, b2) {
        if (a2.isZero() || b2.isZero()) return new BN(0)._forceRed(this);
        var t2 = a2.mul(b2);
        var c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
        var u2 = t2.isub(c2).iushrn(this.shift);
        var res = u2;
        if (u2.cmp(this.m) >= 0) {
          res = u2.isub(this.m);
        } else if (u2.cmpn(0) < 0) {
          res = u2.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Mont.prototype.invm = function invm(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(module2, bn$2);
  })(bn$3);
  return bn$3.exports;
}
var brorand = { exports: {} };
var hasRequiredBrorand;
function requireBrorand() {
  if (hasRequiredBrorand) return brorand.exports;
  hasRequiredBrorand = 1;
  var r2;
  brorand.exports = function rand(len) {
    if (!r2)
      r2 = new Rand(null);
    return r2.generate(len);
  };
  function Rand(rand) {
    this.rand = rand;
  }
  brorand.exports.Rand = Rand;
  Rand.prototype.generate = function generate(len) {
    return this._rand(len);
  };
  Rand.prototype._rand = function _rand(n2) {
    if (this.rand.getBytes)
      return this.rand.getBytes(n2);
    var res = new Uint8Array(n2);
    for (var i2 = 0; i2 < res.length; i2++)
      res[i2] = this.rand.getByte();
    return res;
  };
  if (typeof self === "object") {
    if (self.crypto && self.crypto.getRandomValues) {
      Rand.prototype._rand = function _rand(n2) {
        var arr = new Uint8Array(n2);
        self.crypto.getRandomValues(arr);
        return arr;
      };
    } else if (self.msCrypto && self.msCrypto.getRandomValues) {
      Rand.prototype._rand = function _rand(n2) {
        var arr = new Uint8Array(n2);
        self.msCrypto.getRandomValues(arr);
        return arr;
      };
    } else if (typeof window === "object") {
      Rand.prototype._rand = function() {
        throw new Error("Not implemented yet");
      };
    }
  } else {
    try {
      var crypto2 = /* @__PURE__ */ requireCryptoBrowserify();
      if (typeof crypto2.randomBytes !== "function")
        throw new Error("Not supported");
      Rand.prototype._rand = function _rand(n2) {
        return crypto2.randomBytes(n2);
      };
    } catch (e4) {
    }
  }
  return brorand.exports;
}
var mr;
var hasRequiredMr;
function requireMr() {
  if (hasRequiredMr) return mr;
  hasRequiredMr = 1;
  var bn2 = requireBn$1();
  var brorand2 = requireBrorand();
  function MillerRabin(rand) {
    this.rand = rand || new brorand2.Rand();
  }
  mr = MillerRabin;
  MillerRabin.create = function create2(rand) {
    return new MillerRabin(rand);
  };
  MillerRabin.prototype._randbelow = function _randbelow(n2) {
    var len = n2.bitLength();
    var min_bytes = Math.ceil(len / 8);
    do
      var a2 = new bn2(this.rand.generate(min_bytes));
    while (a2.cmp(n2) >= 0);
    return a2;
  };
  MillerRabin.prototype._randrange = function _randrange(start, stop) {
    var size = stop.sub(start);
    return start.add(this._randbelow(size));
  };
  MillerRabin.prototype.test = function test(n2, k2, cb) {
    var len = n2.bitLength();
    var red = bn2.mont(n2);
    var rone = new bn2(1).toRed(red);
    if (!k2)
      k2 = Math.max(1, len / 48 | 0);
    var n1 = n2.subn(1);
    for (var s2 = 0; !n1.testn(s2); s2++) {
    }
    var d = n2.shrn(s2);
    var rn1 = n1.toRed(red);
    var prime = true;
    for (; k2 > 0; k2--) {
      var a2 = this._randrange(new bn2(2), n1);
      if (cb)
        cb(a2);
      var x2 = a2.toRed(red).redPow(d);
      if (x2.cmp(rone) === 0 || x2.cmp(rn1) === 0)
        continue;
      for (var i2 = 1; i2 < s2; i2++) {
        x2 = x2.redSqr();
        if (x2.cmp(rone) === 0)
          return false;
        if (x2.cmp(rn1) === 0)
          break;
      }
      if (i2 === s2)
        return false;
    }
    return prime;
  };
  MillerRabin.prototype.getDivisor = function getDivisor(n2, k2) {
    var len = n2.bitLength();
    var red = bn2.mont(n2);
    var rone = new bn2(1).toRed(red);
    if (!k2)
      k2 = Math.max(1, len / 48 | 0);
    var n1 = n2.subn(1);
    for (var s2 = 0; !n1.testn(s2); s2++) {
    }
    var d = n2.shrn(s2);
    var rn1 = n1.toRed(red);
    for (; k2 > 0; k2--) {
      var a2 = this._randrange(new bn2(2), n1);
      var g = n2.gcd(a2);
      if (g.cmpn(1) !== 0)
        return g;
      var x2 = a2.toRed(red).redPow(d);
      if (x2.cmp(rone) === 0 || x2.cmp(rn1) === 0)
        continue;
      for (var i2 = 1; i2 < s2; i2++) {
        x2 = x2.redSqr();
        if (x2.cmp(rone) === 0)
          return x2.fromRed().subn(1).gcd(n2);
        if (x2.cmp(rn1) === 0)
          break;
      }
      if (i2 === s2) {
        x2 = x2.redSqr();
        return x2.fromRed().subn(1).gcd(n2);
      }
    }
    return false;
  };
  return mr;
}
var generatePrime;
var hasRequiredGeneratePrime;
function requireGeneratePrime() {
  if (hasRequiredGeneratePrime) return generatePrime;
  hasRequiredGeneratePrime = 1;
  var randomBytes = requireBrowser$e();
  generatePrime = findPrime;
  findPrime.simpleSieve = simpleSieve;
  findPrime.fermatTest = fermatTest;
  var BN = requireBn$1();
  var TWENTYFOUR = new BN(24);
  var MillerRabin = requireMr();
  var millerRabin = new MillerRabin();
  var ONE = new BN(1);
  var TWO = new BN(2);
  var FIVE = new BN(5);
  new BN(16);
  new BN(8);
  var TEN = new BN(10);
  var THREE2 = new BN(3);
  new BN(7);
  var ELEVEN = new BN(11);
  var FOUR = new BN(4);
  new BN(12);
  var primes = null;
  function _getPrimes() {
    if (primes !== null)
      return primes;
    var limit = 1048576;
    var res = [];
    res[0] = 2;
    for (var i2 = 1, k2 = 3; k2 < limit; k2 += 2) {
      var sqrt = Math.ceil(Math.sqrt(k2));
      for (var j = 0; j < i2 && res[j] <= sqrt; j++)
        if (k2 % res[j] === 0)
          break;
      if (i2 !== j && res[j] <= sqrt)
        continue;
      res[i2++] = k2;
    }
    primes = res;
    return res;
  }
  function simpleSieve(p2) {
    var primes2 = _getPrimes();
    for (var i2 = 0; i2 < primes2.length; i2++)
      if (p2.modn(primes2[i2]) === 0) {
        if (p2.cmpn(primes2[i2]) === 0) {
          return true;
        } else {
          return false;
        }
      }
    return true;
  }
  function fermatTest(p2) {
    var red = BN.mont(p2);
    return TWO.toRed(red).redPow(p2.subn(1)).fromRed().cmpn(1) === 0;
  }
  function findPrime(bits, gen) {
    if (bits < 16) {
      if (gen === 2 || gen === 5) {
        return new BN([140, 123]);
      } else {
        return new BN([140, 39]);
      }
    }
    gen = new BN(gen);
    var num, n2;
    while (true) {
      num = new BN(randomBytes(Math.ceil(bits / 8)));
      while (num.bitLength() > bits) {
        num.ishrn(1);
      }
      if (num.isEven()) {
        num.iadd(ONE);
      }
      if (!num.testn(1)) {
        num.iadd(TWO);
      }
      if (!gen.cmp(TWO)) {
        while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
          num.iadd(FOUR);
        }
      } else if (!gen.cmp(FIVE)) {
        while (num.mod(TEN).cmp(THREE2)) {
          num.iadd(FOUR);
        }
      }
      n2 = num.shrn(1);
      if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) {
        return num;
      }
    }
  }
  return generatePrime;
}
const modp1 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" };
const modp2 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" };
const modp5 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" };
const modp14 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" };
const modp15 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" };
const modp16 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" };
const modp17 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" };
const modp18 = { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" };
const require$$1$1 = {
  modp1,
  modp2,
  modp5,
  modp14,
  modp15,
  modp16,
  modp17,
  modp18
};
var dh;
var hasRequiredDh;
function requireDh() {
  if (hasRequiredDh) return dh;
  hasRequiredDh = 1;
  var BN = requireBn$1();
  var MillerRabin = requireMr();
  var millerRabin = new MillerRabin();
  var TWENTYFOUR = new BN(24);
  var ELEVEN = new BN(11);
  var TEN = new BN(10);
  var THREE2 = new BN(3);
  var SEVEN = new BN(7);
  var primes = requireGeneratePrime();
  var randomBytes = requireBrowser$e();
  dh = DH;
  function setPublicKey(pub, enc) {
    enc = enc || "utf8";
    if (!Buffer.isBuffer(pub)) {
      pub = new Buffer(pub, enc);
    }
    this._pub = new BN(pub);
    return this;
  }
  function setPrivateKey(priv, enc) {
    enc = enc || "utf8";
    if (!Buffer.isBuffer(priv)) {
      priv = new Buffer(priv, enc);
    }
    this._priv = new BN(priv);
    return this;
  }
  var primeCache = {};
  function checkPrime(prime, generator) {
    var gen = generator.toString("hex");
    var hex = [gen, prime.toString(16)].join("_");
    if (hex in primeCache) {
      return primeCache[hex];
    }
    var error = 0;
    if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) {
      error += 1;
      if (gen === "02" || gen === "05") {
        error += 8;
      } else {
        error += 4;
      }
      primeCache[hex] = error;
      return error;
    }
    if (!millerRabin.test(prime.shrn(1))) {
      error += 2;
    }
    var rem;
    switch (gen) {
      case "02":
        if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
          error += 8;
        }
        break;
      case "05":
        rem = prime.mod(TEN);
        if (rem.cmp(THREE2) && rem.cmp(SEVEN)) {
          error += 8;
        }
        break;
      default:
        error += 4;
    }
    primeCache[hex] = error;
    return error;
  }
  function DH(prime, generator, malleable) {
    this.setGenerator(generator);
    this.__prime = new BN(prime);
    this._prime = BN.mont(this.__prime);
    this._primeLen = prime.length;
    this._pub = void 0;
    this._priv = void 0;
    this._primeCode = void 0;
    if (malleable) {
      this.setPublicKey = setPublicKey;
      this.setPrivateKey = setPrivateKey;
    } else {
      this._primeCode = 8;
    }
  }
  Object.defineProperty(DH.prototype, "verifyError", {
    enumerable: true,
    get: function() {
      if (typeof this._primeCode !== "number") {
        this._primeCode = checkPrime(this.__prime, this.__gen);
      }
      return this._primeCode;
    }
  });
  DH.prototype.generateKeys = function() {
    if (!this._priv) {
      this._priv = new BN(randomBytes(this._primeLen));
    }
    this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
    return this.getPublicKey();
  };
  DH.prototype.computeSecret = function(other) {
    other = new BN(other);
    other = other.toRed(this._prime);
    var secret = other.redPow(this._priv).fromRed();
    var out = new Buffer(secret.toArray());
    var prime = this.getPrime();
    if (out.length < prime.length) {
      var front = new Buffer(prime.length - out.length);
      front.fill(0);
      out = Buffer.concat([front, out]);
    }
    return out;
  };
  DH.prototype.getPublicKey = function getPublicKey(enc) {
    return formatReturnValue(this._pub, enc);
  };
  DH.prototype.getPrivateKey = function getPrivateKey(enc) {
    return formatReturnValue(this._priv, enc);
  };
  DH.prototype.getPrime = function(enc) {
    return formatReturnValue(this.__prime, enc);
  };
  DH.prototype.getGenerator = function(enc) {
    return formatReturnValue(this._gen, enc);
  };
  DH.prototype.setGenerator = function(gen, enc) {
    enc = enc || "utf8";
    if (!Buffer.isBuffer(gen)) {
      gen = new Buffer(gen, enc);
    }
    this.__gen = gen;
    this._gen = new BN(gen);
    return this;
  };
  function formatReturnValue(bn2, enc) {
    var buf = new Buffer(bn2.toArray());
    if (!enc) {
      return buf;
    } else {
      return buf.toString(enc);
    }
  }
  return dh;
}
var hasRequiredBrowser$7;
function requireBrowser$7() {
  if (hasRequiredBrowser$7) return browser$9;
  hasRequiredBrowser$7 = 1;
  var generatePrime2 = requireGeneratePrime();
  var primes = require$$1$1;
  var DH = requireDh();
  function getDiffieHellman(mod) {
    var prime = new Buffer(primes[mod].prime, "hex");
    var gen = new Buffer(primes[mod].gen, "hex");
    return new DH(prime, gen);
  }
  var ENCODINGS = {
    "binary": true,
    "hex": true,
    "base64": true
  };
  function createDiffieHellman(prime, enc, generator, genc) {
    if (Buffer.isBuffer(enc) || ENCODINGS[enc] === void 0) {
      return createDiffieHellman(prime, "binary", enc, generator);
    }
    enc = enc || "binary";
    genc = genc || "binary";
    generator = generator || new Buffer([2]);
    if (!Buffer.isBuffer(generator)) {
      generator = new Buffer(generator, genc);
    }
    if (typeof prime === "number") {
      return new DH(generatePrime2(prime, generator), generator, true);
    }
    if (!Buffer.isBuffer(prime)) {
      prime = new Buffer(prime, enc);
    }
    return new DH(prime, generator, true);
  }
  browser$9.DiffieHellmanGroup = browser$9.createDiffieHellmanGroup = browser$9.getDiffieHellman = getDiffieHellman;
  browser$9.createDiffieHellman = browser$9.DiffieHellman = createDiffieHellman;
  return browser$9;
}
var sign = { exports: {} };
var bn$1 = { exports: {} };
var bn = bn$1.exports;
var hasRequiredBn;
function requireBn() {
  if (hasRequiredBn) return bn$1.exports;
  hasRequiredBn = 1;
  (function(module2) {
    (function(module3, exports) {
      function assert(val, msg) {
        if (!val) throw new Error(msg || "Assertion failed");
      }
      function inherits(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {
        };
        TempCtor.prototype = superCtor.prototype;
        ctor.prototype = new TempCtor();
        ctor.prototype.constructor = ctor;
      }
      function BN(number, base2, endian) {
        if (BN.isBN(number)) {
          return number;
        }
        this.negative = 0;
        this.words = null;
        this.length = 0;
        this.red = null;
        if (number !== null) {
          if (base2 === "le" || base2 === "be") {
            endian = base2;
            base2 = 10;
          }
          this._init(number || 0, base2 || 10, endian || "be");
        }
      }
      if (typeof module3 === "object") {
        module3.exports = BN;
      } else {
        exports.BN = BN;
      }
      BN.BN = BN;
      BN.wordSize = 26;
      var Buffer2;
      try {
        if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") {
          Buffer2 = window.Buffer;
        } else {
          Buffer2 = require$$0$2.Buffer;
        }
      } catch (e4) {
      }
      BN.isBN = function isBN(num) {
        if (num instanceof BN) {
          return true;
        }
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      };
      BN.max = function max2(left, right) {
        if (left.cmp(right) > 0) return left;
        return right;
      };
      BN.min = function min2(left, right) {
        if (left.cmp(right) < 0) return left;
        return right;
      };
      BN.prototype._init = function init2(number, base2, endian) {
        if (typeof number === "number") {
          return this._initNumber(number, base2, endian);
        }
        if (typeof number === "object") {
          return this._initArray(number, base2, endian);
        }
        if (base2 === "hex") {
          base2 = 16;
        }
        assert(base2 === (base2 | 0) && base2 >= 2 && base2 <= 36);
        number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-") {
          start++;
          this.negative = 1;
        }
        if (start < number.length) {
          if (base2 === 16) {
            this._parseHex(number, start, endian);
          } else {
            this._parseBase(number, base2, start);
            if (endian === "le") {
              this._initArray(this.toArray(), base2, endian);
            }
          }
        }
      };
      BN.prototype._initNumber = function _initNumber(number, base2, endian) {
        if (number < 0) {
          this.negative = 1;
          number = -number;
        }
        if (number < 67108864) {
          this.words = [number & 67108863];
          this.length = 1;
        } else if (number < 4503599627370496) {
          this.words = [
            number & 67108863,
            number / 67108864 & 67108863
          ];
          this.length = 2;
        } else {
          assert(number < 9007199254740992);
          this.words = [
            number & 67108863,
            number / 67108864 & 67108863,
            1
          ];
          this.length = 3;
        }
        if (endian !== "le") return;
        this._initArray(this.toArray(), base2, endian);
      };
      BN.prototype._initArray = function _initArray(number, base2, endian) {
        assert(typeof number.length === "number");
        if (number.length <= 0) {
          this.words = [0];
          this.length = 1;
          return this;
        }
        this.length = Math.ceil(number.length / 3);
        this.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          this.words[i2] = 0;
        }
        var j, w;
        var off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0; i2 >= 0; i2 -= 3) {
            w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16;
            this.words[j] |= w << off & 67108863;
            this.words[j + 1] = w >>> 26 - off & 67108863;
            off += 24;
            if (off >= 26) {
              off -= 26;
              j++;
            }
          }
        } else if (endian === "le") {
          for (i2 = 0, j = 0; i2 < number.length; i2 += 3) {
            w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16;
            this.words[j] |= w << off & 67108863;
            this.words[j + 1] = w >>> 26 - off & 67108863;
            off += 24;
            if (off >= 26) {
              off -= 26;
              j++;
            }
          }
        }
        return this._strip();
      };
      function parseHex4Bits(string, index2) {
        var c2 = string.charCodeAt(index2);
        if (c2 >= 48 && c2 <= 57) {
          return c2 - 48;
        } else if (c2 >= 65 && c2 <= 70) {
          return c2 - 55;
        } else if (c2 >= 97 && c2 <= 102) {
          return c2 - 87;
        } else {
          assert(false, "Invalid character in " + string);
        }
      }
      function parseHexByte(string, lowerBound, index2) {
        var r2 = parseHex4Bits(string, index2);
        if (index2 - 1 >= lowerBound) {
          r2 |= parseHex4Bits(string, index2 - 1) << 4;
        }
        return r2;
      }
      BN.prototype._parseHex = function _parseHex(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6);
        this.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          this.words[i2] = 0;
        }
        var off = 0;
        var j = 0;
        var w;
        if (endian === "be") {
          for (i2 = number.length - 1; i2 >= start; i2 -= 2) {
            w = parseHexByte(number, start, i2) << off;
            this.words[j] |= w & 67108863;
            if (off >= 18) {
              off -= 18;
              j += 1;
              this.words[j] |= w >>> 26;
            } else {
              off += 8;
            }
          }
        } else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start; i2 < number.length; i2 += 2) {
            w = parseHexByte(number, start, i2) << off;
            this.words[j] |= w & 67108863;
            if (off >= 18) {
              off -= 18;
              j += 1;
              this.words[j] |= w >>> 26;
            } else {
              off += 8;
            }
          }
        }
        this._strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0;
        var b2 = 0;
        var len = Math.min(str.length, end);
        for (var i2 = start; i2 < len; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          r2 *= mul;
          if (c2 >= 49) {
            b2 = c2 - 49 + 10;
          } else if (c2 >= 17) {
            b2 = c2 - 17 + 10;
          } else {
            b2 = c2;
          }
          assert(c2 >= 0 && b2 < mul, "Invalid character");
          r2 += b2;
        }
        return r2;
      }
      BN.prototype._parseBase = function _parseBase(number, base2, start) {
        this.words = [0];
        this.length = 1;
        for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base2) {
          limbLen++;
        }
        limbLen--;
        limbPow = limbPow / base2 | 0;
        var total = number.length - start;
        var mod = total % limbLen;
        var end = Math.min(total, total - mod) + start;
        var word = 0;
        for (var i2 = start; i2 < end; i2 += limbLen) {
          word = parseBase(number, i2, i2 + limbLen, base2);
          this.imuln(limbPow);
          if (this.words[0] + word < 67108864) {
            this.words[0] += word;
          } else {
            this._iaddn(word);
          }
        }
        if (mod !== 0) {
          var pow2 = 1;
          word = parseBase(number, i2, number.length, base2);
          for (i2 = 0; i2 < mod; i2++) {
            pow2 *= base2;
          }
          this.imuln(pow2);
          if (this.words[0] + word < 67108864) {
            this.words[0] += word;
          } else {
            this._iaddn(word);
          }
        }
        this._strip();
      };
      BN.prototype.copy = function copy2(dest) {
        dest.words = new Array(this.length);
        for (var i2 = 0; i2 < this.length; i2++) {
          dest.words[i2] = this.words[i2];
        }
        dest.length = this.length;
        dest.negative = this.negative;
        dest.red = this.red;
      };
      function move(dest, src2) {
        dest.words = src2.words;
        dest.length = src2.length;
        dest.negative = src2.negative;
        dest.red = src2.red;
      }
      BN.prototype._move = function _move(dest) {
        move(dest, this);
      };
      BN.prototype.clone = function clone2() {
        var r2 = new BN(null);
        this.copy(r2);
        return r2;
      };
      BN.prototype._expand = function _expand(size) {
        while (this.length < size) {
          this.words[this.length++] = 0;
        }
        return this;
      };
      BN.prototype._strip = function strip() {
        while (this.length > 1 && this.words[this.length - 1] === 0) {
          this.length--;
        }
        return this._normSign();
      };
      BN.prototype._normSign = function _normSign() {
        if (this.length === 1 && this.words[0] === 0) {
          this.negative = 0;
        }
        return this;
      };
      if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") {
        try {
          BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect;
        } catch (e4) {
          BN.prototype.inspect = inspect;
        }
      } else {
        BN.prototype.inspect = inspect;
      }
      function inspect() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      }
      var zeros = [
        "",
        "0",
        "00",
        "000",
        "0000",
        "00000",
        "000000",
        "0000000",
        "00000000",
        "000000000",
        "0000000000",
        "00000000000",
        "000000000000",
        "0000000000000",
        "00000000000000",
        "000000000000000",
        "0000000000000000",
        "00000000000000000",
        "000000000000000000",
        "0000000000000000000",
        "00000000000000000000",
        "000000000000000000000",
        "0000000000000000000000",
        "00000000000000000000000",
        "000000000000000000000000",
        "0000000000000000000000000"
      ];
      var groupSizes = [
        0,
        0,
        25,
        16,
        12,
        11,
        10,
        9,
        8,
        8,
        7,
        7,
        7,
        7,
        6,
        6,
        6,
        6,
        6,
        6,
        6,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5,
        5
      ];
      var groupBases = [
        0,
        0,
        33554432,
        43046721,
        16777216,
        48828125,
        60466176,
        40353607,
        16777216,
        43046721,
        1e7,
        19487171,
        35831808,
        62748517,
        7529536,
        11390625,
        16777216,
        24137569,
        34012224,
        47045881,
        64e6,
        4084101,
        5153632,
        6436343,
        7962624,
        9765625,
        11881376,
        14348907,
        17210368,
        20511149,
        243e5,
        28629151,
        33554432,
        39135393,
        45435424,
        52521875,
        60466176
      ];
      BN.prototype.toString = function toString2(base2, padding) {
        base2 = base2 || 10;
        padding = padding | 0 || 1;
        var out;
        if (base2 === 16 || base2 === "hex") {
          out = "";
          var off = 0;
          var carry = 0;
          for (var i2 = 0; i2 < this.length; i2++) {
            var w = this.words[i2];
            var word = ((w << off | carry) & 16777215).toString(16);
            carry = w >>> 24 - off & 16777215;
            off += 2;
            if (off >= 26) {
              off -= 26;
              i2--;
            }
            if (carry !== 0 || i2 !== this.length - 1) {
              out = zeros[6 - word.length] + word + out;
            } else {
              out = word + out;
            }
          }
          if (carry !== 0) {
            out = carry.toString(16) + out;
          }
          while (out.length % padding !== 0) {
            out = "0" + out;
          }
          if (this.negative !== 0) {
            out = "-" + out;
          }
          return out;
        }
        if (base2 === (base2 | 0) && base2 >= 2 && base2 <= 36) {
          var groupSize = groupSizes[base2];
          var groupBase = groupBases[base2];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modrn(groupBase).toString(base2);
            c2 = c2.idivn(groupBase);
            if (!c2.isZero()) {
              out = zeros[groupSize - r2.length] + r2 + out;
            } else {
              out = r2 + out;
            }
          }
          if (this.isZero()) {
            out = "0" + out;
          }
          while (out.length % padding !== 0) {
            out = "0" + out;
          }
          if (this.negative !== 0) {
            out = "-" + out;
          }
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      };
      BN.prototype.toNumber = function toNumber() {
        var ret = this.words[0];
        if (this.length === 2) {
          ret += this.words[1] * 67108864;
        } else if (this.length === 3 && this.words[2] === 1) {
          ret += 4503599627370496 + this.words[1] * 67108864;
        } else if (this.length > 2) {
          assert(false, "Number can only safely store up to 53 bits");
        }
        return this.negative !== 0 ? -ret : ret;
      };
      BN.prototype.toJSON = function toJSON() {
        return this.toString(16, 2);
      };
      if (Buffer2) {
        BN.prototype.toBuffer = function toBuffer2(endian, length) {
          return this.toArrayLike(Buffer2, endian, length);
        };
      }
      BN.prototype.toArray = function toArray(endian, length) {
        return this.toArrayLike(Array, endian, length);
      };
      var allocate = function allocate2(ArrayType, size) {
        if (ArrayType.allocUnsafe) {
          return ArrayType.allocUnsafe(size);
        }
        return new ArrayType(size);
      };
      BN.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) {
        this._strip();
        var byteLength2 = this.byteLength();
        var reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length");
        assert(reqLength > 0, "Requested array length <= 0");
        var res = allocate(ArrayType, reqLength);
        var postfix = endian === "le" ? "LE" : "BE";
        this["_toArrayLike" + postfix](res, byteLength2);
        return res;
      };
      BN.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength2) {
        var position = 0;
        var carry = 0;
        for (var i2 = 0, shift = 0; i2 < this.length; i2++) {
          var word = this.words[i2] << shift | carry;
          res[position++] = word & 255;
          if (position < res.length) {
            res[position++] = word >> 8 & 255;
          }
          if (position < res.length) {
            res[position++] = word >> 16 & 255;
          }
          if (shift === 6) {
            if (position < res.length) {
              res[position++] = word >> 24 & 255;
            }
            carry = 0;
            shift = 0;
          } else {
            carry = word >>> 24;
            shift += 2;
          }
        }
        if (position < res.length) {
          res[position++] = carry;
          while (position < res.length) {
            res[position++] = 0;
          }
        }
      };
      BN.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength2) {
        var position = res.length - 1;
        var carry = 0;
        for (var i2 = 0, shift = 0; i2 < this.length; i2++) {
          var word = this.words[i2] << shift | carry;
          res[position--] = word & 255;
          if (position >= 0) {
            res[position--] = word >> 8 & 255;
          }
          if (position >= 0) {
            res[position--] = word >> 16 & 255;
          }
          if (shift === 6) {
            if (position >= 0) {
              res[position--] = word >> 24 & 255;
            }
            carry = 0;
            shift = 0;
          } else {
            carry = word >>> 24;
            shift += 2;
          }
        }
        if (position >= 0) {
          res[position--] = carry;
          while (position >= 0) {
            res[position--] = 0;
          }
        }
      };
      if (Math.clz32) {
        BN.prototype._countBits = function _countBits(w) {
          return 32 - Math.clz32(w);
        };
      } else {
        BN.prototype._countBits = function _countBits(w) {
          var t2 = w;
          var r2 = 0;
          if (t2 >= 4096) {
            r2 += 13;
            t2 >>>= 13;
          }
          if (t2 >= 64) {
            r2 += 7;
            t2 >>>= 7;
          }
          if (t2 >= 8) {
            r2 += 4;
            t2 >>>= 4;
          }
          if (t2 >= 2) {
            r2 += 2;
            t2 >>>= 2;
          }
          return r2 + t2;
        };
      }
      BN.prototype._zeroBits = function _zeroBits(w) {
        if (w === 0) return 26;
        var t2 = w;
        var r2 = 0;
        if ((t2 & 8191) === 0) {
          r2 += 13;
          t2 >>>= 13;
        }
        if ((t2 & 127) === 0) {
          r2 += 7;
          t2 >>>= 7;
        }
        if ((t2 & 15) === 0) {
          r2 += 4;
          t2 >>>= 4;
        }
        if ((t2 & 3) === 0) {
          r2 += 2;
          t2 >>>= 2;
        }
        if ((t2 & 1) === 0) {
          r2++;
        }
        return r2;
      };
      BN.prototype.bitLength = function bitLength() {
        var w = this.words[this.length - 1];
        var hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = new Array(num.bitLength());
        for (var bit = 0; bit < w.length; bit++) {
          var off = bit / 26 | 0;
          var wbit = bit % 26;
          w[bit] = num.words[off] >>> wbit & 1;
        }
        return w;
      }
      BN.prototype.zeroBits = function zeroBits() {
        if (this.isZero()) return 0;
        var r2 = 0;
        for (var i2 = 0; i2 < this.length; i2++) {
          var b2 = this._zeroBits(this.words[i2]);
          r2 += b2;
          if (b2 !== 26) break;
        }
        return r2;
      };
      BN.prototype.byteLength = function byteLength2() {
        return Math.ceil(this.bitLength() / 8);
      };
      BN.prototype.toTwos = function toTwos(width) {
        if (this.negative !== 0) {
          return this.abs().inotn(width).iaddn(1);
        }
        return this.clone();
      };
      BN.prototype.fromTwos = function fromTwos(width) {
        if (this.testn(width - 1)) {
          return this.notn(width).iaddn(1).ineg();
        }
        return this.clone();
      };
      BN.prototype.isNeg = function isNeg() {
        return this.negative !== 0;
      };
      BN.prototype.neg = function neg() {
        return this.clone().ineg();
      };
      BN.prototype.ineg = function ineg() {
        if (!this.isZero()) {
          this.negative ^= 1;
        }
        return this;
      };
      BN.prototype.iuor = function iuor(num) {
        while (this.length < num.length) {
          this.words[this.length++] = 0;
        }
        for (var i2 = 0; i2 < num.length; i2++) {
          this.words[i2] = this.words[i2] | num.words[i2];
        }
        return this._strip();
      };
      BN.prototype.ior = function ior(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuor(num);
      };
      BN.prototype.or = function or2(num) {
        if (this.length > num.length) return this.clone().ior(num);
        return num.clone().ior(this);
      };
      BN.prototype.uor = function uor(num) {
        if (this.length > num.length) return this.clone().iuor(num);
        return num.clone().iuor(this);
      };
      BN.prototype.iuand = function iuand(num) {
        var b2;
        if (this.length > num.length) {
          b2 = num;
        } else {
          b2 = this;
        }
        for (var i2 = 0; i2 < b2.length; i2++) {
          this.words[i2] = this.words[i2] & num.words[i2];
        }
        this.length = b2.length;
        return this._strip();
      };
      BN.prototype.iand = function iand(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuand(num);
      };
      BN.prototype.and = function and2(num) {
        if (this.length > num.length) return this.clone().iand(num);
        return num.clone().iand(this);
      };
      BN.prototype.uand = function uand(num) {
        if (this.length > num.length) return this.clone().iuand(num);
        return num.clone().iuand(this);
      };
      BN.prototype.iuxor = function iuxor(num) {
        var a2;
        var b2;
        if (this.length > num.length) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        for (var i2 = 0; i2 < b2.length; i2++) {
          this.words[i2] = a2.words[i2] ^ b2.words[i2];
        }
        if (this !== a2) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        this.length = a2.length;
        return this._strip();
      };
      BN.prototype.ixor = function ixor(num) {
        assert((this.negative | num.negative) === 0);
        return this.iuxor(num);
      };
      BN.prototype.xor = function xor2(num) {
        if (this.length > num.length) return this.clone().ixor(num);
        return num.clone().ixor(this);
      };
      BN.prototype.uxor = function uxor(num) {
        if (this.length > num.length) return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      };
      BN.prototype.inotn = function inotn(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0;
        var bitsLeft = width % 26;
        this._expand(bytesNeeded);
        if (bitsLeft > 0) {
          bytesNeeded--;
        }
        for (var i2 = 0; i2 < bytesNeeded; i2++) {
          this.words[i2] = ~this.words[i2] & 67108863;
        }
        if (bitsLeft > 0) {
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        }
        return this._strip();
      };
      BN.prototype.notn = function notn(width) {
        return this.clone().inotn(width);
      };
      BN.prototype.setn = function setn(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0;
        var wbit = bit % 26;
        this._expand(off + 1);
        if (val) {
          this.words[off] = this.words[off] | 1 << wbit;
        } else {
          this.words[off] = this.words[off] & ~(1 << wbit);
        }
        return this._strip();
      };
      BN.prototype.iadd = function iadd(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0) {
          this.negative = 0;
          r2 = this.isub(num);
          this.negative ^= 1;
          return this._normSign();
        } else if (this.negative === 0 && num.negative !== 0) {
          num.negative = 0;
          r2 = this.isub(num);
          num.negative = 1;
          return r2._normSign();
        }
        var a2, b2;
        if (this.length > num.length) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        var carry = 0;
        for (var i2 = 0; i2 < b2.length; i2++) {
          r2 = (a2.words[i2] | 0) + (b2.words[i2] | 0) + carry;
          this.words[i2] = r2 & 67108863;
          carry = r2 >>> 26;
        }
        for (; carry !== 0 && i2 < a2.length; i2++) {
          r2 = (a2.words[i2] | 0) + carry;
          this.words[i2] = r2 & 67108863;
          carry = r2 >>> 26;
        }
        this.length = a2.length;
        if (carry !== 0) {
          this.words[this.length] = carry;
          this.length++;
        } else if (a2 !== this) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        return this;
      };
      BN.prototype.add = function add2(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0) {
          num.negative = 0;
          res = this.sub(num);
          num.negative ^= 1;
          return res;
        } else if (num.negative === 0 && this.negative !== 0) {
          this.negative = 0;
          res = num.sub(this);
          this.negative = 1;
          return res;
        }
        if (this.length > num.length) return this.clone().iadd(num);
        return num.clone().iadd(this);
      };
      BN.prototype.isub = function isub(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          num.negative = 1;
          return r2._normSign();
        } else if (this.negative !== 0) {
          this.negative = 0;
          this.iadd(num);
          this.negative = 1;
          return this._normSign();
        }
        var cmp = this.cmp(num);
        if (cmp === 0) {
          this.negative = 0;
          this.length = 1;
          this.words[0] = 0;
          return this;
        }
        var a2, b2;
        if (cmp > 0) {
          a2 = this;
          b2 = num;
        } else {
          a2 = num;
          b2 = this;
        }
        var carry = 0;
        for (var i2 = 0; i2 < b2.length; i2++) {
          r2 = (a2.words[i2] | 0) - (b2.words[i2] | 0) + carry;
          carry = r2 >> 26;
          this.words[i2] = r2 & 67108863;
        }
        for (; carry !== 0 && i2 < a2.length; i2++) {
          r2 = (a2.words[i2] | 0) + carry;
          carry = r2 >> 26;
          this.words[i2] = r2 & 67108863;
        }
        if (carry === 0 && i2 < a2.length && a2 !== this) {
          for (; i2 < a2.length; i2++) {
            this.words[i2] = a2.words[i2];
          }
        }
        this.length = Math.max(this.length, i2);
        if (a2 !== this) {
          this.negative = 1;
        }
        return this._strip();
      };
      BN.prototype.sub = function sub(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len = self2.length + num.length | 0;
        out.length = len;
        len = len - 1 | 0;
        var a2 = self2.words[0] | 0;
        var b2 = num.words[0] | 0;
        var r2 = a2 * b2;
        var lo = r2 & 67108863;
        var carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k2 = 1; k2 < len; k2++) {
          var ncarry = carry >>> 26;
          var rword = carry & 67108863;
          var maxJ = Math.min(k2, num.length - 1);
          for (var j = Math.max(0, k2 - self2.length + 1); j <= maxJ; j++) {
            var i2 = k2 - j | 0;
            a2 = self2.words[i2] | 0;
            b2 = num.words[j] | 0;
            r2 = a2 * b2 + rword;
            ncarry += r2 / 67108864 | 0;
            rword = r2 & 67108863;
          }
          out.words[k2] = rword | 0;
          carry = ncarry | 0;
        }
        if (carry !== 0) {
          out.words[k2] = carry | 0;
        } else {
          out.length--;
        }
        return out._strip();
      }
      var comb10MulTo = function comb10MulTo2(self2, num, out) {
        var a2 = self2.words;
        var b2 = num.words;
        var o2 = out.words;
        var c2 = 0;
        var lo;
        var mid;
        var hi;
        var a0 = a2[0] | 0;
        var al0 = a0 & 8191;
        var ah0 = a0 >>> 13;
        var a1 = a2[1] | 0;
        var al1 = a1 & 8191;
        var ah1 = a1 >>> 13;
        var a22 = a2[2] | 0;
        var al2 = a22 & 8191;
        var ah2 = a22 >>> 13;
        var a3 = a2[3] | 0;
        var al3 = a3 & 8191;
        var ah3 = a3 >>> 13;
        var a4 = a2[4] | 0;
        var al4 = a4 & 8191;
        var ah4 = a4 >>> 13;
        var a5 = a2[5] | 0;
        var al5 = a5 & 8191;
        var ah5 = a5 >>> 13;
        var a6 = a2[6] | 0;
        var al6 = a6 & 8191;
        var ah6 = a6 >>> 13;
        var a7 = a2[7] | 0;
        var al7 = a7 & 8191;
        var ah7 = a7 >>> 13;
        var a8 = a2[8] | 0;
        var al8 = a8 & 8191;
        var ah8 = a8 >>> 13;
        var a9 = a2[9] | 0;
        var al9 = a9 & 8191;
        var ah9 = a9 >>> 13;
        var b0 = b2[0] | 0;
        var bl0 = b0 & 8191;
        var bh0 = b0 >>> 13;
        var b1 = b2[1] | 0;
        var bl1 = b1 & 8191;
        var bh1 = b1 >>> 13;
        var b22 = b2[2] | 0;
        var bl2 = b22 & 8191;
        var bh2 = b22 >>> 13;
        var b3 = b2[3] | 0;
        var bl3 = b3 & 8191;
        var bh3 = b3 >>> 13;
        var b4 = b2[4] | 0;
        var bl4 = b4 & 8191;
        var bh4 = b4 >>> 13;
        var b5 = b2[5] | 0;
        var bl5 = b5 & 8191;
        var bh5 = b5 >>> 13;
        var b6 = b2[6] | 0;
        var bl6 = b6 & 8191;
        var bh6 = b6 >>> 13;
        var b7 = b2[7] | 0;
        var bl7 = b7 & 8191;
        var bh7 = b7 >>> 13;
        var b8 = b2[8] | 0;
        var bl8 = b8 & 8191;
        var bh8 = b8 >>> 13;
        var b9 = b2[9] | 0;
        var bl9 = b9 & 8191;
        var bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative;
        out.length = 19;
        lo = Math.imul(al0, bl0);
        mid = Math.imul(al0, bh0);
        mid = mid + Math.imul(ah0, bl0) | 0;
        hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0;
        w0 &= 67108863;
        lo = Math.imul(al1, bl0);
        mid = Math.imul(al1, bh0);
        mid = mid + Math.imul(ah1, bl0) | 0;
        hi = Math.imul(ah1, bh0);
        lo = lo + Math.imul(al0, bl1) | 0;
        mid = mid + Math.imul(al0, bh1) | 0;
        mid = mid + Math.imul(ah0, bl1) | 0;
        hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0;
        w1 &= 67108863;
        lo = Math.imul(al2, bl0);
        mid = Math.imul(al2, bh0);
        mid = mid + Math.imul(ah2, bl0) | 0;
        hi = Math.imul(ah2, bh0);
        lo = lo + Math.imul(al1, bl1) | 0;
        mid = mid + Math.imul(al1, bh1) | 0;
        mid = mid + Math.imul(ah1, bl1) | 0;
        hi = hi + Math.imul(ah1, bh1) | 0;
        lo = lo + Math.imul(al0, bl2) | 0;
        mid = mid + Math.imul(al0, bh2) | 0;
        mid = mid + Math.imul(ah0, bl2) | 0;
        hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0;
        w2 &= 67108863;
        lo = Math.imul(al3, bl0);
        mid = Math.imul(al3, bh0);
        mid = mid + Math.imul(ah3, bl0) | 0;
        hi = Math.imul(ah3, bh0);
        lo = lo + Math.imul(al2, bl1) | 0;
        mid = mid + Math.imul(al2, bh1) | 0;
        mid = mid + Math.imul(ah2, bl1) | 0;
        hi = hi + Math.imul(ah2, bh1) | 0;
        lo = lo + Math.imul(al1, bl2) | 0;
        mid = mid + Math.imul(al1, bh2) | 0;
        mid = mid + Math.imul(ah1, bl2) | 0;
        hi = hi + Math.imul(ah1, bh2) | 0;
        lo = lo + Math.imul(al0, bl3) | 0;
        mid = mid + Math.imul(al0, bh3) | 0;
        mid = mid + Math.imul(ah0, bl3) | 0;
        hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0;
        w3 &= 67108863;
        lo = Math.imul(al4, bl0);
        mid = Math.imul(al4, bh0);
        mid = mid + Math.imul(ah4, bl0) | 0;
        hi = Math.imul(ah4, bh0);
        lo = lo + Math.imul(al3, bl1) | 0;
        mid = mid + Math.imul(al3, bh1) | 0;
        mid = mid + Math.imul(ah3, bl1) | 0;
        hi = hi + Math.imul(ah3, bh1) | 0;
        lo = lo + Math.imul(al2, bl2) | 0;
        mid = mid + Math.imul(al2, bh2) | 0;
        mid = mid + Math.imul(ah2, bl2) | 0;
        hi = hi + Math.imul(ah2, bh2) | 0;
        lo = lo + Math.imul(al1, bl3) | 0;
        mid = mid + Math.imul(al1, bh3) | 0;
        mid = mid + Math.imul(ah1, bl3) | 0;
        hi = hi + Math.imul(ah1, bh3) | 0;
        lo = lo + Math.imul(al0, bl4) | 0;
        mid = mid + Math.imul(al0, bh4) | 0;
        mid = mid + Math.imul(ah0, bl4) | 0;
        hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0;
        w4 &= 67108863;
        lo = Math.imul(al5, bl0);
        mid = Math.imul(al5, bh0);
        mid = mid + Math.imul(ah5, bl0) | 0;
        hi = Math.imul(ah5, bh0);
        lo = lo + Math.imul(al4, bl1) | 0;
        mid = mid + Math.imul(al4, bh1) | 0;
        mid = mid + Math.imul(ah4, bl1) | 0;
        hi = hi + Math.imul(ah4, bh1) | 0;
        lo = lo + Math.imul(al3, bl2) | 0;
        mid = mid + Math.imul(al3, bh2) | 0;
        mid = mid + Math.imul(ah3, bl2) | 0;
        hi = hi + Math.imul(ah3, bh2) | 0;
        lo = lo + Math.imul(al2, bl3) | 0;
        mid = mid + Math.imul(al2, bh3) | 0;
        mid = mid + Math.imul(ah2, bl3) | 0;
        hi = hi + Math.imul(ah2, bh3) | 0;
        lo = lo + Math.imul(al1, bl4) | 0;
        mid = mid + Math.imul(al1, bh4) | 0;
        mid = mid + Math.imul(ah1, bl4) | 0;
        hi = hi + Math.imul(ah1, bh4) | 0;
        lo = lo + Math.imul(al0, bl5) | 0;
        mid = mid + Math.imul(al0, bh5) | 0;
        mid = mid + Math.imul(ah0, bl5) | 0;
        hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0;
        w5 &= 67108863;
        lo = Math.imul(al6, bl0);
        mid = Math.imul(al6, bh0);
        mid = mid + Math.imul(ah6, bl0) | 0;
        hi = Math.imul(ah6, bh0);
        lo = lo + Math.imul(al5, bl1) | 0;
        mid = mid + Math.imul(al5, bh1) | 0;
        mid = mid + Math.imul(ah5, bl1) | 0;
        hi = hi + Math.imul(ah5, bh1) | 0;
        lo = lo + Math.imul(al4, bl2) | 0;
        mid = mid + Math.imul(al4, bh2) | 0;
        mid = mid + Math.imul(ah4, bl2) | 0;
        hi = hi + Math.imul(ah4, bh2) | 0;
        lo = lo + Math.imul(al3, bl3) | 0;
        mid = mid + Math.imul(al3, bh3) | 0;
        mid = mid + Math.imul(ah3, bl3) | 0;
        hi = hi + Math.imul(ah3, bh3) | 0;
        lo = lo + Math.imul(al2, bl4) | 0;
        mid = mid + Math.imul(al2, bh4) | 0;
        mid = mid + Math.imul(ah2, bl4) | 0;
        hi = hi + Math.imul(ah2, bh4) | 0;
        lo = lo + Math.imul(al1, bl5) | 0;
        mid = mid + Math.imul(al1, bh5) | 0;
        mid = mid + Math.imul(ah1, bl5) | 0;
        hi = hi + Math.imul(ah1, bh5) | 0;
        lo = lo + Math.imul(al0, bl6) | 0;
        mid = mid + Math.imul(al0, bh6) | 0;
        mid = mid + Math.imul(ah0, bl6) | 0;
        hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0;
        w6 &= 67108863;
        lo = Math.imul(al7, bl0);
        mid = Math.imul(al7, bh0);
        mid = mid + Math.imul(ah7, bl0) | 0;
        hi = Math.imul(ah7, bh0);
        lo = lo + Math.imul(al6, bl1) | 0;
        mid = mid + Math.imul(al6, bh1) | 0;
        mid = mid + Math.imul(ah6, bl1) | 0;
        hi = hi + Math.imul(ah6, bh1) | 0;
        lo = lo + Math.imul(al5, bl2) | 0;
        mid = mid + Math.imul(al5, bh2) | 0;
        mid = mid + Math.imul(ah5, bl2) | 0;
        hi = hi + Math.imul(ah5, bh2) | 0;
        lo = lo + Math.imul(al4, bl3) | 0;
        mid = mid + Math.imul(al4, bh3) | 0;
        mid = mid + Math.imul(ah4, bl3) | 0;
        hi = hi + Math.imul(ah4, bh3) | 0;
        lo = lo + Math.imul(al3, bl4) | 0;
        mid = mid + Math.imul(al3, bh4) | 0;
        mid = mid + Math.imul(ah3, bl4) | 0;
        hi = hi + Math.imul(ah3, bh4) | 0;
        lo = lo + Math.imul(al2, bl5) | 0;
        mid = mid + Math.imul(al2, bh5) | 0;
        mid = mid + Math.imul(ah2, bl5) | 0;
        hi = hi + Math.imul(ah2, bh5) | 0;
        lo = lo + Math.imul(al1, bl6) | 0;
        mid = mid + Math.imul(al1, bh6) | 0;
        mid = mid + Math.imul(ah1, bl6) | 0;
        hi = hi + Math.imul(ah1, bh6) | 0;
        lo = lo + Math.imul(al0, bl7) | 0;
        mid = mid + Math.imul(al0, bh7) | 0;
        mid = mid + Math.imul(ah0, bl7) | 0;
        hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0;
        w7 &= 67108863;
        lo = Math.imul(al8, bl0);
        mid = Math.imul(al8, bh0);
        mid = mid + Math.imul(ah8, bl0) | 0;
        hi = Math.imul(ah8, bh0);
        lo = lo + Math.imul(al7, bl1) | 0;
        mid = mid + Math.imul(al7, bh1) | 0;
        mid = mid + Math.imul(ah7, bl1) | 0;
        hi = hi + Math.imul(ah7, bh1) | 0;
        lo = lo + Math.imul(al6, bl2) | 0;
        mid = mid + Math.imul(al6, bh2) | 0;
        mid = mid + Math.imul(ah6, bl2) | 0;
        hi = hi + Math.imul(ah6, bh2) | 0;
        lo = lo + Math.imul(al5, bl3) | 0;
        mid = mid + Math.imul(al5, bh3) | 0;
        mid = mid + Math.imul(ah5, bl3) | 0;
        hi = hi + Math.imul(ah5, bh3) | 0;
        lo = lo + Math.imul(al4, bl4) | 0;
        mid = mid + Math.imul(al4, bh4) | 0;
        mid = mid + Math.imul(ah4, bl4) | 0;
        hi = hi + Math.imul(ah4, bh4) | 0;
        lo = lo + Math.imul(al3, bl5) | 0;
        mid = mid + Math.imul(al3, bh5) | 0;
        mid = mid + Math.imul(ah3, bl5) | 0;
        hi = hi + Math.imul(ah3, bh5) | 0;
        lo = lo + Math.imul(al2, bl6) | 0;
        mid = mid + Math.imul(al2, bh6) | 0;
        mid = mid + Math.imul(ah2, bl6) | 0;
        hi = hi + Math.imul(ah2, bh6) | 0;
        lo = lo + Math.imul(al1, bl7) | 0;
        mid = mid + Math.imul(al1, bh7) | 0;
        mid = mid + Math.imul(ah1, bl7) | 0;
        hi = hi + Math.imul(ah1, bh7) | 0;
        lo = lo + Math.imul(al0, bl8) | 0;
        mid = mid + Math.imul(al0, bh8) | 0;
        mid = mid + Math.imul(ah0, bl8) | 0;
        hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0;
        w8 &= 67108863;
        lo = Math.imul(al9, bl0);
        mid = Math.imul(al9, bh0);
        mid = mid + Math.imul(ah9, bl0) | 0;
        hi = Math.imul(ah9, bh0);
        lo = lo + Math.imul(al8, bl1) | 0;
        mid = mid + Math.imul(al8, bh1) | 0;
        mid = mid + Math.imul(ah8, bl1) | 0;
        hi = hi + Math.imul(ah8, bh1) | 0;
        lo = lo + Math.imul(al7, bl2) | 0;
        mid = mid + Math.imul(al7, bh2) | 0;
        mid = mid + Math.imul(ah7, bl2) | 0;
        hi = hi + Math.imul(ah7, bh2) | 0;
        lo = lo + Math.imul(al6, bl3) | 0;
        mid = mid + Math.imul(al6, bh3) | 0;
        mid = mid + Math.imul(ah6, bl3) | 0;
        hi = hi + Math.imul(ah6, bh3) | 0;
        lo = lo + Math.imul(al5, bl4) | 0;
        mid = mid + Math.imul(al5, bh4) | 0;
        mid = mid + Math.imul(ah5, bl4) | 0;
        hi = hi + Math.imul(ah5, bh4) | 0;
        lo = lo + Math.imul(al4, bl5) | 0;
        mid = mid + Math.imul(al4, bh5) | 0;
        mid = mid + Math.imul(ah4, bl5) | 0;
        hi = hi + Math.imul(ah4, bh5) | 0;
        lo = lo + Math.imul(al3, bl6) | 0;
        mid = mid + Math.imul(al3, bh6) | 0;
        mid = mid + Math.imul(ah3, bl6) | 0;
        hi = hi + Math.imul(ah3, bh6) | 0;
        lo = lo + Math.imul(al2, bl7) | 0;
        mid = mid + Math.imul(al2, bh7) | 0;
        mid = mid + Math.imul(ah2, bl7) | 0;
        hi = hi + Math.imul(ah2, bh7) | 0;
        lo = lo + Math.imul(al1, bl8) | 0;
        mid = mid + Math.imul(al1, bh8) | 0;
        mid = mid + Math.imul(ah1, bl8) | 0;
        hi = hi + Math.imul(ah1, bh8) | 0;
        lo = lo + Math.imul(al0, bl9) | 0;
        mid = mid + Math.imul(al0, bh9) | 0;
        mid = mid + Math.imul(ah0, bl9) | 0;
        hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0;
        w9 &= 67108863;
        lo = Math.imul(al9, bl1);
        mid = Math.imul(al9, bh1);
        mid = mid + Math.imul(ah9, bl1) | 0;
        hi = Math.imul(ah9, bh1);
        lo = lo + Math.imul(al8, bl2) | 0;
        mid = mid + Math.imul(al8, bh2) | 0;
        mid = mid + Math.imul(ah8, bl2) | 0;
        hi = hi + Math.imul(ah8, bh2) | 0;
        lo = lo + Math.imul(al7, bl3) | 0;
        mid = mid + Math.imul(al7, bh3) | 0;
        mid = mid + Math.imul(ah7, bl3) | 0;
        hi = hi + Math.imul(ah7, bh3) | 0;
        lo = lo + Math.imul(al6, bl4) | 0;
        mid = mid + Math.imul(al6, bh4) | 0;
        mid = mid + Math.imul(ah6, bl4) | 0;
        hi = hi + Math.imul(ah6, bh4) | 0;
        lo = lo + Math.imul(al5, bl5) | 0;
        mid = mid + Math.imul(al5, bh5) | 0;
        mid = mid + Math.imul(ah5, bl5) | 0;
        hi = hi + Math.imul(ah5, bh5) | 0;
        lo = lo + Math.imul(al4, bl6) | 0;
        mid = mid + Math.imul(al4, bh6) | 0;
        mid = mid + Math.imul(ah4, bl6) | 0;
        hi = hi + Math.imul(ah4, bh6) | 0;
        lo = lo + Math.imul(al3, bl7) | 0;
        mid = mid + Math.imul(al3, bh7) | 0;
        mid = mid + Math.imul(ah3, bl7) | 0;
        hi = hi + Math.imul(ah3, bh7) | 0;
        lo = lo + Math.imul(al2, bl8) | 0;
        mid = mid + Math.imul(al2, bh8) | 0;
        mid = mid + Math.imul(ah2, bl8) | 0;
        hi = hi + Math.imul(ah2, bh8) | 0;
        lo = lo + Math.imul(al1, bl9) | 0;
        mid = mid + Math.imul(al1, bh9) | 0;
        mid = mid + Math.imul(ah1, bl9) | 0;
        hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0;
        w10 &= 67108863;
        lo = Math.imul(al9, bl2);
        mid = Math.imul(al9, bh2);
        mid = mid + Math.imul(ah9, bl2) | 0;
        hi = Math.imul(ah9, bh2);
        lo = lo + Math.imul(al8, bl3) | 0;
        mid = mid + Math.imul(al8, bh3) | 0;
        mid = mid + Math.imul(ah8, bl3) | 0;
        hi = hi + Math.imul(ah8, bh3) | 0;
        lo = lo + Math.imul(al7, bl4) | 0;
        mid = mid + Math.imul(al7, bh4) | 0;
        mid = mid + Math.imul(ah7, bl4) | 0;
        hi = hi + Math.imul(ah7, bh4) | 0;
        lo = lo + Math.imul(al6, bl5) | 0;
        mid = mid + Math.imul(al6, bh5) | 0;
        mid = mid + Math.imul(ah6, bl5) | 0;
        hi = hi + Math.imul(ah6, bh5) | 0;
        lo = lo + Math.imul(al5, bl6) | 0;
        mid = mid + Math.imul(al5, bh6) | 0;
        mid = mid + Math.imul(ah5, bl6) | 0;
        hi = hi + Math.imul(ah5, bh6) | 0;
        lo = lo + Math.imul(al4, bl7) | 0;
        mid = mid + Math.imul(al4, bh7) | 0;
        mid = mid + Math.imul(ah4, bl7) | 0;
        hi = hi + Math.imul(ah4, bh7) | 0;
        lo = lo + Math.imul(al3, bl8) | 0;
        mid = mid + Math.imul(al3, bh8) | 0;
        mid = mid + Math.imul(ah3, bl8) | 0;
        hi = hi + Math.imul(ah3, bh8) | 0;
        lo = lo + Math.imul(al2, bl9) | 0;
        mid = mid + Math.imul(al2, bh9) | 0;
        mid = mid + Math.imul(ah2, bl9) | 0;
        hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0;
        w11 &= 67108863;
        lo = Math.imul(al9, bl3);
        mid = Math.imul(al9, bh3);
        mid = mid + Math.imul(ah9, bl3) | 0;
        hi = Math.imul(ah9, bh3);
        lo = lo + Math.imul(al8, bl4) | 0;
        mid = mid + Math.imul(al8, bh4) | 0;
        mid = mid + Math.imul(ah8, bl4) | 0;
        hi = hi + Math.imul(ah8, bh4) | 0;
        lo = lo + Math.imul(al7, bl5) | 0;
        mid = mid + Math.imul(al7, bh5) | 0;
        mid = mid + Math.imul(ah7, bl5) | 0;
        hi = hi + Math.imul(ah7, bh5) | 0;
        lo = lo + Math.imul(al6, bl6) | 0;
        mid = mid + Math.imul(al6, bh6) | 0;
        mid = mid + Math.imul(ah6, bl6) | 0;
        hi = hi + Math.imul(ah6, bh6) | 0;
        lo = lo + Math.imul(al5, bl7) | 0;
        mid = mid + Math.imul(al5, bh7) | 0;
        mid = mid + Math.imul(ah5, bl7) | 0;
        hi = hi + Math.imul(ah5, bh7) | 0;
        lo = lo + Math.imul(al4, bl8) | 0;
        mid = mid + Math.imul(al4, bh8) | 0;
        mid = mid + Math.imul(ah4, bl8) | 0;
        hi = hi + Math.imul(ah4, bh8) | 0;
        lo = lo + Math.imul(al3, bl9) | 0;
        mid = mid + Math.imul(al3, bh9) | 0;
        mid = mid + Math.imul(ah3, bl9) | 0;
        hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0;
        w12 &= 67108863;
        lo = Math.imul(al9, bl4);
        mid = Math.imul(al9, bh4);
        mid = mid + Math.imul(ah9, bl4) | 0;
        hi = Math.imul(ah9, bh4);
        lo = lo + Math.imul(al8, bl5) | 0;
        mid = mid + Math.imul(al8, bh5) | 0;
        mid = mid + Math.imul(ah8, bl5) | 0;
        hi = hi + Math.imul(ah8, bh5) | 0;
        lo = lo + Math.imul(al7, bl6) | 0;
        mid = mid + Math.imul(al7, bh6) | 0;
        mid = mid + Math.imul(ah7, bl6) | 0;
        hi = hi + Math.imul(ah7, bh6) | 0;
        lo = lo + Math.imul(al6, bl7) | 0;
        mid = mid + Math.imul(al6, bh7) | 0;
        mid = mid + Math.imul(ah6, bl7) | 0;
        hi = hi + Math.imul(ah6, bh7) | 0;
        lo = lo + Math.imul(al5, bl8) | 0;
        mid = mid + Math.imul(al5, bh8) | 0;
        mid = mid + Math.imul(ah5, bl8) | 0;
        hi = hi + Math.imul(ah5, bh8) | 0;
        lo = lo + Math.imul(al4, bl9) | 0;
        mid = mid + Math.imul(al4, bh9) | 0;
        mid = mid + Math.imul(ah4, bl9) | 0;
        hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0;
        w13 &= 67108863;
        lo = Math.imul(al9, bl5);
        mid = Math.imul(al9, bh5);
        mid = mid + Math.imul(ah9, bl5) | 0;
        hi = Math.imul(ah9, bh5);
        lo = lo + Math.imul(al8, bl6) | 0;
        mid = mid + Math.imul(al8, bh6) | 0;
        mid = mid + Math.imul(ah8, bl6) | 0;
        hi = hi + Math.imul(ah8, bh6) | 0;
        lo = lo + Math.imul(al7, bl7) | 0;
        mid = mid + Math.imul(al7, bh7) | 0;
        mid = mid + Math.imul(ah7, bl7) | 0;
        hi = hi + Math.imul(ah7, bh7) | 0;
        lo = lo + Math.imul(al6, bl8) | 0;
        mid = mid + Math.imul(al6, bh8) | 0;
        mid = mid + Math.imul(ah6, bl8) | 0;
        hi = hi + Math.imul(ah6, bh8) | 0;
        lo = lo + Math.imul(al5, bl9) | 0;
        mid = mid + Math.imul(al5, bh9) | 0;
        mid = mid + Math.imul(ah5, bl9) | 0;
        hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0;
        w14 &= 67108863;
        lo = Math.imul(al9, bl6);
        mid = Math.imul(al9, bh6);
        mid = mid + Math.imul(ah9, bl6) | 0;
        hi = Math.imul(ah9, bh6);
        lo = lo + Math.imul(al8, bl7) | 0;
        mid = mid + Math.imul(al8, bh7) | 0;
        mid = mid + Math.imul(ah8, bl7) | 0;
        hi = hi + Math.imul(ah8, bh7) | 0;
        lo = lo + Math.imul(al7, bl8) | 0;
        mid = mid + Math.imul(al7, bh8) | 0;
        mid = mid + Math.imul(ah7, bl8) | 0;
        hi = hi + Math.imul(ah7, bh8) | 0;
        lo = lo + Math.imul(al6, bl9) | 0;
        mid = mid + Math.imul(al6, bh9) | 0;
        mid = mid + Math.imul(ah6, bl9) | 0;
        hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0;
        w15 &= 67108863;
        lo = Math.imul(al9, bl7);
        mid = Math.imul(al9, bh7);
        mid = mid + Math.imul(ah9, bl7) | 0;
        hi = Math.imul(ah9, bh7);
        lo = lo + Math.imul(al8, bl8) | 0;
        mid = mid + Math.imul(al8, bh8) | 0;
        mid = mid + Math.imul(ah8, bl8) | 0;
        hi = hi + Math.imul(ah8, bh8) | 0;
        lo = lo + Math.imul(al7, bl9) | 0;
        mid = mid + Math.imul(al7, bh9) | 0;
        mid = mid + Math.imul(ah7, bl9) | 0;
        hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0;
        w16 &= 67108863;
        lo = Math.imul(al9, bl8);
        mid = Math.imul(al9, bh8);
        mid = mid + Math.imul(ah9, bl8) | 0;
        hi = Math.imul(ah9, bh8);
        lo = lo + Math.imul(al8, bl9) | 0;
        mid = mid + Math.imul(al8, bh9) | 0;
        mid = mid + Math.imul(ah8, bl9) | 0;
        hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0;
        w17 &= 67108863;
        lo = Math.imul(al9, bl9);
        mid = Math.imul(al9, bh9);
        mid = mid + Math.imul(ah9, bl9) | 0;
        hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0;
        w18 &= 67108863;
        o2[0] = w0;
        o2[1] = w1;
        o2[2] = w2;
        o2[3] = w3;
        o2[4] = w4;
        o2[5] = w5;
        o2[6] = w6;
        o2[7] = w7;
        o2[8] = w8;
        o2[9] = w9;
        o2[10] = w10;
        o2[11] = w11;
        o2[12] = w12;
        o2[13] = w13;
        o2[14] = w14;
        o2[15] = w15;
        o2[16] = w16;
        o2[17] = w17;
        o2[18] = w18;
        if (c2 !== 0) {
          o2[19] = c2;
          out.length++;
        }
        return out;
      };
      if (!Math.imul) {
        comb10MulTo = smallMulTo;
      }
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        out.length = self2.length + num.length;
        var carry = 0;
        var hncarry = 0;
        for (var k2 = 0; k2 < out.length - 1; k2++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863;
          var maxJ = Math.min(k2, num.length - 1);
          for (var j = Math.max(0, k2 - self2.length + 1); j <= maxJ; j++) {
            var i2 = k2 - j;
            var a2 = self2.words[i2] | 0;
            var b2 = num.words[j] | 0;
            var r2 = a2 * b2;
            var lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0;
            lo = lo + rword | 0;
            rword = lo & 67108863;
            ncarry = ncarry + (lo >>> 26) | 0;
            hncarry += ncarry >>> 26;
            ncarry &= 67108863;
          }
          out.words[k2] = rword;
          carry = ncarry;
          ncarry = hncarry;
        }
        if (carry !== 0) {
          out.words[k2] = carry;
        } else {
          out.length--;
        }
        return out._strip();
      }
      function jumboMulTo(self2, num, out) {
        return bigMulTo(self2, num, out);
      }
      BN.prototype.mulTo = function mulTo(num, out) {
        var res;
        var len = this.length + num.length;
        if (this.length === 10 && num.length === 10) {
          res = comb10MulTo(this, num, out);
        } else if (len < 63) {
          res = smallMulTo(this, num, out);
        } else if (len < 1024) {
          res = bigMulTo(this, num, out);
        } else {
          res = jumboMulTo(this, num, out);
        }
        return res;
      };
      BN.prototype.mul = function mul(num) {
        var out = new BN(null);
        out.words = new Array(this.length + num.length);
        return this.mulTo(num, out);
      };
      BN.prototype.mulf = function mulf(num) {
        var out = new BN(null);
        out.words = new Array(this.length + num.length);
        return jumboMulTo(this, num, out);
      };
      BN.prototype.imul = function imul(num) {
        return this.clone().mulTo(num, this);
      };
      BN.prototype.imuln = function imuln(num) {
        var isNegNum = num < 0;
        if (isNegNum) num = -num;
        assert(typeof num === "number");
        assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0; i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num;
          var lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26;
          carry += w / 67108864 | 0;
          carry += lo >>> 26;
          this.words[i2] = lo & 67108863;
        }
        if (carry !== 0) {
          this.words[i2] = carry;
          this.length++;
        }
        this.length = num === 0 ? 1 : this.length;
        return isNegNum ? this.ineg() : this;
      };
      BN.prototype.muln = function muln(num) {
        return this.clone().imuln(num);
      };
      BN.prototype.sqr = function sqr() {
        return this.mul(this);
      };
      BN.prototype.isqr = function isqr() {
        return this.imul(this.clone());
      };
      BN.prototype.pow = function pow2(num) {
        var w = toBitArray(num);
        if (w.length === 0) return new BN(1);
        var res = this;
        for (var i2 = 0; i2 < w.length; i2++, res = res.sqr()) {
          if (w[i2] !== 0) break;
        }
        if (++i2 < w.length) {
          for (var q = res.sqr(); i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0) continue;
            res = res.mul(q);
          }
        }
        return res;
      };
      BN.prototype.iushln = function iushln(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26;
        var s2 = (bits - r2) / 26;
        var carryMask = 67108863 >>> 26 - r2 << 26 - r2;
        var i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0; i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask;
            var c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry;
            carry = newCarry >>> 26 - r2;
          }
          if (carry) {
            this.words[i2] = carry;
            this.length++;
          }
        }
        if (s2 !== 0) {
          for (i2 = this.length - 1; i2 >= 0; i2--) {
            this.words[i2 + s2] = this.words[i2];
          }
          for (i2 = 0; i2 < s2; i2++) {
            this.words[i2] = 0;
          }
          this.length += s2;
        }
        return this._strip();
      };
      BN.prototype.ishln = function ishln(bits) {
        assert(this.negative === 0);
        return this.iushln(bits);
      };
      BN.prototype.iushrn = function iushrn(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h2;
        if (hint) {
          h2 = (hint - hint % 26) / 26;
        } else {
          h2 = 0;
        }
        var r2 = bits % 26;
        var s2 = Math.min((bits - r2) / 26, this.length);
        var mask = 67108863 ^ 67108863 >>> r2 << r2;
        var maskedWords = extended;
        h2 -= s2;
        h2 = Math.max(0, h2);
        if (maskedWords) {
          for (var i2 = 0; i2 < s2; i2++) {
            maskedWords.words[i2] = this.words[i2];
          }
          maskedWords.length = s2;
        }
        if (s2 === 0) ;
        else if (this.length > s2) {
          this.length -= s2;
          for (i2 = 0; i2 < this.length; i2++) {
            this.words[i2] = this.words[i2 + s2];
          }
        } else {
          this.words[0] = 0;
          this.length = 1;
        }
        var carry = 0;
        for (i2 = this.length - 1; i2 >= 0 && (carry !== 0 || i2 >= h2); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2;
          carry = word & mask;
        }
        if (maskedWords && carry !== 0) {
          maskedWords.words[maskedWords.length++] = carry;
        }
        if (this.length === 0) {
          this.words[0] = 0;
          this.length = 1;
        }
        return this._strip();
      };
      BN.prototype.ishrn = function ishrn(bits, hint, extended) {
        assert(this.negative === 0);
        return this.iushrn(bits, hint, extended);
      };
      BN.prototype.shln = function shln(bits) {
        return this.clone().ishln(bits);
      };
      BN.prototype.ushln = function ushln(bits) {
        return this.clone().iushln(bits);
      };
      BN.prototype.shrn = function shrn(bits) {
        return this.clone().ishrn(bits);
      };
      BN.prototype.ushrn = function ushrn(bits) {
        return this.clone().iushrn(bits);
      };
      BN.prototype.testn = function testn(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26;
        var s2 = (bit - r2) / 26;
        var q = 1 << r2;
        if (this.length <= s2) return false;
        var w = this.words[s2];
        return !!(w & q);
      };
      BN.prototype.imaskn = function imaskn(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26;
        var s2 = (bits - r2) / 26;
        assert(this.negative === 0, "imaskn works only with positive numbers");
        if (this.length <= s2) {
          return this;
        }
        if (r2 !== 0) {
          s2++;
        }
        this.length = Math.min(s2, this.length);
        if (r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this._strip();
      };
      BN.prototype.maskn = function maskn(bits) {
        return this.clone().imaskn(bits);
      };
      BN.prototype.iaddn = function iaddn(num) {
        assert(typeof num === "number");
        assert(num < 67108864);
        if (num < 0) return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) <= num) {
            this.words[0] = num - (this.words[0] | 0);
            this.negative = 0;
            return this;
          }
          this.negative = 0;
          this.isubn(num);
          this.negative = 1;
          return this;
        }
        return this._iaddn(num);
      };
      BN.prototype._iaddn = function _iaddn(num) {
        this.words[0] += num;
        for (var i2 = 0; i2 < this.length && this.words[i2] >= 67108864; i2++) {
          this.words[i2] -= 67108864;
          if (i2 === this.length - 1) {
            this.words[i2 + 1] = 1;
          } else {
            this.words[i2 + 1]++;
          }
        }
        this.length = Math.max(this.length, i2 + 1);
        return this;
      };
      BN.prototype.isubn = function isubn(num) {
        assert(typeof num === "number");
        assert(num < 67108864);
        if (num < 0) return this.iaddn(-num);
        if (this.negative !== 0) {
          this.negative = 0;
          this.iaddn(num);
          this.negative = 1;
          return this;
        }
        this.words[0] -= num;
        if (this.length === 1 && this.words[0] < 0) {
          this.words[0] = -this.words[0];
          this.negative = 1;
        } else {
          for (var i2 = 0; i2 < this.length && this.words[i2] < 0; i2++) {
            this.words[i2] += 67108864;
            this.words[i2 + 1] -= 1;
          }
        }
        return this._strip();
      };
      BN.prototype.addn = function addn(num) {
        return this.clone().iaddn(num);
      };
      BN.prototype.subn = function subn(num) {
        return this.clone().isubn(num);
      };
      BN.prototype.iabs = function iabs() {
        this.negative = 0;
        return this;
      };
      BN.prototype.abs = function abs2() {
        return this.clone().iabs();
      };
      BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
        var len = num.length + shift;
        var i2;
        this._expand(len);
        var w;
        var carry = 0;
        for (i2 = 0; i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863;
          carry = (w >> 26) - (right / 67108864 | 0);
          this.words[i2 + shift] = w & 67108863;
        }
        for (; i2 < this.length - shift; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          carry = w >> 26;
          this.words[i2 + shift] = w & 67108863;
        }
        if (carry === 0) return this._strip();
        assert(carry === -1);
        carry = 0;
        for (i2 = 0; i2 < this.length; i2++) {
          w = -(this.words[i2] | 0) + carry;
          carry = w >> 26;
          this.words[i2] = w & 67108863;
        }
        this.negative = 1;
        return this._strip();
      };
      BN.prototype._wordDiv = function _wordDiv(num, mode) {
        var shift = this.length - num.length;
        var a2 = this.clone();
        var b2 = num;
        var bhi = b2.words[b2.length - 1] | 0;
        var bhiBits = this._countBits(bhi);
        shift = 26 - bhiBits;
        if (shift !== 0) {
          b2 = b2.ushln(shift);
          a2.iushln(shift);
          bhi = b2.words[b2.length - 1] | 0;
        }
        var m = a2.length - b2.length;
        var q;
        if (mode !== "mod") {
          q = new BN(null);
          q.length = m + 1;
          q.words = new Array(q.length);
          for (var i2 = 0; i2 < q.length; i2++) {
            q.words[i2] = 0;
          }
        }
        var diff = a2.clone()._ishlnsubmul(b2, 1, m);
        if (diff.negative === 0) {
          a2 = diff;
          if (q) {
            q.words[m] = 1;
          }
        }
        for (var j = m - 1; j >= 0; j--) {
          var qj = (a2.words[b2.length + j] | 0) * 67108864 + (a2.words[b2.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863);
          a2._ishlnsubmul(b2, qj, j);
          while (a2.negative !== 0) {
            qj--;
            a2.negative = 0;
            a2._ishlnsubmul(b2, 1, j);
            if (!a2.isZero()) {
              a2.negative ^= 1;
            }
          }
          if (q) {
            q.words[j] = qj;
          }
        }
        if (q) {
          q._strip();
        }
        a2._strip();
        if (mode !== "div" && shift !== 0) {
          a2.iushrn(shift);
        }
        return {
          div: q || null,
          mod: a2
        };
      };
      BN.prototype.divmod = function divmod(num, mode, positive) {
        assert(!num.isZero());
        if (this.isZero()) {
          return {
            div: new BN(0),
            mod: new BN(0)
          };
        }
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          res = this.neg().divmod(num, mode);
          if (mode !== "mod") {
            div = res.div.neg();
          }
          if (mode !== "div") {
            mod = res.mod.neg();
            if (positive && mod.negative !== 0) {
              mod.iadd(num);
            }
          }
          return {
            div,
            mod
          };
        }
        if (this.negative === 0 && num.negative !== 0) {
          res = this.divmod(num.neg(), mode);
          if (mode !== "mod") {
            div = res.div.neg();
          }
          return {
            div,
            mod: res.mod
          };
        }
        if ((this.negative & num.negative) !== 0) {
          res = this.neg().divmod(num.neg(), mode);
          if (mode !== "div") {
            mod = res.mod.neg();
            if (positive && mod.negative !== 0) {
              mod.isub(num);
            }
          }
          return {
            div: res.div,
            mod
          };
        }
        if (num.length > this.length || this.cmp(num) < 0) {
          return {
            div: new BN(0),
            mod: this
          };
        }
        if (num.length === 1) {
          if (mode === "div") {
            return {
              div: this.divn(num.words[0]),
              mod: null
            };
          }
          if (mode === "mod") {
            return {
              div: null,
              mod: new BN(this.modrn(num.words[0]))
            };
          }
          return {
            div: this.divn(num.words[0]),
            mod: new BN(this.modrn(num.words[0]))
          };
        }
        return this._wordDiv(num, mode);
      };
      BN.prototype.div = function div(num) {
        return this.divmod(num, "div", false).div;
      };
      BN.prototype.mod = function mod(num) {
        return this.divmod(num, "mod", false).mod;
      };
      BN.prototype.umod = function umod(num) {
        return this.divmod(num, "mod", true).mod;
      };
      BN.prototype.divRound = function divRound(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero()) return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
        var half = num.ushrn(1);
        var r2 = num.andln(1);
        var cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      };
      BN.prototype.modrn = function modrn(num) {
        var isNegNum = num < 0;
        if (isNegNum) num = -num;
        assert(num <= 67108863);
        var p2 = (1 << 26) % num;
        var acc = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        }
        return isNegNum ? -acc : acc;
      };
      BN.prototype.modn = function modn(num) {
        return this.modrn(num);
      };
      BN.prototype.idivn = function idivn(num) {
        var isNegNum = num < 0;
        if (isNegNum) num = -num;
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0;
          carry = w % num;
        }
        this._strip();
        return isNegNum ? this.ineg() : this;
      };
      BN.prototype.divn = function divn(num) {
        return this.clone().idivn(num);
      };
      BN.prototype.egcd = function egcd(p2) {
        assert(p2.negative === 0);
        assert(!p2.isZero());
        var x2 = this;
        var y2 = p2.clone();
        if (x2.negative !== 0) {
          x2 = x2.umod(p2);
        } else {
          x2 = x2.clone();
        }
        var A2 = new BN(1);
        var B2 = new BN(0);
        var C2 = new BN(0);
        var D = new BN(1);
        var g = 0;
        while (x2.isEven() && y2.isEven()) {
          x2.iushrn(1);
          y2.iushrn(1);
          ++g;
        }
        var yp = y2.clone();
        var xp = x2.clone();
        while (!x2.isZero()) {
          for (var i2 = 0, im = 1; (x2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1) ;
          if (i2 > 0) {
            x2.iushrn(i2);
            while (i2-- > 0) {
              if (A2.isOdd() || B2.isOdd()) {
                A2.iadd(yp);
                B2.isub(xp);
              }
              A2.iushrn(1);
              B2.iushrn(1);
            }
          }
          for (var j = 0, jm = 1; (y2.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
          if (j > 0) {
            y2.iushrn(j);
            while (j-- > 0) {
              if (C2.isOdd() || D.isOdd()) {
                C2.iadd(yp);
                D.isub(xp);
              }
              C2.iushrn(1);
              D.iushrn(1);
            }
          }
          if (x2.cmp(y2) >= 0) {
            x2.isub(y2);
            A2.isub(C2);
            B2.isub(D);
          } else {
            y2.isub(x2);
            C2.isub(A2);
            D.isub(B2);
          }
        }
        return {
          a: C2,
          b: D,
          gcd: y2.iushln(g)
        };
      };
      BN.prototype._invmp = function _invmp(p2) {
        assert(p2.negative === 0);
        assert(!p2.isZero());
        var a2 = this;
        var b2 = p2.clone();
        if (a2.negative !== 0) {
          a2 = a2.umod(p2);
        } else {
          a2 = a2.clone();
        }
        var x1 = new BN(1);
        var x2 = new BN(0);
        var delta = b2.clone();
        while (a2.cmpn(1) > 0 && b2.cmpn(1) > 0) {
          for (var i2 = 0, im = 1; (a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1) ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd()) {
                x1.iadd(delta);
              }
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1; (b2.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1) ;
          if (j > 0) {
            b2.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd()) {
                x2.iadd(delta);
              }
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b2) >= 0) {
            a2.isub(b2);
            x1.isub(x2);
          } else {
            b2.isub(a2);
            x2.isub(x1);
          }
        }
        var res;
        if (a2.cmpn(1) === 0) {
          res = x1;
        } else {
          res = x2;
        }
        if (res.cmpn(0) < 0) {
          res.iadd(p2);
        }
        return res;
      };
      BN.prototype.gcd = function gcd(num) {
        if (this.isZero()) return num.abs();
        if (num.isZero()) return this.abs();
        var a2 = this.clone();
        var b2 = num.clone();
        a2.negative = 0;
        b2.negative = 0;
        for (var shift = 0; a2.isEven() && b2.isEven(); shift++) {
          a2.iushrn(1);
          b2.iushrn(1);
        }
        do {
          while (a2.isEven()) {
            a2.iushrn(1);
          }
          while (b2.isEven()) {
            b2.iushrn(1);
          }
          var r2 = a2.cmp(b2);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b2;
            b2 = t2;
          } else if (r2 === 0 || b2.cmpn(1) === 0) {
            break;
          }
          a2.isub(b2);
        } while (true);
        return b2.iushln(shift);
      };
      BN.prototype.invm = function invm(num) {
        return this.egcd(num).a.umod(num);
      };
      BN.prototype.isEven = function isEven() {
        return (this.words[0] & 1) === 0;
      };
      BN.prototype.isOdd = function isOdd() {
        return (this.words[0] & 1) === 1;
      };
      BN.prototype.andln = function andln(num) {
        return this.words[0] & num;
      };
      BN.prototype.bincn = function bincn(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26;
        var s2 = (bit - r2) / 26;
        var q = 1 << r2;
        if (this.length <= s2) {
          this._expand(s2 + 1);
          this.words[s2] |= q;
          return this;
        }
        var carry = q;
        for (var i2 = s2; carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry;
          carry = w >>> 26;
          w &= 67108863;
          this.words[i2] = w;
        }
        if (carry !== 0) {
          this.words[i2] = carry;
          this.length++;
        }
        return this;
      };
      BN.prototype.isZero = function isZero() {
        return this.length === 1 && this.words[0] === 0;
      };
      BN.prototype.cmpn = function cmpn(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative) return -1;
        if (this.negative === 0 && negative) return 1;
        this._strip();
        var res;
        if (this.length > 1) {
          res = 1;
        } else {
          if (negative) {
            num = -num;
          }
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0) return -res | 0;
        return res;
      };
      BN.prototype.cmp = function cmp(num) {
        if (this.negative !== 0 && num.negative === 0) return -1;
        if (this.negative === 0 && num.negative !== 0) return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0) return -res | 0;
        return res;
      };
      BN.prototype.ucmp = function ucmp(num) {
        if (this.length > num.length) return 1;
        if (this.length < num.length) return -1;
        var res = 0;
        for (var i2 = this.length - 1; i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0;
          var b2 = num.words[i2] | 0;
          if (a2 === b2) continue;
          if (a2 < b2) {
            res = -1;
          } else if (a2 > b2) {
            res = 1;
          }
          break;
        }
        return res;
      };
      BN.prototype.gtn = function gtn(num) {
        return this.cmpn(num) === 1;
      };
      BN.prototype.gt = function gt(num) {
        return this.cmp(num) === 1;
      };
      BN.prototype.gten = function gten(num) {
        return this.cmpn(num) >= 0;
      };
      BN.prototype.gte = function gte(num) {
        return this.cmp(num) >= 0;
      };
      BN.prototype.ltn = function ltn(num) {
        return this.cmpn(num) === -1;
      };
      BN.prototype.lt = function lt(num) {
        return this.cmp(num) === -1;
      };
      BN.prototype.lten = function lten(num) {
        return this.cmpn(num) <= 0;
      };
      BN.prototype.lte = function lte(num) {
        return this.cmp(num) <= 0;
      };
      BN.prototype.eqn = function eqn(num) {
        return this.cmpn(num) === 0;
      };
      BN.prototype.eq = function eq(num) {
        return this.cmp(num) === 0;
      };
      BN.red = function red(num) {
        return new Red(num);
      };
      BN.prototype.toRed = function toRed(ctx) {
        assert(!this.red, "Already a number in reduction context");
        assert(this.negative === 0, "red works only with positives");
        return ctx.convertTo(this)._forceRed(ctx);
      };
      BN.prototype.fromRed = function fromRed() {
        assert(this.red, "fromRed works only with numbers in reduction context");
        return this.red.convertFrom(this);
      };
      BN.prototype._forceRed = function _forceRed(ctx) {
        this.red = ctx;
        return this;
      };
      BN.prototype.forceRed = function forceRed(ctx) {
        assert(!this.red, "Already a number in reduction context");
        return this._forceRed(ctx);
      };
      BN.prototype.redAdd = function redAdd(num) {
        assert(this.red, "redAdd works only with red numbers");
        return this.red.add(this, num);
      };
      BN.prototype.redIAdd = function redIAdd(num) {
        assert(this.red, "redIAdd works only with red numbers");
        return this.red.iadd(this, num);
      };
      BN.prototype.redSub = function redSub(num) {
        assert(this.red, "redSub works only with red numbers");
        return this.red.sub(this, num);
      };
      BN.prototype.redISub = function redISub(num) {
        assert(this.red, "redISub works only with red numbers");
        return this.red.isub(this, num);
      };
      BN.prototype.redShl = function redShl(num) {
        assert(this.red, "redShl works only with red numbers");
        return this.red.shl(this, num);
      };
      BN.prototype.redMul = function redMul(num) {
        assert(this.red, "redMul works only with red numbers");
        this.red._verify2(this, num);
        return this.red.mul(this, num);
      };
      BN.prototype.redIMul = function redIMul(num) {
        assert(this.red, "redMul works only with red numbers");
        this.red._verify2(this, num);
        return this.red.imul(this, num);
      };
      BN.prototype.redSqr = function redSqr() {
        assert(this.red, "redSqr works only with red numbers");
        this.red._verify1(this);
        return this.red.sqr(this);
      };
      BN.prototype.redISqr = function redISqr() {
        assert(this.red, "redISqr works only with red numbers");
        this.red._verify1(this);
        return this.red.isqr(this);
      };
      BN.prototype.redSqrt = function redSqrt() {
        assert(this.red, "redSqrt works only with red numbers");
        this.red._verify1(this);
        return this.red.sqrt(this);
      };
      BN.prototype.redInvm = function redInvm() {
        assert(this.red, "redInvm works only with red numbers");
        this.red._verify1(this);
        return this.red.invm(this);
      };
      BN.prototype.redNeg = function redNeg() {
        assert(this.red, "redNeg works only with red numbers");
        this.red._verify1(this);
        return this.red.neg(this);
      };
      BN.prototype.redPow = function redPow(num) {
        assert(this.red && !num.red, "redPow(normalNum)");
        this.red._verify1(this);
        return this.red.pow(this, num);
      };
      var primes = {
        k256: null,
        p224: null,
        p192: null,
        p25519: null
      };
      function MPrime(name, p2) {
        this.name = name;
        this.p = new BN(p2, 16);
        this.n = this.p.bitLength();
        this.k = new BN(1).iushln(this.n).isub(this.p);
        this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function _tmp() {
        var tmp = new BN(null);
        tmp.words = new Array(Math.ceil(this.n / 13));
        return tmp;
      };
      MPrime.prototype.ireduce = function ireduce(num) {
        var r2 = num;
        var rlen;
        do {
          this.split(r2, this.tmp);
          r2 = this.imulK(r2);
          r2 = r2.iadd(this.tmp);
          rlen = r2.bitLength();
        } while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0) {
          r2.words[0] = 0;
          r2.length = 1;
        } else if (cmp > 0) {
          r2.isub(this.p);
        } else {
          if (r2.strip !== void 0) {
            r2.strip();
          } else {
            r2._strip();
          }
        }
        return r2;
      };
      MPrime.prototype.split = function split(input, out) {
        input.iushrn(this.n, 0, out);
      };
      MPrime.prototype.imulK = function imulK(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(
          this,
          "k256",
          "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"
        );
      }
      inherits(K256, MPrime);
      K256.prototype.split = function split(input, output) {
        var mask = 4194303;
        var outLen = Math.min(input.length, 9);
        for (var i2 = 0; i2 < outLen; i2++) {
          output.words[i2] = input.words[i2];
        }
        output.length = outLen;
        if (input.length <= 9) {
          input.words[0] = 0;
          input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10; i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22;
          prev = next;
        }
        prev >>>= 22;
        input.words[i2 - 10] = prev;
        if (prev === 0 && input.length > 10) {
          input.length -= 10;
        } else {
          input.length -= 9;
        }
      };
      K256.prototype.imulK = function imulK(num) {
        num.words[num.length] = 0;
        num.words[num.length + 1] = 0;
        num.length += 2;
        var lo = 0;
        for (var i2 = 0; i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977;
          num.words[i2] = lo & 67108863;
          lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          num.length--;
          if (num.words[num.length - 1] === 0) {
            num.length--;
          }
        }
        return num;
      };
      function P224() {
        MPrime.call(
          this,
          "p224",
          "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"
        );
      }
      inherits(P224, MPrime);
      function P192() {
        MPrime.call(
          this,
          "p192",
          "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"
        );
      }
      inherits(P192, MPrime);
      function P25519() {
        MPrime.call(
          this,
          "25519",
          "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"
        );
      }
      inherits(P25519, MPrime);
      P25519.prototype.imulK = function imulK(num) {
        var carry = 0;
        for (var i2 = 0; i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry;
          var lo = hi & 67108863;
          hi >>>= 26;
          num.words[i2] = lo;
          carry = hi;
        }
        if (carry !== 0) {
          num.words[num.length++] = carry;
        }
        return num;
      };
      BN._prime = function prime(name) {
        if (primes[name]) return primes[name];
        var prime2;
        if (name === "k256") {
          prime2 = new K256();
        } else if (name === "p224") {
          prime2 = new P224();
        } else if (name === "p192") {
          prime2 = new P192();
        } else if (name === "p25519") {
          prime2 = new P25519();
        } else {
          throw new Error("Unknown prime " + name);
        }
        primes[name] = prime2;
        return prime2;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p;
          this.prime = prime;
        } else {
          assert(m.gtn(1), "modulus must be greater than 1");
          this.m = m;
          this.prime = null;
        }
      }
      Red.prototype._verify1 = function _verify1(a2) {
        assert(a2.negative === 0, "red works only with positives");
        assert(a2.red, "red works only with red numbers");
      };
      Red.prototype._verify2 = function _verify2(a2, b2) {
        assert((a2.negative | b2.negative) === 0, "red works only with positives");
        assert(
          a2.red && a2.red === b2.red,
          "red works only with red numbers"
        );
      };
      Red.prototype.imod = function imod(a2) {
        if (this.prime) return this.prime.ireduce(a2)._forceRed(this);
        move(a2, a2.umod(this.m)._forceRed(this));
        return a2;
      };
      Red.prototype.neg = function neg(a2) {
        if (a2.isZero()) {
          return a2.clone();
        }
        return this.m.sub(a2)._forceRed(this);
      };
      Red.prototype.add = function add2(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.add(b2);
        if (res.cmp(this.m) >= 0) {
          res.isub(this.m);
        }
        return res._forceRed(this);
      };
      Red.prototype.iadd = function iadd(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.iadd(b2);
        if (res.cmp(this.m) >= 0) {
          res.isub(this.m);
        }
        return res;
      };
      Red.prototype.sub = function sub(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.sub(b2);
        if (res.cmpn(0) < 0) {
          res.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Red.prototype.isub = function isub(a2, b2) {
        this._verify2(a2, b2);
        var res = a2.isub(b2);
        if (res.cmpn(0) < 0) {
          res.iadd(this.m);
        }
        return res;
      };
      Red.prototype.shl = function shl(a2, num) {
        this._verify1(a2);
        return this.imod(a2.ushln(num));
      };
      Red.prototype.imul = function imul(a2, b2) {
        this._verify2(a2, b2);
        return this.imod(a2.imul(b2));
      };
      Red.prototype.mul = function mul(a2, b2) {
        this._verify2(a2, b2);
        return this.imod(a2.mul(b2));
      };
      Red.prototype.isqr = function isqr(a2) {
        return this.imul(a2, a2.clone());
      };
      Red.prototype.sqr = function sqr(a2) {
        return this.mul(a2, a2);
      };
      Red.prototype.sqrt = function sqrt(a2) {
        if (a2.isZero()) return a2.clone();
        var mod3 = this.m.andln(3);
        assert(mod3 % 2 === 1);
        if (mod3 === 3) {
          var pow2 = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow2);
        }
        var q = this.m.subn(1);
        var s2 = 0;
        while (!q.isZero() && q.andln(1) === 0) {
          s2++;
          q.iushrn(1);
        }
        assert(!q.isZero());
        var one = new BN(1).toRed(this);
        var nOne = one.redNeg();
        var lpow = this.m.subn(1).iushrn(1);
        var z2 = this.m.bitLength();
        z2 = new BN(2 * z2 * z2).toRed(this);
        while (this.pow(z2, lpow).cmp(nOne) !== 0) {
          z2.redIAdd(nOne);
        }
        var c2 = this.pow(z2, q);
        var r2 = this.pow(a2, q.addn(1).iushrn(1));
        var t2 = this.pow(a2, q);
        var m = s2;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0; tmp.cmp(one) !== 0; i2++) {
            tmp = tmp.redSqr();
          }
          assert(i2 < m);
          var b2 = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b2);
          c2 = b2.redSqr();
          t2 = t2.redMul(c2);
          m = i2;
        }
        return r2;
      };
      Red.prototype.invm = function invm(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0) {
          inv.negative = 0;
          return this.imod(inv).redNeg();
        } else {
          return this.imod(inv);
        }
      };
      Red.prototype.pow = function pow2(a2, num) {
        if (num.isZero()) return new BN(1).toRed(this);
        if (num.cmpn(1) === 0) return a2.clone();
        var windowSize = 4;
        var wnd = new Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this);
        wnd[1] = a2;
        for (var i2 = 2; i2 < wnd.length; i2++) {
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        }
        var res = wnd[0];
        var current = 0;
        var currentLen = 0;
        var start = num.bitLength() % 26;
        if (start === 0) {
          start = 26;
        }
        for (i2 = num.length - 1; i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1; j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0]) {
              res = this.sqr(res);
            }
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            current <<= 1;
            current |= bit;
            currentLen++;
            if (currentLen !== windowSize && (i2 !== 0 || j !== 0)) continue;
            res = this.mul(res, wnd[current]);
            currentLen = 0;
            current = 0;
          }
          start = 26;
        }
        return res;
      };
      Red.prototype.convertTo = function convertTo(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      };
      Red.prototype.convertFrom = function convertFrom(num) {
        var res = num.clone();
        res.red = null;
        return res;
      };
      BN.mont = function mont2(num) {
        return new Mont(num);
      };
      function Mont(m) {
        Red.call(this, m);
        this.shift = this.m.bitLength();
        if (this.shift % 26 !== 0) {
          this.shift += 26 - this.shift % 26;
        }
        this.r = new BN(1).iushln(this.shift);
        this.r2 = this.imod(this.r.sqr());
        this.rinv = this.r._invmp(this.m);
        this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
        this.minv = this.minv.umod(this.r);
        this.minv = this.r.sub(this.minv);
      }
      inherits(Mont, Red);
      Mont.prototype.convertTo = function convertTo(num) {
        return this.imod(num.ushln(this.shift));
      };
      Mont.prototype.convertFrom = function convertFrom(num) {
        var r2 = this.imod(num.mul(this.rinv));
        r2.red = null;
        return r2;
      };
      Mont.prototype.imul = function imul(a2, b2) {
        if (a2.isZero() || b2.isZero()) {
          a2.words[0] = 0;
          a2.length = 1;
          return a2;
        }
        var t2 = a2.imul(b2);
        var c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
        var u2 = t2.isub(c2).iushrn(this.shift);
        var res = u2;
        if (u2.cmp(this.m) >= 0) {
          res = u2.isub(this.m);
        } else if (u2.cmpn(0) < 0) {
          res = u2.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Mont.prototype.mul = function mul(a2, b2) {
        if (a2.isZero() || b2.isZero()) return new BN(0)._forceRed(this);
        var t2 = a2.mul(b2);
        var c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
        var u2 = t2.isub(c2).iushrn(this.shift);
        var res = u2;
        if (u2.cmp(this.m) >= 0) {
          res = u2.isub(this.m);
        } else if (u2.cmpn(0) < 0) {
          res = u2.iadd(this.m);
        }
        return res._forceRed(this);
      };
      Mont.prototype.invm = function invm(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(module2, bn);
  })(bn$1);
  return bn$1.exports;
}
var browserifyRsa;
var hasRequiredBrowserifyRsa;
function requireBrowserifyRsa() {
  if (hasRequiredBrowserifyRsa) return browserifyRsa;
  hasRequiredBrowserifyRsa = 1;
  var BN = requireBn();
  var randomBytes = requireBrowser$e();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function getr(priv) {
    var len = priv.modulus.byteLength();
    var r2;
    do {
      r2 = new BN(randomBytes(len));
    } while (r2.cmp(priv.modulus) >= 0 || !r2.umod(priv.prime1) || !r2.umod(priv.prime2));
    return r2;
  }
  function blind(priv) {
    var r2 = getr(priv);
    var blinder = r2.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();
    return { blinder, unblinder: r2.invm(priv.modulus) };
  }
  function crt(msg, priv) {
    var blinds = blind(priv);
    var len = priv.modulus.byteLength();
    var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus);
    var c1 = blinded.toRed(BN.mont(priv.prime1));
    var c2 = blinded.toRed(BN.mont(priv.prime2));
    var qinv = priv.coefficient;
    var p2 = priv.prime1;
    var q = priv.prime2;
    var m1 = c1.redPow(priv.exponent1).fromRed();
    var m2 = c2.redPow(priv.exponent2).fromRed();
    var h2 = m1.isub(m2).imul(qinv).umod(p2).imul(q);
    return m2.iadd(h2).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer2, "be", len);
  }
  crt.getr = getr;
  browserifyRsa = crt;
  return browserifyRsa;
}
var elliptic = {};
const version$1 = "6.6.1";
const require$$0$1 = {
  version: version$1
};
var utils$3 = {};
var utils$2 = {};
var hasRequiredUtils$3;
function requireUtils$3() {
  if (hasRequiredUtils$3) return utils$2;
  hasRequiredUtils$3 = 1;
  (function(exports) {
    var utils2 = exports;
    function toArray(msg, enc) {
      if (Array.isArray(msg))
        return msg.slice();
      if (!msg)
        return [];
      var res = [];
      if (typeof msg !== "string") {
        for (var i2 = 0; i2 < msg.length; i2++)
          res[i2] = msg[i2] | 0;
        return res;
      }
      if (enc === "hex") {
        msg = msg.replace(/[^a-z0-9]+/ig, "");
        if (msg.length % 2 !== 0)
          msg = "0" + msg;
        for (var i2 = 0; i2 < msg.length; i2 += 2)
          res.push(parseInt(msg[i2] + msg[i2 + 1], 16));
      } else {
        for (var i2 = 0; i2 < msg.length; i2++) {
          var c2 = msg.charCodeAt(i2);
          var hi = c2 >> 8;
          var lo = c2 & 255;
          if (hi)
            res.push(hi, lo);
          else
            res.push(lo);
        }
      }
      return res;
    }
    utils2.toArray = toArray;
    function zero2(word) {
      if (word.length === 1)
        return "0" + word;
      else
        return word;
    }
    utils2.zero2 = zero2;
    function toHex2(msg) {
      var res = "";
      for (var i2 = 0; i2 < msg.length; i2++)
        res += zero2(msg[i2].toString(16));
      return res;
    }
    utils2.toHex = toHex2;
    utils2.encode = function encode2(arr, enc) {
      if (enc === "hex")
        return toHex2(arr);
      else
        return arr;
    };
  })(utils$2);
  return utils$2;
}
var hasRequiredUtils$2;
function requireUtils$2() {
  if (hasRequiredUtils$2) return utils$3;
  hasRequiredUtils$2 = 1;
  (function(exports) {
    var utils2 = exports;
    var BN = requireBn$1();
    var minAssert = requireMinimalisticAssert();
    var minUtils = requireUtils$3();
    utils2.assert = minAssert;
    utils2.toArray = minUtils.toArray;
    utils2.zero2 = minUtils.zero2;
    utils2.toHex = minUtils.toHex;
    utils2.encode = minUtils.encode;
    function getNAF(num, w, bits) {
      var naf = new Array(Math.max(num.bitLength(), bits) + 1);
      var i2;
      for (i2 = 0; i2 < naf.length; i2 += 1) {
        naf[i2] = 0;
      }
      var ws = 1 << w + 1;
      var k2 = num.clone();
      for (i2 = 0; i2 < naf.length; i2++) {
        var z2;
        var mod = k2.andln(ws - 1);
        if (k2.isOdd()) {
          if (mod > (ws >> 1) - 1)
            z2 = (ws >> 1) - mod;
          else
            z2 = mod;
          k2.isubn(z2);
        } else {
          z2 = 0;
        }
        naf[i2] = z2;
        k2.iushrn(1);
      }
      return naf;
    }
    utils2.getNAF = getNAF;
    function getJSF(k1, k2) {
      var jsf = [
        [],
        []
      ];
      k1 = k1.clone();
      k2 = k2.clone();
      var d1 = 0;
      var d2 = 0;
      var m8;
      while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
        var m14 = k1.andln(3) + d1 & 3;
        var m24 = k2.andln(3) + d2 & 3;
        if (m14 === 3)
          m14 = -1;
        if (m24 === 3)
          m24 = -1;
        var u1;
        if ((m14 & 1) === 0) {
          u1 = 0;
        } else {
          m8 = k1.andln(7) + d1 & 7;
          if ((m8 === 3 || m8 === 5) && m24 === 2)
            u1 = -m14;
          else
            u1 = m14;
        }
        jsf[0].push(u1);
        var u2;
        if ((m24 & 1) === 0) {
          u2 = 0;
        } else {
          m8 = k2.andln(7) + d2 & 7;
          if ((m8 === 3 || m8 === 5) && m14 === 2)
            u2 = -m24;
          else
            u2 = m24;
        }
        jsf[1].push(u2);
        if (2 * d1 === u1 + 1)
          d1 = 1 - d1;
        if (2 * d2 === u2 + 1)
          d2 = 1 - d2;
        k1.iushrn(1);
        k2.iushrn(1);
      }
      return jsf;
    }
    utils2.getJSF = getJSF;
    function cachedProperty(obj, name, computer) {
      var key2 = "_" + name;
      obj.prototype[name] = function cachedProperty2() {
        return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this);
      };
    }
    utils2.cachedProperty = cachedProperty;
    function parseBytes(bytes) {
      return typeof bytes === "string" ? utils2.toArray(bytes, "hex") : bytes;
    }
    utils2.parseBytes = parseBytes;
    function intFromLE(bytes) {
      return new BN(bytes, "hex", "le");
    }
    utils2.intFromLE = intFromLE;
  })(utils$3);
  return utils$3;
}
var curve$1 = {};
var base$1;
var hasRequiredBase$1;
function requireBase$1() {
  if (hasRequiredBase$1) return base$1;
  hasRequiredBase$1 = 1;
  var BN = requireBn$1();
  var utils2 = requireUtils$2();
  var getNAF = utils2.getNAF;
  var getJSF = utils2.getJSF;
  var assert = utils2.assert;
  function BaseCurve(type2, conf) {
    this.type = type2;
    this.p = new BN(conf.p, 16);
    this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
    this.zero = new BN(0).toRed(this.red);
    this.one = new BN(1).toRed(this.red);
    this.two = new BN(2).toRed(this.red);
    this.n = conf.n && new BN(conf.n, 16);
    this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
    this._wnafT1 = new Array(4);
    this._wnafT2 = new Array(4);
    this._wnafT3 = new Array(4);
    this._wnafT4 = new Array(4);
    this._bitLength = this.n ? this.n.bitLength() : 0;
    var adjustCount = this.n && this.p.div(this.n);
    if (!adjustCount || adjustCount.cmpn(100) > 0) {
      this.redN = null;
    } else {
      this._maxwellTrick = true;
      this.redN = this.n.toRed(this.red);
    }
  }
  base$1 = BaseCurve;
  BaseCurve.prototype.point = function point() {
    throw new Error("Not implemented");
  };
  BaseCurve.prototype.validate = function validate2() {
    throw new Error("Not implemented");
  };
  BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p2, k2) {
    assert(p2.precomputed);
    var doubles = p2._getDoubles();
    var naf = getNAF(k2, 1, this._bitLength);
    var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1);
    I /= 3;
    var repr = [];
    var j;
    var nafW;
    for (j = 0; j < naf.length; j += doubles.step) {
      nafW = 0;
      for (var l2 = j + doubles.step - 1; l2 >= j; l2--)
        nafW = (nafW << 1) + naf[l2];
      repr.push(nafW);
    }
    var a2 = this.jpoint(null, null, null);
    var b2 = this.jpoint(null, null, null);
    for (var i2 = I; i2 > 0; i2--) {
      for (j = 0; j < repr.length; j++) {
        nafW = repr[j];
        if (nafW === i2)
          b2 = b2.mixedAdd(doubles.points[j]);
        else if (nafW === -i2)
          b2 = b2.mixedAdd(doubles.points[j].neg());
      }
      a2 = a2.add(b2);
    }
    return a2.toP();
  };
  BaseCurve.prototype._wnafMul = function _wnafMul(p2, k2) {
    var w = 4;
    var nafPoints = p2._getNAFPoints(w);
    w = nafPoints.wnd;
    var wnd = nafPoints.points;
    var naf = getNAF(k2, w, this._bitLength);
    var acc = this.jpoint(null, null, null);
    for (var i2 = naf.length - 1; i2 >= 0; i2--) {
      for (var l2 = 0; i2 >= 0 && naf[i2] === 0; i2--)
        l2++;
      if (i2 >= 0)
        l2++;
      acc = acc.dblp(l2);
      if (i2 < 0)
        break;
      var z2 = naf[i2];
      assert(z2 !== 0);
      if (p2.type === "affine") {
        if (z2 > 0)
          acc = acc.mixedAdd(wnd[z2 - 1 >> 1]);
        else
          acc = acc.mixedAdd(wnd[-z2 - 1 >> 1].neg());
      } else {
        if (z2 > 0)
          acc = acc.add(wnd[z2 - 1 >> 1]);
        else
          acc = acc.add(wnd[-z2 - 1 >> 1].neg());
      }
    }
    return p2.type === "affine" ? acc.toP() : acc;
  };
  BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) {
    var wndWidth = this._wnafT1;
    var wnd = this._wnafT2;
    var naf = this._wnafT3;
    var max2 = 0;
    var i2;
    var j;
    var p2;
    for (i2 = 0; i2 < len; i2++) {
      p2 = points[i2];
      var nafPoints = p2._getNAFPoints(defW);
      wndWidth[i2] = nafPoints.wnd;
      wnd[i2] = nafPoints.points;
    }
    for (i2 = len - 1; i2 >= 1; i2 -= 2) {
      var a2 = i2 - 1;
      var b2 = i2;
      if (wndWidth[a2] !== 1 || wndWidth[b2] !== 1) {
        naf[a2] = getNAF(coeffs[a2], wndWidth[a2], this._bitLength);
        naf[b2] = getNAF(coeffs[b2], wndWidth[b2], this._bitLength);
        max2 = Math.max(naf[a2].length, max2);
        max2 = Math.max(naf[b2].length, max2);
        continue;
      }
      var comb = [
        points[a2],
        /* 1 */
        null,
        /* 3 */
        null,
        /* 5 */
        points[b2]
        /* 7 */
      ];
      if (points[a2].y.cmp(points[b2].y) === 0) {
        comb[1] = points[a2].add(points[b2]);
        comb[2] = points[a2].toJ().mixedAdd(points[b2].neg());
      } else if (points[a2].y.cmp(points[b2].y.redNeg()) === 0) {
        comb[1] = points[a2].toJ().mixedAdd(points[b2]);
        comb[2] = points[a2].add(points[b2].neg());
      } else {
        comb[1] = points[a2].toJ().mixedAdd(points[b2]);
        comb[2] = points[a2].toJ().mixedAdd(points[b2].neg());
      }
      var index2 = [
        -3,
        /* -1 -1 */
        -1,
        /* -1 0 */
        -5,
        /* -1 1 */
        -7,
        /* 0 -1 */
        0,
        /* 0 0 */
        7,
        /* 0 1 */
        5,
        /* 1 -1 */
        1,
        /* 1 0 */
        3
        /* 1 1 */
      ];
      var jsf = getJSF(coeffs[a2], coeffs[b2]);
      max2 = Math.max(jsf[0].length, max2);
      naf[a2] = new Array(max2);
      naf[b2] = new Array(max2);
      for (j = 0; j < max2; j++) {
        var ja = jsf[0][j] | 0;
        var jb = jsf[1][j] | 0;
        naf[a2][j] = index2[(ja + 1) * 3 + (jb + 1)];
        naf[b2][j] = 0;
        wnd[a2] = comb;
      }
    }
    var acc = this.jpoint(null, null, null);
    var tmp = this._wnafT4;
    for (i2 = max2; i2 >= 0; i2--) {
      var k2 = 0;
      while (i2 >= 0) {
        var zero = true;
        for (j = 0; j < len; j++) {
          tmp[j] = naf[j][i2] | 0;
          if (tmp[j] !== 0)
            zero = false;
        }
        if (!zero)
          break;
        k2++;
        i2--;
      }
      if (i2 >= 0)
        k2++;
      acc = acc.dblp(k2);
      if (i2 < 0)
        break;
      for (j = 0; j < len; j++) {
        var z2 = tmp[j];
        if (z2 === 0)
          continue;
        else if (z2 > 0)
          p2 = wnd[j][z2 - 1 >> 1];
        else if (z2 < 0)
          p2 = wnd[j][-z2 - 1 >> 1].neg();
        if (p2.type === "affine")
          acc = acc.mixedAdd(p2);
        else
          acc = acc.add(p2);
      }
    }
    for (i2 = 0; i2 < len; i2++)
      wnd[i2] = null;
    if (jacobianResult)
      return acc;
    else
      return acc.toP();
  };
  function BasePoint(curve2, type2) {
    this.curve = curve2;
    this.type = type2;
    this.precomputed = null;
  }
  BaseCurve.BasePoint = BasePoint;
  BasePoint.prototype.eq = function eq() {
    throw new Error("Not implemented");
  };
  BasePoint.prototype.validate = function validate2() {
    return this.curve.validate(this);
  };
  BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
    bytes = utils2.toArray(bytes, enc);
    var len = this.p.byteLength();
    if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) {
      if (bytes[0] === 6)
        assert(bytes[bytes.length - 1] % 2 === 0);
      else if (bytes[0] === 7)
        assert(bytes[bytes.length - 1] % 2 === 1);
      var res = this.point(
        bytes.slice(1, 1 + len),
        bytes.slice(1 + len, 1 + 2 * len)
      );
      return res;
    } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) {
      return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3);
    }
    throw new Error("Unknown point format");
  };
  BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
    return this.encode(enc, true);
  };
  BasePoint.prototype._encode = function _encode(compact) {
    var len = this.curve.p.byteLength();
    var x2 = this.getX().toArray("be", len);
    if (compact)
      return [this.getY().isEven() ? 2 : 3].concat(x2);
    return [4].concat(x2, this.getY().toArray("be", len));
  };
  BasePoint.prototype.encode = function encode2(enc, compact) {
    return utils2.encode(this._encode(compact), enc);
  };
  BasePoint.prototype.precompute = function precompute(power) {
    if (this.precomputed)
      return this;
    var precomputed = {
      doubles: null,
      naf: null,
      beta: null
    };
    precomputed.naf = this._getNAFPoints(8);
    precomputed.doubles = this._getDoubles(4, power);
    precomputed.beta = this._getBeta();
    this.precomputed = precomputed;
    return this;
  };
  BasePoint.prototype._hasDoubles = function _hasDoubles(k2) {
    if (!this.precomputed)
      return false;
    var doubles = this.precomputed.doubles;
    if (!doubles)
      return false;
    return doubles.points.length >= Math.ceil((k2.bitLength() + 1) / doubles.step);
  };
  BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
    if (this.precomputed && this.precomputed.doubles)
      return this.precomputed.doubles;
    var doubles = [this];
    var acc = this;
    for (var i2 = 0; i2 < power; i2 += step) {
      for (var j = 0; j < step; j++)
        acc = acc.dbl();
      doubles.push(acc);
    }
    return {
      step,
      points: doubles
    };
  };
  BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
    if (this.precomputed && this.precomputed.naf)
      return this.precomputed.naf;
    var res = [this];
    var max2 = (1 << wnd) - 1;
    var dbl = max2 === 1 ? null : this.dbl();
    for (var i2 = 1; i2 < max2; i2++)
      res[i2] = res[i2 - 1].add(dbl);
    return {
      wnd,
      points: res
    };
  };
  BasePoint.prototype._getBeta = function _getBeta() {
    return null;
  };
  BasePoint.prototype.dblp = function dblp(k2) {
    var r2 = this;
    for (var i2 = 0; i2 < k2; i2++)
      r2 = r2.dbl();
    return r2;
  };
  return base$1;
}
var short;
var hasRequiredShort;
function requireShort() {
  if (hasRequiredShort) return short;
  hasRequiredShort = 1;
  var utils2 = requireUtils$2();
  var BN = requireBn$1();
  var inherits = requireInherits_browser();
  var Base = requireBase$1();
  var assert = utils2.assert;
  function ShortCurve(conf) {
    Base.call(this, "short", conf);
    this.a = new BN(conf.a, 16).toRed(this.red);
    this.b = new BN(conf.b, 16).toRed(this.red);
    this.tinv = this.two.redInvm();
    this.zeroA = this.a.fromRed().cmpn(0) === 0;
    this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
    this.endo = this._getEndomorphism(conf);
    this._endoWnafT1 = new Array(4);
    this._endoWnafT2 = new Array(4);
  }
  inherits(ShortCurve, Base);
  short = ShortCurve;
  ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
    if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
      return;
    var beta;
    var lambda;
    if (conf.beta) {
      beta = new BN(conf.beta, 16).toRed(this.red);
    } else {
      var betas = this._getEndoRoots(this.p);
      beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
      beta = beta.toRed(this.red);
    }
    if (conf.lambda) {
      lambda = new BN(conf.lambda, 16);
    } else {
      var lambdas = this._getEndoRoots(this.n);
      if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
        lambda = lambdas[0];
      } else {
        lambda = lambdas[1];
        assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
      }
    }
    var basis;
    if (conf.basis) {
      basis = conf.basis.map(function(vec) {
        return {
          a: new BN(vec.a, 16),
          b: new BN(vec.b, 16)
        };
      });
    } else {
      basis = this._getEndoBasis(lambda);
    }
    return {
      beta,
      lambda,
      basis
    };
  };
  ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
    var red = num === this.p ? this.red : BN.mont(num);
    var tinv = new BN(2).toRed(red).redInvm();
    var ntinv = tinv.redNeg();
    var s2 = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
    var l1 = ntinv.redAdd(s2).fromRed();
    var l2 = ntinv.redSub(s2).fromRed();
    return [l1, l2];
  };
  ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
    var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
    var u2 = lambda;
    var v2 = this.n.clone();
    var x1 = new BN(1);
    var y1 = new BN(0);
    var x2 = new BN(0);
    var y2 = new BN(1);
    var a0;
    var b0;
    var a1;
    var b1;
    var a2;
    var b2;
    var prevR;
    var i2 = 0;
    var r2;
    var x3;
    while (u2.cmpn(0) !== 0) {
      var q = v2.div(u2);
      r2 = v2.sub(q.mul(u2));
      x3 = x2.sub(q.mul(x1));
      var y3 = y2.sub(q.mul(y1));
      if (!a1 && r2.cmp(aprxSqrt) < 0) {
        a0 = prevR.neg();
        b0 = x1;
        a1 = r2.neg();
        b1 = x3;
      } else if (a1 && ++i2 === 2) {
        break;
      }
      prevR = r2;
      v2 = u2;
      u2 = r2;
      x2 = x1;
      x1 = x3;
      y2 = y1;
      y1 = y3;
    }
    a2 = r2.neg();
    b2 = x3;
    var len1 = a1.sqr().add(b1.sqr());
    var len2 = a2.sqr().add(b2.sqr());
    if (len2.cmp(len1) >= 0) {
      a2 = a0;
      b2 = b0;
    }
    if (a1.negative) {
      a1 = a1.neg();
      b1 = b1.neg();
    }
    if (a2.negative) {
      a2 = a2.neg();
      b2 = b2.neg();
    }
    return [
      { a: a1, b: b1 },
      { a: a2, b: b2 }
    ];
  };
  ShortCurve.prototype._endoSplit = function _endoSplit(k2) {
    var basis = this.endo.basis;
    var v1 = basis[0];
    var v2 = basis[1];
    var c1 = v2.b.mul(k2).divRound(this.n);
    var c2 = v1.b.neg().mul(k2).divRound(this.n);
    var p1 = c1.mul(v1.a);
    var p2 = c2.mul(v2.a);
    var q1 = c1.mul(v1.b);
    var q2 = c2.mul(v2.b);
    var k1 = k2.sub(p1).sub(p2);
    var k22 = q1.add(q2).neg();
    return { k1, k2: k22 };
  };
  ShortCurve.prototype.pointFromX = function pointFromX(x2, odd) {
    x2 = new BN(x2, 16);
    if (!x2.red)
      x2 = x2.toRed(this.red);
    var y2 = x2.redSqr().redMul(x2).redIAdd(x2.redMul(this.a)).redIAdd(this.b);
    var y3 = y2.redSqrt();
    if (y3.redSqr().redSub(y2).cmp(this.zero) !== 0)
      throw new Error("invalid point");
    var isOdd = y3.fromRed().isOdd();
    if (odd && !isOdd || !odd && isOdd)
      y3 = y3.redNeg();
    return this.point(x2, y3);
  };
  ShortCurve.prototype.validate = function validate2(point) {
    if (point.inf)
      return true;
    var x2 = point.x;
    var y2 = point.y;
    var ax = this.a.redMul(x2);
    var rhs = x2.redSqr().redMul(x2).redIAdd(ax).redIAdd(this.b);
    return y2.redSqr().redISub(rhs).cmpn(0) === 0;
  };
  ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) {
    var npoints = this._endoWnafT1;
    var ncoeffs = this._endoWnafT2;
    for (var i2 = 0; i2 < points.length; i2++) {
      var split = this._endoSplit(coeffs[i2]);
      var p2 = points[i2];
      var beta = p2._getBeta();
      if (split.k1.negative) {
        split.k1.ineg();
        p2 = p2.neg(true);
      }
      if (split.k2.negative) {
        split.k2.ineg();
        beta = beta.neg(true);
      }
      npoints[i2 * 2] = p2;
      npoints[i2 * 2 + 1] = beta;
      ncoeffs[i2 * 2] = split.k1;
      ncoeffs[i2 * 2 + 1] = split.k2;
    }
    var res = this._wnafMulAdd(1, npoints, ncoeffs, i2 * 2, jacobianResult);
    for (var j = 0; j < i2 * 2; j++) {
      npoints[j] = null;
      ncoeffs[j] = null;
    }
    return res;
  };
  function Point2(curve2, x2, y2, isRed) {
    Base.BasePoint.call(this, curve2, "affine");
    if (x2 === null && y2 === null) {
      this.x = null;
      this.y = null;
      this.inf = true;
    } else {
      this.x = new BN(x2, 16);
      this.y = new BN(y2, 16);
      if (isRed) {
        this.x.forceRed(this.curve.red);
        this.y.forceRed(this.curve.red);
      }
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.y.red)
        this.y = this.y.toRed(this.curve.red);
      this.inf = false;
    }
  }
  inherits(Point2, Base.BasePoint);
  ShortCurve.prototype.point = function point(x2, y2, isRed) {
    return new Point2(this, x2, y2, isRed);
  };
  ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
    return Point2.fromJSON(this, obj, red);
  };
  Point2.prototype._getBeta = function _getBeta() {
    if (!this.curve.endo)
      return;
    var pre = this.precomputed;
    if (pre && pre.beta)
      return pre.beta;
    var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
    if (pre) {
      var curve2 = this.curve;
      var endoMul = function(p2) {
        return curve2.point(p2.x.redMul(curve2.endo.beta), p2.y);
      };
      pre.beta = beta;
      beta.precomputed = {
        beta: null,
        naf: pre.naf && {
          wnd: pre.naf.wnd,
          points: pre.naf.points.map(endoMul)
        },
        doubles: pre.doubles && {
          step: pre.doubles.step,
          points: pre.doubles.points.map(endoMul)
        }
      };
    }
    return beta;
  };
  Point2.prototype.toJSON = function toJSON() {
    if (!this.precomputed)
      return [this.x, this.y];
    return [this.x, this.y, this.precomputed && {
      doubles: this.precomputed.doubles && {
        step: this.precomputed.doubles.step,
        points: this.precomputed.doubles.points.slice(1)
      },
      naf: this.precomputed.naf && {
        wnd: this.precomputed.naf.wnd,
        points: this.precomputed.naf.points.slice(1)
      }
    }];
  };
  Point2.fromJSON = function fromJSON(curve2, obj, red) {
    if (typeof obj === "string")
      obj = JSON.parse(obj);
    var res = curve2.point(obj[0], obj[1], red);
    if (!obj[2])
      return res;
    function obj2point(obj2) {
      return curve2.point(obj2[0], obj2[1], red);
    }
    var pre = obj[2];
    res.precomputed = {
      beta: null,
      doubles: pre.doubles && {
        step: pre.doubles.step,
        points: [res].concat(pre.doubles.points.map(obj2point))
      },
      naf: pre.naf && {
        wnd: pre.naf.wnd,
        points: [res].concat(pre.naf.points.map(obj2point))
      }
    };
    return res;
  };
  Point2.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return "<EC Point Infinity>";
    return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " y: " + this.y.fromRed().toString(16, 2) + ">";
  };
  Point2.prototype.isInfinity = function isInfinity() {
    return this.inf;
  };
  Point2.prototype.add = function add2(p2) {
    if (this.inf)
      return p2;
    if (p2.inf)
      return this;
    if (this.eq(p2))
      return this.dbl();
    if (this.neg().eq(p2))
      return this.curve.point(null, null);
    if (this.x.cmp(p2.x) === 0)
      return this.curve.point(null, null);
    var c2 = this.y.redSub(p2.y);
    if (c2.cmpn(0) !== 0)
      c2 = c2.redMul(this.x.redSub(p2.x).redInvm());
    var nx = c2.redSqr().redISub(this.x).redISub(p2.x);
    var ny = c2.redMul(this.x.redSub(nx)).redISub(this.y);
    return this.curve.point(nx, ny);
  };
  Point2.prototype.dbl = function dbl() {
    if (this.inf)
      return this;
    var ys1 = this.y.redAdd(this.y);
    if (ys1.cmpn(0) === 0)
      return this.curve.point(null, null);
    var a2 = this.curve.a;
    var x2 = this.x.redSqr();
    var dyinv = ys1.redInvm();
    var c2 = x2.redAdd(x2).redIAdd(x2).redIAdd(a2).redMul(dyinv);
    var nx = c2.redSqr().redISub(this.x.redAdd(this.x));
    var ny = c2.redMul(this.x.redSub(nx)).redISub(this.y);
    return this.curve.point(nx, ny);
  };
  Point2.prototype.getX = function getX() {
    return this.x.fromRed();
  };
  Point2.prototype.getY = function getY() {
    return this.y.fromRed();
  };
  Point2.prototype.mul = function mul(k2) {
    k2 = new BN(k2, 16);
    if (this.isInfinity())
      return this;
    else if (this._hasDoubles(k2))
      return this.curve._fixedNafMul(this, k2);
    else if (this.curve.endo)
      return this.curve._endoWnafMulAdd([this], [k2]);
    else
      return this.curve._wnafMul(this, k2);
  };
  Point2.prototype.mulAdd = function mulAdd(k1, p2, k2) {
    var points = [this, p2];
    var coeffs = [k1, k2];
    if (this.curve.endo)
      return this.curve._endoWnafMulAdd(points, coeffs);
    else
      return this.curve._wnafMulAdd(1, points, coeffs, 2);
  };
  Point2.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
    var points = [this, p2];
    var coeffs = [k1, k2];
    if (this.curve.endo)
      return this.curve._endoWnafMulAdd(points, coeffs, true);
    else
      return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
  };
  Point2.prototype.eq = function eq(p2) {
    return this === p2 || this.inf === p2.inf && (this.inf || this.x.cmp(p2.x) === 0 && this.y.cmp(p2.y) === 0);
  };
  Point2.prototype.neg = function neg(_precompute) {
    if (this.inf)
      return this;
    var res = this.curve.point(this.x, this.y.redNeg());
    if (_precompute && this.precomputed) {
      var pre = this.precomputed;
      var negate = function(p2) {
        return p2.neg();
      };
      res.precomputed = {
        naf: pre.naf && {
          wnd: pre.naf.wnd,
          points: pre.naf.points.map(negate)
        },
        doubles: pre.doubles && {
          step: pre.doubles.step,
          points: pre.doubles.points.map(negate)
        }
      };
    }
    return res;
  };
  Point2.prototype.toJ = function toJ() {
    if (this.inf)
      return this.curve.jpoint(null, null, null);
    var res = this.curve.jpoint(this.x, this.y, this.curve.one);
    return res;
  };
  function JPoint(curve2, x2, y2, z2) {
    Base.BasePoint.call(this, curve2, "jacobian");
    if (x2 === null && y2 === null && z2 === null) {
      this.x = this.curve.one;
      this.y = this.curve.one;
      this.z = new BN(0);
    } else {
      this.x = new BN(x2, 16);
      this.y = new BN(y2, 16);
      this.z = new BN(z2, 16);
    }
    if (!this.x.red)
      this.x = this.x.toRed(this.curve.red);
    if (!this.y.red)
      this.y = this.y.toRed(this.curve.red);
    if (!this.z.red)
      this.z = this.z.toRed(this.curve.red);
    this.zOne = this.z === this.curve.one;
  }
  inherits(JPoint, Base.BasePoint);
  ShortCurve.prototype.jpoint = function jpoint(x2, y2, z2) {
    return new JPoint(this, x2, y2, z2);
  };
  JPoint.prototype.toP = function toP() {
    if (this.isInfinity())
      return this.curve.point(null, null);
    var zinv = this.z.redInvm();
    var zinv2 = zinv.redSqr();
    var ax = this.x.redMul(zinv2);
    var ay = this.y.redMul(zinv2).redMul(zinv);
    return this.curve.point(ax, ay);
  };
  JPoint.prototype.neg = function neg() {
    return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  };
  JPoint.prototype.add = function add2(p2) {
    if (this.isInfinity())
      return p2;
    if (p2.isInfinity())
      return this;
    var pz2 = p2.z.redSqr();
    var z2 = this.z.redSqr();
    var u1 = this.x.redMul(pz2);
    var u2 = p2.x.redMul(z2);
    var s1 = this.y.redMul(pz2.redMul(p2.z));
    var s2 = p2.y.redMul(z2.redMul(this.z));
    var h2 = u1.redSub(u2);
    var r2 = s1.redSub(s2);
    if (h2.cmpn(0) === 0) {
      if (r2.cmpn(0) !== 0)
        return this.curve.jpoint(null, null, null);
      else
        return this.dbl();
    }
    var h22 = h2.redSqr();
    var h3 = h22.redMul(h2);
    var v2 = u1.redMul(h22);
    var nx = r2.redSqr().redIAdd(h3).redISub(v2).redISub(v2);
    var ny = r2.redMul(v2.redISub(nx)).redISub(s1.redMul(h3));
    var nz = this.z.redMul(p2.z).redMul(h2);
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype.mixedAdd = function mixedAdd(p2) {
    if (this.isInfinity())
      return p2.toJ();
    if (p2.isInfinity())
      return this;
    var z2 = this.z.redSqr();
    var u1 = this.x;
    var u2 = p2.x.redMul(z2);
    var s1 = this.y;
    var s2 = p2.y.redMul(z2).redMul(this.z);
    var h2 = u1.redSub(u2);
    var r2 = s1.redSub(s2);
    if (h2.cmpn(0) === 0) {
      if (r2.cmpn(0) !== 0)
        return this.curve.jpoint(null, null, null);
      else
        return this.dbl();
    }
    var h22 = h2.redSqr();
    var h3 = h22.redMul(h2);
    var v2 = u1.redMul(h22);
    var nx = r2.redSqr().redIAdd(h3).redISub(v2).redISub(v2);
    var ny = r2.redMul(v2.redISub(nx)).redISub(s1.redMul(h3));
    var nz = this.z.redMul(h2);
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype.dblp = function dblp(pow2) {
    if (pow2 === 0)
      return this;
    if (this.isInfinity())
      return this;
    if (!pow2)
      return this.dbl();
    var i2;
    if (this.curve.zeroA || this.curve.threeA) {
      var r2 = this;
      for (i2 = 0; i2 < pow2; i2++)
        r2 = r2.dbl();
      return r2;
    }
    var a2 = this.curve.a;
    var tinv = this.curve.tinv;
    var jx = this.x;
    var jy = this.y;
    var jz = this.z;
    var jz4 = jz.redSqr().redSqr();
    var jyd = jy.redAdd(jy);
    for (i2 = 0; i2 < pow2; i2++) {
      var jx2 = jx.redSqr();
      var jyd2 = jyd.redSqr();
      var jyd4 = jyd2.redSqr();
      var c2 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a2.redMul(jz4));
      var t1 = jx.redMul(jyd2);
      var nx = c2.redSqr().redISub(t1.redAdd(t1));
      var t2 = t1.redISub(nx);
      var dny = c2.redMul(t2);
      dny = dny.redIAdd(dny).redISub(jyd4);
      var nz = jyd.redMul(jz);
      if (i2 + 1 < pow2)
        jz4 = jz4.redMul(jyd4);
      jx = nx;
      jz = nz;
      jyd = dny;
    }
    return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  };
  JPoint.prototype.dbl = function dbl() {
    if (this.isInfinity())
      return this;
    if (this.curve.zeroA)
      return this._zeroDbl();
    else if (this.curve.threeA)
      return this._threeDbl();
    else
      return this._dbl();
  };
  JPoint.prototype._zeroDbl = function _zeroDbl() {
    var nx;
    var ny;
    var nz;
    if (this.zOne) {
      var xx = this.x.redSqr();
      var yy = this.y.redSqr();
      var yyyy = yy.redSqr();
      var s2 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
      s2 = s2.redIAdd(s2);
      var m = xx.redAdd(xx).redIAdd(xx);
      var t2 = m.redSqr().redISub(s2).redISub(s2);
      var yyyy8 = yyyy.redIAdd(yyyy);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      nx = t2;
      ny = m.redMul(s2.redISub(t2)).redISub(yyyy8);
      nz = this.y.redAdd(this.y);
    } else {
      var a2 = this.x.redSqr();
      var b2 = this.y.redSqr();
      var c2 = b2.redSqr();
      var d = this.x.redAdd(b2).redSqr().redISub(a2).redISub(c2);
      d = d.redIAdd(d);
      var e4 = a2.redAdd(a2).redIAdd(a2);
      var f2 = e4.redSqr();
      var c8 = c2.redIAdd(c2);
      c8 = c8.redIAdd(c8);
      c8 = c8.redIAdd(c8);
      nx = f2.redISub(d).redISub(d);
      ny = e4.redMul(d.redISub(nx)).redISub(c8);
      nz = this.y.redMul(this.z);
      nz = nz.redIAdd(nz);
    }
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype._threeDbl = function _threeDbl() {
    var nx;
    var ny;
    var nz;
    if (this.zOne) {
      var xx = this.x.redSqr();
      var yy = this.y.redSqr();
      var yyyy = yy.redSqr();
      var s2 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
      s2 = s2.redIAdd(s2);
      var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
      var t2 = m.redSqr().redISub(s2).redISub(s2);
      nx = t2;
      var yyyy8 = yyyy.redIAdd(yyyy);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      yyyy8 = yyyy8.redIAdd(yyyy8);
      ny = m.redMul(s2.redISub(t2)).redISub(yyyy8);
      nz = this.y.redAdd(this.y);
    } else {
      var delta = this.z.redSqr();
      var gamma = this.y.redSqr();
      var beta = this.x.redMul(gamma);
      var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
      alpha = alpha.redAdd(alpha).redIAdd(alpha);
      var beta4 = beta.redIAdd(beta);
      beta4 = beta4.redIAdd(beta4);
      var beta8 = beta4.redAdd(beta4);
      nx = alpha.redSqr().redISub(beta8);
      nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
      var ggamma8 = gamma.redSqr();
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ggamma8 = ggamma8.redIAdd(ggamma8);
      ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
    }
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype._dbl = function _dbl() {
    var a2 = this.curve.a;
    var jx = this.x;
    var jy = this.y;
    var jz = this.z;
    var jz4 = jz.redSqr().redSqr();
    var jx2 = jx.redSqr();
    var jy2 = jy.redSqr();
    var c2 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a2.redMul(jz4));
    var jxd4 = jx.redAdd(jx);
    jxd4 = jxd4.redIAdd(jxd4);
    var t1 = jxd4.redMul(jy2);
    var nx = c2.redSqr().redISub(t1.redAdd(t1));
    var t2 = t1.redISub(nx);
    var jyd8 = jy2.redSqr();
    jyd8 = jyd8.redIAdd(jyd8);
    jyd8 = jyd8.redIAdd(jyd8);
    jyd8 = jyd8.redIAdd(jyd8);
    var ny = c2.redMul(t2).redISub(jyd8);
    var nz = jy.redAdd(jy).redMul(jz);
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype.trpl = function trpl() {
    if (!this.curve.zeroA)
      return this.dbl().add(this);
    var xx = this.x.redSqr();
    var yy = this.y.redSqr();
    var zz = this.z.redSqr();
    var yyyy = yy.redSqr();
    var m = xx.redAdd(xx).redIAdd(xx);
    var mm = m.redSqr();
    var e4 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
    e4 = e4.redIAdd(e4);
    e4 = e4.redAdd(e4).redIAdd(e4);
    e4 = e4.redISub(mm);
    var ee = e4.redSqr();
    var t2 = yyyy.redIAdd(yyyy);
    t2 = t2.redIAdd(t2);
    t2 = t2.redIAdd(t2);
    t2 = t2.redIAdd(t2);
    var u2 = m.redIAdd(e4).redSqr().redISub(mm).redISub(ee).redISub(t2);
    var yyu4 = yy.redMul(u2);
    yyu4 = yyu4.redIAdd(yyu4);
    yyu4 = yyu4.redIAdd(yyu4);
    var nx = this.x.redMul(ee).redISub(yyu4);
    nx = nx.redIAdd(nx);
    nx = nx.redIAdd(nx);
    var ny = this.y.redMul(u2.redMul(t2.redISub(u2)).redISub(e4.redMul(ee)));
    ny = ny.redIAdd(ny);
    ny = ny.redIAdd(ny);
    ny = ny.redIAdd(ny);
    var nz = this.z.redAdd(e4).redSqr().redISub(zz).redISub(ee);
    return this.curve.jpoint(nx, ny, nz);
  };
  JPoint.prototype.mul = function mul(k2, kbase) {
    k2 = new BN(k2, kbase);
    return this.curve._wnafMul(this, k2);
  };
  JPoint.prototype.eq = function eq(p2) {
    if (p2.type === "affine")
      return this.eq(p2.toJ());
    if (this === p2)
      return true;
    var z2 = this.z.redSqr();
    var pz2 = p2.z.redSqr();
    if (this.x.redMul(pz2).redISub(p2.x.redMul(z2)).cmpn(0) !== 0)
      return false;
    var z3 = z2.redMul(this.z);
    var pz3 = pz2.redMul(p2.z);
    return this.y.redMul(pz3).redISub(p2.y.redMul(z3)).cmpn(0) === 0;
  };
  JPoint.prototype.eqXToP = function eqXToP(x2) {
    var zs = this.z.redSqr();
    var rx = x2.toRed(this.curve.red).redMul(zs);
    if (this.x.cmp(rx) === 0)
      return true;
    var xc = x2.clone();
    var t2 = this.curve.redN.redMul(zs);
    for (; ; ) {
      xc.iadd(this.curve.n);
      if (xc.cmp(this.curve.p) >= 0)
        return false;
      rx.redIAdd(t2);
      if (this.x.cmp(rx) === 0)
        return true;
    }
  };
  JPoint.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return "<EC JPoint Infinity>";
    return "<EC JPoint x: " + this.x.toString(16, 2) + " y: " + this.y.toString(16, 2) + " z: " + this.z.toString(16, 2) + ">";
  };
  JPoint.prototype.isInfinity = function isInfinity() {
    return this.z.cmpn(0) === 0;
  };
  return short;
}
var mont;
var hasRequiredMont;
function requireMont() {
  if (hasRequiredMont) return mont;
  hasRequiredMont = 1;
  var BN = requireBn$1();
  var inherits = requireInherits_browser();
  var Base = requireBase$1();
  var utils2 = requireUtils$2();
  function MontCurve(conf) {
    Base.call(this, "mont", conf);
    this.a = new BN(conf.a, 16).toRed(this.red);
    this.b = new BN(conf.b, 16).toRed(this.red);
    this.i4 = new BN(4).toRed(this.red).redInvm();
    this.two = new BN(2).toRed(this.red);
    this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  }
  inherits(MontCurve, Base);
  mont = MontCurve;
  MontCurve.prototype.validate = function validate2(point) {
    var x2 = point.normalize().x;
    var x22 = x2.redSqr();
    var rhs = x22.redMul(x2).redAdd(x22.redMul(this.a)).redAdd(x2);
    var y2 = rhs.redSqrt();
    return y2.redSqr().cmp(rhs) === 0;
  };
  function Point2(curve2, x2, z2) {
    Base.BasePoint.call(this, curve2, "projective");
    if (x2 === null && z2 === null) {
      this.x = this.curve.one;
      this.z = this.curve.zero;
    } else {
      this.x = new BN(x2, 16);
      this.z = new BN(z2, 16);
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.z.red)
        this.z = this.z.toRed(this.curve.red);
    }
  }
  inherits(Point2, Base.BasePoint);
  MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
    return this.point(utils2.toArray(bytes, enc), 1);
  };
  MontCurve.prototype.point = function point(x2, z2) {
    return new Point2(this, x2, z2);
  };
  MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
    return Point2.fromJSON(this, obj);
  };
  Point2.prototype.precompute = function precompute() {
  };
  Point2.prototype._encode = function _encode() {
    return this.getX().toArray("be", this.curve.p.byteLength());
  };
  Point2.fromJSON = function fromJSON(curve2, obj) {
    return new Point2(curve2, obj[0], obj[1] || curve2.one);
  };
  Point2.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return "<EC Point Infinity>";
    return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " z: " + this.z.fromRed().toString(16, 2) + ">";
  };
  Point2.prototype.isInfinity = function isInfinity() {
    return this.z.cmpn(0) === 0;
  };
  Point2.prototype.dbl = function dbl() {
    var a2 = this.x.redAdd(this.z);
    var aa = a2.redSqr();
    var b2 = this.x.redSub(this.z);
    var bb = b2.redSqr();
    var c2 = aa.redSub(bb);
    var nx = aa.redMul(bb);
    var nz = c2.redMul(bb.redAdd(this.curve.a24.redMul(c2)));
    return this.curve.point(nx, nz);
  };
  Point2.prototype.add = function add2() {
    throw new Error("Not supported on Montgomery curve");
  };
  Point2.prototype.diffAdd = function diffAdd(p2, diff) {
    var a2 = this.x.redAdd(this.z);
    var b2 = this.x.redSub(this.z);
    var c2 = p2.x.redAdd(p2.z);
    var d = p2.x.redSub(p2.z);
    var da = d.redMul(a2);
    var cb = c2.redMul(b2);
    var nx = diff.z.redMul(da.redAdd(cb).redSqr());
    var nz = diff.x.redMul(da.redISub(cb).redSqr());
    return this.curve.point(nx, nz);
  };
  Point2.prototype.mul = function mul(k2) {
    var t2 = k2.clone();
    var a2 = this;
    var b2 = this.curve.point(null, null);
    var c2 = this;
    for (var bits = []; t2.cmpn(0) !== 0; t2.iushrn(1))
      bits.push(t2.andln(1));
    for (var i2 = bits.length - 1; i2 >= 0; i2--) {
      if (bits[i2] === 0) {
        a2 = a2.diffAdd(b2, c2);
        b2 = b2.dbl();
      } else {
        b2 = a2.diffAdd(b2, c2);
        a2 = a2.dbl();
      }
    }
    return b2;
  };
  Point2.prototype.mulAdd = function mulAdd() {
    throw new Error("Not supported on Montgomery curve");
  };
  Point2.prototype.jumlAdd = function jumlAdd() {
    throw new Error("Not supported on Montgomery curve");
  };
  Point2.prototype.eq = function eq(other) {
    return this.getX().cmp(other.getX()) === 0;
  };
  Point2.prototype.normalize = function normalize() {
    this.x = this.x.redMul(this.z.redInvm());
    this.z = this.curve.one;
    return this;
  };
  Point2.prototype.getX = function getX() {
    this.normalize();
    return this.x.fromRed();
  };
  return mont;
}
var edwards;
var hasRequiredEdwards;
function requireEdwards() {
  if (hasRequiredEdwards) return edwards;
  hasRequiredEdwards = 1;
  var utils2 = requireUtils$2();
  var BN = requireBn$1();
  var inherits = requireInherits_browser();
  var Base = requireBase$1();
  var assert = utils2.assert;
  function EdwardsCurve(conf) {
    this.twisted = (conf.a | 0) !== 1;
    this.mOneA = this.twisted && (conf.a | 0) === -1;
    this.extended = this.mOneA;
    Base.call(this, "edwards", conf);
    this.a = new BN(conf.a, 16).umod(this.red.m);
    this.a = this.a.toRed(this.red);
    this.c = new BN(conf.c, 16).toRed(this.red);
    this.c2 = this.c.redSqr();
    this.d = new BN(conf.d, 16).toRed(this.red);
    this.dd = this.d.redAdd(this.d);
    assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
    this.oneC = (conf.c | 0) === 1;
  }
  inherits(EdwardsCurve, Base);
  edwards = EdwardsCurve;
  EdwardsCurve.prototype._mulA = function _mulA(num) {
    if (this.mOneA)
      return num.redNeg();
    else
      return this.a.redMul(num);
  };
  EdwardsCurve.prototype._mulC = function _mulC(num) {
    if (this.oneC)
      return num;
    else
      return this.c.redMul(num);
  };
  EdwardsCurve.prototype.jpoint = function jpoint(x2, y2, z2, t2) {
    return this.point(x2, y2, z2, t2);
  };
  EdwardsCurve.prototype.pointFromX = function pointFromX(x2, odd) {
    x2 = new BN(x2, 16);
    if (!x2.red)
      x2 = x2.toRed(this.red);
    var x22 = x2.redSqr();
    var rhs = this.c2.redSub(this.a.redMul(x22));
    var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x22));
    var y2 = rhs.redMul(lhs.redInvm());
    var y3 = y2.redSqrt();
    if (y3.redSqr().redSub(y2).cmp(this.zero) !== 0)
      throw new Error("invalid point");
    var isOdd = y3.fromRed().isOdd();
    if (odd && !isOdd || !odd && isOdd)
      y3 = y3.redNeg();
    return this.point(x2, y3);
  };
  EdwardsCurve.prototype.pointFromY = function pointFromY(y2, odd) {
    y2 = new BN(y2, 16);
    if (!y2.red)
      y2 = y2.toRed(this.red);
    var y22 = y2.redSqr();
    var lhs = y22.redSub(this.c2);
    var rhs = y22.redMul(this.d).redMul(this.c2).redSub(this.a);
    var x2 = lhs.redMul(rhs.redInvm());
    if (x2.cmp(this.zero) === 0) {
      if (odd)
        throw new Error("invalid point");
      else
        return this.point(this.zero, y2);
    }
    var x3 = x2.redSqrt();
    if (x3.redSqr().redSub(x2).cmp(this.zero) !== 0)
      throw new Error("invalid point");
    if (x3.fromRed().isOdd() !== odd)
      x3 = x3.redNeg();
    return this.point(x3, y2);
  };
  EdwardsCurve.prototype.validate = function validate2(point) {
    if (point.isInfinity())
      return true;
    point.normalize();
    var x2 = point.x.redSqr();
    var y2 = point.y.redSqr();
    var lhs = x2.redMul(this.a).redAdd(y2);
    var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
    return lhs.cmp(rhs) === 0;
  };
  function Point2(curve2, x2, y2, z2, t2) {
    Base.BasePoint.call(this, curve2, "projective");
    if (x2 === null && y2 === null && z2 === null) {
      this.x = this.curve.zero;
      this.y = this.curve.one;
      this.z = this.curve.one;
      this.t = this.curve.zero;
      this.zOne = true;
    } else {
      this.x = new BN(x2, 16);
      this.y = new BN(y2, 16);
      this.z = z2 ? new BN(z2, 16) : this.curve.one;
      this.t = t2 && new BN(t2, 16);
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.y.red)
        this.y = this.y.toRed(this.curve.red);
      if (!this.z.red)
        this.z = this.z.toRed(this.curve.red);
      if (this.t && !this.t.red)
        this.t = this.t.toRed(this.curve.red);
      this.zOne = this.z === this.curve.one;
      if (this.curve.extended && !this.t) {
        this.t = this.x.redMul(this.y);
        if (!this.zOne)
          this.t = this.t.redMul(this.z.redInvm());
      }
    }
  }
  inherits(Point2, Base.BasePoint);
  EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
    return Point2.fromJSON(this, obj);
  };
  EdwardsCurve.prototype.point = function point(x2, y2, z2, t2) {
    return new Point2(this, x2, y2, z2, t2);
  };
  Point2.fromJSON = function fromJSON(curve2, obj) {
    return new Point2(curve2, obj[0], obj[1], obj[2]);
  };
  Point2.prototype.inspect = function inspect() {
    if (this.isInfinity())
      return "<EC Point Infinity>";
    return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " y: " + this.y.fromRed().toString(16, 2) + " z: " + this.z.fromRed().toString(16, 2) + ">";
  };
  Point2.prototype.isInfinity = function isInfinity() {
    return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0);
  };
  Point2.prototype._extDbl = function _extDbl() {
    var a2 = this.x.redSqr();
    var b2 = this.y.redSqr();
    var c2 = this.z.redSqr();
    c2 = c2.redIAdd(c2);
    var d = this.curve._mulA(a2);
    var e4 = this.x.redAdd(this.y).redSqr().redISub(a2).redISub(b2);
    var g = d.redAdd(b2);
    var f2 = g.redSub(c2);
    var h2 = d.redSub(b2);
    var nx = e4.redMul(f2);
    var ny = g.redMul(h2);
    var nt = e4.redMul(h2);
    var nz = f2.redMul(g);
    return this.curve.point(nx, ny, nz, nt);
  };
  Point2.prototype._projDbl = function _projDbl() {
    var b2 = this.x.redAdd(this.y).redSqr();
    var c2 = this.x.redSqr();
    var d = this.y.redSqr();
    var nx;
    var ny;
    var nz;
    var e4;
    var h2;
    var j;
    if (this.curve.twisted) {
      e4 = this.curve._mulA(c2);
      var f2 = e4.redAdd(d);
      if (this.zOne) {
        nx = b2.redSub(c2).redSub(d).redMul(f2.redSub(this.curve.two));
        ny = f2.redMul(e4.redSub(d));
        nz = f2.redSqr().redSub(f2).redSub(f2);
      } else {
        h2 = this.z.redSqr();
        j = f2.redSub(h2).redISub(h2);
        nx = b2.redSub(c2).redISub(d).redMul(j);
        ny = f2.redMul(e4.redSub(d));
        nz = f2.redMul(j);
      }
    } else {
      e4 = c2.redAdd(d);
      h2 = this.curve._mulC(this.z).redSqr();
      j = e4.redSub(h2).redSub(h2);
      nx = this.curve._mulC(b2.redISub(e4)).redMul(j);
      ny = this.curve._mulC(e4).redMul(c2.redISub(d));
      nz = e4.redMul(j);
    }
    return this.curve.point(nx, ny, nz);
  };
  Point2.prototype.dbl = function dbl() {
    if (this.isInfinity())
      return this;
    if (this.curve.extended)
      return this._extDbl();
    else
      return this._projDbl();
  };
  Point2.prototype._extAdd = function _extAdd(p2) {
    var a2 = this.y.redSub(this.x).redMul(p2.y.redSub(p2.x));
    var b2 = this.y.redAdd(this.x).redMul(p2.y.redAdd(p2.x));
    var c2 = this.t.redMul(this.curve.dd).redMul(p2.t);
    var d = this.z.redMul(p2.z.redAdd(p2.z));
    var e4 = b2.redSub(a2);
    var f2 = d.redSub(c2);
    var g = d.redAdd(c2);
    var h2 = b2.redAdd(a2);
    var nx = e4.redMul(f2);
    var ny = g.redMul(h2);
    var nt = e4.redMul(h2);
    var nz = f2.redMul(g);
    return this.curve.point(nx, ny, nz, nt);
  };
  Point2.prototype._projAdd = function _projAdd(p2) {
    var a2 = this.z.redMul(p2.z);
    var b2 = a2.redSqr();
    var c2 = this.x.redMul(p2.x);
    var d = this.y.redMul(p2.y);
    var e4 = this.curve.d.redMul(c2).redMul(d);
    var f2 = b2.redSub(e4);
    var g = b2.redAdd(e4);
    var tmp = this.x.redAdd(this.y).redMul(p2.x.redAdd(p2.y)).redISub(c2).redISub(d);
    var nx = a2.redMul(f2).redMul(tmp);
    var ny;
    var nz;
    if (this.curve.twisted) {
      ny = a2.redMul(g).redMul(d.redSub(this.curve._mulA(c2)));
      nz = f2.redMul(g);
    } else {
      ny = a2.redMul(g).redMul(d.redSub(c2));
      nz = this.curve._mulC(f2).redMul(g);
    }
    return this.curve.point(nx, ny, nz);
  };
  Point2.prototype.add = function add2(p2) {
    if (this.isInfinity())
      return p2;
    if (p2.isInfinity())
      return this;
    if (this.curve.extended)
      return this._extAdd(p2);
    else
      return this._projAdd(p2);
  };
  Point2.prototype.mul = function mul(k2) {
    if (this._hasDoubles(k2))
      return this.curve._fixedNafMul(this, k2);
    else
      return this.curve._wnafMul(this, k2);
  };
  Point2.prototype.mulAdd = function mulAdd(k1, p2, k2) {
    return this.curve._wnafMulAdd(1, [this, p2], [k1, k2], 2, false);
  };
  Point2.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
    return this.curve._wnafMulAdd(1, [this, p2], [k1, k2], 2, true);
  };
  Point2.prototype.normalize = function normalize() {
    if (this.zOne)
      return this;
    var zi = this.z.redInvm();
    this.x = this.x.redMul(zi);
    this.y = this.y.redMul(zi);
    if (this.t)
      this.t = this.t.redMul(zi);
    this.z = this.curve.one;
    this.zOne = true;
    return this;
  };
  Point2.prototype.neg = function neg() {
    return this.curve.point(
      this.x.redNeg(),
      this.y,
      this.z,
      this.t && this.t.redNeg()
    );
  };
  Point2.prototype.getX = function getX() {
    this.normalize();
    return this.x.fromRed();
  };
  Point2.prototype.getY = function getY() {
    this.normalize();
    return this.y.fromRed();
  };
  Point2.prototype.eq = function eq(other) {
    return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0;
  };
  Point2.prototype.eqXToP = function eqXToP(x2) {
    var rx = x2.toRed(this.curve.red).redMul(this.z);
    if (this.x.cmp(rx) === 0)
      return true;
    var xc = x2.clone();
    var t2 = this.curve.redN.redMul(this.z);
    for (; ; ) {
      xc.iadd(this.curve.n);
      if (xc.cmp(this.curve.p) >= 0)
        return false;
      rx.redIAdd(t2);
      if (this.x.cmp(rx) === 0)
        return true;
    }
  };
  Point2.prototype.toP = Point2.prototype.normalize;
  Point2.prototype.mixedAdd = Point2.prototype.add;
  return edwards;
}
var hasRequiredCurve;
function requireCurve() {
  if (hasRequiredCurve) return curve$1;
  hasRequiredCurve = 1;
  (function(exports) {
    var curve2 = exports;
    curve2.base = requireBase$1();
    curve2.short = requireShort();
    curve2.mont = requireMont();
    curve2.edwards = requireEdwards();
  })(curve$1);
  return curve$1;
}
var curves = {};
var hash = {};
var utils$1 = {};
var hasRequiredUtils$1;
function requireUtils$1() {
  if (hasRequiredUtils$1) return utils$1;
  hasRequiredUtils$1 = 1;
  var assert = requireMinimalisticAssert();
  var inherits = requireInherits_browser();
  utils$1.inherits = inherits;
  function isSurrogatePair(msg, i2) {
    if ((msg.charCodeAt(i2) & 64512) !== 55296) {
      return false;
    }
    if (i2 < 0 || i2 + 1 >= msg.length) {
      return false;
    }
    return (msg.charCodeAt(i2 + 1) & 64512) === 56320;
  }
  function toArray(msg, enc) {
    if (Array.isArray(msg))
      return msg.slice();
    if (!msg)
      return [];
    var res = [];
    if (typeof msg === "string") {
      if (!enc) {
        var p2 = 0;
        for (var i2 = 0; i2 < msg.length; i2++) {
          var c2 = msg.charCodeAt(i2);
          if (c2 < 128) {
            res[p2++] = c2;
          } else if (c2 < 2048) {
            res[p2++] = c2 >> 6 | 192;
            res[p2++] = c2 & 63 | 128;
          } else if (isSurrogatePair(msg, i2)) {
            c2 = 65536 + ((c2 & 1023) << 10) + (msg.charCodeAt(++i2) & 1023);
            res[p2++] = c2 >> 18 | 240;
            res[p2++] = c2 >> 12 & 63 | 128;
            res[p2++] = c2 >> 6 & 63 | 128;
            res[p2++] = c2 & 63 | 128;
          } else {
            res[p2++] = c2 >> 12 | 224;
            res[p2++] = c2 >> 6 & 63 | 128;
            res[p2++] = c2 & 63 | 128;
          }
        }
      } else if (enc === "hex") {
        msg = msg.replace(/[^a-z0-9]+/ig, "");
        if (msg.length % 2 !== 0)
          msg = "0" + msg;
        for (i2 = 0; i2 < msg.length; i2 += 2)
          res.push(parseInt(msg[i2] + msg[i2 + 1], 16));
      }
    } else {
      for (i2 = 0; i2 < msg.length; i2++)
        res[i2] = msg[i2] | 0;
    }
    return res;
  }
  utils$1.toArray = toArray;
  function toHex2(msg) {
    var res = "";
    for (var i2 = 0; i2 < msg.length; i2++)
      res += zero2(msg[i2].toString(16));
    return res;
  }
  utils$1.toHex = toHex2;
  function htonl(w) {
    var res = w >>> 24 | w >>> 8 & 65280 | w << 8 & 16711680 | (w & 255) << 24;
    return res >>> 0;
  }
  utils$1.htonl = htonl;
  function toHex32(msg, endian) {
    var res = "";
    for (var i2 = 0; i2 < msg.length; i2++) {
      var w = msg[i2];
      if (endian === "little")
        w = htonl(w);
      res += zero8(w.toString(16));
    }
    return res;
  }
  utils$1.toHex32 = toHex32;
  function zero2(word) {
    if (word.length === 1)
      return "0" + word;
    else
      return word;
  }
  utils$1.zero2 = zero2;
  function zero8(word) {
    if (word.length === 7)
      return "0" + word;
    else if (word.length === 6)
      return "00" + word;
    else if (word.length === 5)
      return "000" + word;
    else if (word.length === 4)
      return "0000" + word;
    else if (word.length === 3)
      return "00000" + word;
    else if (word.length === 2)
      return "000000" + word;
    else if (word.length === 1)
      return "0000000" + word;
    else
      return word;
  }
  utils$1.zero8 = zero8;
  function join32(msg, start, end, endian) {
    var len = end - start;
    assert(len % 4 === 0);
    var res = new Array(len / 4);
    for (var i2 = 0, k2 = start; i2 < res.length; i2++, k2 += 4) {
      var w;
      if (endian === "big")
        w = msg[k2] << 24 | msg[k2 + 1] << 16 | msg[k2 + 2] << 8 | msg[k2 + 3];
      else
        w = msg[k2 + 3] << 24 | msg[k2 + 2] << 16 | msg[k2 + 1] << 8 | msg[k2];
      res[i2] = w >>> 0;
    }
    return res;
  }
  utils$1.join32 = join32;
  function split32(msg, endian) {
    var res = new Array(msg.length * 4);
    for (var i2 = 0, k2 = 0; i2 < msg.length; i2++, k2 += 4) {
      var m = msg[i2];
      if (endian === "big") {
        res[k2] = m >>> 24;
        res[k2 + 1] = m >>> 16 & 255;
        res[k2 + 2] = m >>> 8 & 255;
        res[k2 + 3] = m & 255;
      } else {
        res[k2 + 3] = m >>> 24;
        res[k2 + 2] = m >>> 16 & 255;
        res[k2 + 1] = m >>> 8 & 255;
        res[k2] = m & 255;
      }
    }
    return res;
  }
  utils$1.split32 = split32;
  function rotr32(w, b2) {
    return w >>> b2 | w << 32 - b2;
  }
  utils$1.rotr32 = rotr32;
  function rotl32(w, b2) {
    return w << b2 | w >>> 32 - b2;
  }
  utils$1.rotl32 = rotl32;
  function sum32(a2, b2) {
    return a2 + b2 >>> 0;
  }
  utils$1.sum32 = sum32;
  function sum32_3(a2, b2, c2) {
    return a2 + b2 + c2 >>> 0;
  }
  utils$1.sum32_3 = sum32_3;
  function sum32_4(a2, b2, c2, d) {
    return a2 + b2 + c2 + d >>> 0;
  }
  utils$1.sum32_4 = sum32_4;
  function sum32_5(a2, b2, c2, d, e4) {
    return a2 + b2 + c2 + d + e4 >>> 0;
  }
  utils$1.sum32_5 = sum32_5;
  function sum64(buf, pos, ah, al) {
    var bh = buf[pos];
    var bl = buf[pos + 1];
    var lo = al + bl >>> 0;
    var hi = (lo < al ? 1 : 0) + ah + bh;
    buf[pos] = hi >>> 0;
    buf[pos + 1] = lo;
  }
  utils$1.sum64 = sum64;
  function sum64_hi(ah, al, bh, bl) {
    var lo = al + bl >>> 0;
    var hi = (lo < al ? 1 : 0) + ah + bh;
    return hi >>> 0;
  }
  utils$1.sum64_hi = sum64_hi;
  function sum64_lo(ah, al, bh, bl) {
    var lo = al + bl;
    return lo >>> 0;
  }
  utils$1.sum64_lo = sum64_lo;
  function sum64_4_hi(ah, al, bh, bl, ch, cl, dh2, dl) {
    var carry = 0;
    var lo = al;
    lo = lo + bl >>> 0;
    carry += lo < al ? 1 : 0;
    lo = lo + cl >>> 0;
    carry += lo < cl ? 1 : 0;
    lo = lo + dl >>> 0;
    carry += lo < dl ? 1 : 0;
    var hi = ah + bh + ch + dh2 + carry;
    return hi >>> 0;
  }
  utils$1.sum64_4_hi = sum64_4_hi;
  function sum64_4_lo(ah, al, bh, bl, ch, cl, dh2, dl) {
    var lo = al + bl + cl + dl;
    return lo >>> 0;
  }
  utils$1.sum64_4_lo = sum64_4_lo;
  function sum64_5_hi(ah, al, bh, bl, ch, cl, dh2, dl, eh, el) {
    var carry = 0;
    var lo = al;
    lo = lo + bl >>> 0;
    carry += lo < al ? 1 : 0;
    lo = lo + cl >>> 0;
    carry += lo < cl ? 1 : 0;
    lo = lo + dl >>> 0;
    carry += lo < dl ? 1 : 0;
    lo = lo + el >>> 0;
    carry += lo < el ? 1 : 0;
    var hi = ah + bh + ch + dh2 + eh + carry;
    return hi >>> 0;
  }
  utils$1.sum64_5_hi = sum64_5_hi;
  function sum64_5_lo(ah, al, bh, bl, ch, cl, dh2, dl, eh, el) {
    var lo = al + bl + cl + dl + el;
    return lo >>> 0;
  }
  utils$1.sum64_5_lo = sum64_5_lo;
  function rotr64_hi(ah, al, num) {
    var r2 = al << 32 - num | ah >>> num;
    return r2 >>> 0;
  }
  utils$1.rotr64_hi = rotr64_hi;
  function rotr64_lo(ah, al, num) {
    var r2 = ah << 32 - num | al >>> num;
    return r2 >>> 0;
  }
  utils$1.rotr64_lo = rotr64_lo;
  function shr64_hi(ah, al, num) {
    return ah >>> num;
  }
  utils$1.shr64_hi = shr64_hi;
  function shr64_lo(ah, al, num) {
    var r2 = ah << 32 - num | al >>> num;
    return r2 >>> 0;
  }
  utils$1.shr64_lo = shr64_lo;
  return utils$1;
}
var common$3 = {};
var hasRequiredCommon$3;
function requireCommon$3() {
  if (hasRequiredCommon$3) return common$3;
  hasRequiredCommon$3 = 1;
  var utils2 = requireUtils$1();
  var assert = requireMinimalisticAssert();
  function BlockHash() {
    this.pending = null;
    this.pendingTotal = 0;
    this.blockSize = this.constructor.blockSize;
    this.outSize = this.constructor.outSize;
    this.hmacStrength = this.constructor.hmacStrength;
    this.padLength = this.constructor.padLength / 8;
    this.endian = "big";
    this._delta8 = this.blockSize / 8;
    this._delta32 = this.blockSize / 32;
  }
  common$3.BlockHash = BlockHash;
  BlockHash.prototype.update = function update(msg, enc) {
    msg = utils2.toArray(msg, enc);
    if (!this.pending)
      this.pending = msg;
    else
      this.pending = this.pending.concat(msg);
    this.pendingTotal += msg.length;
    if (this.pending.length >= this._delta8) {
      msg = this.pending;
      var r2 = msg.length % this._delta8;
      this.pending = msg.slice(msg.length - r2, msg.length);
      if (this.pending.length === 0)
        this.pending = null;
      msg = utils2.join32(msg, 0, msg.length - r2, this.endian);
      for (var i2 = 0; i2 < msg.length; i2 += this._delta32)
        this._update(msg, i2, i2 + this._delta32);
    }
    return this;
  };
  BlockHash.prototype.digest = function digest(enc) {
    this.update(this._pad());
    assert(this.pending === null);
    return this._digest(enc);
  };
  BlockHash.prototype._pad = function pad() {
    var len = this.pendingTotal;
    var bytes = this._delta8;
    var k2 = bytes - (len + this.padLength) % bytes;
    var res = new Array(k2 + this.padLength);
    res[0] = 128;
    for (var i2 = 1; i2 < k2; i2++)
      res[i2] = 0;
    len <<= 3;
    if (this.endian === "big") {
      for (var t2 = 8; t2 < this.padLength; t2++)
        res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = len >>> 24 & 255;
      res[i2++] = len >>> 16 & 255;
      res[i2++] = len >>> 8 & 255;
      res[i2++] = len & 255;
    } else {
      res[i2++] = len & 255;
      res[i2++] = len >>> 8 & 255;
      res[i2++] = len >>> 16 & 255;
      res[i2++] = len >>> 24 & 255;
      res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = 0;
      res[i2++] = 0;
      for (t2 = 8; t2 < this.padLength; t2++)
        res[i2++] = 0;
    }
    return res;
  };
  return common$3;
}
var sha = {};
var common$2 = {};
var hasRequiredCommon$2;
function requireCommon$2() {
  if (hasRequiredCommon$2) return common$2;
  hasRequiredCommon$2 = 1;
  var utils2 = requireUtils$1();
  var rotr32 = utils2.rotr32;
  function ft_1(s2, x2, y2, z2) {
    if (s2 === 0)
      return ch32(x2, y2, z2);
    if (s2 === 1 || s2 === 3)
      return p32(x2, y2, z2);
    if (s2 === 2)
      return maj32(x2, y2, z2);
  }
  common$2.ft_1 = ft_1;
  function ch32(x2, y2, z2) {
    return x2 & y2 ^ ~x2 & z2;
  }
  common$2.ch32 = ch32;
  function maj32(x2, y2, z2) {
    return x2 & y2 ^ x2 & z2 ^ y2 & z2;
  }
  common$2.maj32 = maj32;
  function p32(x2, y2, z2) {
    return x2 ^ y2 ^ z2;
  }
  common$2.p32 = p32;
  function s0_256(x2) {
    return rotr32(x2, 2) ^ rotr32(x2, 13) ^ rotr32(x2, 22);
  }
  common$2.s0_256 = s0_256;
  function s1_256(x2) {
    return rotr32(x2, 6) ^ rotr32(x2, 11) ^ rotr32(x2, 25);
  }
  common$2.s1_256 = s1_256;
  function g0_256(x2) {
    return rotr32(x2, 7) ^ rotr32(x2, 18) ^ x2 >>> 3;
  }
  common$2.g0_256 = g0_256;
  function g1_256(x2) {
    return rotr32(x2, 17) ^ rotr32(x2, 19) ^ x2 >>> 10;
  }
  common$2.g1_256 = g1_256;
  return common$2;
}
var _1;
var hasRequired_1;
function require_1() {
  if (hasRequired_1) return _1;
  hasRequired_1 = 1;
  var utils2 = requireUtils$1();
  var common2 = requireCommon$3();
  var shaCommon = requireCommon$2();
  var rotl32 = utils2.rotl32;
  var sum32 = utils2.sum32;
  var sum32_5 = utils2.sum32_5;
  var ft_1 = shaCommon.ft_1;
  var BlockHash = common2.BlockHash;
  var sha1_K = [
    1518500249,
    1859775393,
    2400959708,
    3395469782
  ];
  function SHA1() {
    if (!(this instanceof SHA1))
      return new SHA1();
    BlockHash.call(this);
    this.h = [
      1732584193,
      4023233417,
      2562383102,
      271733878,
      3285377520
    ];
    this.W = new Array(80);
  }
  utils2.inherits(SHA1, BlockHash);
  _1 = SHA1;
  SHA1.blockSize = 512;
  SHA1.outSize = 160;
  SHA1.hmacStrength = 80;
  SHA1.padLength = 64;
  SHA1.prototype._update = function _update(msg, start) {
    var W = this.W;
    for (var i2 = 0; i2 < 16; i2++)
      W[i2] = msg[start + i2];
    for (; i2 < W.length; i2++)
      W[i2] = rotl32(W[i2 - 3] ^ W[i2 - 8] ^ W[i2 - 14] ^ W[i2 - 16], 1);
    var a2 = this.h[0];
    var b2 = this.h[1];
    var c2 = this.h[2];
    var d = this.h[3];
    var e4 = this.h[4];
    for (i2 = 0; i2 < W.length; i2++) {
      var s2 = ~~(i2 / 20);
      var t2 = sum32_5(rotl32(a2, 5), ft_1(s2, b2, c2, d), e4, W[i2], sha1_K[s2]);
      e4 = d;
      d = c2;
      c2 = rotl32(b2, 30);
      b2 = a2;
      a2 = t2;
    }
    this.h[0] = sum32(this.h[0], a2);
    this.h[1] = sum32(this.h[1], b2);
    this.h[2] = sum32(this.h[2], c2);
    this.h[3] = sum32(this.h[3], d);
    this.h[4] = sum32(this.h[4], e4);
  };
  SHA1.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h, "big");
    else
      return utils2.split32(this.h, "big");
  };
  return _1;
}
var _256;
var hasRequired_256;
function require_256() {
  if (hasRequired_256) return _256;
  hasRequired_256 = 1;
  var utils2 = requireUtils$1();
  var common2 = requireCommon$3();
  var shaCommon = requireCommon$2();
  var assert = requireMinimalisticAssert();
  var sum32 = utils2.sum32;
  var sum32_4 = utils2.sum32_4;
  var sum32_5 = utils2.sum32_5;
  var ch32 = shaCommon.ch32;
  var maj32 = shaCommon.maj32;
  var s0_256 = shaCommon.s0_256;
  var s1_256 = shaCommon.s1_256;
  var g0_256 = shaCommon.g0_256;
  var g1_256 = shaCommon.g1_256;
  var BlockHash = common2.BlockHash;
  var sha256_K = [
    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
  ];
  function SHA256() {
    if (!(this instanceof SHA256))
      return new SHA256();
    BlockHash.call(this);
    this.h = [
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ];
    this.k = sha256_K;
    this.W = new Array(64);
  }
  utils2.inherits(SHA256, BlockHash);
  _256 = SHA256;
  SHA256.blockSize = 512;
  SHA256.outSize = 256;
  SHA256.hmacStrength = 192;
  SHA256.padLength = 64;
  SHA256.prototype._update = function _update(msg, start) {
    var W = this.W;
    for (var i2 = 0; i2 < 16; i2++)
      W[i2] = msg[start + i2];
    for (; i2 < W.length; i2++)
      W[i2] = sum32_4(g1_256(W[i2 - 2]), W[i2 - 7], g0_256(W[i2 - 15]), W[i2 - 16]);
    var a2 = this.h[0];
    var b2 = this.h[1];
    var c2 = this.h[2];
    var d = this.h[3];
    var e4 = this.h[4];
    var f2 = this.h[5];
    var g = this.h[6];
    var h2 = this.h[7];
    assert(this.k.length === W.length);
    for (i2 = 0; i2 < W.length; i2++) {
      var T1 = sum32_5(h2, s1_256(e4), ch32(e4, f2, g), this.k[i2], W[i2]);
      var T2 = sum32(s0_256(a2), maj32(a2, b2, c2));
      h2 = g;
      g = f2;
      f2 = e4;
      e4 = sum32(d, T1);
      d = c2;
      c2 = b2;
      b2 = a2;
      a2 = sum32(T1, T2);
    }
    this.h[0] = sum32(this.h[0], a2);
    this.h[1] = sum32(this.h[1], b2);
    this.h[2] = sum32(this.h[2], c2);
    this.h[3] = sum32(this.h[3], d);
    this.h[4] = sum32(this.h[4], e4);
    this.h[5] = sum32(this.h[5], f2);
    this.h[6] = sum32(this.h[6], g);
    this.h[7] = sum32(this.h[7], h2);
  };
  SHA256.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h, "big");
    else
      return utils2.split32(this.h, "big");
  };
  return _256;
}
var _224;
var hasRequired_224;
function require_224() {
  if (hasRequired_224) return _224;
  hasRequired_224 = 1;
  var utils2 = requireUtils$1();
  var SHA256 = require_256();
  function SHA224() {
    if (!(this instanceof SHA224))
      return new SHA224();
    SHA256.call(this);
    this.h = [
      3238371032,
      914150663,
      812702999,
      4144912697,
      4290775857,
      1750603025,
      1694076839,
      3204075428
    ];
  }
  utils2.inherits(SHA224, SHA256);
  _224 = SHA224;
  SHA224.blockSize = 512;
  SHA224.outSize = 224;
  SHA224.hmacStrength = 192;
  SHA224.padLength = 64;
  SHA224.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h.slice(0, 7), "big");
    else
      return utils2.split32(this.h.slice(0, 7), "big");
  };
  return _224;
}
var _512;
var hasRequired_512;
function require_512() {
  if (hasRequired_512) return _512;
  hasRequired_512 = 1;
  var utils2 = requireUtils$1();
  var common2 = requireCommon$3();
  var assert = requireMinimalisticAssert();
  var rotr64_hi = utils2.rotr64_hi;
  var rotr64_lo = utils2.rotr64_lo;
  var shr64_hi = utils2.shr64_hi;
  var shr64_lo = utils2.shr64_lo;
  var sum64 = utils2.sum64;
  var sum64_hi = utils2.sum64_hi;
  var sum64_lo = utils2.sum64_lo;
  var sum64_4_hi = utils2.sum64_4_hi;
  var sum64_4_lo = utils2.sum64_4_lo;
  var sum64_5_hi = utils2.sum64_5_hi;
  var sum64_5_lo = utils2.sum64_5_lo;
  var BlockHash = common2.BlockHash;
  var sha512_K = [
    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 SHA512() {
    if (!(this instanceof SHA512))
      return new SHA512();
    BlockHash.call(this);
    this.h = [
      1779033703,
      4089235720,
      3144134277,
      2227873595,
      1013904242,
      4271175723,
      2773480762,
      1595750129,
      1359893119,
      2917565137,
      2600822924,
      725511199,
      528734635,
      4215389547,
      1541459225,
      327033209
    ];
    this.k = sha512_K;
    this.W = new Array(160);
  }
  utils2.inherits(SHA512, BlockHash);
  _512 = SHA512;
  SHA512.blockSize = 1024;
  SHA512.outSize = 512;
  SHA512.hmacStrength = 192;
  SHA512.padLength = 128;
  SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
    var W = this.W;
    for (var i2 = 0; i2 < 32; i2++)
      W[i2] = msg[start + i2];
    for (; i2 < W.length; i2 += 2) {
      var c0_hi = g1_512_hi(W[i2 - 4], W[i2 - 3]);
      var c0_lo = g1_512_lo(W[i2 - 4], W[i2 - 3]);
      var c1_hi = W[i2 - 14];
      var c1_lo = W[i2 - 13];
      var c2_hi = g0_512_hi(W[i2 - 30], W[i2 - 29]);
      var c2_lo = g0_512_lo(W[i2 - 30], W[i2 - 29]);
      var c3_hi = W[i2 - 32];
      var c3_lo = W[i2 - 31];
      W[i2] = sum64_4_hi(
        c0_hi,
        c0_lo,
        c1_hi,
        c1_lo,
        c2_hi,
        c2_lo,
        c3_hi,
        c3_lo
      );
      W[i2 + 1] = sum64_4_lo(
        c0_hi,
        c0_lo,
        c1_hi,
        c1_lo,
        c2_hi,
        c2_lo,
        c3_hi,
        c3_lo
      );
    }
  };
  SHA512.prototype._update = function _update(msg, start) {
    this._prepareBlock(msg, start);
    var W = this.W;
    var ah = this.h[0];
    var al = this.h[1];
    var bh = this.h[2];
    var bl = this.h[3];
    var ch = this.h[4];
    var cl = this.h[5];
    var dh2 = this.h[6];
    var dl = this.h[7];
    var eh = this.h[8];
    var el = this.h[9];
    var fh = this.h[10];
    var fl = this.h[11];
    var gh = this.h[12];
    var gl = this.h[13];
    var hh = this.h[14];
    var hl = this.h[15];
    assert(this.k.length === W.length);
    for (var i2 = 0; i2 < W.length; i2 += 2) {
      var c0_hi = hh;
      var c0_lo = hl;
      var c1_hi = s1_512_hi(eh, el);
      var c1_lo = s1_512_lo(eh, el);
      var c2_hi = ch64_hi(eh, el, fh, fl, gh);
      var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
      var c3_hi = this.k[i2];
      var c3_lo = this.k[i2 + 1];
      var c4_hi = W[i2];
      var c4_lo = W[i2 + 1];
      var T1_hi = sum64_5_hi(
        c0_hi,
        c0_lo,
        c1_hi,
        c1_lo,
        c2_hi,
        c2_lo,
        c3_hi,
        c3_lo,
        c4_hi,
        c4_lo
      );
      var T1_lo = sum64_5_lo(
        c0_hi,
        c0_lo,
        c1_hi,
        c1_lo,
        c2_hi,
        c2_lo,
        c3_hi,
        c3_lo,
        c4_hi,
        c4_lo
      );
      c0_hi = s0_512_hi(ah, al);
      c0_lo = s0_512_lo(ah, al);
      c1_hi = maj64_hi(ah, al, bh, bl, ch);
      c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
      var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
      var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
      hh = gh;
      hl = gl;
      gh = fh;
      gl = fl;
      fh = eh;
      fl = el;
      eh = sum64_hi(dh2, dl, T1_hi, T1_lo);
      el = sum64_lo(dl, dl, T1_hi, T1_lo);
      dh2 = ch;
      dl = cl;
      ch = bh;
      cl = bl;
      bh = ah;
      bl = al;
      ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
      al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
    }
    sum64(this.h, 0, ah, al);
    sum64(this.h, 2, bh, bl);
    sum64(this.h, 4, ch, cl);
    sum64(this.h, 6, dh2, dl);
    sum64(this.h, 8, eh, el);
    sum64(this.h, 10, fh, fl);
    sum64(this.h, 12, gh, gl);
    sum64(this.h, 14, hh, hl);
  };
  SHA512.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h, "big");
    else
      return utils2.split32(this.h, "big");
  };
  function ch64_hi(xh, xl, yh, yl, zh) {
    var r2 = xh & yh ^ ~xh & zh;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function ch64_lo(xh, xl, yh, yl, zh, zl) {
    var r2 = xl & yl ^ ~xl & zl;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function maj64_hi(xh, xl, yh, yl, zh) {
    var r2 = xh & yh ^ xh & zh ^ yh & zh;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function maj64_lo(xh, xl, yh, yl, zh, zl) {
    var r2 = xl & yl ^ xl & zl ^ yl & zl;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function s0_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 28);
    var c1_hi = rotr64_hi(xl, xh, 2);
    var c2_hi = rotr64_hi(xl, xh, 7);
    var r2 = c0_hi ^ c1_hi ^ c2_hi;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function s0_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 28);
    var c1_lo = rotr64_lo(xl, xh, 2);
    var c2_lo = rotr64_lo(xl, xh, 7);
    var r2 = c0_lo ^ c1_lo ^ c2_lo;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function s1_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 14);
    var c1_hi = rotr64_hi(xh, xl, 18);
    var c2_hi = rotr64_hi(xl, xh, 9);
    var r2 = c0_hi ^ c1_hi ^ c2_hi;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function s1_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 14);
    var c1_lo = rotr64_lo(xh, xl, 18);
    var c2_lo = rotr64_lo(xl, xh, 9);
    var r2 = c0_lo ^ c1_lo ^ c2_lo;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function g0_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 1);
    var c1_hi = rotr64_hi(xh, xl, 8);
    var c2_hi = shr64_hi(xh, xl, 7);
    var r2 = c0_hi ^ c1_hi ^ c2_hi;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function g0_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 1);
    var c1_lo = rotr64_lo(xh, xl, 8);
    var c2_lo = shr64_lo(xh, xl, 7);
    var r2 = c0_lo ^ c1_lo ^ c2_lo;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function g1_512_hi(xh, xl) {
    var c0_hi = rotr64_hi(xh, xl, 19);
    var c1_hi = rotr64_hi(xl, xh, 29);
    var c2_hi = shr64_hi(xh, xl, 6);
    var r2 = c0_hi ^ c1_hi ^ c2_hi;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  function g1_512_lo(xh, xl) {
    var c0_lo = rotr64_lo(xh, xl, 19);
    var c1_lo = rotr64_lo(xl, xh, 29);
    var c2_lo = shr64_lo(xh, xl, 6);
    var r2 = c0_lo ^ c1_lo ^ c2_lo;
    if (r2 < 0)
      r2 += 4294967296;
    return r2;
  }
  return _512;
}
var _384;
var hasRequired_384;
function require_384() {
  if (hasRequired_384) return _384;
  hasRequired_384 = 1;
  var utils2 = requireUtils$1();
  var SHA512 = require_512();
  function SHA384() {
    if (!(this instanceof SHA384))
      return new SHA384();
    SHA512.call(this);
    this.h = [
      3418070365,
      3238371032,
      1654270250,
      914150663,
      2438529370,
      812702999,
      355462360,
      4144912697,
      1731405415,
      4290775857,
      2394180231,
      1750603025,
      3675008525,
      1694076839,
      1203062813,
      3204075428
    ];
  }
  utils2.inherits(SHA384, SHA512);
  _384 = SHA384;
  SHA384.blockSize = 1024;
  SHA384.outSize = 384;
  SHA384.hmacStrength = 192;
  SHA384.padLength = 128;
  SHA384.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h.slice(0, 12), "big");
    else
      return utils2.split32(this.h.slice(0, 12), "big");
  };
  return _384;
}
var hasRequiredSha;
function requireSha() {
  if (hasRequiredSha) return sha;
  hasRequiredSha = 1;
  sha.sha1 = require_1();
  sha.sha224 = require_224();
  sha.sha256 = require_256();
  sha.sha384 = require_384();
  sha.sha512 = require_512();
  return sha;
}
var ripemd = {};
var hasRequiredRipemd;
function requireRipemd() {
  if (hasRequiredRipemd) return ripemd;
  hasRequiredRipemd = 1;
  var utils2 = requireUtils$1();
  var common2 = requireCommon$3();
  var rotl32 = utils2.rotl32;
  var sum32 = utils2.sum32;
  var sum32_3 = utils2.sum32_3;
  var sum32_4 = utils2.sum32_4;
  var BlockHash = common2.BlockHash;
  function RIPEMD160() {
    if (!(this instanceof RIPEMD160))
      return new RIPEMD160();
    BlockHash.call(this);
    this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
    this.endian = "little";
  }
  utils2.inherits(RIPEMD160, BlockHash);
  ripemd.ripemd160 = RIPEMD160;
  RIPEMD160.blockSize = 512;
  RIPEMD160.outSize = 160;
  RIPEMD160.hmacStrength = 192;
  RIPEMD160.padLength = 64;
  RIPEMD160.prototype._update = function update(msg, start) {
    var A2 = this.h[0];
    var B2 = this.h[1];
    var C2 = this.h[2];
    var D = this.h[3];
    var E2 = this.h[4];
    var Ah = A2;
    var Bh = B2;
    var Ch = C2;
    var Dh = D;
    var Eh = E2;
    for (var j = 0; j < 80; j++) {
      var T2 = sum32(
        rotl32(
          sum32_4(A2, f2(j, B2, C2, D), msg[r2[j] + start], K(j)),
          s2[j]
        ),
        E2
      );
      A2 = E2;
      E2 = D;
      D = rotl32(C2, 10);
      C2 = B2;
      B2 = T2;
      T2 = sum32(
        rotl32(
          sum32_4(Ah, f2(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
          sh[j]
        ),
        Eh
      );
      Ah = Eh;
      Eh = Dh;
      Dh = rotl32(Ch, 10);
      Ch = Bh;
      Bh = T2;
    }
    T2 = sum32_3(this.h[1], C2, Dh);
    this.h[1] = sum32_3(this.h[2], D, Eh);
    this.h[2] = sum32_3(this.h[3], E2, Ah);
    this.h[3] = sum32_3(this.h[4], A2, Bh);
    this.h[4] = sum32_3(this.h[0], B2, Ch);
    this.h[0] = T2;
  };
  RIPEMD160.prototype._digest = function digest(enc) {
    if (enc === "hex")
      return utils2.toHex32(this.h, "little");
    else
      return utils2.split32(this.h, "little");
  };
  function f2(j, x2, y2, z2) {
    if (j <= 15)
      return x2 ^ y2 ^ z2;
    else if (j <= 31)
      return x2 & y2 | ~x2 & z2;
    else if (j <= 47)
      return (x2 | ~y2) ^ z2;
    else if (j <= 63)
      return x2 & z2 | y2 & ~z2;
    else
      return x2 ^ (y2 | ~z2);
  }
  function K(j) {
    if (j <= 15)
      return 0;
    else if (j <= 31)
      return 1518500249;
    else if (j <= 47)
      return 1859775393;
    else if (j <= 63)
      return 2400959708;
    else
      return 2840853838;
  }
  function Kh(j) {
    if (j <= 15)
      return 1352829926;
    else if (j <= 31)
      return 1548603684;
    else if (j <= 47)
      return 1836072691;
    else if (j <= 63)
      return 2053994217;
    else
      return 0;
  }
  var r2 = [
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    7,
    4,
    13,
    1,
    10,
    6,
    15,
    3,
    12,
    0,
    9,
    5,
    2,
    14,
    11,
    8,
    3,
    10,
    14,
    4,
    9,
    15,
    8,
    1,
    2,
    7,
    0,
    6,
    13,
    11,
    5,
    12,
    1,
    9,
    11,
    10,
    0,
    8,
    12,
    4,
    13,
    3,
    7,
    15,
    14,
    5,
    6,
    2,
    4,
    0,
    5,
    9,
    7,
    12,
    2,
    10,
    14,
    1,
    3,
    8,
    11,
    6,
    15,
    13
  ];
  var rh = [
    5,
    14,
    7,
    0,
    9,
    2,
    11,
    4,
    13,
    6,
    15,
    8,
    1,
    10,
    3,
    12,
    6,
    11,
    3,
    7,
    0,
    13,
    5,
    10,
    14,
    15,
    8,
    12,
    4,
    9,
    1,
    2,
    15,
    5,
    1,
    3,
    7,
    14,
    6,
    9,
    11,
    8,
    12,
    2,
    10,
    0,
    4,
    13,
    8,
    6,
    4,
    1,
    3,
    11,
    15,
    0,
    5,
    12,
    2,
    13,
    9,
    7,
    10,
    14,
    12,
    15,
    10,
    4,
    1,
    5,
    8,
    7,
    6,
    2,
    13,
    14,
    0,
    3,
    9,
    11
  ];
  var s2 = [
    11,
    14,
    15,
    12,
    5,
    8,
    7,
    9,
    11,
    13,
    14,
    15,
    6,
    7,
    9,
    8,
    7,
    6,
    8,
    13,
    11,
    9,
    7,
    15,
    7,
    12,
    15,
    9,
    11,
    7,
    13,
    12,
    11,
    13,
    6,
    7,
    14,
    9,
    13,
    15,
    14,
    8,
    13,
    6,
    5,
    12,
    7,
    5,
    11,
    12,
    14,
    15,
    14,
    15,
    9,
    8,
    9,
    14,
    5,
    6,
    8,
    6,
    5,
    12,
    9,
    15,
    5,
    11,
    6,
    8,
    13,
    12,
    5,
    12,
    13,
    14,
    11,
    8,
    5,
    6
  ];
  var sh = [
    8,
    9,
    9,
    11,
    13,
    15,
    15,
    5,
    7,
    7,
    8,
    11,
    14,
    14,
    12,
    6,
    9,
    13,
    15,
    7,
    12,
    8,
    9,
    11,
    7,
    7,
    12,
    7,
    6,
    15,
    13,
    11,
    9,
    7,
    15,
    11,
    8,
    6,
    6,
    14,
    12,
    13,
    5,
    14,
    13,
    13,
    7,
    5,
    15,
    5,
    8,
    11,
    14,
    14,
    6,
    14,
    6,
    9,
    12,
    9,
    12,
    5,
    15,
    8,
    8,
    5,
    12,
    9,
    12,
    5,
    14,
    6,
    8,
    13,
    6,
    5,
    15,
    13,
    11,
    11
  ];
  return ripemd;
}
var hmac$2;
var hasRequiredHmac$1;
function requireHmac$1() {
  if (hasRequiredHmac$1) return hmac$2;
  hasRequiredHmac$1 = 1;
  var utils2 = requireUtils$1();
  var assert = requireMinimalisticAssert();
  function Hmac(hash2, key2, enc) {
    if (!(this instanceof Hmac))
      return new Hmac(hash2, key2, enc);
    this.Hash = hash2;
    this.blockSize = hash2.blockSize / 8;
    this.outSize = hash2.outSize / 8;
    this.inner = null;
    this.outer = null;
    this._init(utils2.toArray(key2, enc));
  }
  hmac$2 = Hmac;
  Hmac.prototype._init = function init2(key2) {
    if (key2.length > this.blockSize)
      key2 = new this.Hash().update(key2).digest();
    assert(key2.length <= this.blockSize);
    for (var i2 = key2.length; i2 < this.blockSize; i2++)
      key2.push(0);
    for (i2 = 0; i2 < key2.length; i2++)
      key2[i2] ^= 54;
    this.inner = new this.Hash().update(key2);
    for (i2 = 0; i2 < key2.length; i2++)
      key2[i2] ^= 106;
    this.outer = new this.Hash().update(key2);
  };
  Hmac.prototype.update = function update(msg, enc) {
    this.inner.update(msg, enc);
    return this;
  };
  Hmac.prototype.digest = function digest(enc) {
    this.outer.update(this.inner.digest());
    return this.outer.digest(enc);
  };
  return hmac$2;
}
var hasRequiredHash;
function requireHash() {
  if (hasRequiredHash) return hash;
  hasRequiredHash = 1;
  (function(exports) {
    var hash2 = exports;
    hash2.utils = requireUtils$1();
    hash2.common = requireCommon$3();
    hash2.sha = requireSha();
    hash2.ripemd = requireRipemd();
    hash2.hmac = requireHmac$1();
    hash2.sha1 = hash2.sha.sha1;
    hash2.sha256 = hash2.sha.sha256;
    hash2.sha224 = hash2.sha.sha224;
    hash2.sha384 = hash2.sha.sha384;
    hash2.sha512 = hash2.sha.sha512;
    hash2.ripemd160 = hash2.ripemd.ripemd160;
  })(hash);
  return hash;
}
var secp256k1;
var hasRequiredSecp256k1;
function requireSecp256k1() {
  if (hasRequiredSecp256k1) return secp256k1;
  hasRequiredSecp256k1 = 1;
  secp256k1 = {
    doubles: {
      step: 4,
      points: [
        [
          "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a",
          "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"
        ],
        [
          "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508",
          "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"
        ],
        [
          "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739",
          "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"
        ],
        [
          "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640",
          "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"
        ],
        [
          "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c",
          "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"
        ],
        [
          "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda",
          "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"
        ],
        [
          "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa",
          "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"
        ],
        [
          "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0",
          "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"
        ],
        [
          "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d",
          "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"
        ],
        [
          "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d",
          "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"
        ],
        [
          "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1",
          "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"
        ],
        [
          "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0",
          "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"
        ],
        [
          "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047",
          "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"
        ],
        [
          "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862",
          "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"
        ],
        [
          "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7",
          "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"
        ],
        [
          "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd",
          "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"
        ],
        [
          "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83",
          "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"
        ],
        [
          "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a",
          "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"
        ],
        [
          "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8",
          "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"
        ],
        [
          "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d",
          "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"
        ],
        [
          "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725",
          "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"
        ],
        [
          "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754",
          "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"
        ],
        [
          "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c",
          "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"
        ],
        [
          "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6",
          "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"
        ],
        [
          "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39",
          "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"
        ],
        [
          "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891",
          "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"
        ],
        [
          "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b",
          "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"
        ],
        [
          "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03",
          "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"
        ],
        [
          "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d",
          "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"
        ],
        [
          "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070",
          "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"
        ],
        [
          "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4",
          "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"
        ],
        [
          "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da",
          "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"
        ],
        [
          "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11",
          "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"
        ],
        [
          "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e",
          "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"
        ],
        [
          "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41",
          "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"
        ],
        [
          "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef",
          "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"
        ],
        [
          "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8",
          "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"
        ],
        [
          "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d",
          "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"
        ],
        [
          "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96",
          "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"
        ],
        [
          "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd",
          "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"
        ],
        [
          "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5",
          "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"
        ],
        [
          "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266",
          "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"
        ],
        [
          "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71",
          "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"
        ],
        [
          "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac",
          "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"
        ],
        [
          "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751",
          "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"
        ],
        [
          "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e",
          "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"
        ],
        [
          "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241",
          "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"
        ],
        [
          "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3",
          "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"
        ],
        [
          "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f",
          "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"
        ],
        [
          "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19",
          "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"
        ],
        [
          "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be",
          "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"
        ],
        [
          "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9",
          "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"
        ],
        [
          "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2",
          "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"
        ],
        [
          "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13",
          "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"
        ],
        [
          "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c",
          "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"
        ],
        [
          "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba",
          "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"
        ],
        [
          "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151",
          "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"
        ],
        [
          "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073",
          "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"
        ],
        [
          "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458",
          "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"
        ],
        [
          "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b",
          "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"
        ],
        [
          "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366",
          "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"
        ],
        [
          "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa",
          "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"
        ],
        [
          "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0",
          "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"
        ],
        [
          "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787",
          "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"
        ],
        [
          "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e",
          "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"
        ]
      ]
    },
    naf: {
      wnd: 7,
      points: [
        [
          "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9",
          "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"
        ],
        [
          "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4",
          "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"
        ],
        [
          "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc",
          "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"
        ],
        [
          "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe",
          "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"
        ],
        [
          "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb",
          "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"
        ],
        [
          "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8",
          "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"
        ],
        [
          "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e",
          "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"
        ],
        [
          "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34",
          "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"
        ],
        [
          "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c",
          "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"
        ],
        [
          "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5",
          "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"
        ],
        [
          "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f",
          "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"
        ],
        [
          "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714",
          "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"
        ],
        [
          "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729",
          "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"
        ],
        [
          "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db",
          "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"
        ],
        [
          "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4",
          "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"
        ],
        [
          "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5",
          "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"
        ],
        [
          "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479",
          "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"
        ],
        [
          "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d",
          "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"
        ],
        [
          "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f",
          "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"
        ],
        [
          "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb",
          "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"
        ],
        [
          "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9",
          "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"
        ],
        [
          "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963",
          "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"
        ],
        [
          "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74",
          "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"
        ],
        [
          "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530",
          "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"
        ],
        [
          "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b",
          "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"
        ],
        [
          "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247",
          "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"
        ],
        [
          "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1",
          "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"
        ],
        [
          "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120",
          "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"
        ],
        [
          "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435",
          "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"
        ],
        [
          "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18",
          "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"
        ],
        [
          "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8",
          "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"
        ],
        [
          "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb",
          "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"
        ],
        [
          "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f",
          "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"
        ],
        [
          "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143",
          "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"
        ],
        [
          "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba",
          "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"
        ],
        [
          "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45",
          "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"
        ],
        [
          "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a",
          "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"
        ],
        [
          "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e",
          "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"
        ],
        [
          "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8",
          "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"
        ],
        [
          "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c",
          "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"
        ],
        [
          "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519",
          "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"
        ],
        [
          "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab",
          "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"
        ],
        [
          "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca",
          "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"
        ],
        [
          "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf",
          "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"
        ],
        [
          "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610",
          "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"
        ],
        [
          "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4",
          "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"
        ],
        [
          "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c",
          "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"
        ],
        [
          "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940",
          "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"
        ],
        [
          "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980",
          "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"
        ],
        [
          "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3",
          "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"
        ],
        [
          "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf",
          "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"
        ],
        [
          "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63",
          "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"
        ],
        [
          "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448",
          "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"
        ],
        [
          "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf",
          "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"
        ],
        [
          "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5",
          "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"
        ],
        [
          "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6",
          "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"
        ],
        [
          "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5",
          "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"
        ],
        [
          "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99",
          "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"
        ],
        [
          "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51",
          "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"
        ],
        [
          "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5",
          "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"
        ],
        [
          "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5",
          "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"
        ],
        [
          "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997",
          "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"
        ],
        [
          "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881",
          "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"
        ],
        [
          "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5",
          "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"
        ],
        [
          "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66",
          "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"
        ],
        [
          "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726",
          "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"
        ],
        [
          "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede",
          "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"
        ],
        [
          "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94",
          "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"
        ],
        [
          "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31",
          "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"
        ],
        [
          "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51",
          "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"
        ],
        [
          "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252",
          "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"
        ],
        [
          "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5",
          "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"
        ],
        [
          "d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b",
          "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"
        ],
        [
          "ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4",
          "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"
        ],
        [
          "af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f",
          "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"
        ],
        [
          "e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889",
          "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"
        ],
        [
          "591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246",
          "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"
        ],
        [
          "11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984",
          "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"
        ],
        [
          "3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a",
          "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"
        ],
        [
          "cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030",
          "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"
        ],
        [
          "c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197",
          "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"
        ],
        [
          "c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593",
          "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"
        ],
        [
          "a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef",
          "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"
        ],
        [
          "347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38",
          "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"
        ],
        [
          "da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a",
          "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"
        ],
        [
          "c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111",
          "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"
        ],
        [
          "4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502",
          "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"
        ],
        [
          "3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea",
          "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"
        ],
        [
          "cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26",
          "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"
        ],
        [
          "b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986",
          "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"
        ],
        [
          "d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e",
          "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"
        ],
        [
          "48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4",
          "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"
        ],
        [
          "dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda",
          "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"
        ],
        [
          "6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859",
          "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"
        ],
        [
          "e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f",
          "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"
        ],
        [
          "eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c",
          "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"
        ],
        [
          "13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942",
          "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"
        ],
        [
          "ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a",
          "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"
        ],
        [
          "b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80",
          "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"
        ],
        [
          "ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d",
          "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"
        ],
        [
          "8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1",
          "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"
        ],
        [
          "52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63",
          "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"
        ],
        [
          "e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352",
          "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"
        ],
        [
          "7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193",
          "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"
        ],
        [
          "5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00",
          "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"
        ],
        [
          "32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58",
          "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"
        ],
        [
          "e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7",
          "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"
        ],
        [
          "8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8",
          "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"
        ],
        [
          "4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e",
          "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"
        ],
        [
          "3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d",
          "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"
        ],
        [
          "674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b",
          "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"
        ],
        [
          "d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f",
          "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"
        ],
        [
          "30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6",
          "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"
        ],
        [
          "be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297",
          "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"
        ],
        [
          "93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a",
          "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"
        ],
        [
          "b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c",
          "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"
        ],
        [
          "d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52",
          "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"
        ],
        [
          "d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb",
          "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"
        ],
        [
          "463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065",
          "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"
        ],
        [
          "7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917",
          "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"
        ],
        [
          "74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9",
          "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"
        ],
        [
          "30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3",
          "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"
        ],
        [
          "9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57",
          "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"
        ],
        [
          "176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66",
          "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"
        ],
        [
          "75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8",
          "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"
        ],
        [
          "809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721",
          "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"
        ],
        [
          "1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180",
          "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"
        ]
      ]
    }
  };
  return secp256k1;
}
var hasRequiredCurves;
function requireCurves() {
  if (hasRequiredCurves) return curves;
  hasRequiredCurves = 1;
  (function(exports) {
    var curves2 = exports;
    var hash2 = requireHash();
    var curve2 = requireCurve();
    var utils2 = requireUtils$2();
    var assert = utils2.assert;
    function PresetCurve(options2) {
      if (options2.type === "short")
        this.curve = new curve2.short(options2);
      else if (options2.type === "edwards")
        this.curve = new curve2.edwards(options2);
      else
        this.curve = new curve2.mont(options2);
      this.g = this.curve.g;
      this.n = this.curve.n;
      this.hash = options2.hash;
      assert(this.g.validate(), "Invalid curve");
      assert(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O");
    }
    curves2.PresetCurve = PresetCurve;
    function defineCurve(name, options2) {
      Object.defineProperty(curves2, name, {
        configurable: true,
        enumerable: true,
        get: function() {
          var curve3 = new PresetCurve(options2);
          Object.defineProperty(curves2, name, {
            configurable: true,
            enumerable: true,
            value: curve3
          });
          return curve3;
        }
      });
    }
    defineCurve("p192", {
      type: "short",
      prime: "p192",
      p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",
      a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",
      b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",
      n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",
      hash: hash2.sha256,
      gRed: false,
      g: [
        "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012",
        "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"
      ]
    });
    defineCurve("p224", {
      type: "short",
      prime: "p224",
      p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",
      a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",
      b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",
      n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",
      hash: hash2.sha256,
      gRed: false,
      g: [
        "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21",
        "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"
      ]
    });
    defineCurve("p256", {
      type: "short",
      prime: null,
      p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",
      a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",
      b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",
      n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",
      hash: hash2.sha256,
      gRed: false,
      g: [
        "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296",
        "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"
      ]
    });
    defineCurve("p384", {
      type: "short",
      prime: null,
      p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",
      a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",
      b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",
      n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",
      hash: hash2.sha384,
      gRed: false,
      g: [
        "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7",
        "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"
      ]
    });
    defineCurve("p521", {
      type: "short",
      prime: null,
      p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",
      a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",
      b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",
      n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",
      hash: hash2.sha512,
      gRed: false,
      g: [
        "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66",
        "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"
      ]
    });
    defineCurve("curve25519", {
      type: "mont",
      prime: "p25519",
      p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",
      a: "76d06",
      b: "1",
      n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",
      hash: hash2.sha256,
      gRed: false,
      g: [
        "9"
      ]
    });
    defineCurve("ed25519", {
      type: "edwards",
      prime: "p25519",
      p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",
      a: "-1",
      c: "1",
      // -121665 * (121666^(-1)) (mod P)
      d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",
      n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",
      hash: hash2.sha256,
      gRed: false,
      g: [
        "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a",
        // 4/5
        "6666666666666666666666666666666666666666666666666666666666666658"
      ]
    });
    var pre;
    try {
      pre = requireSecp256k1();
    } catch (e4) {
      pre = void 0;
    }
    defineCurve("secp256k1", {
      type: "short",
      prime: "k256",
      p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",
      a: "0",
      b: "7",
      n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",
      h: "1",
      hash: hash2.sha256,
      // Precomputed endomorphism
      beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",
      lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",
      basis: [
        {
          a: "3086d221a7d46bcde86c90e49284eb15",
          b: "-e4437ed6010e88286f547fa90abfe4c3"
        },
        {
          a: "114ca50f7a8e2f3f657c1108d9d44cfd8",
          b: "3086d221a7d46bcde86c90e49284eb15"
        }
      ],
      gRed: false,
      g: [
        "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
        "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",
        pre
      ]
    });
  })(curves);
  return curves;
}
var hmacDrbg;
var hasRequiredHmacDrbg;
function requireHmacDrbg() {
  if (hasRequiredHmacDrbg) return hmacDrbg;
  hasRequiredHmacDrbg = 1;
  var hash2 = requireHash();
  var utils2 = requireUtils$3();
  var assert = requireMinimalisticAssert();
  function HmacDRBG(options2) {
    if (!(this instanceof HmacDRBG))
      return new HmacDRBG(options2);
    this.hash = options2.hash;
    this.predResist = !!options2.predResist;
    this.outLen = this.hash.outSize;
    this.minEntropy = options2.minEntropy || this.hash.hmacStrength;
    this._reseed = null;
    this.reseedInterval = null;
    this.K = null;
    this.V = null;
    var entropy = utils2.toArray(options2.entropy, options2.entropyEnc || "hex");
    var nonce = utils2.toArray(options2.nonce, options2.nonceEnc || "hex");
    var pers = utils2.toArray(options2.pers, options2.persEnc || "hex");
    assert(
      entropy.length >= this.minEntropy / 8,
      "Not enough entropy. Minimum is: " + this.minEntropy + " bits"
    );
    this._init(entropy, nonce, pers);
  }
  hmacDrbg = HmacDRBG;
  HmacDRBG.prototype._init = function init2(entropy, nonce, pers) {
    var seed = entropy.concat(nonce).concat(pers);
    this.K = new Array(this.outLen / 8);
    this.V = new Array(this.outLen / 8);
    for (var i2 = 0; i2 < this.V.length; i2++) {
      this.K[i2] = 0;
      this.V[i2] = 1;
    }
    this._update(seed);
    this._reseed = 1;
    this.reseedInterval = 281474976710656;
  };
  HmacDRBG.prototype._hmac = function hmac2() {
    return new hash2.hmac(this.hash, this.K);
  };
  HmacDRBG.prototype._update = function update(seed) {
    var kmac = this._hmac().update(this.V).update([0]);
    if (seed)
      kmac = kmac.update(seed);
    this.K = kmac.digest();
    this.V = this._hmac().update(this.V).digest();
    if (!seed)
      return;
    this.K = this._hmac().update(this.V).update([1]).update(seed).digest();
    this.V = this._hmac().update(this.V).digest();
  };
  HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add2, addEnc) {
    if (typeof entropyEnc !== "string") {
      addEnc = add2;
      add2 = entropyEnc;
      entropyEnc = null;
    }
    entropy = utils2.toArray(entropy, entropyEnc);
    add2 = utils2.toArray(add2, addEnc);
    assert(
      entropy.length >= this.minEntropy / 8,
      "Not enough entropy. Minimum is: " + this.minEntropy + " bits"
    );
    this._update(entropy.concat(add2 || []));
    this._reseed = 1;
  };
  HmacDRBG.prototype.generate = function generate(len, enc, add2, addEnc) {
    if (this._reseed > this.reseedInterval)
      throw new Error("Reseed is required");
    if (typeof enc !== "string") {
      addEnc = add2;
      add2 = enc;
      enc = null;
    }
    if (add2) {
      add2 = utils2.toArray(add2, addEnc || "hex");
      this._update(add2);
    }
    var temp = [];
    while (temp.length < len) {
      this.V = this._hmac().update(this.V).digest();
      temp = temp.concat(this.V);
    }
    var res = temp.slice(0, len);
    this._update(add2);
    this._reseed++;
    return utils2.encode(res, enc);
  };
  return hmacDrbg;
}
var key$1;
var hasRequiredKey$1;
function requireKey$1() {
  if (hasRequiredKey$1) return key$1;
  hasRequiredKey$1 = 1;
  var BN = requireBn$1();
  var utils2 = requireUtils$2();
  var assert = utils2.assert;
  function KeyPair(ec2, options2) {
    this.ec = ec2;
    this.priv = null;
    this.pub = null;
    if (options2.priv)
      this._importPrivate(options2.priv, options2.privEnc);
    if (options2.pub)
      this._importPublic(options2.pub, options2.pubEnc);
  }
  key$1 = KeyPair;
  KeyPair.fromPublic = function fromPublic(ec2, pub, enc) {
    if (pub instanceof KeyPair)
      return pub;
    return new KeyPair(ec2, {
      pub,
      pubEnc: enc
    });
  };
  KeyPair.fromPrivate = function fromPrivate(ec2, priv, enc) {
    if (priv instanceof KeyPair)
      return priv;
    return new KeyPair(ec2, {
      priv,
      privEnc: enc
    });
  };
  KeyPair.prototype.validate = function validate2() {
    var pub = this.getPublic();
    if (pub.isInfinity())
      return { result: false, reason: "Invalid public key" };
    if (!pub.validate())
      return { result: false, reason: "Public key is not a point" };
    if (!pub.mul(this.ec.curve.n).isInfinity())
      return { result: false, reason: "Public key * N != O" };
    return { result: true, reason: null };
  };
  KeyPair.prototype.getPublic = function getPublic(compact, enc) {
    if (typeof compact === "string") {
      enc = compact;
      compact = null;
    }
    if (!this.pub)
      this.pub = this.ec.g.mul(this.priv);
    if (!enc)
      return this.pub;
    return this.pub.encode(enc, compact);
  };
  KeyPair.prototype.getPrivate = function getPrivate(enc) {
    if (enc === "hex")
      return this.priv.toString(16, 2);
    else
      return this.priv;
  };
  KeyPair.prototype._importPrivate = function _importPrivate(key2, enc) {
    this.priv = new BN(key2, enc || 16);
    this.priv = this.priv.umod(this.ec.curve.n);
  };
  KeyPair.prototype._importPublic = function _importPublic(key2, enc) {
    if (key2.x || key2.y) {
      if (this.ec.curve.type === "mont") {
        assert(key2.x, "Need x coordinate");
      } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") {
        assert(key2.x && key2.y, "Need both x and y coordinate");
      }
      this.pub = this.ec.curve.point(key2.x, key2.y);
      return;
    }
    this.pub = this.ec.curve.decodePoint(key2, enc);
  };
  KeyPair.prototype.derive = function derive(pub) {
    if (!pub.validate()) {
      assert(pub.validate(), "public point not validated");
    }
    return pub.mul(this.priv).getX();
  };
  KeyPair.prototype.sign = function sign2(msg, enc, options2) {
    return this.ec.sign(msg, this, enc, options2);
  };
  KeyPair.prototype.verify = function verify(msg, signature2, options2) {
    return this.ec.verify(msg, signature2, this, void 0, options2);
  };
  KeyPair.prototype.inspect = function inspect() {
    return "<Key priv: " + (this.priv && this.priv.toString(16, 2)) + " pub: " + (this.pub && this.pub.inspect()) + " >";
  };
  return key$1;
}
var signature$1;
var hasRequiredSignature$1;
function requireSignature$1() {
  if (hasRequiredSignature$1) return signature$1;
  hasRequiredSignature$1 = 1;
  var BN = requireBn$1();
  var utils2 = requireUtils$2();
  var assert = utils2.assert;
  function Signature(options2, enc) {
    if (options2 instanceof Signature)
      return options2;
    if (this._importDER(options2, enc))
      return;
    assert(options2.r && options2.s, "Signature without r or s");
    this.r = new BN(options2.r, 16);
    this.s = new BN(options2.s, 16);
    if (options2.recoveryParam === void 0)
      this.recoveryParam = null;
    else
      this.recoveryParam = options2.recoveryParam;
  }
  signature$1 = Signature;
  function Position() {
    this.place = 0;
  }
  function getLength(buf, p2) {
    var initial = buf[p2.place++];
    if (!(initial & 128)) {
      return initial;
    }
    var octetLen = initial & 15;
    if (octetLen === 0 || octetLen > 4) {
      return false;
    }
    if (buf[p2.place] === 0) {
      return false;
    }
    var val = 0;
    for (var i2 = 0, off = p2.place; i2 < octetLen; i2++, off++) {
      val <<= 8;
      val |= buf[off];
      val >>>= 0;
    }
    if (val <= 127) {
      return false;
    }
    p2.place = off;
    return val;
  }
  function rmPadding(buf) {
    var i2 = 0;
    var len = buf.length - 1;
    while (!buf[i2] && !(buf[i2 + 1] & 128) && i2 < len) {
      i2++;
    }
    if (i2 === 0) {
      return buf;
    }
    return buf.slice(i2);
  }
  Signature.prototype._importDER = function _importDER(data2, enc) {
    data2 = utils2.toArray(data2, enc);
    var p2 = new Position();
    if (data2[p2.place++] !== 48) {
      return false;
    }
    var len = getLength(data2, p2);
    if (len === false) {
      return false;
    }
    if (len + p2.place !== data2.length) {
      return false;
    }
    if (data2[p2.place++] !== 2) {
      return false;
    }
    var rlen = getLength(data2, p2);
    if (rlen === false) {
      return false;
    }
    if ((data2[p2.place] & 128) !== 0) {
      return false;
    }
    var r2 = data2.slice(p2.place, rlen + p2.place);
    p2.place += rlen;
    if (data2[p2.place++] !== 2) {
      return false;
    }
    var slen = getLength(data2, p2);
    if (slen === false) {
      return false;
    }
    if (data2.length !== slen + p2.place) {
      return false;
    }
    if ((data2[p2.place] & 128) !== 0) {
      return false;
    }
    var s2 = data2.slice(p2.place, slen + p2.place);
    if (r2[0] === 0) {
      if (r2[1] & 128) {
        r2 = r2.slice(1);
      } else {
        return false;
      }
    }
    if (s2[0] === 0) {
      if (s2[1] & 128) {
        s2 = s2.slice(1);
      } else {
        return false;
      }
    }
    this.r = new BN(r2);
    this.s = new BN(s2);
    this.recoveryParam = null;
    return true;
  };
  function constructLength(arr, len) {
    if (len < 128) {
      arr.push(len);
      return;
    }
    var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
    arr.push(octets | 128);
    while (--octets) {
      arr.push(len >>> (octets << 3) & 255);
    }
    arr.push(len);
  }
  Signature.prototype.toDER = function toDER(enc) {
    var r2 = this.r.toArray();
    var s2 = this.s.toArray();
    if (r2[0] & 128)
      r2 = [0].concat(r2);
    if (s2[0] & 128)
      s2 = [0].concat(s2);
    r2 = rmPadding(r2);
    s2 = rmPadding(s2);
    while (!s2[0] && !(s2[1] & 128)) {
      s2 = s2.slice(1);
    }
    var arr = [2];
    constructLength(arr, r2.length);
    arr = arr.concat(r2);
    arr.push(2);
    constructLength(arr, s2.length);
    var backHalf = arr.concat(s2);
    var res = [48];
    constructLength(res, backHalf.length);
    res = res.concat(backHalf);
    return utils2.encode(res, enc);
  };
  return signature$1;
}
var ec;
var hasRequiredEc;
function requireEc() {
  if (hasRequiredEc) return ec;
  hasRequiredEc = 1;
  var BN = requireBn$1();
  var HmacDRBG = requireHmacDrbg();
  var utils2 = requireUtils$2();
  var curves2 = requireCurves();
  var rand = requireBrorand();
  var assert = utils2.assert;
  var KeyPair = requireKey$1();
  var Signature = requireSignature$1();
  function EC(options2) {
    if (!(this instanceof EC))
      return new EC(options2);
    if (typeof options2 === "string") {
      assert(
        Object.prototype.hasOwnProperty.call(curves2, options2),
        "Unknown curve " + options2
      );
      options2 = curves2[options2];
    }
    if (options2 instanceof curves2.PresetCurve)
      options2 = { curve: options2 };
    this.curve = options2.curve.curve;
    this.n = this.curve.n;
    this.nh = this.n.ushrn(1);
    this.g = this.curve.g;
    this.g = options2.curve.g;
    this.g.precompute(options2.curve.n.bitLength() + 1);
    this.hash = options2.hash || options2.curve.hash;
  }
  ec = EC;
  EC.prototype.keyPair = function keyPair(options2) {
    return new KeyPair(this, options2);
  };
  EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
    return KeyPair.fromPrivate(this, priv, enc);
  };
  EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
    return KeyPair.fromPublic(this, pub, enc);
  };
  EC.prototype.genKeyPair = function genKeyPair(options2) {
    if (!options2)
      options2 = {};
    var drbg = new HmacDRBG({
      hash: this.hash,
      pers: options2.pers,
      persEnc: options2.persEnc || "utf8",
      entropy: options2.entropy || rand(this.hash.hmacStrength),
      entropyEnc: options2.entropy && options2.entropyEnc || "utf8",
      nonce: this.n.toArray()
    });
    var bytes = this.n.byteLength();
    var ns2 = this.n.sub(new BN(2));
    for (; ; ) {
      var priv = new BN(drbg.generate(bytes));
      if (priv.cmp(ns2) > 0)
        continue;
      priv.iaddn(1);
      return this.keyFromPrivate(priv);
    }
  };
  EC.prototype._truncateToN = function _truncateToN(msg, truncOnly, bitLength) {
    var byteLength2;
    if (BN.isBN(msg) || typeof msg === "number") {
      msg = new BN(msg, 16);
      byteLength2 = msg.byteLength();
    } else if (typeof msg === "object") {
      byteLength2 = msg.length;
      msg = new BN(msg, 16);
    } else {
      var str = msg.toString();
      byteLength2 = str.length + 1 >>> 1;
      msg = new BN(str, 16);
    }
    if (typeof bitLength !== "number") {
      bitLength = byteLength2 * 8;
    }
    var delta = bitLength - this.n.bitLength();
    if (delta > 0)
      msg = msg.ushrn(delta);
    if (!truncOnly && msg.cmp(this.n) >= 0)
      return msg.sub(this.n);
    else
      return msg;
  };
  EC.prototype.sign = function sign2(msg, key2, enc, options2) {
    if (typeof enc === "object") {
      options2 = enc;
      enc = null;
    }
    if (!options2)
      options2 = {};
    if (typeof msg !== "string" && typeof msg !== "number" && !BN.isBN(msg)) {
      assert(
        typeof msg === "object" && msg && typeof msg.length === "number",
        "Expected message to be an array-like, a hex string, or a BN instance"
      );
      assert(msg.length >>> 0 === msg.length);
      for (var i2 = 0; i2 < msg.length; i2++) assert((msg[i2] & 255) === msg[i2]);
    }
    key2 = this.keyFromPrivate(key2, enc);
    msg = this._truncateToN(msg, false, options2.msgBitLength);
    assert(!msg.isNeg(), "Can not sign a negative message");
    var bytes = this.n.byteLength();
    var bkey = key2.getPrivate().toArray("be", bytes);
    var nonce = msg.toArray("be", bytes);
    assert(new BN(nonce).eq(msg), "Can not sign message");
    var drbg = new HmacDRBG({
      hash: this.hash,
      entropy: bkey,
      nonce,
      pers: options2.pers,
      persEnc: options2.persEnc || "utf8"
    });
    var ns1 = this.n.sub(new BN(1));
    for (var iter = 0; ; iter++) {
      var k2 = options2.k ? options2.k(iter) : new BN(drbg.generate(this.n.byteLength()));
      k2 = this._truncateToN(k2, true);
      if (k2.cmpn(1) <= 0 || k2.cmp(ns1) >= 0)
        continue;
      var kp = this.g.mul(k2);
      if (kp.isInfinity())
        continue;
      var kpX = kp.getX();
      var r2 = kpX.umod(this.n);
      if (r2.cmpn(0) === 0)
        continue;
      var s2 = k2.invm(this.n).mul(r2.mul(key2.getPrivate()).iadd(msg));
      s2 = s2.umod(this.n);
      if (s2.cmpn(0) === 0)
        continue;
      var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r2) !== 0 ? 2 : 0);
      if (options2.canonical && s2.cmp(this.nh) > 0) {
        s2 = this.n.sub(s2);
        recoveryParam ^= 1;
      }
      return new Signature({ r: r2, s: s2, recoveryParam });
    }
  };
  EC.prototype.verify = function verify(msg, signature2, key2, enc, options2) {
    if (!options2)
      options2 = {};
    msg = this._truncateToN(msg, false, options2.msgBitLength);
    key2 = this.keyFromPublic(key2, enc);
    signature2 = new Signature(signature2, "hex");
    var r2 = signature2.r;
    var s2 = signature2.s;
    if (r2.cmpn(1) < 0 || r2.cmp(this.n) >= 0)
      return false;
    if (s2.cmpn(1) < 0 || s2.cmp(this.n) >= 0)
      return false;
    var sinv = s2.invm(this.n);
    var u1 = sinv.mul(msg).umod(this.n);
    var u2 = sinv.mul(r2).umod(this.n);
    var p2;
    if (!this.curve._maxwellTrick) {
      p2 = this.g.mulAdd(u1, key2.getPublic(), u2);
      if (p2.isInfinity())
        return false;
      return p2.getX().umod(this.n).cmp(r2) === 0;
    }
    p2 = this.g.jmulAdd(u1, key2.getPublic(), u2);
    if (p2.isInfinity())
      return false;
    return p2.eqXToP(r2);
  };
  EC.prototype.recoverPubKey = function(msg, signature2, j, enc) {
    assert((3 & j) === j, "The recovery param is more than two bits");
    signature2 = new Signature(signature2, enc);
    var n2 = this.n;
    var e4 = new BN(msg);
    var r2 = signature2.r;
    var s2 = signature2.s;
    var isYOdd = j & 1;
    var isSecondKey = j >> 1;
    if (r2.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
      throw new Error("Unable to find sencond key candinate");
    if (isSecondKey)
      r2 = this.curve.pointFromX(r2.add(this.curve.n), isYOdd);
    else
      r2 = this.curve.pointFromX(r2, isYOdd);
    var rInv = signature2.r.invm(n2);
    var s1 = n2.sub(e4).mul(rInv).umod(n2);
    var s22 = s2.mul(rInv).umod(n2);
    return this.g.mulAdd(s1, r2, s22);
  };
  EC.prototype.getKeyRecoveryParam = function(e4, signature2, Q, enc) {
    signature2 = new Signature(signature2, enc);
    if (signature2.recoveryParam !== null)
      return signature2.recoveryParam;
    for (var i2 = 0; i2 < 4; i2++) {
      var Qprime;
      try {
        Qprime = this.recoverPubKey(e4, signature2, i2);
      } catch (e5) {
        continue;
      }
      if (Qprime.eq(Q))
        return i2;
    }
    throw new Error("Unable to find valid recovery factor");
  };
  return ec;
}
var key;
var hasRequiredKey;
function requireKey() {
  if (hasRequiredKey) return key;
  hasRequiredKey = 1;
  var utils2 = requireUtils$2();
  var assert = utils2.assert;
  var parseBytes = utils2.parseBytes;
  var cachedProperty = utils2.cachedProperty;
  function KeyPair(eddsa2, params) {
    this.eddsa = eddsa2;
    this._secret = parseBytes(params.secret);
    if (eddsa2.isPoint(params.pub))
      this._pub = params.pub;
    else
      this._pubBytes = parseBytes(params.pub);
  }
  KeyPair.fromPublic = function fromPublic(eddsa2, pub) {
    if (pub instanceof KeyPair)
      return pub;
    return new KeyPair(eddsa2, { pub });
  };
  KeyPair.fromSecret = function fromSecret(eddsa2, secret) {
    if (secret instanceof KeyPair)
      return secret;
    return new KeyPair(eddsa2, { secret });
  };
  KeyPair.prototype.secret = function secret() {
    return this._secret;
  };
  cachedProperty(KeyPair, "pubBytes", function pubBytes() {
    return this.eddsa.encodePoint(this.pub());
  });
  cachedProperty(KeyPair, "pub", function pub() {
    if (this._pubBytes)
      return this.eddsa.decodePoint(this._pubBytes);
    return this.eddsa.g.mul(this.priv());
  });
  cachedProperty(KeyPair, "privBytes", function privBytes() {
    var eddsa2 = this.eddsa;
    var hash2 = this.hash();
    var lastIx = eddsa2.encodingLength - 1;
    var a2 = hash2.slice(0, eddsa2.encodingLength);
    a2[0] &= 248;
    a2[lastIx] &= 127;
    a2[lastIx] |= 64;
    return a2;
  });
  cachedProperty(KeyPair, "priv", function priv() {
    return this.eddsa.decodeInt(this.privBytes());
  });
  cachedProperty(KeyPair, "hash", function hash2() {
    return this.eddsa.hash().update(this.secret()).digest();
  });
  cachedProperty(KeyPair, "messagePrefix", function messagePrefix() {
    return this.hash().slice(this.eddsa.encodingLength);
  });
  KeyPair.prototype.sign = function sign2(message) {
    assert(this._secret, "KeyPair can only verify");
    return this.eddsa.sign(message, this);
  };
  KeyPair.prototype.verify = function verify(message, sig) {
    return this.eddsa.verify(message, sig, this);
  };
  KeyPair.prototype.getSecret = function getSecret(enc) {
    assert(this._secret, "KeyPair is public only");
    return utils2.encode(this.secret(), enc);
  };
  KeyPair.prototype.getPublic = function getPublic(enc) {
    return utils2.encode(this.pubBytes(), enc);
  };
  key = KeyPair;
  return key;
}
var signature;
var hasRequiredSignature;
function requireSignature() {
  if (hasRequiredSignature) return signature;
  hasRequiredSignature = 1;
  var BN = requireBn$1();
  var utils2 = requireUtils$2();
  var assert = utils2.assert;
  var cachedProperty = utils2.cachedProperty;
  var parseBytes = utils2.parseBytes;
  function Signature(eddsa2, sig) {
    this.eddsa = eddsa2;
    if (typeof sig !== "object")
      sig = parseBytes(sig);
    if (Array.isArray(sig)) {
      assert(sig.length === eddsa2.encodingLength * 2, "Signature has invalid size");
      sig = {
        R: sig.slice(0, eddsa2.encodingLength),
        S: sig.slice(eddsa2.encodingLength)
      };
    }
    assert(sig.R && sig.S, "Signature without R or S");
    if (eddsa2.isPoint(sig.R))
      this._R = sig.R;
    if (sig.S instanceof BN)
      this._S = sig.S;
    this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
    this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  }
  cachedProperty(Signature, "S", function S2() {
    return this.eddsa.decodeInt(this.Sencoded());
  });
  cachedProperty(Signature, "R", function R2() {
    return this.eddsa.decodePoint(this.Rencoded());
  });
  cachedProperty(Signature, "Rencoded", function Rencoded() {
    return this.eddsa.encodePoint(this.R());
  });
  cachedProperty(Signature, "Sencoded", function Sencoded() {
    return this.eddsa.encodeInt(this.S());
  });
  Signature.prototype.toBytes = function toBytes() {
    return this.Rencoded().concat(this.Sencoded());
  };
  Signature.prototype.toHex = function toHex2() {
    return utils2.encode(this.toBytes(), "hex").toUpperCase();
  };
  signature = Signature;
  return signature;
}
var eddsa;
var hasRequiredEddsa;
function requireEddsa() {
  if (hasRequiredEddsa) return eddsa;
  hasRequiredEddsa = 1;
  var hash2 = requireHash();
  var curves2 = requireCurves();
  var utils2 = requireUtils$2();
  var assert = utils2.assert;
  var parseBytes = utils2.parseBytes;
  var KeyPair = requireKey();
  var Signature = requireSignature();
  function EDDSA(curve2) {
    assert(curve2 === "ed25519", "only tested with ed25519 so far");
    if (!(this instanceof EDDSA))
      return new EDDSA(curve2);
    curve2 = curves2[curve2].curve;
    this.curve = curve2;
    this.g = curve2.g;
    this.g.precompute(curve2.n.bitLength() + 1);
    this.pointClass = curve2.point().constructor;
    this.encodingLength = Math.ceil(curve2.n.bitLength() / 8);
    this.hash = hash2.sha512;
  }
  eddsa = EDDSA;
  EDDSA.prototype.sign = function sign2(message, secret) {
    message = parseBytes(message);
    var key2 = this.keyFromSecret(secret);
    var r2 = this.hashInt(key2.messagePrefix(), message);
    var R2 = this.g.mul(r2);
    var Rencoded = this.encodePoint(R2);
    var s_ = this.hashInt(Rencoded, key2.pubBytes(), message).mul(key2.priv());
    var S2 = r2.add(s_).umod(this.curve.n);
    return this.makeSignature({ R: R2, S: S2, Rencoded });
  };
  EDDSA.prototype.verify = function verify(message, sig, pub) {
    message = parseBytes(message);
    sig = this.makeSignature(sig);
    if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) {
      return false;
    }
    var key2 = this.keyFromPublic(pub);
    var h2 = this.hashInt(sig.Rencoded(), key2.pubBytes(), message);
    var SG = this.g.mul(sig.S());
    var RplusAh = sig.R().add(key2.pub().mul(h2));
    return RplusAh.eq(SG);
  };
  EDDSA.prototype.hashInt = function hashInt() {
    var hash3 = this.hash();
    for (var i2 = 0; i2 < arguments.length; i2++)
      hash3.update(arguments[i2]);
    return utils2.intFromLE(hash3.digest()).umod(this.curve.n);
  };
  EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
    return KeyPair.fromPublic(this, pub);
  };
  EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
    return KeyPair.fromSecret(this, secret);
  };
  EDDSA.prototype.makeSignature = function makeSignature(sig) {
    if (sig instanceof Signature)
      return sig;
    return new Signature(this, sig);
  };
  EDDSA.prototype.encodePoint = function encodePoint(point) {
    var enc = point.getY().toArray("le", this.encodingLength);
    enc[this.encodingLength - 1] |= point.getX().isOdd() ? 128 : 0;
    return enc;
  };
  EDDSA.prototype.decodePoint = function decodePoint(bytes) {
    bytes = utils2.parseBytes(bytes);
    var lastIx = bytes.length - 1;
    var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & -129);
    var xIsOdd = (bytes[lastIx] & 128) !== 0;
    var y2 = utils2.intFromLE(normed);
    return this.curve.pointFromY(y2, xIsOdd);
  };
  EDDSA.prototype.encodeInt = function encodeInt(num) {
    return num.toArray("le", this.encodingLength);
  };
  EDDSA.prototype.decodeInt = function decodeInt(bytes) {
    return utils2.intFromLE(bytes);
  };
  EDDSA.prototype.isPoint = function isPoint(val) {
    return val instanceof this.pointClass;
  };
  return eddsa;
}
var hasRequiredElliptic;
function requireElliptic() {
  if (hasRequiredElliptic) return elliptic;
  hasRequiredElliptic = 1;
  (function(exports) {
    var elliptic2 = exports;
    elliptic2.version = require$$0$1.version;
    elliptic2.utils = requireUtils$2();
    elliptic2.rand = requireBrorand();
    elliptic2.curve = requireCurve();
    elliptic2.curves = requireCurves();
    elliptic2.ec = requireEc();
    elliptic2.eddsa = requireEddsa();
  })(elliptic);
  return elliptic;
}
var asn1$1 = {};
var asn1 = {};
var api = {};
const __viteBrowserExternal_vm = new Proxy({}, {
  get(_2, key2) {
    throw new Error(`Module "vm" has been externalized for browser compatibility. Cannot access "vm.${key2}" in client code.  See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  }
});
const __viteBrowserExternal_vm$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: __viteBrowserExternal_vm
}, Symbol.toStringTag, { value: "Module" }));
const require$$2 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal_vm$1);
var hasRequiredApi;
function requireApi() {
  if (hasRequiredApi) return api;
  hasRequiredApi = 1;
  (function(exports) {
    var asn12 = requireAsn1$1();
    var inherits = requireInherits_browser();
    var api2 = exports;
    api2.define = function define(name, body) {
      return new Entity(name, body);
    };
    function Entity(name, body) {
      this.name = name;
      this.body = body;
      this.decoders = {};
      this.encoders = {};
    }
    Entity.prototype._createNamed = function createNamed(base2) {
      var named;
      try {
        named = require$$2.runInThisContext(
          "(function " + this.name + "(entity) {\n  this._initNamed(entity);\n})"
        );
      } catch (e4) {
        named = function(entity) {
          this._initNamed(entity);
        };
      }
      inherits(named, base2);
      named.prototype._initNamed = function initnamed(entity) {
        base2.call(this, entity);
      };
      return new named(this);
    };
    Entity.prototype._getDecoder = function _getDecoder(enc) {
      enc = enc || "der";
      if (!this.decoders.hasOwnProperty(enc))
        this.decoders[enc] = this._createNamed(asn12.decoders[enc]);
      return this.decoders[enc];
    };
    Entity.prototype.decode = function decode2(data2, enc, options2) {
      return this._getDecoder(enc).decode(data2, options2);
    };
    Entity.prototype._getEncoder = function _getEncoder(enc) {
      enc = enc || "der";
      if (!this.encoders.hasOwnProperty(enc))
        this.encoders[enc] = this._createNamed(asn12.encoders[enc]);
      return this.encoders[enc];
    };
    Entity.prototype.encode = function encode2(data2, enc, reporter2) {
      return this._getEncoder(enc).encode(data2, reporter2);
    };
  })(api);
  return api;
}
var base = {};
var reporter = {};
var hasRequiredReporter;
function requireReporter() {
  if (hasRequiredReporter) return reporter;
  hasRequiredReporter = 1;
  var inherits = requireInherits_browser();
  function Reporter(options2) {
    this._reporterState = {
      obj: null,
      path: [],
      options: options2 || {},
      errors: []
    };
  }
  reporter.Reporter = Reporter;
  Reporter.prototype.isError = function isError(obj) {
    return obj instanceof ReporterError;
  };
  Reporter.prototype.save = function save() {
    var state = this._reporterState;
    return { obj: state.obj, pathLen: state.path.length };
  };
  Reporter.prototype.restore = function restore(data2) {
    var state = this._reporterState;
    state.obj = data2.obj;
    state.path = state.path.slice(0, data2.pathLen);
  };
  Reporter.prototype.enterKey = function enterKey(key2) {
    return this._reporterState.path.push(key2);
  };
  Reporter.prototype.exitKey = function exitKey(index2) {
    var state = this._reporterState;
    state.path = state.path.slice(0, index2 - 1);
  };
  Reporter.prototype.leaveKey = function leaveKey(index2, key2, value) {
    var state = this._reporterState;
    this.exitKey(index2);
    if (state.obj !== null)
      state.obj[key2] = value;
  };
  Reporter.prototype.path = function path() {
    return this._reporterState.path.join("/");
  };
  Reporter.prototype.enterObject = function enterObject() {
    var state = this._reporterState;
    var prev = state.obj;
    state.obj = {};
    return prev;
  };
  Reporter.prototype.leaveObject = function leaveObject(prev) {
    var state = this._reporterState;
    var now = state.obj;
    state.obj = prev;
    return now;
  };
  Reporter.prototype.error = function error(msg) {
    var err;
    var state = this._reporterState;
    var inherited = msg instanceof ReporterError;
    if (inherited) {
      err = msg;
    } else {
      err = new ReporterError(state.path.map(function(elem) {
        return "[" + JSON.stringify(elem) + "]";
      }).join(""), msg.message || msg, msg.stack);
    }
    if (!state.options.partial)
      throw err;
    if (!inherited)
      state.errors.push(err);
    return err;
  };
  Reporter.prototype.wrapResult = function wrapResult(result) {
    var state = this._reporterState;
    if (!state.options.partial)
      return result;
    return {
      result: this.isError(result) ? null : result,
      errors: state.errors
    };
  };
  function ReporterError(path, msg) {
    this.path = path;
    this.rethrow(msg);
  }
  inherits(ReporterError, Error);
  ReporterError.prototype.rethrow = function rethrow(msg) {
    this.message = msg + " at: " + (this.path || "(shallow)");
    if (Error.captureStackTrace)
      Error.captureStackTrace(this, ReporterError);
    if (!this.stack) {
      try {
        throw new Error(this.message);
      } catch (e4) {
        this.stack = e4.stack;
      }
    }
    return this;
  };
  return reporter;
}
var buffer = {};
var hasRequiredBuffer;
function requireBuffer() {
  if (hasRequiredBuffer) return buffer;
  hasRequiredBuffer = 1;
  var inherits = requireInherits_browser();
  var Reporter = requireBase().Reporter;
  var Buffer2 = requireBuffer$1().Buffer;
  function DecoderBuffer(base2, options2) {
    Reporter.call(this, options2);
    if (!Buffer2.isBuffer(base2)) {
      this.error("Input not Buffer");
      return;
    }
    this.base = base2;
    this.offset = 0;
    this.length = base2.length;
  }
  inherits(DecoderBuffer, Reporter);
  buffer.DecoderBuffer = DecoderBuffer;
  DecoderBuffer.prototype.save = function save() {
    return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
  };
  DecoderBuffer.prototype.restore = function restore(save) {
    var res = new DecoderBuffer(this.base);
    res.offset = save.offset;
    res.length = this.offset;
    this.offset = save.offset;
    Reporter.prototype.restore.call(this, save.reporter);
    return res;
  };
  DecoderBuffer.prototype.isEmpty = function isEmpty() {
    return this.offset === this.length;
  };
  DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
    if (this.offset + 1 <= this.length)
      return this.base.readUInt8(this.offset++, true);
    else
      return this.error(fail || "DecoderBuffer overrun");
  };
  DecoderBuffer.prototype.skip = function skip(bytes, fail) {
    if (!(this.offset + bytes <= this.length))
      return this.error(fail || "DecoderBuffer overrun");
    var res = new DecoderBuffer(this.base);
    res._reporterState = this._reporterState;
    res.offset = this.offset;
    res.length = this.offset + bytes;
    this.offset += bytes;
    return res;
  };
  DecoderBuffer.prototype.raw = function raw(save) {
    return this.base.slice(save ? save.offset : this.offset, this.length);
  };
  function EncoderBuffer(value, reporter2) {
    if (Array.isArray(value)) {
      this.length = 0;
      this.value = value.map(function(item) {
        if (!(item instanceof EncoderBuffer))
          item = new EncoderBuffer(item, reporter2);
        this.length += item.length;
        return item;
      }, this);
    } else if (typeof value === "number") {
      if (!(0 <= value && value <= 255))
        return reporter2.error("non-byte EncoderBuffer value");
      this.value = value;
      this.length = 1;
    } else if (typeof value === "string") {
      this.value = value;
      this.length = Buffer2.byteLength(value);
    } else if (Buffer2.isBuffer(value)) {
      this.value = value;
      this.length = value.length;
    } else {
      return reporter2.error("Unsupported type: " + typeof value);
    }
  }
  buffer.EncoderBuffer = EncoderBuffer;
  EncoderBuffer.prototype.join = function join(out, offset) {
    if (!out)
      out = new Buffer2(this.length);
    if (!offset)
      offset = 0;
    if (this.length === 0)
      return out;
    if (Array.isArray(this.value)) {
      this.value.forEach(function(item) {
        item.join(out, offset);
        offset += item.length;
      });
    } else {
      if (typeof this.value === "number")
        out[offset] = this.value;
      else if (typeof this.value === "string")
        out.write(this.value, offset);
      else if (Buffer2.isBuffer(this.value))
        this.value.copy(out, offset);
      offset += this.length;
    }
    return out;
  };
  return buffer;
}
var node;
var hasRequiredNode;
function requireNode() {
  if (hasRequiredNode) return node;
  hasRequiredNode = 1;
  var Reporter = requireBase().Reporter;
  var EncoderBuffer = requireBase().EncoderBuffer;
  var DecoderBuffer = requireBase().DecoderBuffer;
  var assert = requireMinimalisticAssert();
  var tags = [
    "seq",
    "seqof",
    "set",
    "setof",
    "objid",
    "bool",
    "gentime",
    "utctime",
    "null_",
    "enum",
    "int",
    "objDesc",
    "bitstr",
    "bmpstr",
    "charstr",
    "genstr",
    "graphstr",
    "ia5str",
    "iso646str",
    "numstr",
    "octstr",
    "printstr",
    "t61str",
    "unistr",
    "utf8str",
    "videostr"
  ];
  var methods2 = [
    "key",
    "obj",
    "use",
    "optional",
    "explicit",
    "implicit",
    "def",
    "choice",
    "any",
    "contains"
  ].concat(tags);
  var overrided = [
    "_peekTag",
    "_decodeTag",
    "_use",
    "_decodeStr",
    "_decodeObjid",
    "_decodeTime",
    "_decodeNull",
    "_decodeInt",
    "_decodeBool",
    "_decodeList",
    "_encodeComposite",
    "_encodeStr",
    "_encodeObjid",
    "_encodeTime",
    "_encodeNull",
    "_encodeInt",
    "_encodeBool"
  ];
  function Node(enc, parent) {
    var state = {};
    this._baseState = state;
    state.enc = enc;
    state.parent = parent || null;
    state.children = null;
    state.tag = null;
    state.args = null;
    state.reverseArgs = null;
    state.choice = null;
    state.optional = false;
    state.any = false;
    state.obj = false;
    state.use = null;
    state.useDecoder = null;
    state.key = null;
    state["default"] = null;
    state.explicit = null;
    state.implicit = null;
    state.contains = null;
    if (!state.parent) {
      state.children = [];
      this._wrap();
    }
  }
  node = Node;
  var stateProps = [
    "enc",
    "parent",
    "children",
    "tag",
    "args",
    "reverseArgs",
    "choice",
    "optional",
    "any",
    "obj",
    "use",
    "alteredUse",
    "key",
    "default",
    "explicit",
    "implicit",
    "contains"
  ];
  Node.prototype.clone = function clone2() {
    var state = this._baseState;
    var cstate = {};
    stateProps.forEach(function(prop) {
      cstate[prop] = state[prop];
    });
    var res = new this.constructor(cstate.parent);
    res._baseState = cstate;
    return res;
  };
  Node.prototype._wrap = function wrap() {
    var state = this._baseState;
    methods2.forEach(function(method) {
      this[method] = function _wrappedMethod() {
        var clone2 = new this.constructor(this);
        state.children.push(clone2);
        return clone2[method].apply(clone2, arguments);
      };
    }, this);
  };
  Node.prototype._init = function init2(body) {
    var state = this._baseState;
    assert(state.parent === null);
    body.call(this);
    state.children = state.children.filter(function(child) {
      return child._baseState.parent === this;
    }, this);
    assert.equal(state.children.length, 1, "Root node can have only one child");
  };
  Node.prototype._useArgs = function useArgs(args) {
    var state = this._baseState;
    var children = args.filter(function(arg) {
      return arg instanceof this.constructor;
    }, this);
    args = args.filter(function(arg) {
      return !(arg instanceof this.constructor);
    }, this);
    if (children.length !== 0) {
      assert(state.children === null);
      state.children = children;
      children.forEach(function(child) {
        child._baseState.parent = this;
      }, this);
    }
    if (args.length !== 0) {
      assert(state.args === null);
      state.args = args;
      state.reverseArgs = args.map(function(arg) {
        if (typeof arg !== "object" || arg.constructor !== Object)
          return arg;
        var res = {};
        Object.keys(arg).forEach(function(key2) {
          if (key2 == (key2 | 0))
            key2 |= 0;
          var value = arg[key2];
          res[value] = key2;
        });
        return res;
      });
    }
  };
  overrided.forEach(function(method) {
    Node.prototype[method] = function _overrided() {
      var state = this._baseState;
      throw new Error(method + " not implemented for encoding: " + state.enc);
    };
  });
  tags.forEach(function(tag) {
    Node.prototype[tag] = function _tagMethod() {
      var state = this._baseState;
      var args = Array.prototype.slice.call(arguments);
      assert(state.tag === null);
      state.tag = tag;
      this._useArgs(args);
      return this;
    };
  });
  Node.prototype.use = function use(item) {
    assert(item);
    var state = this._baseState;
    assert(state.use === null);
    state.use = item;
    return this;
  };
  Node.prototype.optional = function optional() {
    var state = this._baseState;
    state.optional = true;
    return this;
  };
  Node.prototype.def = function def(val) {
    var state = this._baseState;
    assert(state["default"] === null);
    state["default"] = val;
    state.optional = true;
    return this;
  };
  Node.prototype.explicit = function explicit(num) {
    var state = this._baseState;
    assert(state.explicit === null && state.implicit === null);
    state.explicit = num;
    return this;
  };
  Node.prototype.implicit = function implicit(num) {
    var state = this._baseState;
    assert(state.explicit === null && state.implicit === null);
    state.implicit = num;
    return this;
  };
  Node.prototype.obj = function obj() {
    var state = this._baseState;
    var args = Array.prototype.slice.call(arguments);
    state.obj = true;
    if (args.length !== 0)
      this._useArgs(args);
    return this;
  };
  Node.prototype.key = function key2(newKey) {
    var state = this._baseState;
    assert(state.key === null);
    state.key = newKey;
    return this;
  };
  Node.prototype.any = function any() {
    var state = this._baseState;
    state.any = true;
    return this;
  };
  Node.prototype.choice = function choice(obj) {
    var state = this._baseState;
    assert(state.choice === null);
    state.choice = obj;
    this._useArgs(Object.keys(obj).map(function(key2) {
      return obj[key2];
    }));
    return this;
  };
  Node.prototype.contains = function contains2(item) {
    var state = this._baseState;
    assert(state.use === null);
    state.contains = item;
    return this;
  };
  Node.prototype._decode = function decode2(input, options2) {
    var state = this._baseState;
    if (state.parent === null)
      return input.wrapResult(state.children[0]._decode(input, options2));
    var result = state["default"];
    var present = true;
    var prevKey = null;
    if (state.key !== null)
      prevKey = input.enterKey(state.key);
    if (state.optional) {
      var tag = null;
      if (state.explicit !== null)
        tag = state.explicit;
      else if (state.implicit !== null)
        tag = state.implicit;
      else if (state.tag !== null)
        tag = state.tag;
      if (tag === null && !state.any) {
        var save = input.save();
        try {
          if (state.choice === null)
            this._decodeGeneric(state.tag, input, options2);
          else
            this._decodeChoice(input, options2);
          present = true;
        } catch (e4) {
          present = false;
        }
        input.restore(save);
      } else {
        present = this._peekTag(input, tag, state.any);
        if (input.isError(present))
          return present;
      }
    }
    var prevObj;
    if (state.obj && present)
      prevObj = input.enterObject();
    if (present) {
      if (state.explicit !== null) {
        var explicit = this._decodeTag(input, state.explicit);
        if (input.isError(explicit))
          return explicit;
        input = explicit;
      }
      var start = input.offset;
      if (state.use === null && state.choice === null) {
        if (state.any)
          var save = input.save();
        var body = this._decodeTag(
          input,
          state.implicit !== null ? state.implicit : state.tag,
          state.any
        );
        if (input.isError(body))
          return body;
        if (state.any)
          result = input.raw(save);
        else
          input = body;
      }
      if (options2 && options2.track && state.tag !== null)
        options2.track(input.path(), start, input.length, "tagged");
      if (options2 && options2.track && state.tag !== null)
        options2.track(input.path(), input.offset, input.length, "content");
      if (state.any)
        result = result;
      else if (state.choice === null)
        result = this._decodeGeneric(state.tag, input, options2);
      else
        result = this._decodeChoice(input, options2);
      if (input.isError(result))
        return result;
      if (!state.any && state.choice === null && state.children !== null) {
        state.children.forEach(function decodeChildren(child) {
          child._decode(input, options2);
        });
      }
      if (state.contains && (state.tag === "octstr" || state.tag === "bitstr")) {
        var data2 = new DecoderBuffer(result);
        result = this._getUse(state.contains, input._reporterState.obj)._decode(data2, options2);
      }
    }
    if (state.obj && present)
      result = input.leaveObject(prevObj);
    if (state.key !== null && (result !== null || present === true))
      input.leaveKey(prevKey, state.key, result);
    else if (prevKey !== null)
      input.exitKey(prevKey);
    return result;
  };
  Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options2) {
    var state = this._baseState;
    if (tag === "seq" || tag === "set")
      return null;
    if (tag === "seqof" || tag === "setof")
      return this._decodeList(input, tag, state.args[0], options2);
    else if (/str$/.test(tag))
      return this._decodeStr(input, tag, options2);
    else if (tag === "objid" && state.args)
      return this._decodeObjid(input, state.args[0], state.args[1], options2);
    else if (tag === "objid")
      return this._decodeObjid(input, null, null, options2);
    else if (tag === "gentime" || tag === "utctime")
      return this._decodeTime(input, tag, options2);
    else if (tag === "null_")
      return this._decodeNull(input, options2);
    else if (tag === "bool")
      return this._decodeBool(input, options2);
    else if (tag === "objDesc")
      return this._decodeStr(input, tag, options2);
    else if (tag === "int" || tag === "enum")
      return this._decodeInt(input, state.args && state.args[0], options2);
    if (state.use !== null) {
      return this._getUse(state.use, input._reporterState.obj)._decode(input, options2);
    } else {
      return input.error("unknown tag: " + tag);
    }
  };
  Node.prototype._getUse = function _getUse(entity, obj) {
    var state = this._baseState;
    state.useDecoder = this._use(entity, obj);
    assert(state.useDecoder._baseState.parent === null);
    state.useDecoder = state.useDecoder._baseState.children[0];
    if (state.implicit !== state.useDecoder._baseState.implicit) {
      state.useDecoder = state.useDecoder.clone();
      state.useDecoder._baseState.implicit = state.implicit;
    }
    return state.useDecoder;
  };
  Node.prototype._decodeChoice = function decodeChoice(input, options2) {
    var state = this._baseState;
    var result = null;
    var match = false;
    Object.keys(state.choice).some(function(key2) {
      var save = input.save();
      var node2 = state.choice[key2];
      try {
        var value = node2._decode(input, options2);
        if (input.isError(value))
          return false;
        result = { type: key2, value };
        match = true;
      } catch (e4) {
        input.restore(save);
        return false;
      }
      return true;
    }, this);
    if (!match)
      return input.error("Choice not matched");
    return result;
  };
  Node.prototype._createEncoderBuffer = function createEncoderBuffer(data2) {
    return new EncoderBuffer(data2, this.reporter);
  };
  Node.prototype._encode = function encode2(data2, reporter2, parent) {
    var state = this._baseState;
    if (state["default"] !== null && state["default"] === data2)
      return;
    var result = this._encodeValue(data2, reporter2, parent);
    if (result === void 0)
      return;
    if (this._skipDefault(result, reporter2, parent))
      return;
    return result;
  };
  Node.prototype._encodeValue = function encode2(data2, reporter2, parent) {
    var state = this._baseState;
    if (state.parent === null)
      return state.children[0]._encode(data2, reporter2 || new Reporter());
    var result = null;
    this.reporter = reporter2;
    if (state.optional && data2 === void 0) {
      if (state["default"] !== null)
        data2 = state["default"];
      else
        return;
    }
    var content = null;
    var primitive = false;
    if (state.any) {
      result = this._createEncoderBuffer(data2);
    } else if (state.choice) {
      result = this._encodeChoice(data2, reporter2);
    } else if (state.contains) {
      content = this._getUse(state.contains, parent)._encode(data2, reporter2);
      primitive = true;
    } else if (state.children) {
      content = state.children.map(function(child2) {
        if (child2._baseState.tag === "null_")
          return child2._encode(null, reporter2, data2);
        if (child2._baseState.key === null)
          return reporter2.error("Child should have a key");
        var prevKey = reporter2.enterKey(child2._baseState.key);
        if (typeof data2 !== "object")
          return reporter2.error("Child expected, but input is not object");
        var res = child2._encode(data2[child2._baseState.key], reporter2, data2);
        reporter2.leaveKey(prevKey);
        return res;
      }, this).filter(function(child2) {
        return child2;
      });
      content = this._createEncoderBuffer(content);
    } else {
      if (state.tag === "seqof" || state.tag === "setof") {
        if (!(state.args && state.args.length === 1))
          return reporter2.error("Too many args for : " + state.tag);
        if (!Array.isArray(data2))
          return reporter2.error("seqof/setof, but data is not Array");
        var child = this.clone();
        child._baseState.implicit = null;
        content = this._createEncoderBuffer(data2.map(function(item) {
          var state2 = this._baseState;
          return this._getUse(state2.args[0], data2)._encode(item, reporter2);
        }, child));
      } else if (state.use !== null) {
        result = this._getUse(state.use, parent)._encode(data2, reporter2);
      } else {
        content = this._encodePrimitive(state.tag, data2);
        primitive = true;
      }
    }
    var result;
    if (!state.any && state.choice === null) {
      var tag = state.implicit !== null ? state.implicit : state.tag;
      var cls = state.implicit === null ? "universal" : "context";
      if (tag === null) {
        if (state.use === null)
          reporter2.error("Tag could be omitted only for .use()");
      } else {
        if (state.use === null)
          result = this._encodeComposite(tag, primitive, cls, content);
      }
    }
    if (state.explicit !== null)
      result = this._encodeComposite(state.explicit, false, "context", result);
    return result;
  };
  Node.prototype._encodeChoice = function encodeChoice(data2, reporter2) {
    var state = this._baseState;
    var node2 = state.choice[data2.type];
    if (!node2) {
      assert(
        false,
        data2.type + " not found in " + JSON.stringify(Object.keys(state.choice))
      );
    }
    return node2._encode(data2.value, reporter2);
  };
  Node.prototype._encodePrimitive = function encodePrimitive(tag, data2) {
    var state = this._baseState;
    if (/str$/.test(tag))
      return this._encodeStr(data2, tag);
    else if (tag === "objid" && state.args)
      return this._encodeObjid(data2, state.reverseArgs[0], state.args[1]);
    else if (tag === "objid")
      return this._encodeObjid(data2, null, null);
    else if (tag === "gentime" || tag === "utctime")
      return this._encodeTime(data2, tag);
    else if (tag === "null_")
      return this._encodeNull();
    else if (tag === "int" || tag === "enum")
      return this._encodeInt(data2, state.args && state.reverseArgs[0]);
    else if (tag === "bool")
      return this._encodeBool(data2);
    else if (tag === "objDesc")
      return this._encodeStr(data2, tag);
    else
      throw new Error("Unsupported tag: " + tag);
  };
  Node.prototype._isNumstr = function isNumstr(str) {
    return /^[0-9 ]*$/.test(str);
  };
  Node.prototype._isPrintstr = function isPrintstr(str) {
    return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
  };
  return node;
}
var hasRequiredBase;
function requireBase() {
  if (hasRequiredBase) return base;
  hasRequiredBase = 1;
  (function(exports) {
    var base2 = exports;
    base2.Reporter = requireReporter().Reporter;
    base2.DecoderBuffer = requireBuffer().DecoderBuffer;
    base2.EncoderBuffer = requireBuffer().EncoderBuffer;
    base2.Node = requireNode();
  })(base);
  return base;
}
var constants$1 = {};
var der = {};
var hasRequiredDer$2;
function requireDer$2() {
  if (hasRequiredDer$2) return der;
  hasRequiredDer$2 = 1;
  (function(exports) {
    var constants2 = requireConstants$1();
    exports.tagClass = {
      0: "universal",
      1: "application",
      2: "context",
      3: "private"
    };
    exports.tagClassByName = constants2._reverse(exports.tagClass);
    exports.tag = {
      0: "end",
      1: "bool",
      2: "int",
      3: "bitstr",
      4: "octstr",
      5: "null_",
      6: "objid",
      7: "objDesc",
      8: "external",
      9: "real",
      10: "enum",
      11: "embed",
      12: "utf8str",
      13: "relativeOid",
      16: "seq",
      17: "set",
      18: "numstr",
      19: "printstr",
      20: "t61str",
      21: "videostr",
      22: "ia5str",
      23: "utctime",
      24: "gentime",
      25: "graphstr",
      26: "iso646str",
      27: "genstr",
      28: "unistr",
      29: "charstr",
      30: "bmpstr"
    };
    exports.tagByName = constants2._reverse(exports.tag);
  })(der);
  return der;
}
var hasRequiredConstants$1;
function requireConstants$1() {
  if (hasRequiredConstants$1) return constants$1;
  hasRequiredConstants$1 = 1;
  (function(exports) {
    var constants2 = exports;
    constants2._reverse = function reverse(map) {
      var res = {};
      Object.keys(map).forEach(function(key2) {
        if ((key2 | 0) == key2)
          key2 = key2 | 0;
        var value = map[key2];
        res[value] = key2;
      });
      return res;
    };
    constants2.der = requireDer$2();
  })(constants$1);
  return constants$1;
}
var decoders = {};
var der_1$1;
var hasRequiredDer$1;
function requireDer$1() {
  if (hasRequiredDer$1) return der_1$1;
  hasRequiredDer$1 = 1;
  var inherits = requireInherits_browser();
  var asn12 = requireAsn1$1();
  var base2 = asn12.base;
  var bignum = asn12.bignum;
  var der2 = asn12.constants.der;
  function DERDecoder(entity) {
    this.enc = "der";
    this.name = entity.name;
    this.entity = entity;
    this.tree = new DERNode();
    this.tree._init(entity.body);
  }
  der_1$1 = DERDecoder;
  DERDecoder.prototype.decode = function decode2(data2, options2) {
    if (!(data2 instanceof base2.DecoderBuffer))
      data2 = new base2.DecoderBuffer(data2, options2);
    return this.tree._decode(data2, options2);
  };
  function DERNode(parent) {
    base2.Node.call(this, "der", parent);
  }
  inherits(DERNode, base2.Node);
  DERNode.prototype._peekTag = function peekTag(buffer2, tag, any) {
    if (buffer2.isEmpty())
      return false;
    var state = buffer2.save();
    var decodedTag = derDecodeTag(buffer2, 'Failed to peek tag: "' + tag + '"');
    if (buffer2.isError(decodedTag))
      return decodedTag;
    buffer2.restore(state);
    return decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + "of" === tag || any;
  };
  DERNode.prototype._decodeTag = function decodeTag(buffer2, tag, any) {
    var decodedTag = derDecodeTag(
      buffer2,
      'Failed to decode tag of "' + tag + '"'
    );
    if (buffer2.isError(decodedTag))
      return decodedTag;
    var len = derDecodeLen(
      buffer2,
      decodedTag.primitive,
      'Failed to get length of "' + tag + '"'
    );
    if (buffer2.isError(len))
      return len;
    if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + "of" !== tag) {
      return buffer2.error('Failed to match tag: "' + tag + '"');
    }
    if (decodedTag.primitive || len !== null)
      return buffer2.skip(len, 'Failed to match body of: "' + tag + '"');
    var state = buffer2.save();
    var res = this._skipUntilEnd(
      buffer2,
      'Failed to skip indefinite length body: "' + this.tag + '"'
    );
    if (buffer2.isError(res))
      return res;
    len = buffer2.offset - state.offset;
    buffer2.restore(state);
    return buffer2.skip(len, 'Failed to match body of: "' + tag + '"');
  };
  DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer2, fail) {
    while (true) {
      var tag = derDecodeTag(buffer2, fail);
      if (buffer2.isError(tag))
        return tag;
      var len = derDecodeLen(buffer2, tag.primitive, fail);
      if (buffer2.isError(len))
        return len;
      var res;
      if (tag.primitive || len !== null)
        res = buffer2.skip(len);
      else
        res = this._skipUntilEnd(buffer2, fail);
      if (buffer2.isError(res))
        return res;
      if (tag.tagStr === "end")
        break;
    }
  };
  DERNode.prototype._decodeList = function decodeList(buffer2, tag, decoder2, options2) {
    var result = [];
    while (!buffer2.isEmpty()) {
      var possibleEnd = this._peekTag(buffer2, "end");
      if (buffer2.isError(possibleEnd))
        return possibleEnd;
      var res = decoder2.decode(buffer2, "der", options2);
      if (buffer2.isError(res) && possibleEnd)
        break;
      result.push(res);
    }
    return result;
  };
  DERNode.prototype._decodeStr = function decodeStr(buffer2, tag) {
    if (tag === "bitstr") {
      var unused = buffer2.readUInt8();
      if (buffer2.isError(unused))
        return unused;
      return { unused, data: buffer2.raw() };
    } else if (tag === "bmpstr") {
      var raw = buffer2.raw();
      if (raw.length % 2 === 1)
        return buffer2.error("Decoding of string type: bmpstr length mismatch");
      var str = "";
      for (var i2 = 0; i2 < raw.length / 2; i2++) {
        str += String.fromCharCode(raw.readUInt16BE(i2 * 2));
      }
      return str;
    } else if (tag === "numstr") {
      var numstr = buffer2.raw().toString("ascii");
      if (!this._isNumstr(numstr)) {
        return buffer2.error("Decoding of string type: numstr unsupported characters");
      }
      return numstr;
    } else if (tag === "octstr") {
      return buffer2.raw();
    } else if (tag === "objDesc") {
      return buffer2.raw();
    } else if (tag === "printstr") {
      var printstr = buffer2.raw().toString("ascii");
      if (!this._isPrintstr(printstr)) {
        return buffer2.error("Decoding of string type: printstr unsupported characters");
      }
      return printstr;
    } else if (/str$/.test(tag)) {
      return buffer2.raw().toString();
    } else {
      return buffer2.error("Decoding of string type: " + tag + " unsupported");
    }
  };
  DERNode.prototype._decodeObjid = function decodeObjid(buffer2, values, relative) {
    var result;
    var identifiers = [];
    var ident = 0;
    while (!buffer2.isEmpty()) {
      var subident = buffer2.readUInt8();
      ident <<= 7;
      ident |= subident & 127;
      if ((subident & 128) === 0) {
        identifiers.push(ident);
        ident = 0;
      }
    }
    if (subident & 128)
      identifiers.push(ident);
    var first = identifiers[0] / 40 | 0;
    var second = identifiers[0] % 40;
    if (relative)
      result = identifiers;
    else
      result = [first, second].concat(identifiers.slice(1));
    if (values) {
      var tmp = values[result.join(" ")];
      if (tmp === void 0)
        tmp = values[result.join(".")];
      if (tmp !== void 0)
        result = tmp;
    }
    return result;
  };
  DERNode.prototype._decodeTime = function decodeTime(buffer2, tag) {
    var str = buffer2.raw().toString();
    if (tag === "gentime") {
      var year = str.slice(0, 4) | 0;
      var mon = str.slice(4, 6) | 0;
      var day = str.slice(6, 8) | 0;
      var hour = str.slice(8, 10) | 0;
      var min2 = str.slice(10, 12) | 0;
      var sec = str.slice(12, 14) | 0;
    } else if (tag === "utctime") {
      var year = str.slice(0, 2) | 0;
      var mon = str.slice(2, 4) | 0;
      var day = str.slice(4, 6) | 0;
      var hour = str.slice(6, 8) | 0;
      var min2 = str.slice(8, 10) | 0;
      var sec = str.slice(10, 12) | 0;
      if (year < 70)
        year = 2e3 + year;
      else
        year = 1900 + year;
    } else {
      return buffer2.error("Decoding " + tag + " time is not supported yet");
    }
    return Date.UTC(year, mon - 1, day, hour, min2, sec, 0);
  };
  DERNode.prototype._decodeNull = function decodeNull(buffer2) {
    return null;
  };
  DERNode.prototype._decodeBool = function decodeBool(buffer2) {
    var res = buffer2.readUInt8();
    if (buffer2.isError(res))
      return res;
    else
      return res !== 0;
  };
  DERNode.prototype._decodeInt = function decodeInt(buffer2, values) {
    var raw = buffer2.raw();
    var res = new bignum(raw);
    if (values)
      res = values[res.toString(10)] || res;
    return res;
  };
  DERNode.prototype._use = function use(entity, obj) {
    if (typeof entity === "function")
      entity = entity(obj);
    return entity._getDecoder("der").tree;
  };
  function derDecodeTag(buf, fail) {
    var tag = buf.readUInt8(fail);
    if (buf.isError(tag))
      return tag;
    var cls = der2.tagClass[tag >> 6];
    var primitive = (tag & 32) === 0;
    if ((tag & 31) === 31) {
      var oct = tag;
      tag = 0;
      while ((oct & 128) === 128) {
        oct = buf.readUInt8(fail);
        if (buf.isError(oct))
          return oct;
        tag <<= 7;
        tag |= oct & 127;
      }
    } else {
      tag &= 31;
    }
    var tagStr = der2.tag[tag];
    return {
      cls,
      primitive,
      tag,
      tagStr
    };
  }
  function derDecodeLen(buf, primitive, fail) {
    var len = buf.readUInt8(fail);
    if (buf.isError(len))
      return len;
    if (!primitive && len === 128)
      return null;
    if ((len & 128) === 0) {
      return len;
    }
    var num = len & 127;
    if (num > 4)
      return buf.error("length octect is too long");
    len = 0;
    for (var i2 = 0; i2 < num; i2++) {
      len <<= 8;
      var j = buf.readUInt8(fail);
      if (buf.isError(j))
        return j;
      len |= j;
    }
    return len;
  }
  return der_1$1;
}
var pem$1;
var hasRequiredPem$1;
function requirePem$1() {
  if (hasRequiredPem$1) return pem$1;
  hasRequiredPem$1 = 1;
  var inherits = requireInherits_browser();
  var Buffer2 = requireBuffer$1().Buffer;
  var DERDecoder = requireDer$1();
  function PEMDecoder(entity) {
    DERDecoder.call(this, entity);
    this.enc = "pem";
  }
  inherits(PEMDecoder, DERDecoder);
  pem$1 = PEMDecoder;
  PEMDecoder.prototype.decode = function decode2(data2, options2) {
    var lines = data2.toString().split(/[\r\n]+/g);
    var label = options2.label.toUpperCase();
    var re = /^-----(BEGIN|END) ([^-]+)-----$/;
    var start = -1;
    var end = -1;
    for (var i2 = 0; i2 < lines.length; i2++) {
      var match = lines[i2].match(re);
      if (match === null)
        continue;
      if (match[2] !== label)
        continue;
      if (start === -1) {
        if (match[1] !== "BEGIN")
          break;
        start = i2;
      } else {
        if (match[1] !== "END")
          break;
        end = i2;
        break;
      }
    }
    if (start === -1 || end === -1)
      throw new Error("PEM section not found for: " + label);
    var base64 = lines.slice(start + 1, end).join("");
    base64.replace(/[^a-z0-9\+\/=]+/gi, "");
    var input = new Buffer2(base64, "base64");
    return DERDecoder.prototype.decode.call(this, input, options2);
  };
  return pem$1;
}
var hasRequiredDecoders;
function requireDecoders() {
  if (hasRequiredDecoders) return decoders;
  hasRequiredDecoders = 1;
  (function(exports) {
    var decoders2 = exports;
    decoders2.der = requireDer$1();
    decoders2.pem = requirePem$1();
  })(decoders);
  return decoders;
}
var encoders = {};
var der_1;
var hasRequiredDer;
function requireDer() {
  if (hasRequiredDer) return der_1;
  hasRequiredDer = 1;
  var inherits = requireInherits_browser();
  var Buffer2 = requireBuffer$1().Buffer;
  var asn12 = requireAsn1$1();
  var base2 = asn12.base;
  var der2 = asn12.constants.der;
  function DEREncoder(entity) {
    this.enc = "der";
    this.name = entity.name;
    this.entity = entity;
    this.tree = new DERNode();
    this.tree._init(entity.body);
  }
  der_1 = DEREncoder;
  DEREncoder.prototype.encode = function encode2(data2, reporter2) {
    return this.tree._encode(data2, reporter2).join();
  };
  function DERNode(parent) {
    base2.Node.call(this, "der", parent);
  }
  inherits(DERNode, base2.Node);
  DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) {
    var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
    if (content.length < 128) {
      var header = new Buffer2(2);
      header[0] = encodedTag;
      header[1] = content.length;
      return this._createEncoderBuffer([header, content]);
    }
    var lenOctets = 1;
    for (var i2 = content.length; i2 >= 256; i2 >>= 8)
      lenOctets++;
    var header = new Buffer2(1 + 1 + lenOctets);
    header[0] = encodedTag;
    header[1] = 128 | lenOctets;
    for (var i2 = 1 + lenOctets, j = content.length; j > 0; i2--, j >>= 8)
      header[i2] = j & 255;
    return this._createEncoderBuffer([header, content]);
  };
  DERNode.prototype._encodeStr = function encodeStr(str, tag) {
    if (tag === "bitstr") {
      return this._createEncoderBuffer([str.unused | 0, str.data]);
    } else if (tag === "bmpstr") {
      var buf = new Buffer2(str.length * 2);
      for (var i2 = 0; i2 < str.length; i2++) {
        buf.writeUInt16BE(str.charCodeAt(i2), i2 * 2);
      }
      return this._createEncoderBuffer(buf);
    } else if (tag === "numstr") {
      if (!this._isNumstr(str)) {
        return this.reporter.error("Encoding of string type: numstr supports only digits and space");
      }
      return this._createEncoderBuffer(str);
    } else if (tag === "printstr") {
      if (!this._isPrintstr(str)) {
        return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");
      }
      return this._createEncoderBuffer(str);
    } else if (/str$/.test(tag)) {
      return this._createEncoderBuffer(str);
    } else if (tag === "objDesc") {
      return this._createEncoderBuffer(str);
    } else {
      return this.reporter.error("Encoding of string type: " + tag + " unsupported");
    }
  };
  DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
    if (typeof id === "string") {
      if (!values)
        return this.reporter.error("string objid given, but no values map found");
      if (!values.hasOwnProperty(id))
        return this.reporter.error("objid not found in values map");
      id = values[id].split(/[\s\.]+/g);
      for (var i2 = 0; i2 < id.length; i2++)
        id[i2] |= 0;
    } else if (Array.isArray(id)) {
      id = id.slice();
      for (var i2 = 0; i2 < id.length; i2++)
        id[i2] |= 0;
    }
    if (!Array.isArray(id)) {
      return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(id));
    }
    if (!relative) {
      if (id[1] >= 40)
        return this.reporter.error("Second objid identifier OOB");
      id.splice(0, 2, id[0] * 40 + id[1]);
    }
    var size = 0;
    for (var i2 = 0; i2 < id.length; i2++) {
      var ident = id[i2];
      for (size++; ident >= 128; ident >>= 7)
        size++;
    }
    var objid = new Buffer2(size);
    var offset = objid.length - 1;
    for (var i2 = id.length - 1; i2 >= 0; i2--) {
      var ident = id[i2];
      objid[offset--] = ident & 127;
      while ((ident >>= 7) > 0)
        objid[offset--] = 128 | ident & 127;
    }
    return this._createEncoderBuffer(objid);
  };
  function two(num) {
    if (num < 10)
      return "0" + num;
    else
      return num;
  }
  DERNode.prototype._encodeTime = function encodeTime(time, tag) {
    var str;
    var date2 = new Date(time);
    if (tag === "gentime") {
      str = [
        two(date2.getFullYear()),
        two(date2.getUTCMonth() + 1),
        two(date2.getUTCDate()),
        two(date2.getUTCHours()),
        two(date2.getUTCMinutes()),
        two(date2.getUTCSeconds()),
        "Z"
      ].join("");
    } else if (tag === "utctime") {
      str = [
        two(date2.getFullYear() % 100),
        two(date2.getUTCMonth() + 1),
        two(date2.getUTCDate()),
        two(date2.getUTCHours()),
        two(date2.getUTCMinutes()),
        two(date2.getUTCSeconds()),
        "Z"
      ].join("");
    } else {
      this.reporter.error("Encoding " + tag + " time is not supported yet");
    }
    return this._encodeStr(str, "octstr");
  };
  DERNode.prototype._encodeNull = function encodeNull() {
    return this._createEncoderBuffer("");
  };
  DERNode.prototype._encodeInt = function encodeInt(num, values) {
    if (typeof num === "string") {
      if (!values)
        return this.reporter.error("String int or enum given, but no values map");
      if (!values.hasOwnProperty(num)) {
        return this.reporter.error("Values map doesn't contain: " + JSON.stringify(num));
      }
      num = values[num];
    }
    if (typeof num !== "number" && !Buffer2.isBuffer(num)) {
      var numArray = num.toArray();
      if (!num.sign && numArray[0] & 128) {
        numArray.unshift(0);
      }
      num = new Buffer2(numArray);
    }
    if (Buffer2.isBuffer(num)) {
      var size = num.length;
      if (num.length === 0)
        size++;
      var out = new Buffer2(size);
      num.copy(out);
      if (num.length === 0)
        out[0] = 0;
      return this._createEncoderBuffer(out);
    }
    if (num < 128)
      return this._createEncoderBuffer(num);
    if (num < 256)
      return this._createEncoderBuffer([0, num]);
    var size = 1;
    for (var i2 = num; i2 >= 256; i2 >>= 8)
      size++;
    var out = new Array(size);
    for (var i2 = out.length - 1; i2 >= 0; i2--) {
      out[i2] = num & 255;
      num >>= 8;
    }
    if (out[0] & 128) {
      out.unshift(0);
    }
    return this._createEncoderBuffer(new Buffer2(out));
  };
  DERNode.prototype._encodeBool = function encodeBool(value) {
    return this._createEncoderBuffer(value ? 255 : 0);
  };
  DERNode.prototype._use = function use(entity, obj) {
    if (typeof entity === "function")
      entity = entity(obj);
    return entity._getEncoder("der").tree;
  };
  DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter2, parent) {
    var state = this._baseState;
    var i2;
    if (state["default"] === null)
      return false;
    var data2 = dataBuffer.join();
    if (state.defaultBuffer === void 0)
      state.defaultBuffer = this._encodeValue(state["default"], reporter2, parent).join();
    if (data2.length !== state.defaultBuffer.length)
      return false;
    for (i2 = 0; i2 < data2.length; i2++)
      if (data2[i2] !== state.defaultBuffer[i2])
        return false;
    return true;
  };
  function encodeTag(tag, primitive, cls, reporter2) {
    var res;
    if (tag === "seqof")
      tag = "seq";
    else if (tag === "setof")
      tag = "set";
    if (der2.tagByName.hasOwnProperty(tag))
      res = der2.tagByName[tag];
    else if (typeof tag === "number" && (tag | 0) === tag)
      res = tag;
    else
      return reporter2.error("Unknown tag: " + tag);
    if (res >= 31)
      return reporter2.error("Multi-octet tag encoding unsupported");
    if (!primitive)
      res |= 32;
    res |= der2.tagClassByName[cls || "universal"] << 6;
    return res;
  }
  return der_1;
}
var pem;
var hasRequiredPem;
function requirePem() {
  if (hasRequiredPem) return pem;
  hasRequiredPem = 1;
  var inherits = requireInherits_browser();
  var DEREncoder = requireDer();
  function PEMEncoder(entity) {
    DEREncoder.call(this, entity);
    this.enc = "pem";
  }
  inherits(PEMEncoder, DEREncoder);
  pem = PEMEncoder;
  PEMEncoder.prototype.encode = function encode2(data2, options2) {
    var buf = DEREncoder.prototype.encode.call(this, data2);
    var p2 = buf.toString("base64");
    var out = ["-----BEGIN " + options2.label + "-----"];
    for (var i2 = 0; i2 < p2.length; i2 += 64)
      out.push(p2.slice(i2, i2 + 64));
    out.push("-----END " + options2.label + "-----");
    return out.join("\n");
  };
  return pem;
}
var hasRequiredEncoders;
function requireEncoders() {
  if (hasRequiredEncoders) return encoders;
  hasRequiredEncoders = 1;
  (function(exports) {
    var encoders2 = exports;
    encoders2.der = requireDer();
    encoders2.pem = requirePem();
  })(encoders);
  return encoders;
}
var hasRequiredAsn1$1;
function requireAsn1$1() {
  if (hasRequiredAsn1$1) return asn1;
  hasRequiredAsn1$1 = 1;
  (function(exports) {
    var asn12 = exports;
    asn12.bignum = requireBn$1();
    asn12.define = requireApi().define;
    asn12.base = requireBase();
    asn12.constants = requireConstants$1();
    asn12.decoders = requireDecoders();
    asn12.encoders = requireEncoders();
  })(asn1);
  return asn1;
}
var certificate;
var hasRequiredCertificate;
function requireCertificate() {
  if (hasRequiredCertificate) return certificate;
  hasRequiredCertificate = 1;
  var asn = requireAsn1$1();
  var Time = asn.define("Time", function() {
    this.choice({
      utcTime: this.utctime(),
      generalTime: this.gentime()
    });
  });
  var AttributeTypeValue = asn.define("AttributeTypeValue", function() {
    this.seq().obj(
      this.key("type").objid(),
      this.key("value").any()
    );
  });
  var AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function() {
    this.seq().obj(
      this.key("algorithm").objid(),
      this.key("parameters").optional(),
      this.key("curve").objid().optional()
    );
  });
  var SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function() {
    this.seq().obj(
      this.key("algorithm").use(AlgorithmIdentifier),
      this.key("subjectPublicKey").bitstr()
    );
  });
  var RelativeDistinguishedName = asn.define("RelativeDistinguishedName", function() {
    this.setof(AttributeTypeValue);
  });
  var RDNSequence = asn.define("RDNSequence", function() {
    this.seqof(RelativeDistinguishedName);
  });
  var Name = asn.define("Name", function() {
    this.choice({
      rdnSequence: this.use(RDNSequence)
    });
  });
  var Validity = asn.define("Validity", function() {
    this.seq().obj(
      this.key("notBefore").use(Time),
      this.key("notAfter").use(Time)
    );
  });
  var Extension = asn.define("Extension", function() {
    this.seq().obj(
      this.key("extnID").objid(),
      this.key("critical").bool().def(false),
      this.key("extnValue").octstr()
    );
  });
  var TBSCertificate = asn.define("TBSCertificate", function() {
    this.seq().obj(
      this.key("version").explicit(0)["int"]().optional(),
      this.key("serialNumber")["int"](),
      this.key("signature").use(AlgorithmIdentifier),
      this.key("issuer").use(Name),
      this.key("validity").use(Validity),
      this.key("subject").use(Name),
      this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo),
      this.key("issuerUniqueID").implicit(1).bitstr().optional(),
      this.key("subjectUniqueID").implicit(2).bitstr().optional(),
      this.key("extensions").explicit(3).seqof(Extension).optional()
    );
  });
  var X509Certificate = asn.define("X509Certificate", function() {
    this.seq().obj(
      this.key("tbsCertificate").use(TBSCertificate),
      this.key("signatureAlgorithm").use(AlgorithmIdentifier),
      this.key("signatureValue").bitstr()
    );
  });
  certificate = X509Certificate;
  return certificate;
}
var hasRequiredAsn1;
function requireAsn1() {
  if (hasRequiredAsn1) return asn1$1;
  hasRequiredAsn1 = 1;
  var asn12 = requireAsn1$1();
  asn1$1.certificate = requireCertificate();
  var RSAPrivateKey = asn12.define("RSAPrivateKey", function() {
    this.seq().obj(
      this.key("version")["int"](),
      this.key("modulus")["int"](),
      this.key("publicExponent")["int"](),
      this.key("privateExponent")["int"](),
      this.key("prime1")["int"](),
      this.key("prime2")["int"](),
      this.key("exponent1")["int"](),
      this.key("exponent2")["int"](),
      this.key("coefficient")["int"]()
    );
  });
  asn1$1.RSAPrivateKey = RSAPrivateKey;
  var RSAPublicKey = asn12.define("RSAPublicKey", function() {
    this.seq().obj(
      this.key("modulus")["int"](),
      this.key("publicExponent")["int"]()
    );
  });
  asn1$1.RSAPublicKey = RSAPublicKey;
  var AlgorithmIdentifier = asn12.define("AlgorithmIdentifier", function() {
    this.seq().obj(
      this.key("algorithm").objid(),
      this.key("none").null_().optional(),
      this.key("curve").objid().optional(),
      this.key("params").seq().obj(
        this.key("p")["int"](),
        this.key("q")["int"](),
        this.key("g")["int"]()
      ).optional()
    );
  });
  var PublicKey = asn12.define("SubjectPublicKeyInfo", function() {
    this.seq().obj(
      this.key("algorithm").use(AlgorithmIdentifier),
      this.key("subjectPublicKey").bitstr()
    );
  });
  asn1$1.PublicKey = PublicKey;
  var PrivateKeyInfo = asn12.define("PrivateKeyInfo", function() {
    this.seq().obj(
      this.key("version")["int"](),
      this.key("algorithm").use(AlgorithmIdentifier),
      this.key("subjectPrivateKey").octstr()
    );
  });
  asn1$1.PrivateKey = PrivateKeyInfo;
  var EncryptedPrivateKeyInfo = asn12.define("EncryptedPrivateKeyInfo", function() {
    this.seq().obj(
      this.key("algorithm").seq().obj(
        this.key("id").objid(),
        this.key("decrypt").seq().obj(
          this.key("kde").seq().obj(
            this.key("id").objid(),
            this.key("kdeparams").seq().obj(
              this.key("salt").octstr(),
              this.key("iters")["int"]()
            )
          ),
          this.key("cipher").seq().obj(
            this.key("algo").objid(),
            this.key("iv").octstr()
          )
        )
      ),
      this.key("subjectPrivateKey").octstr()
    );
  });
  asn1$1.EncryptedPrivateKey = EncryptedPrivateKeyInfo;
  var DSAPrivateKey = asn12.define("DSAPrivateKey", function() {
    this.seq().obj(
      this.key("version")["int"](),
      this.key("p")["int"](),
      this.key("q")["int"](),
      this.key("g")["int"](),
      this.key("pub_key")["int"](),
      this.key("priv_key")["int"]()
    );
  });
  asn1$1.DSAPrivateKey = DSAPrivateKey;
  asn1$1.DSAparam = asn12.define("DSAparam", function() {
    this["int"]();
  });
  var ECParameters = asn12.define("ECParameters", function() {
    this.choice({
      namedCurve: this.objid()
    });
  });
  var ECPrivateKey = asn12.define("ECPrivateKey", function() {
    this.seq().obj(
      this.key("version")["int"](),
      this.key("privateKey").octstr(),
      this.key("parameters").optional().explicit(0).use(ECParameters),
      this.key("publicKey").optional().explicit(1).bitstr()
    );
  });
  asn1$1.ECPrivateKey = ECPrivateKey;
  asn1$1.signature = asn12.define("signature", function() {
    this.seq().obj(
      this.key("r")["int"](),
      this.key("s")["int"]()
    );
  });
  return asn1$1;
}
const require$$1 = {
  "2.16.840.1.101.3.4.1.1": "aes-128-ecb",
  "2.16.840.1.101.3.4.1.2": "aes-128-cbc",
  "2.16.840.1.101.3.4.1.3": "aes-128-ofb",
  "2.16.840.1.101.3.4.1.4": "aes-128-cfb",
  "2.16.840.1.101.3.4.1.21": "aes-192-ecb",
  "2.16.840.1.101.3.4.1.22": "aes-192-cbc",
  "2.16.840.1.101.3.4.1.23": "aes-192-ofb",
  "2.16.840.1.101.3.4.1.24": "aes-192-cfb",
  "2.16.840.1.101.3.4.1.41": "aes-256-ecb",
  "2.16.840.1.101.3.4.1.42": "aes-256-cbc",
  "2.16.840.1.101.3.4.1.43": "aes-256-ofb",
  "2.16.840.1.101.3.4.1.44": "aes-256-cfb"
};
var fixProc;
var hasRequiredFixProc;
function requireFixProc() {
  if (hasRequiredFixProc) return fixProc;
  hasRequiredFixProc = 1;
  var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m;
  var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m;
  var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m;
  var evp = requireEvp_bytestokey();
  var ciphers = requireBrowser$9();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  fixProc = function(okey, password) {
    var key2 = okey.toString();
    var match = key2.match(findProc);
    var decrypted;
    if (!match) {
      var match2 = key2.match(fullRegex);
      decrypted = Buffer2.from(match2[2].replace(/[\r\n]/g, ""), "base64");
    } else {
      var suite = "aes" + match[1];
      var iv = Buffer2.from(match[2], "hex");
      var cipherText = Buffer2.from(match[3].replace(/[\r\n]/g, ""), "base64");
      var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key;
      var out = [];
      var cipher2 = ciphers.createDecipheriv(suite, cipherKey, iv);
      out.push(cipher2.update(cipherText));
      out.push(cipher2["final"]());
      decrypted = Buffer2.concat(out);
    }
    var tag = key2.match(startRegex)[1];
    return {
      tag,
      data: decrypted
    };
  };
  return fixProc;
}
var parseAsn1;
var hasRequiredParseAsn1;
function requireParseAsn1() {
  if (hasRequiredParseAsn1) return parseAsn1;
  hasRequiredParseAsn1 = 1;
  var asn12 = requireAsn1();
  var aesid = require$$1;
  var fixProc2 = requireFixProc();
  var ciphers = requireBrowser$9();
  var pbkdf2Sync = requireBrowser$a().pbkdf2Sync;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function decrypt2(data2, password) {
    var salt = data2.algorithm.decrypt.kde.kdeparams.salt;
    var iters = parseInt(data2.algorithm.decrypt.kde.kdeparams.iters.toString(), 10);
    var algo = aesid[data2.algorithm.decrypt.cipher.algo.join(".")];
    var iv = data2.algorithm.decrypt.cipher.iv;
    var cipherText = data2.subjectPrivateKey;
    var keylen = parseInt(algo.split("-")[1], 10) / 8;
    var key2 = pbkdf2Sync(password, salt, iters, keylen, "sha1");
    var cipher2 = ciphers.createDecipheriv(algo, key2, iv);
    var out = [];
    out.push(cipher2.update(cipherText));
    out.push(cipher2["final"]());
    return Buffer2.concat(out);
  }
  function parseKeys(buffer2) {
    var password;
    if (typeof buffer2 === "object" && !Buffer2.isBuffer(buffer2)) {
      password = buffer2.passphrase;
      buffer2 = buffer2.key;
    }
    if (typeof buffer2 === "string") {
      buffer2 = Buffer2.from(buffer2);
    }
    var stripped = fixProc2(buffer2, password);
    var type2 = stripped.tag;
    var data2 = stripped.data;
    var subtype, ndata;
    switch (type2) {
      case "CERTIFICATE":
        ndata = asn12.certificate.decode(data2, "der").tbsCertificate.subjectPublicKeyInfo;
      // falls through
      case "PUBLIC KEY":
        if (!ndata) {
          ndata = asn12.PublicKey.decode(data2, "der");
        }
        subtype = ndata.algorithm.algorithm.join(".");
        switch (subtype) {
          case "1.2.840.113549.1.1.1":
            return asn12.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der");
          case "1.2.840.10045.2.1":
            ndata.subjectPrivateKey = ndata.subjectPublicKey;
            return {
              type: "ec",
              data: ndata
            };
          case "1.2.840.10040.4.1":
            ndata.algorithm.params.pub_key = asn12.DSAparam.decode(ndata.subjectPublicKey.data, "der");
            return {
              type: "dsa",
              data: ndata.algorithm.params
            };
          default:
            throw new Error("unknown key id " + subtype);
        }
      // throw new Error('unknown key type ' + type)
      case "ENCRYPTED PRIVATE KEY":
        data2 = asn12.EncryptedPrivateKey.decode(data2, "der");
        data2 = decrypt2(data2, password);
      // falls through
      case "PRIVATE KEY":
        ndata = asn12.PrivateKey.decode(data2, "der");
        subtype = ndata.algorithm.algorithm.join(".");
        switch (subtype) {
          case "1.2.840.113549.1.1.1":
            return asn12.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der");
          case "1.2.840.10045.2.1":
            return {
              curve: ndata.algorithm.curve,
              privateKey: asn12.ECPrivateKey.decode(ndata.subjectPrivateKey, "der").privateKey
            };
          case "1.2.840.10040.4.1":
            ndata.algorithm.params.priv_key = asn12.DSAparam.decode(ndata.subjectPrivateKey, "der");
            return {
              type: "dsa",
              params: ndata.algorithm.params
            };
          default:
            throw new Error("unknown key id " + subtype);
        }
      // throw new Error('unknown key type ' + type)
      case "RSA PUBLIC KEY":
        return asn12.RSAPublicKey.decode(data2, "der");
      case "RSA PRIVATE KEY":
        return asn12.RSAPrivateKey.decode(data2, "der");
      case "DSA PRIVATE KEY":
        return {
          type: "dsa",
          params: asn12.DSAPrivateKey.decode(data2, "der")
        };
      case "EC PRIVATE KEY":
        data2 = asn12.ECPrivateKey.decode(data2, "der");
        return {
          curve: data2.parameters.value,
          privateKey: data2.privateKey
        };
      default:
        throw new Error("unknown key type " + type2);
    }
  }
  parseKeys.signature = asn12.signature;
  parseAsn1 = parseKeys;
  return parseAsn1;
}
const require$$4 = {
  "1.3.132.0.10": "secp256k1",
  "1.3.132.0.33": "p224",
  "1.2.840.10045.3.1.1": "p192",
  "1.2.840.10045.3.1.7": "p256",
  "1.3.132.0.34": "p384",
  "1.3.132.0.35": "p521"
};
var hasRequiredSign;
function requireSign() {
  if (hasRequiredSign) return sign.exports;
  hasRequiredSign = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var createHmac = requireBrowser$b();
  var crt = /* @__PURE__ */ requireBrowserifyRsa();
  var EC = requireElliptic().ec;
  var BN = requireBn();
  var parseKeys = requireParseAsn1();
  var curves2 = require$$4;
  var RSA_PKCS1_PADDING = 1;
  function sign$12(hash2, key2, hashType, signType, tag) {
    var priv = parseKeys(key2);
    if (priv.curve) {
      if (signType !== "ecdsa" && signType !== "ecdsa/rsa") {
        throw new Error("wrong private key type");
      }
      return ecSign(hash2, priv);
    } else if (priv.type === "dsa") {
      if (signType !== "dsa") {
        throw new Error("wrong private key type");
      }
      return dsaSign(hash2, priv, hashType);
    }
    if (signType !== "rsa" && signType !== "ecdsa/rsa") {
      throw new Error("wrong private key type");
    }
    if (key2.padding !== void 0 && key2.padding !== RSA_PKCS1_PADDING) {
      throw new Error("illegal or unsupported padding mode");
    }
    hash2 = Buffer2.concat([tag, hash2]);
    var len = priv.modulus.byteLength();
    var pad = [0, 1];
    while (hash2.length + pad.length + 1 < len) {
      pad.push(255);
    }
    pad.push(0);
    var i2 = -1;
    while (++i2 < hash2.length) {
      pad.push(hash2[i2]);
    }
    var out = crt(pad, priv);
    return out;
  }
  function ecSign(hash2, priv) {
    var curveId = curves2[priv.curve.join(".")];
    if (!curveId) {
      throw new Error("unknown curve " + priv.curve.join("."));
    }
    var curve2 = new EC(curveId);
    var key2 = curve2.keyFromPrivate(priv.privateKey);
    var out = key2.sign(hash2);
    return Buffer2.from(out.toDER());
  }
  function dsaSign(hash2, priv, algo) {
    var x2 = priv.params.priv_key;
    var p2 = priv.params.p;
    var q = priv.params.q;
    var g = priv.params.g;
    var r2 = new BN(0);
    var k2;
    var H = bits2int(hash2, q).mod(q);
    var s2 = false;
    var kv = getKey(x2, q, hash2, algo);
    while (s2 === false) {
      k2 = makeKey(q, kv, algo);
      r2 = makeR(g, k2, p2, q);
      s2 = k2.invm(q).imul(H.add(x2.mul(r2))).mod(q);
      if (s2.cmpn(0) === 0) {
        s2 = false;
        r2 = new BN(0);
      }
    }
    return toDER(r2, s2);
  }
  function toDER(r2, s2) {
    r2 = r2.toArray();
    s2 = s2.toArray();
    if (r2[0] & 128) {
      r2 = [0].concat(r2);
    }
    if (s2[0] & 128) {
      s2 = [0].concat(s2);
    }
    var total = r2.length + s2.length + 4;
    var res = [
      48,
      total,
      2,
      r2.length
    ];
    res = res.concat(r2, [2, s2.length], s2);
    return Buffer2.from(res);
  }
  function getKey(x2, q, hash2, algo) {
    x2 = Buffer2.from(x2.toArray());
    if (x2.length < q.byteLength()) {
      var zeros = Buffer2.alloc(q.byteLength() - x2.length);
      x2 = Buffer2.concat([zeros, x2]);
    }
    var hlen = hash2.length;
    var hbits = bits2octets(hash2, q);
    var v2 = Buffer2.alloc(hlen);
    v2.fill(1);
    var k2 = Buffer2.alloc(hlen);
    k2 = createHmac(algo, k2).update(v2).update(Buffer2.from([0])).update(x2).update(hbits).digest();
    v2 = createHmac(algo, k2).update(v2).digest();
    k2 = createHmac(algo, k2).update(v2).update(Buffer2.from([1])).update(x2).update(hbits).digest();
    v2 = createHmac(algo, k2).update(v2).digest();
    return { k: k2, v: v2 };
  }
  function bits2int(obits, q) {
    var bits = new BN(obits);
    var shift = (obits.length << 3) - q.bitLength();
    if (shift > 0) {
      bits.ishrn(shift);
    }
    return bits;
  }
  function bits2octets(bits, q) {
    bits = bits2int(bits, q);
    bits = bits.mod(q);
    var out = Buffer2.from(bits.toArray());
    if (out.length < q.byteLength()) {
      var zeros = Buffer2.alloc(q.byteLength() - out.length);
      out = Buffer2.concat([zeros, out]);
    }
    return out;
  }
  function makeKey(q, kv, algo) {
    var t2;
    var k2;
    do {
      t2 = Buffer2.alloc(0);
      while (t2.length * 8 < q.bitLength()) {
        kv.v = createHmac(algo, kv.k).update(kv.v).digest();
        t2 = Buffer2.concat([t2, kv.v]);
      }
      k2 = bits2int(t2, q);
      kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer2.from([0])).digest();
      kv.v = createHmac(algo, kv.k).update(kv.v).digest();
    } while (k2.cmp(q) !== -1);
    return k2;
  }
  function makeR(g, k2, p2, q) {
    return g.toRed(BN.mont(p2)).redPow(k2).fromRed().mod(q);
  }
  sign.exports = sign$12;
  sign.exports.getKey = getKey;
  sign.exports.makeKey = makeKey;
  return sign.exports;
}
var verify_1;
var hasRequiredVerify;
function requireVerify() {
  if (hasRequiredVerify) return verify_1;
  hasRequiredVerify = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var BN = requireBn();
  var EC = requireElliptic().ec;
  var parseKeys = requireParseAsn1();
  var curves2 = require$$4;
  function verify(sig, hash2, key2, signType, tag) {
    var pub = parseKeys(key2);
    if (pub.type === "ec") {
      if (signType !== "ecdsa" && signType !== "ecdsa/rsa") {
        throw new Error("wrong public key type");
      }
      return ecVerify(sig, hash2, pub);
    } else if (pub.type === "dsa") {
      if (signType !== "dsa") {
        throw new Error("wrong public key type");
      }
      return dsaVerify(sig, hash2, pub);
    }
    if (signType !== "rsa" && signType !== "ecdsa/rsa") {
      throw new Error("wrong public key type");
    }
    hash2 = Buffer2.concat([tag, hash2]);
    var len = pub.modulus.byteLength();
    var pad = [1];
    var padNum = 0;
    while (hash2.length + pad.length + 2 < len) {
      pad.push(255);
      padNum += 1;
    }
    pad.push(0);
    var i2 = -1;
    while (++i2 < hash2.length) {
      pad.push(hash2[i2]);
    }
    pad = Buffer2.from(pad);
    var red = BN.mont(pub.modulus);
    sig = new BN(sig).toRed(red);
    sig = sig.redPow(new BN(pub.publicExponent));
    sig = Buffer2.from(sig.fromRed().toArray());
    var out = padNum < 8 ? 1 : 0;
    len = Math.min(sig.length, pad.length);
    if (sig.length !== pad.length) {
      out = 1;
    }
    i2 = -1;
    while (++i2 < len) {
      out |= sig[i2] ^ pad[i2];
    }
    return out === 0;
  }
  function ecVerify(sig, hash2, pub) {
    var curveId = curves2[pub.data.algorithm.curve.join(".")];
    if (!curveId) {
      throw new Error("unknown curve " + pub.data.algorithm.curve.join("."));
    }
    var curve2 = new EC(curveId);
    var pubkey = pub.data.subjectPrivateKey.data;
    return curve2.verify(hash2, sig, pubkey);
  }
  function dsaVerify(sig, hash2, pub) {
    var p2 = pub.data.p;
    var q = pub.data.q;
    var g = pub.data.g;
    var y2 = pub.data.pub_key;
    var unpacked = parseKeys.signature.decode(sig, "der");
    var s2 = unpacked.s;
    var r2 = unpacked.r;
    checkValue(s2, q);
    checkValue(r2, q);
    var montp = BN.mont(p2);
    var w = s2.invm(q);
    var v2 = g.toRed(montp).redPow(new BN(hash2).mul(w).mod(q)).fromRed().mul(y2.toRed(montp).redPow(r2.mul(w).mod(q)).fromRed()).mod(p2).mod(q);
    return v2.cmp(r2) === 0;
  }
  function checkValue(b2, q) {
    if (b2.cmpn(0) <= 0) {
      throw new Error("invalid sig");
    }
    if (b2.cmp(q) >= 0) {
      throw new Error("invalid sig");
    }
  }
  verify_1 = verify;
  return verify_1;
}
var browser$8;
var hasRequiredBrowser$6;
function requireBrowser$6() {
  if (hasRequiredBrowser$6) return browser$8;
  hasRequiredBrowser$6 = 1;
  var Buffer2 = requireSafeBuffer$1().Buffer;
  var createHash = requireBrowser$c();
  var stream2 = requireReadableBrowser();
  var inherits = requireInherits_browser();
  var sign2 = requireSign();
  var verify = requireVerify();
  var algorithms = require$$6;
  Object.keys(algorithms).forEach(function(key2) {
    algorithms[key2].id = Buffer2.from(algorithms[key2].id, "hex");
    algorithms[key2.toLowerCase()] = algorithms[key2];
  });
  function Sign(algorithm) {
    stream2.Writable.call(this);
    var data2 = algorithms[algorithm];
    if (!data2) {
      throw new Error("Unknown message digest");
    }
    this._hashType = data2.hash;
    this._hash = createHash(data2.hash);
    this._tag = data2.id;
    this._signType = data2.sign;
  }
  inherits(Sign, stream2.Writable);
  Sign.prototype._write = function _write(data2, _2, done) {
    this._hash.update(data2);
    done();
  };
  Sign.prototype.update = function update(data2, enc) {
    this._hash.update(typeof data2 === "string" ? Buffer2.from(data2, enc) : data2);
    return this;
  };
  Sign.prototype.sign = function signMethod(key2, enc) {
    this.end();
    var hash2 = this._hash.digest();
    var sig = sign2(hash2, key2, this._hashType, this._signType, this._tag);
    return enc ? sig.toString(enc) : sig;
  };
  function Verify(algorithm) {
    stream2.Writable.call(this);
    var data2 = algorithms[algorithm];
    if (!data2) {
      throw new Error("Unknown message digest");
    }
    this._hash = createHash(data2.hash);
    this._tag = data2.id;
    this._signType = data2.sign;
  }
  inherits(Verify, stream2.Writable);
  Verify.prototype._write = function _write(data2, _2, done) {
    this._hash.update(data2);
    done();
  };
  Verify.prototype.update = function update(data2, enc) {
    this._hash.update(typeof data2 === "string" ? Buffer2.from(data2, enc) : data2);
    return this;
  };
  Verify.prototype.verify = function verifyMethod(key2, sig, enc) {
    var sigBuffer = typeof sig === "string" ? Buffer2.from(sig, enc) : sig;
    this.end();
    var hash2 = this._hash.digest();
    return verify(sigBuffer, hash2, key2, this._signType, this._tag);
  };
  function createSign(algorithm) {
    return new Sign(algorithm);
  }
  function createVerify(algorithm) {
    return new Verify(algorithm);
  }
  browser$8 = {
    Sign: createSign,
    Verify: createVerify,
    createSign,
    createVerify
  };
  return browser$8;
}
var browser$7;
var hasRequiredBrowser$5;
function requireBrowser$5() {
  if (hasRequiredBrowser$5) return browser$7;
  hasRequiredBrowser$5 = 1;
  var elliptic2 = requireElliptic();
  var BN = requireBn$1();
  browser$7 = function createECDH(curve2) {
    return new ECDH(curve2);
  };
  var aliases = {
    secp256k1: {
      name: "secp256k1",
      byteLength: 32
    },
    secp224r1: {
      name: "p224",
      byteLength: 28
    },
    prime256v1: {
      name: "p256",
      byteLength: 32
    },
    prime192v1: {
      name: "p192",
      byteLength: 24
    },
    ed25519: {
      name: "ed25519",
      byteLength: 32
    },
    secp384r1: {
      name: "p384",
      byteLength: 48
    },
    secp521r1: {
      name: "p521",
      byteLength: 66
    }
  };
  aliases.p224 = aliases.secp224r1;
  aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
  aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
  aliases.p384 = aliases.secp384r1;
  aliases.p521 = aliases.secp521r1;
  function ECDH(curve2) {
    this.curveType = aliases[curve2];
    if (!this.curveType) {
      this.curveType = {
        name: curve2
      };
    }
    this.curve = new elliptic2.ec(this.curveType.name);
    this.keys = void 0;
  }
  ECDH.prototype.generateKeys = function(enc, format2) {
    this.keys = this.curve.genKeyPair();
    return this.getPublicKey(enc, format2);
  };
  ECDH.prototype.computeSecret = function(other, inenc, enc) {
    inenc = inenc || "utf8";
    if (!Buffer.isBuffer(other)) {
      other = new Buffer(other, inenc);
    }
    var otherPub = this.curve.keyFromPublic(other).getPublic();
    var out = otherPub.mul(this.keys.getPrivate()).getX();
    return formatReturnValue(out, enc, this.curveType.byteLength);
  };
  ECDH.prototype.getPublicKey = function(enc, format2) {
    var key2 = this.keys.getPublic(format2 === "compressed", true);
    if (format2 === "hybrid") {
      if (key2[key2.length - 1] % 2) {
        key2[0] = 7;
      } else {
        key2[0] = 6;
      }
    }
    return formatReturnValue(key2, enc);
  };
  ECDH.prototype.getPrivateKey = function(enc) {
    return formatReturnValue(this.keys.getPrivate(), enc);
  };
  ECDH.prototype.setPublicKey = function(pub, enc) {
    enc = enc || "utf8";
    if (!Buffer.isBuffer(pub)) {
      pub = new Buffer(pub, enc);
    }
    this.keys._importPublic(pub);
    return this;
  };
  ECDH.prototype.setPrivateKey = function(priv, enc) {
    enc = enc || "utf8";
    if (!Buffer.isBuffer(priv)) {
      priv = new Buffer(priv, enc);
    }
    var _priv = new BN(priv);
    _priv = _priv.toString(16);
    this.keys = this.curve.genKeyPair();
    this.keys._importPrivate(_priv);
    return this;
  };
  function formatReturnValue(bn2, enc, len) {
    if (!Array.isArray(bn2)) {
      bn2 = bn2.toArray();
    }
    var buf = new Buffer(bn2);
    if (len && buf.length < len) {
      var zeros = new Buffer(len - buf.length);
      zeros.fill(0);
      buf = Buffer.concat([zeros, buf]);
    }
    if (!enc) {
      return buf;
    } else {
      return buf.toString(enc);
    }
  }
  return browser$7;
}
var browser$6 = {};
var mgf;
var hasRequiredMgf;
function requireMgf() {
  if (hasRequiredMgf) return mgf;
  hasRequiredMgf = 1;
  var createHash = requireBrowser$c();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  mgf = function(seed, len) {
    var t2 = Buffer2.alloc(0);
    var i2 = 0;
    var c2;
    while (t2.length < len) {
      c2 = i2ops(i2++);
      t2 = Buffer2.concat([t2, createHash("sha1").update(seed).update(c2).digest()]);
    }
    return t2.slice(0, len);
  };
  function i2ops(c2) {
    var out = Buffer2.allocUnsafe(4);
    out.writeUInt32BE(c2, 0);
    return out;
  }
  return mgf;
}
var xor$1;
var hasRequiredXor;
function requireXor() {
  if (hasRequiredXor) return xor$1;
  hasRequiredXor = 1;
  xor$1 = function xor2(a2, b2) {
    var len = a2.length;
    var i2 = -1;
    while (++i2 < len) {
      a2[i2] ^= b2[i2];
    }
    return a2;
  };
  return xor$1;
}
var withPublic_1;
var hasRequiredWithPublic;
function requireWithPublic() {
  if (hasRequiredWithPublic) return withPublic_1;
  hasRequiredWithPublic = 1;
  var BN = requireBn$1();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  function withPublic(paddedMsg, key2) {
    return Buffer2.from(paddedMsg.toRed(BN.mont(key2.modulus)).redPow(new BN(key2.publicExponent)).fromRed().toArray());
  }
  withPublic_1 = withPublic;
  return withPublic_1;
}
var publicEncrypt;
var hasRequiredPublicEncrypt;
function requirePublicEncrypt() {
  if (hasRequiredPublicEncrypt) return publicEncrypt;
  hasRequiredPublicEncrypt = 1;
  var parseKeys = requireParseAsn1();
  var randomBytes = requireBrowser$e();
  var createHash = requireBrowser$c();
  var mgf2 = requireMgf();
  var xor2 = requireXor();
  var BN = requireBn$1();
  var withPublic = requireWithPublic();
  var crt = /* @__PURE__ */ requireBrowserifyRsa();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  publicEncrypt = function publicEncrypt2(publicKey2, msg, reverse) {
    var padding;
    if (publicKey2.padding) {
      padding = publicKey2.padding;
    } else if (reverse) {
      padding = 1;
    } else {
      padding = 4;
    }
    var key2 = parseKeys(publicKey2);
    var paddedMsg;
    if (padding === 4) {
      paddedMsg = oaep(key2, msg);
    } else if (padding === 1) {
      paddedMsg = pkcs1(key2, msg, reverse);
    } else if (padding === 3) {
      paddedMsg = new BN(msg);
      if (paddedMsg.cmp(key2.modulus) >= 0) {
        throw new Error("data too long for modulus");
      }
    } else {
      throw new Error("unknown padding");
    }
    if (reverse) {
      return crt(paddedMsg, key2);
    } else {
      return withPublic(paddedMsg, key2);
    }
  };
  function oaep(key2, msg) {
    var k2 = key2.modulus.byteLength();
    var mLen = msg.length;
    var iHash = createHash("sha1").update(Buffer2.alloc(0)).digest();
    var hLen = iHash.length;
    var hLen2 = 2 * hLen;
    if (mLen > k2 - hLen2 - 2) {
      throw new Error("message too long");
    }
    var ps = Buffer2.alloc(k2 - mLen - hLen2 - 2);
    var dblen = k2 - hLen - 1;
    var seed = randomBytes(hLen);
    var maskedDb = xor2(Buffer2.concat([iHash, ps, Buffer2.alloc(1, 1), msg], dblen), mgf2(seed, dblen));
    var maskedSeed = xor2(seed, mgf2(maskedDb, hLen));
    return new BN(Buffer2.concat([Buffer2.alloc(1), maskedSeed, maskedDb], k2));
  }
  function pkcs1(key2, msg, reverse) {
    var mLen = msg.length;
    var k2 = key2.modulus.byteLength();
    if (mLen > k2 - 11) {
      throw new Error("message too long");
    }
    var ps;
    if (reverse) {
      ps = Buffer2.alloc(k2 - mLen - 3, 255);
    } else {
      ps = nonZero(k2 - mLen - 3);
    }
    return new BN(Buffer2.concat([Buffer2.from([0, reverse ? 1 : 2]), ps, Buffer2.alloc(1), msg], k2));
  }
  function nonZero(len) {
    var out = Buffer2.allocUnsafe(len);
    var i2 = 0;
    var cache2 = randomBytes(len * 2);
    var cur = 0;
    var num;
    while (i2 < len) {
      if (cur === cache2.length) {
        cache2 = randomBytes(len * 2);
        cur = 0;
      }
      num = cache2[cur++];
      if (num) {
        out[i2++] = num;
      }
    }
    return out;
  }
  return publicEncrypt;
}
var privateDecrypt;
var hasRequiredPrivateDecrypt;
function requirePrivateDecrypt() {
  if (hasRequiredPrivateDecrypt) return privateDecrypt;
  hasRequiredPrivateDecrypt = 1;
  var parseKeys = requireParseAsn1();
  var mgf2 = requireMgf();
  var xor2 = requireXor();
  var BN = requireBn$1();
  var crt = /* @__PURE__ */ requireBrowserifyRsa();
  var createHash = requireBrowser$c();
  var withPublic = requireWithPublic();
  var Buffer2 = requireSafeBuffer$1().Buffer;
  privateDecrypt = function privateDecrypt2(privateKey, enc, reverse) {
    var padding;
    if (privateKey.padding) {
      padding = privateKey.padding;
    } else if (reverse) {
      padding = 1;
    } else {
      padding = 4;
    }
    var key2 = parseKeys(privateKey);
    var k2 = key2.modulus.byteLength();
    if (enc.length > k2 || new BN(enc).cmp(key2.modulus) >= 0) {
      throw new Error("decryption error");
    }
    var msg;
    if (reverse) {
      msg = withPublic(new BN(enc), key2);
    } else {
      msg = crt(enc, key2);
    }
    var zBuffer = Buffer2.alloc(k2 - msg.length);
    msg = Buffer2.concat([zBuffer, msg], k2);
    if (padding === 4) {
      return oaep(key2, msg);
    } else if (padding === 1) {
      return pkcs1(key2, msg, reverse);
    } else if (padding === 3) {
      return msg;
    } else {
      throw new Error("unknown padding");
    }
  };
  function oaep(key2, msg) {
    var k2 = key2.modulus.byteLength();
    var iHash = createHash("sha1").update(Buffer2.alloc(0)).digest();
    var hLen = iHash.length;
    if (msg[0] !== 0) {
      throw new Error("decryption error");
    }
    var maskedSeed = msg.slice(1, hLen + 1);
    var maskedDb = msg.slice(hLen + 1);
    var seed = xor2(maskedSeed, mgf2(maskedDb, hLen));
    var db = xor2(maskedDb, mgf2(seed, k2 - hLen - 1));
    if (compare(iHash, db.slice(0, hLen))) {
      throw new Error("decryption error");
    }
    var i2 = hLen;
    while (db[i2] === 0) {
      i2++;
    }
    if (db[i2++] !== 1) {
      throw new Error("decryption error");
    }
    return db.slice(i2);
  }
  function pkcs1(key2, msg, reverse) {
    var p1 = msg.slice(0, 2);
    var i2 = 2;
    var status = 0;
    while (msg[i2++] !== 0) {
      if (i2 >= msg.length) {
        status++;
        break;
      }
    }
    var ps = msg.slice(2, i2 - 1);
    if (p1.toString("hex") !== "0002" && !reverse || p1.toString("hex") !== "0001" && reverse) {
      status++;
    }
    if (ps.length < 8) {
      status++;
    }
    if (status) {
      throw new Error("decryption error");
    }
    return msg.slice(i2);
  }
  function compare(a2, b2) {
    a2 = Buffer2.from(a2);
    b2 = Buffer2.from(b2);
    var dif = 0;
    var len = a2.length;
    if (a2.length !== b2.length) {
      dif++;
      len = Math.min(a2.length, b2.length);
    }
    var i2 = -1;
    while (++i2 < len) {
      dif += a2[i2] ^ b2[i2];
    }
    return dif;
  }
  return privateDecrypt;
}
var hasRequiredBrowser$4;
function requireBrowser$4() {
  if (hasRequiredBrowser$4) return browser$6;
  hasRequiredBrowser$4 = 1;
  (function(exports) {
    exports.publicEncrypt = requirePublicEncrypt();
    exports.privateDecrypt = requirePrivateDecrypt();
    exports.privateEncrypt = function privateEncrypt(key2, buf) {
      return exports.publicEncrypt(key2, buf, true);
    };
    exports.publicDecrypt = function publicDecrypt(key2, buf) {
      return exports.privateDecrypt(key2, buf, true);
    };
  })(browser$6);
  return browser$6;
}
var browser$5 = {};
var hasRequiredBrowser$3;
function requireBrowser$3() {
  if (hasRequiredBrowser$3) return browser$5;
  hasRequiredBrowser$3 = 1;
  function oldBrowser() {
    throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11");
  }
  var safeBuffer2 = requireSafeBuffer$1();
  var randombytes = requireBrowser$e();
  var Buffer2 = safeBuffer2.Buffer;
  var kBufferMaxLength = safeBuffer2.kMaxLength;
  var crypto2 = commonjsGlobal$1.crypto || commonjsGlobal$1.msCrypto;
  var kMaxUint32 = Math.pow(2, 32) - 1;
  function assertOffset(offset, length) {
    if (typeof offset !== "number" || offset !== offset) {
      throw new TypeError("offset must be a number");
    }
    if (offset > kMaxUint32 || offset < 0) {
      throw new TypeError("offset must be a uint32");
    }
    if (offset > kBufferMaxLength || offset > length) {
      throw new RangeError("offset out of range");
    }
  }
  function assertSize2(size, offset, length) {
    if (typeof size !== "number" || size !== size) {
      throw new TypeError("size must be a number");
    }
    if (size > kMaxUint32 || size < 0) {
      throw new TypeError("size must be a uint32");
    }
    if (size + offset > length || size > kBufferMaxLength) {
      throw new RangeError("buffer too small");
    }
  }
  if (crypto2 && crypto2.getRandomValues || !process.browser) {
    browser$5.randomFill = randomFill;
    browser$5.randomFillSync = randomFillSync;
  } else {
    browser$5.randomFill = oldBrowser;
    browser$5.randomFillSync = oldBrowser;
  }
  function randomFill(buf, offset, size, cb) {
    if (!Buffer2.isBuffer(buf) && !(buf instanceof commonjsGlobal$1.Uint8Array)) {
      throw new TypeError('"buf" argument must be a Buffer or Uint8Array');
    }
    if (typeof offset === "function") {
      cb = offset;
      offset = 0;
      size = buf.length;
    } else if (typeof size === "function") {
      cb = size;
      size = buf.length - offset;
    } else if (typeof cb !== "function") {
      throw new TypeError('"cb" argument must be a function');
    }
    assertOffset(offset, buf.length);
    assertSize2(size, offset, buf.length);
    return actualFill(buf, offset, size, cb);
  }
  function actualFill(buf, offset, size, cb) {
    if (process.browser) {
      var ourBuf = buf.buffer;
      var uint = new Uint8Array(ourBuf, offset, size);
      crypto2.getRandomValues(uint);
      if (cb) {
        process.nextTick(function() {
          cb(null, buf);
        });
        return;
      }
      return buf;
    }
    if (cb) {
      randombytes(size, function(err, bytes2) {
        if (err) {
          return cb(err);
        }
        bytes2.copy(buf, offset);
        cb(null, buf);
      });
      return;
    }
    var bytes = randombytes(size);
    bytes.copy(buf, offset);
    return buf;
  }
  function randomFillSync(buf, offset, size) {
    if (typeof offset === "undefined") {
      offset = 0;
    }
    if (!Buffer2.isBuffer(buf) && !(buf instanceof commonjsGlobal$1.Uint8Array)) {
      throw new TypeError('"buf" argument must be a Buffer or Uint8Array');
    }
    assertOffset(offset, buf.length);
    if (size === void 0) size = buf.length - offset;
    assertSize2(size, offset, buf.length);
    return actualFill(buf, offset, size);
  }
  return browser$5;
}
var hasRequiredCryptoBrowserify;
function requireCryptoBrowserify() {
  if (hasRequiredCryptoBrowserify) return cryptoBrowserify;
  hasRequiredCryptoBrowserify = 1;
  cryptoBrowserify.randomBytes = cryptoBrowserify.rng = cryptoBrowserify.pseudoRandomBytes = cryptoBrowserify.prng = requireBrowser$e();
  cryptoBrowserify.createHash = cryptoBrowserify.Hash = requireBrowser$c();
  cryptoBrowserify.createHmac = cryptoBrowserify.Hmac = requireBrowser$b();
  var algos2 = requireAlgos();
  var algoKeys = Object.keys(algos2);
  var hashes = [
    "sha1",
    "sha224",
    "sha256",
    "sha384",
    "sha512",
    "md5",
    "rmd160"
  ].concat(algoKeys);
  cryptoBrowserify.getHashes = function() {
    return hashes;
  };
  var p2 = requireBrowser$a();
  cryptoBrowserify.pbkdf2 = p2.pbkdf2;
  cryptoBrowserify.pbkdf2Sync = p2.pbkdf2Sync;
  var aes2 = requireBrowser$8();
  cryptoBrowserify.Cipher = aes2.Cipher;
  cryptoBrowserify.createCipher = aes2.createCipher;
  cryptoBrowserify.Cipheriv = aes2.Cipheriv;
  cryptoBrowserify.createCipheriv = aes2.createCipheriv;
  cryptoBrowserify.Decipher = aes2.Decipher;
  cryptoBrowserify.createDecipher = aes2.createDecipher;
  cryptoBrowserify.Decipheriv = aes2.Decipheriv;
  cryptoBrowserify.createDecipheriv = aes2.createDecipheriv;
  cryptoBrowserify.getCiphers = aes2.getCiphers;
  cryptoBrowserify.listCiphers = aes2.listCiphers;
  var dh2 = requireBrowser$7();
  cryptoBrowserify.DiffieHellmanGroup = dh2.DiffieHellmanGroup;
  cryptoBrowserify.createDiffieHellmanGroup = dh2.createDiffieHellmanGroup;
  cryptoBrowserify.getDiffieHellman = dh2.getDiffieHellman;
  cryptoBrowserify.createDiffieHellman = dh2.createDiffieHellman;
  cryptoBrowserify.DiffieHellman = dh2.DiffieHellman;
  var sign2 = requireBrowser$6();
  cryptoBrowserify.createSign = sign2.createSign;
  cryptoBrowserify.Sign = sign2.Sign;
  cryptoBrowserify.createVerify = sign2.createVerify;
  cryptoBrowserify.Verify = sign2.Verify;
  cryptoBrowserify.createECDH = requireBrowser$5();
  var publicEncrypt2 = requireBrowser$4();
  cryptoBrowserify.publicEncrypt = publicEncrypt2.publicEncrypt;
  cryptoBrowserify.privateEncrypt = publicEncrypt2.privateEncrypt;
  cryptoBrowserify.publicDecrypt = publicEncrypt2.publicDecrypt;
  cryptoBrowserify.privateDecrypt = publicEncrypt2.privateDecrypt;
  var rf = requireBrowser$3();
  cryptoBrowserify.randomFill = rf.randomFill;
  cryptoBrowserify.randomFillSync = rf.randomFillSync;
  cryptoBrowserify.createCredentials = function() {
    throw new Error("sorry, createCredentials is not implemented yet\nwe accept pull requests\nhttps://github.com/browserify/crypto-browserify");
  };
  cryptoBrowserify.constants = {
    DH_CHECK_P_NOT_SAFE_PRIME: 2,
    DH_CHECK_P_NOT_PRIME: 1,
    DH_UNABLE_TO_CHECK_GENERATOR: 4,
    DH_NOT_SUITABLE_GENERATOR: 8,
    NPN_ENABLED: 1,
    ALPN_ENABLED: 1,
    RSA_PKCS1_PADDING: 1,
    RSA_SSLV23_PADDING: 2,
    RSA_NO_PADDING: 3,
    RSA_PKCS1_OAEP_PADDING: 4,
    RSA_X931_PADDING: 5,
    RSA_PKCS1_PSS_PADDING: 6,
    POINT_CONVERSION_COMPRESSED: 2,
    POINT_CONVERSION_UNCOMPRESSED: 4,
    POINT_CONVERSION_HYBRID: 6
  };
  return cryptoBrowserify;
}
var core$2 = core$3.exports;
var hasRequiredCore;
function requireCore() {
  if (hasRequiredCore) return core$3.exports;
  hasRequiredCore = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory();
      }
    })(core$2, function() {
      var CryptoJS2 = CryptoJS2 || function(Math2, undefined$1) {
        var crypto2;
        if (typeof window !== "undefined" && window.crypto) {
          crypto2 = window.crypto;
        }
        if (typeof self !== "undefined" && self.crypto) {
          crypto2 = self.crypto;
        }
        if (typeof globalThis !== "undefined" && globalThis.crypto) {
          crypto2 = globalThis.crypto;
        }
        if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
          crypto2 = window.msCrypto;
        }
        if (!crypto2 && typeof commonjsGlobal$1 !== "undefined" && commonjsGlobal$1.crypto) {
          crypto2 = commonjsGlobal$1.crypto;
        }
        if (!crypto2 && typeof commonjsRequire$1 === "function") {
          try {
            crypto2 = /* @__PURE__ */ requireCryptoBrowserify();
          } catch (err) {
          }
        }
        var cryptoSecureRandomInt = function() {
          if (crypto2) {
            if (typeof crypto2.getRandomValues === "function") {
              try {
                return crypto2.getRandomValues(new Uint32Array(1))[0];
              } catch (err) {
              }
            }
            if (typeof crypto2.randomBytes === "function") {
              try {
                return crypto2.randomBytes(4).readInt32LE();
              } catch (err) {
              }
            }
          }
          throw new Error("Native crypto module could not be used to get secure random number.");
        };
        var create2 = Object.create || /* @__PURE__ */ function() {
          function F() {
          }
          return function(obj) {
            var subtype;
            F.prototype = obj;
            subtype = new F();
            F.prototype = null;
            return subtype;
          };
        }();
        var C2 = {};
        var C_lib = C2.lib = {};
        var Base = C_lib.Base = /* @__PURE__ */ function() {
          return {
            /**
             * Creates a new object that inherits from this object.
             *
             * @param {Object} overrides Properties to copy into the new object.
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         field: 'value',
             *
             *         method: function () {
             *         }
             *     });
             */
            extend: function(overrides) {
              var subtype = create2(this);
              if (overrides) {
                subtype.mixIn(overrides);
              }
              if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
                subtype.init = function() {
                  subtype.$super.init.apply(this, arguments);
                };
              }
              subtype.init.prototype = subtype;
              subtype.$super = this;
              return subtype;
            },
            /**
             * Extends this object and runs the init method.
             * Arguments to create() will be passed to init().
             *
             * @return {Object} The new object.
             *
             * @static
             *
             * @example
             *
             *     var instance = MyType.create();
             */
            create: function() {
              var instance2 = this.extend();
              instance2.init.apply(instance2, arguments);
              return instance2;
            },
            /**
             * Initializes a newly created object.
             * Override this method to add some logic when your objects are created.
             *
             * @example
             *
             *     var MyType = CryptoJS.lib.Base.extend({
             *         init: function () {
             *             // ...
             *         }
             *     });
             */
            init: function() {
            },
            /**
             * Copies properties into this object.
             *
             * @param {Object} properties The properties to mix in.
             *
             * @example
             *
             *     MyType.mixIn({
             *         field: 'value'
             *     });
             */
            mixIn: function(properties2) {
              for (var propertyName in properties2) {
                if (properties2.hasOwnProperty(propertyName)) {
                  this[propertyName] = properties2[propertyName];
                }
              }
              if (properties2.hasOwnProperty("toString")) {
                this.toString = properties2.toString;
              }
            },
            /**
             * Creates a copy of this object.
             *
             * @return {Object} The clone.
             *
             * @example
             *
             *     var clone = instance.clone();
             */
            clone: function() {
              return this.init.prototype.extend(this);
            }
          };
        }();
        var WordArray = C_lib.WordArray = Base.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of 32-bit words.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.create();
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
           *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
           */
          init: function(words, sigBytes) {
            words = this.words = words || [];
            if (sigBytes != undefined$1) {
              this.sigBytes = sigBytes;
            } else {
              this.sigBytes = words.length * 4;
            }
          },
          /**
           * Converts this word array to a string.
           *
           * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
           *
           * @return {string} The stringified word array.
           *
           * @example
           *
           *     var string = wordArray + '';
           *     var string = wordArray.toString();
           *     var string = wordArray.toString(CryptoJS.enc.Utf8);
           */
          toString: function(encoder2) {
            return (encoder2 || Hex2).stringify(this);
          },
          /**
           * Concatenates a word array to this word array.
           *
           * @param {WordArray} wordArray The word array to append.
           *
           * @return {WordArray} This word array.
           *
           * @example
           *
           *     wordArray1.concat(wordArray2);
           */
          concat: function(wordArray) {
            var thisWords = this.words;
            var thatWords = wordArray.words;
            var thisSigBytes = this.sigBytes;
            var thatSigBytes = wordArray.sigBytes;
            this.clamp();
            if (thisSigBytes % 4) {
              for (var i2 = 0; i2 < thatSigBytes; i2++) {
                var thatByte = thatWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
                thisWords[thisSigBytes + i2 >>> 2] |= thatByte << 24 - (thisSigBytes + i2) % 4 * 8;
              }
            } else {
              for (var j = 0; j < thatSigBytes; j += 4) {
                thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2];
              }
            }
            this.sigBytes += thatSigBytes;
            return this;
          },
          /**
           * Removes insignificant bits.
           *
           * @example
           *
           *     wordArray.clamp();
           */
          clamp: function() {
            var words = this.words;
            var sigBytes = this.sigBytes;
            words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
            words.length = Math2.ceil(sigBytes / 4);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {WordArray} The clone.
           *
           * @example
           *
           *     var clone = wordArray.clone();
           */
          clone: function() {
            var clone2 = Base.clone.call(this);
            clone2.words = this.words.slice(0);
            return clone2;
          },
          /**
           * Creates a word array filled with random bytes.
           *
           * @param {number} nBytes The number of random bytes to generate.
           *
           * @return {WordArray} The random word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.lib.WordArray.random(16);
           */
          random: function(nBytes) {
            var words = [];
            for (var i2 = 0; i2 < nBytes; i2 += 4) {
              words.push(cryptoSecureRandomInt());
            }
            return new WordArray.init(words, nBytes);
          }
        });
        var C_enc = C2.enc = {};
        var Hex2 = C_enc.Hex = {
          /**
           * Converts a word array to a hex string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The hex string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var hexChars = [];
            for (var i2 = 0; i2 < sigBytes; i2++) {
              var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
              hexChars.push((bite >>> 4).toString(16));
              hexChars.push((bite & 15).toString(16));
            }
            return hexChars.join("");
          },
          /**
           * Converts a hex string to a word array.
           *
           * @param {string} hexStr The hex string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
           */
          parse: function(hexStr) {
            var hexStrLength = hexStr.length;
            var words = [];
            for (var i2 = 0; i2 < hexStrLength; i2 += 2) {
              words[i2 >>> 3] |= parseInt(hexStr.substr(i2, 2), 16) << 24 - i2 % 8 * 4;
            }
            return new WordArray.init(words, hexStrLength / 2);
          }
        };
        var Latin1 = C_enc.Latin1 = {
          /**
           * Converts a word array to a Latin1 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Latin1 string.
           *
           * @static
           *
           * @example
           *
           *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var latin1Chars = [];
            for (var i2 = 0; i2 < sigBytes; i2++) {
              var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
              latin1Chars.push(String.fromCharCode(bite));
            }
            return latin1Chars.join("");
          },
          /**
           * Converts a Latin1 string to a word array.
           *
           * @param {string} latin1Str The Latin1 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
           */
          parse: function(latin1Str) {
            var latin1StrLength = latin1Str.length;
            var words = [];
            for (var i2 = 0; i2 < latin1StrLength; i2++) {
              words[i2 >>> 2] |= (latin1Str.charCodeAt(i2) & 255) << 24 - i2 % 4 * 8;
            }
            return new WordArray.init(words, latin1StrLength);
          }
        };
        var Utf8 = C_enc.Utf8 = {
          /**
           * Converts a word array to a UTF-8 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-8 string.
           *
           * @static
           *
           * @example
           *
           *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
           */
          stringify: function(wordArray) {
            try {
              return decodeURIComponent(escape(Latin1.stringify(wordArray)));
            } catch (e4) {
              throw new Error("Malformed UTF-8 data");
            }
          },
          /**
           * Converts a UTF-8 string to a word array.
           *
           * @param {string} utf8Str The UTF-8 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
           */
          parse: function(utf8Str) {
            return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
          }
        };
        var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
          /**
           * Resets this block algorithm's data buffer to its initial state.
           *
           * @example
           *
           *     bufferedBlockAlgorithm.reset();
           */
          reset: function() {
            this._data = new WordArray.init();
            this._nDataBytes = 0;
          },
          /**
           * Adds new data to this block algorithm's buffer.
           *
           * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
           *
           * @example
           *
           *     bufferedBlockAlgorithm._append('data');
           *     bufferedBlockAlgorithm._append(wordArray);
           */
          _append: function(data2) {
            if (typeof data2 == "string") {
              data2 = Utf8.parse(data2);
            }
            this._data.concat(data2);
            this._nDataBytes += data2.sigBytes;
          },
          /**
           * Processes available data blocks.
           *
           * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
           *
           * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
           *
           * @return {WordArray} The processed data.
           *
           * @example
           *
           *     var processedData = bufferedBlockAlgorithm._process();
           *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
           */
          _process: function(doFlush) {
            var processedWords;
            var data2 = this._data;
            var dataWords = data2.words;
            var dataSigBytes = data2.sigBytes;
            var blockSize = this.blockSize;
            var blockSizeBytes = blockSize * 4;
            var nBlocksReady = dataSigBytes / blockSizeBytes;
            if (doFlush) {
              nBlocksReady = Math2.ceil(nBlocksReady);
            } else {
              nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
            }
            var nWordsReady = nBlocksReady * blockSize;
            var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
            if (nWordsReady) {
              for (var offset = 0; offset < nWordsReady; offset += blockSize) {
                this._doProcessBlock(dataWords, offset);
              }
              processedWords = dataWords.splice(0, nWordsReady);
              data2.sigBytes -= nBytesReady;
            }
            return new WordArray.init(processedWords, nBytesReady);
          },
          /**
           * Creates a copy of this object.
           *
           * @return {Object} The clone.
           *
           * @example
           *
           *     var clone = bufferedBlockAlgorithm.clone();
           */
          clone: function() {
            var clone2 = Base.clone.call(this);
            clone2._data = this._data.clone();
            return clone2;
          },
          _minBufferSize: 0
        });
        C_lib.Hasher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           */
          cfg: Base.extend(),
          /**
           * Initializes a newly created hasher.
           *
           * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
           *
           * @example
           *
           *     var hasher = CryptoJS.algo.SHA256.create();
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
            this.reset();
          },
          /**
           * Resets this hasher to its initial state.
           *
           * @example
           *
           *     hasher.reset();
           */
          reset: function() {
            BufferedBlockAlgorithm.reset.call(this);
            this._doReset();
          },
          /**
           * Updates this hasher with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {Hasher} This hasher.
           *
           * @example
           *
           *     hasher.update('message');
           *     hasher.update(wordArray);
           */
          update: function(messageUpdate) {
            this._append(messageUpdate);
            this._process();
            return this;
          },
          /**
           * Finalizes the hash computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The hash.
           *
           * @example
           *
           *     var hash = hasher.finalize();
           *     var hash = hasher.finalize('message');
           *     var hash = hasher.finalize(wordArray);
           */
          finalize: function(messageUpdate) {
            if (messageUpdate) {
              this._append(messageUpdate);
            }
            var hash2 = this._doFinalize();
            return hash2;
          },
          blockSize: 512 / 32,
          /**
           * Creates a shortcut function to a hasher's object interface.
           *
           * @param {Hasher} hasher The hasher to create a helper for.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
           */
          _createHelper: function(hasher) {
            return function(message, cfg) {
              return new hasher.init(cfg).finalize(message);
            };
          },
          /**
           * Creates a shortcut function to the HMAC's object interface.
           *
           * @param {Hasher} hasher The hasher to use in this HMAC helper.
           *
           * @return {Function} The shortcut function.
           *
           * @static
           *
           * @example
           *
           *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
           */
          _createHmacHelper: function(hasher) {
            return function(message, key2) {
              return new C_algo.HMAC.init(hasher, key2).finalize(message);
            };
          }
        });
        var C_algo = C2.algo = {};
        return C2;
      }(Math);
      return CryptoJS2;
    });
  })(core$3);
  return core$3.exports;
}
var x64Core$1 = { exports: {} };
var x64Core = x64Core$1.exports;
var hasRequiredX64Core;
function requireX64Core() {
  if (hasRequiredX64Core) return x64Core$1.exports;
  hasRequiredX64Core = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(x64Core, function(CryptoJS2) {
      (function(undefined$1) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Base = C_lib.Base;
        var X32WordArray = C_lib.WordArray;
        var C_x64 = C2.x64 = {};
        C_x64.Word = Base.extend({
          /**
           * Initializes a newly created 64-bit word.
           *
           * @param {number} high The high 32 bits.
           * @param {number} low The low 32 bits.
           *
           * @example
           *
           *     var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
           */
          init: function(high, low) {
            this.high = high;
            this.low = low;
          }
          /**
           * Bitwise NOTs this word.
           *
           * @return {X64Word} A new x64-Word object after negating.
           *
           * @example
           *
           *     var negated = x64Word.not();
           */
          // not: function () {
          // var high = ~this.high;
          // var low = ~this.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ANDs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to AND with this word.
           *
           * @return {X64Word} A new x64-Word object after ANDing.
           *
           * @example
           *
           *     var anded = x64Word.and(anotherX64Word);
           */
          // and: function (word) {
          // var high = this.high & word.high;
          // var low = this.low & word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise ORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to OR with this word.
           *
           * @return {X64Word} A new x64-Word object after ORing.
           *
           * @example
           *
           *     var ored = x64Word.or(anotherX64Word);
           */
          // or: function (word) {
          // var high = this.high | word.high;
          // var low = this.low | word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Bitwise XORs this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to XOR with this word.
           *
           * @return {X64Word} A new x64-Word object after XORing.
           *
           * @example
           *
           *     var xored = x64Word.xor(anotherX64Word);
           */
          // xor: function (word) {
          // var high = this.high ^ word.high;
          // var low = this.low ^ word.low;
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the left.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftL(25);
           */
          // shiftL: function (n) {
          // if (n < 32) {
          // var high = (this.high << n) | (this.low >>> (32 - n));
          // var low = this.low << n;
          // } else {
          // var high = this.low << (n - 32);
          // var low = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Shifts this word n bits to the right.
           *
           * @param {number} n The number of bits to shift.
           *
           * @return {X64Word} A new x64-Word object after shifting.
           *
           * @example
           *
           *     var shifted = x64Word.shiftR(7);
           */
          // shiftR: function (n) {
          // if (n < 32) {
          // var low = (this.low >>> n) | (this.high << (32 - n));
          // var high = this.high >>> n;
          // } else {
          // var low = this.high >>> (n - 32);
          // var high = 0;
          // }
          // return X64Word.create(high, low);
          // },
          /**
           * Rotates this word n bits to the left.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotL(25);
           */
          // rotL: function (n) {
          // return this.shiftL(n).or(this.shiftR(64 - n));
          // },
          /**
           * Rotates this word n bits to the right.
           *
           * @param {number} n The number of bits to rotate.
           *
           * @return {X64Word} A new x64-Word object after rotating.
           *
           * @example
           *
           *     var rotated = x64Word.rotR(7);
           */
          // rotR: function (n) {
          // return this.shiftR(n).or(this.shiftL(64 - n));
          // },
          /**
           * Adds this word with the passed word.
           *
           * @param {X64Word} word The x64-Word to add with this word.
           *
           * @return {X64Word} A new x64-Word object after adding.
           *
           * @example
           *
           *     var added = x64Word.add(anotherX64Word);
           */
          // add: function (word) {
          // var low = (this.low + word.low) | 0;
          // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
          // var high = (this.high + word.high + carry) | 0;
          // return X64Word.create(high, low);
          // }
        });
        C_x64.WordArray = Base.extend({
          /**
           * Initializes a newly created word array.
           *
           * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
           * @param {number} sigBytes (Optional) The number of significant bytes in the words.
           *
           * @example
           *
           *     var wordArray = CryptoJS.x64.WordArray.create();
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ]);
           *
           *     var wordArray = CryptoJS.x64.WordArray.create([
           *         CryptoJS.x64.Word.create(0x00010203, 0x04050607),
           *         CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
           *     ], 10);
           */
          init: function(words, sigBytes) {
            words = this.words = words || [];
            if (sigBytes != undefined$1) {
              this.sigBytes = sigBytes;
            } else {
              this.sigBytes = words.length * 8;
            }
          },
          /**
           * Converts this 64-bit word array to a 32-bit word array.
           *
           * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
           *
           * @example
           *
           *     var x32WordArray = x64WordArray.toX32();
           */
          toX32: function() {
            var x64Words = this.words;
            var x64WordsLength = x64Words.length;
            var x32Words = [];
            for (var i2 = 0; i2 < x64WordsLength; i2++) {
              var x64Word = x64Words[i2];
              x32Words.push(x64Word.high);
              x32Words.push(x64Word.low);
            }
            return X32WordArray.create(x32Words, this.sigBytes);
          },
          /**
           * Creates a copy of this word array.
           *
           * @return {X64WordArray} The clone.
           *
           * @example
           *
           *     var clone = x64WordArray.clone();
           */
          clone: function() {
            var clone2 = Base.clone.call(this);
            var words = clone2.words = this.words.slice(0);
            var wordsLength = words.length;
            for (var i2 = 0; i2 < wordsLength; i2++) {
              words[i2] = words[i2].clone();
            }
            return clone2;
          }
        });
      })();
      return CryptoJS2;
    });
  })(x64Core$1);
  return x64Core$1.exports;
}
var libTypedarrays$1 = { exports: {} };
var libTypedarrays = libTypedarrays$1.exports;
var hasRequiredLibTypedarrays;
function requireLibTypedarrays() {
  if (hasRequiredLibTypedarrays) return libTypedarrays$1.exports;
  hasRequiredLibTypedarrays = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(libTypedarrays, function(CryptoJS2) {
      (function() {
        if (typeof ArrayBuffer != "function") {
          return;
        }
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var superInit = WordArray.init;
        var subInit = WordArray.init = function(typedArray) {
          if (typedArray instanceof ArrayBuffer) {
            typedArray = new Uint8Array(typedArray);
          }
          if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) {
            typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
          }
          if (typedArray instanceof Uint8Array) {
            var typedArrayByteLength = typedArray.byteLength;
            var words = [];
            for (var i2 = 0; i2 < typedArrayByteLength; i2++) {
              words[i2 >>> 2] |= typedArray[i2] << 24 - i2 % 4 * 8;
            }
            superInit.call(this, words, typedArrayByteLength);
          } else {
            superInit.apply(this, arguments);
          }
        };
        subInit.prototype = WordArray;
      })();
      return CryptoJS2.lib.WordArray;
    });
  })(libTypedarrays$1);
  return libTypedarrays$1.exports;
}
var encUtf16$1 = { exports: {} };
var encUtf16 = encUtf16$1.exports;
var hasRequiredEncUtf16;
function requireEncUtf16() {
  if (hasRequiredEncUtf16) return encUtf16$1.exports;
  hasRequiredEncUtf16 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(encUtf16, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C2.enc;
        C_enc.Utf16 = C_enc.Utf16BE = {
          /**
           * Converts a word array to a UTF-16 BE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 BE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var utf16Chars = [];
            for (var i2 = 0; i2 < sigBytes; i2 += 2) {
              var codePoint = words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535;
              utf16Chars.push(String.fromCharCode(codePoint));
            }
            return utf16Chars.join("");
          },
          /**
           * Converts a UTF-16 BE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 BE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
           */
          parse: function(utf16Str) {
            var utf16StrLength = utf16Str.length;
            var words = [];
            for (var i2 = 0; i2 < utf16StrLength; i2++) {
              words[i2 >>> 1] |= utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16;
            }
            return WordArray.create(words, utf16StrLength * 2);
          }
        };
        C_enc.Utf16LE = {
          /**
           * Converts a word array to a UTF-16 LE string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The UTF-16 LE string.
           *
           * @static
           *
           * @example
           *
           *     var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var utf16Chars = [];
            for (var i2 = 0; i2 < sigBytes; i2 += 2) {
              var codePoint = swapEndian(words[i2 >>> 2] >>> 16 - i2 % 4 * 8 & 65535);
              utf16Chars.push(String.fromCharCode(codePoint));
            }
            return utf16Chars.join("");
          },
          /**
           * Converts a UTF-16 LE string to a word array.
           *
           * @param {string} utf16Str The UTF-16 LE string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
           */
          parse: function(utf16Str) {
            var utf16StrLength = utf16Str.length;
            var words = [];
            for (var i2 = 0; i2 < utf16StrLength; i2++) {
              words[i2 >>> 1] |= swapEndian(utf16Str.charCodeAt(i2) << 16 - i2 % 2 * 16);
            }
            return WordArray.create(words, utf16StrLength * 2);
          }
        };
        function swapEndian(word) {
          return word << 8 & 4278255360 | word >>> 8 & 16711935;
        }
      })();
      return CryptoJS2.enc.Utf16;
    });
  })(encUtf16$1);
  return encUtf16$1.exports;
}
var encBase64$1 = { exports: {} };
var encBase64 = encBase64$1.exports;
var hasRequiredEncBase64;
function requireEncBase64() {
  if (hasRequiredEncBase64) return encBase64$1.exports;
  hasRequiredEncBase64 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(encBase64, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C2.enc;
        C_enc.Base64 = {
          /**
           * Converts a word array to a Base64 string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @return {string} The Base64 string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64.stringify(wordArray);
           */
          stringify: function(wordArray) {
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var map = this._map;
            wordArray.clamp();
            var base64Chars = [];
            for (var i2 = 0; i2 < sigBytes; i2 += 3) {
              var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
              var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
              var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
              var triplet = byte1 << 16 | byte2 << 8 | byte3;
              for (var j = 0; j < 4 && i2 + j * 0.75 < sigBytes; j++) {
                base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 63));
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              while (base64Chars.length % 4) {
                base64Chars.push(paddingChar);
              }
            }
            return base64Chars.join("");
          },
          /**
           * Converts a Base64 string to a word array.
           *
           * @param {string} base64Str The Base64 string.
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64.parse(base64String);
           */
          parse: function(base64Str) {
            var base64StrLength = base64Str.length;
            var map = this._map;
            var reverseMap = this._reverseMap;
            if (!reverseMap) {
              reverseMap = this._reverseMap = [];
              for (var j = 0; j < map.length; j++) {
                reverseMap[map.charCodeAt(j)] = j;
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              var paddingIndex = base64Str.indexOf(paddingChar);
              if (paddingIndex !== -1) {
                base64StrLength = paddingIndex;
              }
            }
            return parseLoop(base64Str, base64StrLength, reverseMap);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
        };
        function parseLoop(base64Str, base64StrLength, reverseMap) {
          var words = [];
          var nBytes = 0;
          for (var i2 = 0; i2 < base64StrLength; i2++) {
            if (i2 % 4) {
              var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
              var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
              var bitsCombined = bits1 | bits2;
              words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
              nBytes++;
            }
          }
          return WordArray.create(words, nBytes);
        }
      })();
      return CryptoJS2.enc.Base64;
    });
  })(encBase64$1);
  return encBase64$1.exports;
}
var encBase64url$1 = { exports: {} };
var encBase64url = encBase64url$1.exports;
var hasRequiredEncBase64url;
function requireEncBase64url() {
  if (hasRequiredEncBase64url) return encBase64url$1.exports;
  hasRequiredEncBase64url = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(encBase64url, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var C_enc = C2.enc;
        C_enc.Base64url = {
          /**
           * Converts a word array to a Base64url string.
           *
           * @param {WordArray} wordArray The word array.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {string} The Base64url string.
           *
           * @static
           *
           * @example
           *
           *     var base64String = CryptoJS.enc.Base64url.stringify(wordArray);
           */
          stringify: function(wordArray, urlSafe) {
            if (urlSafe === void 0) {
              urlSafe = true;
            }
            var words = wordArray.words;
            var sigBytes = wordArray.sigBytes;
            var map = urlSafe ? this._safe_map : this._map;
            wordArray.clamp();
            var base64Chars = [];
            for (var i2 = 0; i2 < sigBytes; i2 += 3) {
              var byte1 = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
              var byte2 = words[i2 + 1 >>> 2] >>> 24 - (i2 + 1) % 4 * 8 & 255;
              var byte3 = words[i2 + 2 >>> 2] >>> 24 - (i2 + 2) % 4 * 8 & 255;
              var triplet = byte1 << 16 | byte2 << 8 | byte3;
              for (var j = 0; j < 4 && i2 + j * 0.75 < sigBytes; j++) {
                base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 63));
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              while (base64Chars.length % 4) {
                base64Chars.push(paddingChar);
              }
            }
            return base64Chars.join("");
          },
          /**
           * Converts a Base64url string to a word array.
           *
           * @param {string} base64Str The Base64url string.
           *
           * @param {boolean} urlSafe Whether to use url safe
           *
           * @return {WordArray} The word array.
           *
           * @static
           *
           * @example
           *
           *     var wordArray = CryptoJS.enc.Base64url.parse(base64String);
           */
          parse: function(base64Str, urlSafe) {
            if (urlSafe === void 0) {
              urlSafe = true;
            }
            var base64StrLength = base64Str.length;
            var map = urlSafe ? this._safe_map : this._map;
            var reverseMap = this._reverseMap;
            if (!reverseMap) {
              reverseMap = this._reverseMap = [];
              for (var j = 0; j < map.length; j++) {
                reverseMap[map.charCodeAt(j)] = j;
              }
            }
            var paddingChar = map.charAt(64);
            if (paddingChar) {
              var paddingIndex = base64Str.indexOf(paddingChar);
              if (paddingIndex !== -1) {
                base64StrLength = paddingIndex;
              }
            }
            return parseLoop(base64Str, base64StrLength, reverseMap);
          },
          _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
          _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
        };
        function parseLoop(base64Str, base64StrLength, reverseMap) {
          var words = [];
          var nBytes = 0;
          for (var i2 = 0; i2 < base64StrLength; i2++) {
            if (i2 % 4) {
              var bits1 = reverseMap[base64Str.charCodeAt(i2 - 1)] << i2 % 4 * 2;
              var bits2 = reverseMap[base64Str.charCodeAt(i2)] >>> 6 - i2 % 4 * 2;
              var bitsCombined = bits1 | bits2;
              words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8;
              nBytes++;
            }
          }
          return WordArray.create(words, nBytes);
        }
      })();
      return CryptoJS2.enc.Base64url;
    });
  })(encBase64url$1);
  return encBase64url$1.exports;
}
var md5$1 = { exports: {} };
var md5 = md5$1.exports;
var hasRequiredMd5;
function requireMd5() {
  if (hasRequiredMd5) return md5$1.exports;
  hasRequiredMd5 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(md5, function(CryptoJS2) {
      (function(Math2) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C2.algo;
        var T2 = [];
        (function() {
          for (var i2 = 0; i2 < 64; i2++) {
            T2[i2] = Math2.abs(Math2.sin(i2 + 1)) * 4294967296 | 0;
          }
        })();
        var MD5 = C_algo.MD5 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              1732584193,
              4023233417,
              2562383102,
              271733878
            ]);
          },
          _doProcessBlock: function(M2, offset) {
            for (var i2 = 0; i2 < 16; i2++) {
              var offset_i = offset + i2;
              var M_offset_i = M2[offset_i];
              M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
            }
            var H = this._hash.words;
            var M_offset_0 = M2[offset + 0];
            var M_offset_1 = M2[offset + 1];
            var M_offset_2 = M2[offset + 2];
            var M_offset_3 = M2[offset + 3];
            var M_offset_4 = M2[offset + 4];
            var M_offset_5 = M2[offset + 5];
            var M_offset_6 = M2[offset + 6];
            var M_offset_7 = M2[offset + 7];
            var M_offset_8 = M2[offset + 8];
            var M_offset_9 = M2[offset + 9];
            var M_offset_10 = M2[offset + 10];
            var M_offset_11 = M2[offset + 11];
            var M_offset_12 = M2[offset + 12];
            var M_offset_13 = M2[offset + 13];
            var M_offset_14 = M2[offset + 14];
            var M_offset_15 = M2[offset + 15];
            var a2 = H[0];
            var b2 = H[1];
            var c2 = H[2];
            var d = H[3];
            a2 = FF2(a2, b2, c2, d, M_offset_0, 7, T2[0]);
            d = FF2(d, a2, b2, c2, M_offset_1, 12, T2[1]);
            c2 = FF2(c2, d, a2, b2, M_offset_2, 17, T2[2]);
            b2 = FF2(b2, c2, d, a2, M_offset_3, 22, T2[3]);
            a2 = FF2(a2, b2, c2, d, M_offset_4, 7, T2[4]);
            d = FF2(d, a2, b2, c2, M_offset_5, 12, T2[5]);
            c2 = FF2(c2, d, a2, b2, M_offset_6, 17, T2[6]);
            b2 = FF2(b2, c2, d, a2, M_offset_7, 22, T2[7]);
            a2 = FF2(a2, b2, c2, d, M_offset_8, 7, T2[8]);
            d = FF2(d, a2, b2, c2, M_offset_9, 12, T2[9]);
            c2 = FF2(c2, d, a2, b2, M_offset_10, 17, T2[10]);
            b2 = FF2(b2, c2, d, a2, M_offset_11, 22, T2[11]);
            a2 = FF2(a2, b2, c2, d, M_offset_12, 7, T2[12]);
            d = FF2(d, a2, b2, c2, M_offset_13, 12, T2[13]);
            c2 = FF2(c2, d, a2, b2, M_offset_14, 17, T2[14]);
            b2 = FF2(b2, c2, d, a2, M_offset_15, 22, T2[15]);
            a2 = GG2(a2, b2, c2, d, M_offset_1, 5, T2[16]);
            d = GG2(d, a2, b2, c2, M_offset_6, 9, T2[17]);
            c2 = GG2(c2, d, a2, b2, M_offset_11, 14, T2[18]);
            b2 = GG2(b2, c2, d, a2, M_offset_0, 20, T2[19]);
            a2 = GG2(a2, b2, c2, d, M_offset_5, 5, T2[20]);
            d = GG2(d, a2, b2, c2, M_offset_10, 9, T2[21]);
            c2 = GG2(c2, d, a2, b2, M_offset_15, 14, T2[22]);
            b2 = GG2(b2, c2, d, a2, M_offset_4, 20, T2[23]);
            a2 = GG2(a2, b2, c2, d, M_offset_9, 5, T2[24]);
            d = GG2(d, a2, b2, c2, M_offset_14, 9, T2[25]);
            c2 = GG2(c2, d, a2, b2, M_offset_3, 14, T2[26]);
            b2 = GG2(b2, c2, d, a2, M_offset_8, 20, T2[27]);
            a2 = GG2(a2, b2, c2, d, M_offset_13, 5, T2[28]);
            d = GG2(d, a2, b2, c2, M_offset_2, 9, T2[29]);
            c2 = GG2(c2, d, a2, b2, M_offset_7, 14, T2[30]);
            b2 = GG2(b2, c2, d, a2, M_offset_12, 20, T2[31]);
            a2 = HH(a2, b2, c2, d, M_offset_5, 4, T2[32]);
            d = HH(d, a2, b2, c2, M_offset_8, 11, T2[33]);
            c2 = HH(c2, d, a2, b2, M_offset_11, 16, T2[34]);
            b2 = HH(b2, c2, d, a2, M_offset_14, 23, T2[35]);
            a2 = HH(a2, b2, c2, d, M_offset_1, 4, T2[36]);
            d = HH(d, a2, b2, c2, M_offset_4, 11, T2[37]);
            c2 = HH(c2, d, a2, b2, M_offset_7, 16, T2[38]);
            b2 = HH(b2, c2, d, a2, M_offset_10, 23, T2[39]);
            a2 = HH(a2, b2, c2, d, M_offset_13, 4, T2[40]);
            d = HH(d, a2, b2, c2, M_offset_0, 11, T2[41]);
            c2 = HH(c2, d, a2, b2, M_offset_3, 16, T2[42]);
            b2 = HH(b2, c2, d, a2, M_offset_6, 23, T2[43]);
            a2 = HH(a2, b2, c2, d, M_offset_9, 4, T2[44]);
            d = HH(d, a2, b2, c2, M_offset_12, 11, T2[45]);
            c2 = HH(c2, d, a2, b2, M_offset_15, 16, T2[46]);
            b2 = HH(b2, c2, d, a2, M_offset_2, 23, T2[47]);
            a2 = II(a2, b2, c2, d, M_offset_0, 6, T2[48]);
            d = II(d, a2, b2, c2, M_offset_7, 10, T2[49]);
            c2 = II(c2, d, a2, b2, M_offset_14, 15, T2[50]);
            b2 = II(b2, c2, d, a2, M_offset_5, 21, T2[51]);
            a2 = II(a2, b2, c2, d, M_offset_12, 6, T2[52]);
            d = II(d, a2, b2, c2, M_offset_3, 10, T2[53]);
            c2 = II(c2, d, a2, b2, M_offset_10, 15, T2[54]);
            b2 = II(b2, c2, d, a2, M_offset_1, 21, T2[55]);
            a2 = II(a2, b2, c2, d, M_offset_8, 6, T2[56]);
            d = II(d, a2, b2, c2, M_offset_15, 10, T2[57]);
            c2 = II(c2, d, a2, b2, M_offset_6, 15, T2[58]);
            b2 = II(b2, c2, d, a2, M_offset_13, 21, T2[59]);
            a2 = II(a2, b2, c2, d, M_offset_4, 6, T2[60]);
            d = II(d, a2, b2, c2, M_offset_11, 10, T2[61]);
            c2 = II(c2, d, a2, b2, M_offset_2, 15, T2[62]);
            b2 = II(b2, c2, d, a2, M_offset_9, 21, T2[63]);
            H[0] = H[0] + a2 | 0;
            H[1] = H[1] + b2 | 0;
            H[2] = H[2] + c2 | 0;
            H[3] = H[3] + d | 0;
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            var nBitsTotalH = Math2.floor(nBitsTotal / 4294967296);
            var nBitsTotalL = nBitsTotal;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 16711935 | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 4278255360;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 16711935 | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 4278255360;
            data2.sigBytes = (dataWords.length + 1) * 4;
            this._process();
            var hash2 = this._hash;
            var H = hash2.words;
            for (var i2 = 0; i2 < 4; i2++) {
              var H_i = H[i2];
              H[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
            }
            return hash2;
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            clone2._hash = this._hash.clone();
            return clone2;
          }
        });
        function FF2(a2, b2, c2, d, x2, s2, t2) {
          var n2 = a2 + (b2 & c2 | ~b2 & d) + x2 + t2;
          return (n2 << s2 | n2 >>> 32 - s2) + b2;
        }
        function GG2(a2, b2, c2, d, x2, s2, t2) {
          var n2 = a2 + (b2 & d | c2 & ~d) + x2 + t2;
          return (n2 << s2 | n2 >>> 32 - s2) + b2;
        }
        function HH(a2, b2, c2, d, x2, s2, t2) {
          var n2 = a2 + (b2 ^ c2 ^ d) + x2 + t2;
          return (n2 << s2 | n2 >>> 32 - s2) + b2;
        }
        function II(a2, b2, c2, d, x2, s2, t2) {
          var n2 = a2 + (c2 ^ (b2 | ~d)) + x2 + t2;
          return (n2 << s2 | n2 >>> 32 - s2) + b2;
        }
        C2.MD5 = Hasher._createHelper(MD5);
        C2.HmacMD5 = Hasher._createHmacHelper(MD5);
      })(Math);
      return CryptoJS2.MD5;
    });
  })(md5$1);
  return md5$1.exports;
}
var sha1$1 = { exports: {} };
var sha1 = sha1$1.exports;
var hasRequiredSha1;
function requireSha1() {
  if (hasRequiredSha1) return sha1$1.exports;
  hasRequiredSha1 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(sha1, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C2.algo;
        var W = [];
        var SHA1 = C_algo.SHA1 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              1732584193,
              4023233417,
              2562383102,
              271733878,
              3285377520
            ]);
          },
          _doProcessBlock: function(M2, offset) {
            var H = this._hash.words;
            var a2 = H[0];
            var b2 = H[1];
            var c2 = H[2];
            var d = H[3];
            var e4 = H[4];
            for (var i2 = 0; i2 < 80; i2++) {
              if (i2 < 16) {
                W[i2] = M2[offset + i2] | 0;
              } else {
                var n2 = W[i2 - 3] ^ W[i2 - 8] ^ W[i2 - 14] ^ W[i2 - 16];
                W[i2] = n2 << 1 | n2 >>> 31;
              }
              var t2 = (a2 << 5 | a2 >>> 27) + e4 + W[i2];
              if (i2 < 20) {
                t2 += (b2 & c2 | ~b2 & d) + 1518500249;
              } else if (i2 < 40) {
                t2 += (b2 ^ c2 ^ d) + 1859775393;
              } else if (i2 < 60) {
                t2 += (b2 & c2 | b2 & d | c2 & d) - 1894007588;
              } else {
                t2 += (b2 ^ c2 ^ d) - 899497514;
              }
              e4 = d;
              d = c2;
              c2 = b2 << 30 | b2 >>> 2;
              b2 = a2;
              a2 = t2;
            }
            H[0] = H[0] + a2 | 0;
            H[1] = H[1] + b2 | 0;
            H[2] = H[2] + c2 | 0;
            H[3] = H[3] + d | 0;
            H[4] = H[4] + e4 | 0;
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data2.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            clone2._hash = this._hash.clone();
            return clone2;
          }
        });
        C2.SHA1 = Hasher._createHelper(SHA1);
        C2.HmacSHA1 = Hasher._createHmacHelper(SHA1);
      })();
      return CryptoJS2.SHA1;
    });
  })(sha1$1);
  return sha1$1.exports;
}
var sha256$2 = { exports: {} };
var sha256$1 = sha256$2.exports;
var hasRequiredSha256;
function requireSha256() {
  if (hasRequiredSha256) return sha256$2.exports;
  hasRequiredSha256 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(sha256$1, function(CryptoJS2) {
      (function(Math2) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C2.algo;
        var H = [];
        var K = [];
        (function() {
          function isPrime(n3) {
            var sqrtN = Math2.sqrt(n3);
            for (var factor = 2; factor <= sqrtN; factor++) {
              if (!(n3 % factor)) {
                return false;
              }
            }
            return true;
          }
          function getFractionalBits(n3) {
            return (n3 - (n3 | 0)) * 4294967296 | 0;
          }
          var n2 = 2;
          var nPrime = 0;
          while (nPrime < 64) {
            if (isPrime(n2)) {
              if (nPrime < 8) {
                H[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 2));
              }
              K[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 3));
              nPrime++;
            }
            n2++;
          }
        })();
        var W = [];
        var SHA256 = C_algo.SHA256 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init(H.slice(0));
          },
          _doProcessBlock: function(M2, offset) {
            var H2 = this._hash.words;
            var a2 = H2[0];
            var b2 = H2[1];
            var c2 = H2[2];
            var d = H2[3];
            var e4 = H2[4];
            var f2 = H2[5];
            var g = H2[6];
            var h2 = H2[7];
            for (var i2 = 0; i2 < 64; i2++) {
              if (i2 < 16) {
                W[i2] = M2[offset + i2] | 0;
              } else {
                var gamma0x = W[i2 - 15];
                var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
                var gamma1x = W[i2 - 2];
                var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
                W[i2] = gamma0 + W[i2 - 7] + gamma1 + W[i2 - 16];
              }
              var ch = e4 & f2 ^ ~e4 & g;
              var maj = a2 & b2 ^ a2 & c2 ^ b2 & c2;
              var sigma0 = (a2 << 30 | a2 >>> 2) ^ (a2 << 19 | a2 >>> 13) ^ (a2 << 10 | a2 >>> 22);
              var sigma1 = (e4 << 26 | e4 >>> 6) ^ (e4 << 21 | e4 >>> 11) ^ (e4 << 7 | e4 >>> 25);
              var t1 = h2 + sigma1 + ch + K[i2] + W[i2];
              var t2 = sigma0 + maj;
              h2 = g;
              g = f2;
              f2 = e4;
              e4 = d + t1 | 0;
              d = c2;
              c2 = b2;
              b2 = a2;
              a2 = t1 + t2 | 0;
            }
            H2[0] = H2[0] + a2 | 0;
            H2[1] = H2[1] + b2 | 0;
            H2[2] = H2[2] + c2 | 0;
            H2[3] = H2[3] + d | 0;
            H2[4] = H2[4] + e4 | 0;
            H2[5] = H2[5] + f2 | 0;
            H2[6] = H2[6] + g | 0;
            H2[7] = H2[7] + h2 | 0;
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data2.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            clone2._hash = this._hash.clone();
            return clone2;
          }
        });
        C2.SHA256 = Hasher._createHelper(SHA256);
        C2.HmacSHA256 = Hasher._createHmacHelper(SHA256);
      })(Math);
      return CryptoJS2.SHA256;
    });
  })(sha256$2);
  return sha256$2.exports;
}
var sha224$1 = { exports: {} };
var sha224 = sha224$1.exports;
var hasRequiredSha224;
function requireSha224() {
  if (hasRequiredSha224) return sha224$1.exports;
  hasRequiredSha224 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireSha256());
      }
    })(sha224, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var C_algo = C2.algo;
        var SHA256 = C_algo.SHA256;
        var SHA224 = C_algo.SHA224 = SHA256.extend({
          _doReset: function() {
            this._hash = new WordArray.init([
              3238371032,
              914150663,
              812702999,
              4144912697,
              4290775857,
              1750603025,
              1694076839,
              3204075428
            ]);
          },
          _doFinalize: function() {
            var hash2 = SHA256._doFinalize.call(this);
            hash2.sigBytes -= 4;
            return hash2;
          }
        });
        C2.SHA224 = SHA256._createHelper(SHA224);
        C2.HmacSHA224 = SHA256._createHmacHelper(SHA224);
      })();
      return CryptoJS2.SHA224;
    });
  })(sha224$1);
  return sha224$1.exports;
}
var sha512$1 = { exports: {} };
var sha512 = sha512$1.exports;
var hasRequiredSha512;
function requireSha512() {
  if (hasRequiredSha512) return sha512$1.exports;
  hasRequiredSha512 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireX64Core());
      }
    })(sha512, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Hasher = C_lib.Hasher;
        var C_x64 = C2.x64;
        var X64Word = C_x64.Word;
        var X64WordArray = C_x64.WordArray;
        var C_algo = C2.algo;
        function X64Word_create() {
          return X64Word.create.apply(X64Word, arguments);
        }
        var K = [
          X64Word_create(1116352408, 3609767458),
          X64Word_create(1899447441, 602891725),
          X64Word_create(3049323471, 3964484399),
          X64Word_create(3921009573, 2173295548),
          X64Word_create(961987163, 4081628472),
          X64Word_create(1508970993, 3053834265),
          X64Word_create(2453635748, 2937671579),
          X64Word_create(2870763221, 3664609560),
          X64Word_create(3624381080, 2734883394),
          X64Word_create(310598401, 1164996542),
          X64Word_create(607225278, 1323610764),
          X64Word_create(1426881987, 3590304994),
          X64Word_create(1925078388, 4068182383),
          X64Word_create(2162078206, 991336113),
          X64Word_create(2614888103, 633803317),
          X64Word_create(3248222580, 3479774868),
          X64Word_create(3835390401, 2666613458),
          X64Word_create(4022224774, 944711139),
          X64Word_create(264347078, 2341262773),
          X64Word_create(604807628, 2007800933),
          X64Word_create(770255983, 1495990901),
          X64Word_create(1249150122, 1856431235),
          X64Word_create(1555081692, 3175218132),
          X64Word_create(1996064986, 2198950837),
          X64Word_create(2554220882, 3999719339),
          X64Word_create(2821834349, 766784016),
          X64Word_create(2952996808, 2566594879),
          X64Word_create(3210313671, 3203337956),
          X64Word_create(3336571891, 1034457026),
          X64Word_create(3584528711, 2466948901),
          X64Word_create(113926993, 3758326383),
          X64Word_create(338241895, 168717936),
          X64Word_create(666307205, 1188179964),
          X64Word_create(773529912, 1546045734),
          X64Word_create(1294757372, 1522805485),
          X64Word_create(1396182291, 2643833823),
          X64Word_create(1695183700, 2343527390),
          X64Word_create(1986661051, 1014477480),
          X64Word_create(2177026350, 1206759142),
          X64Word_create(2456956037, 344077627),
          X64Word_create(2730485921, 1290863460),
          X64Word_create(2820302411, 3158454273),
          X64Word_create(3259730800, 3505952657),
          X64Word_create(3345764771, 106217008),
          X64Word_create(3516065817, 3606008344),
          X64Word_create(3600352804, 1432725776),
          X64Word_create(4094571909, 1467031594),
          X64Word_create(275423344, 851169720),
          X64Word_create(430227734, 3100823752),
          X64Word_create(506948616, 1363258195),
          X64Word_create(659060556, 3750685593),
          X64Word_create(883997877, 3785050280),
          X64Word_create(958139571, 3318307427),
          X64Word_create(1322822218, 3812723403),
          X64Word_create(1537002063, 2003034995),
          X64Word_create(1747873779, 3602036899),
          X64Word_create(1955562222, 1575990012),
          X64Word_create(2024104815, 1125592928),
          X64Word_create(2227730452, 2716904306),
          X64Word_create(2361852424, 442776044),
          X64Word_create(2428436474, 593698344),
          X64Word_create(2756734187, 3733110249),
          X64Word_create(3204031479, 2999351573),
          X64Word_create(3329325298, 3815920427),
          X64Word_create(3391569614, 3928383900),
          X64Word_create(3515267271, 566280711),
          X64Word_create(3940187606, 3454069534),
          X64Word_create(4118630271, 4000239992),
          X64Word_create(116418474, 1914138554),
          X64Word_create(174292421, 2731055270),
          X64Word_create(289380356, 3203993006),
          X64Word_create(460393269, 320620315),
          X64Word_create(685471733, 587496836),
          X64Word_create(852142971, 1086792851),
          X64Word_create(1017036298, 365543100),
          X64Word_create(1126000580, 2618297676),
          X64Word_create(1288033470, 3409855158),
          X64Word_create(1501505948, 4234509866),
          X64Word_create(1607167915, 987167468),
          X64Word_create(1816402316, 1246189591)
        ];
        var W = [];
        (function() {
          for (var i2 = 0; i2 < 80; i2++) {
            W[i2] = X64Word_create();
          }
        })();
        var SHA512 = C_algo.SHA512 = Hasher.extend({
          _doReset: function() {
            this._hash = new X64WordArray.init([
              new X64Word.init(1779033703, 4089235720),
              new X64Word.init(3144134277, 2227873595),
              new X64Word.init(1013904242, 4271175723),
              new X64Word.init(2773480762, 1595750129),
              new X64Word.init(1359893119, 2917565137),
              new X64Word.init(2600822924, 725511199),
              new X64Word.init(528734635, 4215389547),
              new X64Word.init(1541459225, 327033209)
            ]);
          },
          _doProcessBlock: function(M2, offset) {
            var H = this._hash.words;
            var H0 = H[0];
            var H1 = H[1];
            var H2 = H[2];
            var H3 = H[3];
            var H4 = H[4];
            var H5 = H[5];
            var H6 = H[6];
            var H7 = H[7];
            var H0h = H0.high;
            var H0l = H0.low;
            var H1h = H1.high;
            var H1l = H1.low;
            var H2h = H2.high;
            var H2l = H2.low;
            var H3h = H3.high;
            var H3l = H3.low;
            var H4h = H4.high;
            var H4l = H4.low;
            var H5h = H5.high;
            var H5l = H5.low;
            var H6h = H6.high;
            var H6l = H6.low;
            var H7h = H7.high;
            var H7l = H7.low;
            var ah = H0h;
            var al = H0l;
            var bh = H1h;
            var bl = H1l;
            var ch = H2h;
            var cl = H2l;
            var dh2 = H3h;
            var dl = H3l;
            var eh = H4h;
            var el = H4l;
            var fh = H5h;
            var fl = H5l;
            var gh = H6h;
            var gl = H6l;
            var hh = H7h;
            var hl = H7l;
            for (var i2 = 0; i2 < 80; i2++) {
              var Wil;
              var Wih;
              var Wi = W[i2];
              if (i2 < 16) {
                Wih = Wi.high = M2[offset + i2 * 2] | 0;
                Wil = Wi.low = M2[offset + i2 * 2 + 1] | 0;
              } else {
                var gamma0x = W[i2 - 15];
                var gamma0xh = gamma0x.high;
                var gamma0xl = gamma0x.low;
                var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7;
                var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25);
                var gamma1x = W[i2 - 2];
                var gamma1xh = gamma1x.high;
                var gamma1xl = gamma1x.low;
                var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6;
                var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26);
                var Wi7 = W[i2 - 7];
                var Wi7h = Wi7.high;
                var Wi7l = Wi7.low;
                var Wi16 = W[i2 - 16];
                var Wi16h = Wi16.high;
                var Wi16l = Wi16.low;
                Wil = gamma0l + Wi7l;
                Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0);
                Wil = Wil + gamma1l;
                Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0);
                Wil = Wil + Wi16l;
                Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0);
                Wi.high = Wih;
                Wi.low = Wil;
              }
              var chh = eh & fh ^ ~eh & gh;
              var chl = el & fl ^ ~el & gl;
              var majh = ah & bh ^ ah & ch ^ bh & ch;
              var majl = al & bl ^ al & cl ^ bl & cl;
              var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7);
              var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7);
              var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9);
              var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9);
              var Ki = K[i2];
              var Kih = Ki.high;
              var Kil = Ki.low;
              var t1l = hl + sigma1l;
              var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0);
              var t1l = t1l + chl;
              var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0);
              var t1l = t1l + Kil;
              var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0);
              var t1l = t1l + Wil;
              var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0);
              var t2l = sigma0l + majl;
              var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0);
              hh = gh;
              hl = gl;
              gh = fh;
              gl = fl;
              fh = eh;
              fl = el;
              el = dl + t1l | 0;
              eh = dh2 + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0;
              dh2 = ch;
              dl = cl;
              ch = bh;
              cl = bl;
              bh = ah;
              bl = al;
              al = t1l + t2l | 0;
              ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0;
            }
            H0l = H0.low = H0l + al;
            H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0);
            H1l = H1.low = H1l + bl;
            H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0);
            H2l = H2.low = H2l + cl;
            H2.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0);
            H3l = H3.low = H3l + dl;
            H3.high = H3h + dh2 + (H3l >>> 0 < dl >>> 0 ? 1 : 0);
            H4l = H4.low = H4l + el;
            H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0);
            H5l = H5.low = H5l + fl;
            H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0);
            H6l = H6.low = H6l + gl;
            H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0);
            H7l = H7.low = H7l + hl;
            H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0);
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal;
            data2.sigBytes = dataWords.length * 4;
            this._process();
            var hash2 = this._hash.toX32();
            return hash2;
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            clone2._hash = this._hash.clone();
            return clone2;
          },
          blockSize: 1024 / 32
        });
        C2.SHA512 = Hasher._createHelper(SHA512);
        C2.HmacSHA512 = Hasher._createHmacHelper(SHA512);
      })();
      return CryptoJS2.SHA512;
    });
  })(sha512$1);
  return sha512$1.exports;
}
var sha384$1 = { exports: {} };
var sha384 = sha384$1.exports;
var hasRequiredSha384;
function requireSha384() {
  if (hasRequiredSha384) return sha384$1.exports;
  hasRequiredSha384 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireX64Core(), requireSha512());
      }
    })(sha384, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_x64 = C2.x64;
        var X64Word = C_x64.Word;
        var X64WordArray = C_x64.WordArray;
        var C_algo = C2.algo;
        var SHA512 = C_algo.SHA512;
        var SHA384 = C_algo.SHA384 = SHA512.extend({
          _doReset: function() {
            this._hash = new X64WordArray.init([
              new X64Word.init(3418070365, 3238371032),
              new X64Word.init(1654270250, 914150663),
              new X64Word.init(2438529370, 812702999),
              new X64Word.init(355462360, 4144912697),
              new X64Word.init(1731405415, 4290775857),
              new X64Word.init(2394180231, 1750603025),
              new X64Word.init(3675008525, 1694076839),
              new X64Word.init(1203062813, 3204075428)
            ]);
          },
          _doFinalize: function() {
            var hash2 = SHA512._doFinalize.call(this);
            hash2.sigBytes -= 16;
            return hash2;
          }
        });
        C2.SHA384 = SHA512._createHelper(SHA384);
        C2.HmacSHA384 = SHA512._createHmacHelper(SHA384);
      })();
      return CryptoJS2.SHA384;
    });
  })(sha384$1);
  return sha384$1.exports;
}
var sha3$1 = { exports: {} };
var sha3 = sha3$1.exports;
var hasRequiredSha3;
function requireSha3() {
  if (hasRequiredSha3) return sha3$1.exports;
  hasRequiredSha3 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireX64Core());
      }
    })(sha3, function(CryptoJS2) {
      (function(Math2) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_x64 = C2.x64;
        var X64Word = C_x64.Word;
        var C_algo = C2.algo;
        var RHO_OFFSETS = [];
        var PI_INDEXES = [];
        var ROUND_CONSTANTS = [];
        (function() {
          var x2 = 1, y2 = 0;
          for (var t2 = 0; t2 < 24; t2++) {
            RHO_OFFSETS[x2 + 5 * y2] = (t2 + 1) * (t2 + 2) / 2 % 64;
            var newX = y2 % 5;
            var newY = (2 * x2 + 3 * y2) % 5;
            x2 = newX;
            y2 = newY;
          }
          for (var x2 = 0; x2 < 5; x2++) {
            for (var y2 = 0; y2 < 5; y2++) {
              PI_INDEXES[x2 + 5 * y2] = y2 + (2 * x2 + 3 * y2) % 5 * 5;
            }
          }
          var LFSR = 1;
          for (var i2 = 0; i2 < 24; i2++) {
            var roundConstantMsw = 0;
            var roundConstantLsw = 0;
            for (var j = 0; j < 7; j++) {
              if (LFSR & 1) {
                var bitPosition = (1 << j) - 1;
                if (bitPosition < 32) {
                  roundConstantLsw ^= 1 << bitPosition;
                } else {
                  roundConstantMsw ^= 1 << bitPosition - 32;
                }
              }
              if (LFSR & 128) {
                LFSR = LFSR << 1 ^ 113;
              } else {
                LFSR <<= 1;
              }
            }
            ROUND_CONSTANTS[i2] = X64Word.create(roundConstantMsw, roundConstantLsw);
          }
        })();
        var T2 = [];
        (function() {
          for (var i2 = 0; i2 < 25; i2++) {
            T2[i2] = X64Word.create();
          }
        })();
        var SHA3 = C_algo.SHA3 = Hasher.extend({
          /**
           * Configuration options.
           *
           * @property {number} outputLength
           *   The desired number of bits in the output hash.
           *   Only values permitted are: 224, 256, 384, 512.
           *   Default: 512
           */
          cfg: Hasher.cfg.extend({
            outputLength: 512
          }),
          _doReset: function() {
            var state = this._state = [];
            for (var i2 = 0; i2 < 25; i2++) {
              state[i2] = new X64Word.init();
            }
            this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
          },
          _doProcessBlock: function(M2, offset) {
            var state = this._state;
            var nBlockSizeLanes = this.blockSize / 2;
            for (var i2 = 0; i2 < nBlockSizeLanes; i2++) {
              var M2i = M2[offset + 2 * i2];
              var M2i1 = M2[offset + 2 * i2 + 1];
              M2i = (M2i << 8 | M2i >>> 24) & 16711935 | (M2i << 24 | M2i >>> 8) & 4278255360;
              M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 16711935 | (M2i1 << 24 | M2i1 >>> 8) & 4278255360;
              var lane = state[i2];
              lane.high ^= M2i1;
              lane.low ^= M2i;
            }
            for (var round2 = 0; round2 < 24; round2++) {
              for (var x2 = 0; x2 < 5; x2++) {
                var tMsw = 0, tLsw = 0;
                for (var y2 = 0; y2 < 5; y2++) {
                  var lane = state[x2 + 5 * y2];
                  tMsw ^= lane.high;
                  tLsw ^= lane.low;
                }
                var Tx = T2[x2];
                Tx.high = tMsw;
                Tx.low = tLsw;
              }
              for (var x2 = 0; x2 < 5; x2++) {
                var Tx4 = T2[(x2 + 4) % 5];
                var Tx1 = T2[(x2 + 1) % 5];
                var Tx1Msw = Tx1.high;
                var Tx1Lsw = Tx1.low;
                var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31);
                var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31);
                for (var y2 = 0; y2 < 5; y2++) {
                  var lane = state[x2 + 5 * y2];
                  lane.high ^= tMsw;
                  lane.low ^= tLsw;
                }
              }
              for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
                var tMsw;
                var tLsw;
                var lane = state[laneIndex];
                var laneMsw = lane.high;
                var laneLsw = lane.low;
                var rhoOffset = RHO_OFFSETS[laneIndex];
                if (rhoOffset < 32) {
                  tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset;
                  tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset;
                } else {
                  tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset;
                  tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset;
                }
                var TPiLane = T2[PI_INDEXES[laneIndex]];
                TPiLane.high = tMsw;
                TPiLane.low = tLsw;
              }
              var T0 = T2[0];
              var state0 = state[0];
              T0.high = state0.high;
              T0.low = state0.low;
              for (var x2 = 0; x2 < 5; x2++) {
                for (var y2 = 0; y2 < 5; y2++) {
                  var laneIndex = x2 + 5 * y2;
                  var lane = state[laneIndex];
                  var TLane = T2[laneIndex];
                  var Tx1Lane = T2[(x2 + 1) % 5 + 5 * y2];
                  var Tx2Lane = T2[(x2 + 2) % 5 + 5 * y2];
                  lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high;
                  lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low;
                }
              }
              var lane = state[0];
              var roundConstant = ROUND_CONSTANTS[round2];
              lane.high ^= roundConstant.high;
              lane.low ^= roundConstant.low;
            }
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            var blockSizeBits = this.blockSize * 32;
            dataWords[nBitsLeft >>> 5] |= 1 << 24 - nBitsLeft % 32;
            dataWords[(Math2.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 128;
            data2.sigBytes = dataWords.length * 4;
            this._process();
            var state = this._state;
            var outputLengthBytes = this.cfg.outputLength / 8;
            var outputLengthLanes = outputLengthBytes / 8;
            var hashWords = [];
            for (var i2 = 0; i2 < outputLengthLanes; i2++) {
              var lane = state[i2];
              var laneMsw = lane.high;
              var laneLsw = lane.low;
              laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 16711935 | (laneMsw << 24 | laneMsw >>> 8) & 4278255360;
              laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 16711935 | (laneLsw << 24 | laneLsw >>> 8) & 4278255360;
              hashWords.push(laneLsw);
              hashWords.push(laneMsw);
            }
            return new WordArray.init(hashWords, outputLengthBytes);
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            var state = clone2._state = this._state.slice(0);
            for (var i2 = 0; i2 < 25; i2++) {
              state[i2] = state[i2].clone();
            }
            return clone2;
          }
        });
        C2.SHA3 = Hasher._createHelper(SHA3);
        C2.HmacSHA3 = Hasher._createHmacHelper(SHA3);
      })(Math);
      return CryptoJS2.SHA3;
    });
  })(sha3$1);
  return sha3$1.exports;
}
var ripemd160$1 = { exports: {} };
var ripemd160 = ripemd160$1.exports;
var hasRequiredRipemd160;
function requireRipemd160() {
  if (hasRequiredRipemd160) return ripemd160$1.exports;
  hasRequiredRipemd160 = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(ripemd160, function(CryptoJS2) {
      /** @preserve
      			(c) 2012 by Cédric Mesnil. All rights reserved.
      
      			Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
      
      			    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
      			    - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
      
      			THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      			*/
      (function(Math2) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C2.algo;
        var _zl = WordArray.create([
          0,
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8,
          9,
          10,
          11,
          12,
          13,
          14,
          15,
          7,
          4,
          13,
          1,
          10,
          6,
          15,
          3,
          12,
          0,
          9,
          5,
          2,
          14,
          11,
          8,
          3,
          10,
          14,
          4,
          9,
          15,
          8,
          1,
          2,
          7,
          0,
          6,
          13,
          11,
          5,
          12,
          1,
          9,
          11,
          10,
          0,
          8,
          12,
          4,
          13,
          3,
          7,
          15,
          14,
          5,
          6,
          2,
          4,
          0,
          5,
          9,
          7,
          12,
          2,
          10,
          14,
          1,
          3,
          8,
          11,
          6,
          15,
          13
        ]);
        var _zr = WordArray.create([
          5,
          14,
          7,
          0,
          9,
          2,
          11,
          4,
          13,
          6,
          15,
          8,
          1,
          10,
          3,
          12,
          6,
          11,
          3,
          7,
          0,
          13,
          5,
          10,
          14,
          15,
          8,
          12,
          4,
          9,
          1,
          2,
          15,
          5,
          1,
          3,
          7,
          14,
          6,
          9,
          11,
          8,
          12,
          2,
          10,
          0,
          4,
          13,
          8,
          6,
          4,
          1,
          3,
          11,
          15,
          0,
          5,
          12,
          2,
          13,
          9,
          7,
          10,
          14,
          12,
          15,
          10,
          4,
          1,
          5,
          8,
          7,
          6,
          2,
          13,
          14,
          0,
          3,
          9,
          11
        ]);
        var _sl = WordArray.create([
          11,
          14,
          15,
          12,
          5,
          8,
          7,
          9,
          11,
          13,
          14,
          15,
          6,
          7,
          9,
          8,
          7,
          6,
          8,
          13,
          11,
          9,
          7,
          15,
          7,
          12,
          15,
          9,
          11,
          7,
          13,
          12,
          11,
          13,
          6,
          7,
          14,
          9,
          13,
          15,
          14,
          8,
          13,
          6,
          5,
          12,
          7,
          5,
          11,
          12,
          14,
          15,
          14,
          15,
          9,
          8,
          9,
          14,
          5,
          6,
          8,
          6,
          5,
          12,
          9,
          15,
          5,
          11,
          6,
          8,
          13,
          12,
          5,
          12,
          13,
          14,
          11,
          8,
          5,
          6
        ]);
        var _sr = WordArray.create([
          8,
          9,
          9,
          11,
          13,
          15,
          15,
          5,
          7,
          7,
          8,
          11,
          14,
          14,
          12,
          6,
          9,
          13,
          15,
          7,
          12,
          8,
          9,
          11,
          7,
          7,
          12,
          7,
          6,
          15,
          13,
          11,
          9,
          7,
          15,
          11,
          8,
          6,
          6,
          14,
          12,
          13,
          5,
          14,
          13,
          13,
          7,
          5,
          15,
          5,
          8,
          11,
          14,
          14,
          6,
          14,
          6,
          9,
          12,
          9,
          12,
          5,
          15,
          8,
          8,
          5,
          12,
          9,
          12,
          5,
          14,
          6,
          8,
          13,
          6,
          5,
          15,
          13,
          11,
          11
        ]);
        var _hl = WordArray.create([0, 1518500249, 1859775393, 2400959708, 2840853838]);
        var _hr = WordArray.create([1352829926, 1548603684, 1836072691, 2053994217, 0]);
        var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
          _doReset: function() {
            this._hash = WordArray.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
          },
          _doProcessBlock: function(M2, offset) {
            for (var i2 = 0; i2 < 16; i2++) {
              var offset_i = offset + i2;
              var M_offset_i = M2[offset_i];
              M2[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360;
            }
            var H = this._hash.words;
            var hl = _hl.words;
            var hr = _hr.words;
            var zl = _zl.words;
            var zr = _zr.words;
            var sl = _sl.words;
            var sr = _sr.words;
            var al, bl, cl, dl, el;
            var ar, br, cr, dr, er;
            ar = al = H[0];
            br = bl = H[1];
            cr = cl = H[2];
            dr = dl = H[3];
            er = el = H[4];
            var t2;
            for (var i2 = 0; i2 < 80; i2 += 1) {
              t2 = al + M2[offset + zl[i2]] | 0;
              if (i2 < 16) {
                t2 += f1(bl, cl, dl) + hl[0];
              } else if (i2 < 32) {
                t2 += f2(bl, cl, dl) + hl[1];
              } else if (i2 < 48) {
                t2 += f3(bl, cl, dl) + hl[2];
              } else if (i2 < 64) {
                t2 += f4(bl, cl, dl) + hl[3];
              } else {
                t2 += f5(bl, cl, dl) + hl[4];
              }
              t2 = t2 | 0;
              t2 = rotl2(t2, sl[i2]);
              t2 = t2 + el | 0;
              al = el;
              el = dl;
              dl = rotl2(cl, 10);
              cl = bl;
              bl = t2;
              t2 = ar + M2[offset + zr[i2]] | 0;
              if (i2 < 16) {
                t2 += f5(br, cr, dr) + hr[0];
              } else if (i2 < 32) {
                t2 += f4(br, cr, dr) + hr[1];
              } else if (i2 < 48) {
                t2 += f3(br, cr, dr) + hr[2];
              } else if (i2 < 64) {
                t2 += f2(br, cr, dr) + hr[3];
              } else {
                t2 += f1(br, cr, dr) + hr[4];
              }
              t2 = t2 | 0;
              t2 = rotl2(t2, sr[i2]);
              t2 = t2 + er | 0;
              ar = er;
              er = dr;
              dr = rotl2(cr, 10);
              cr = br;
              br = t2;
            }
            t2 = H[1] + cl + dr | 0;
            H[1] = H[2] + dl + er | 0;
            H[2] = H[3] + el + ar | 0;
            H[3] = H[4] + al + br | 0;
            H[4] = H[0] + bl + cr | 0;
            H[0] = t2;
          },
          _doFinalize: function() {
            var data2 = this._data;
            var dataWords = data2.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data2.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 16711935 | (nBitsTotal << 24 | nBitsTotal >>> 8) & 4278255360;
            data2.sigBytes = (dataWords.length + 1) * 4;
            this._process();
            var hash2 = this._hash;
            var H = hash2.words;
            for (var i2 = 0; i2 < 5; i2++) {
              var H_i = H[i2];
              H[i2] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360;
            }
            return hash2;
          },
          clone: function() {
            var clone2 = Hasher.clone.call(this);
            clone2._hash = this._hash.clone();
            return clone2;
          }
        });
        function f1(x2, y2, z2) {
          return x2 ^ y2 ^ z2;
        }
        function f2(x2, y2, z2) {
          return x2 & y2 | ~x2 & z2;
        }
        function f3(x2, y2, z2) {
          return (x2 | ~y2) ^ z2;
        }
        function f4(x2, y2, z2) {
          return x2 & z2 | y2 & ~z2;
        }
        function f5(x2, y2, z2) {
          return x2 ^ (y2 | ~z2);
        }
        function rotl2(x2, n2) {
          return x2 << n2 | x2 >>> 32 - n2;
        }
        C2.RIPEMD160 = Hasher._createHelper(RIPEMD160);
        C2.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
      })();
      return CryptoJS2.RIPEMD160;
    });
  })(ripemd160$1);
  return ripemd160$1.exports;
}
var hmac$1 = { exports: {} };
var hmac = hmac$1.exports;
var hasRequiredHmac;
function requireHmac() {
  if (hasRequiredHmac) return hmac$1.exports;
  hasRequiredHmac = 1;
  (function(module2, exports) {
    (function(root, factory) {
      {
        module2.exports = factory(requireCore());
      }
    })(hmac, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Base = C_lib.Base;
        var C_enc = C2.enc;
        var Utf8 = C_enc.Utf8;
        var C_algo = C2.algo;
        C_algo.HMAC = Base.extend({
          /**
           * Initializes a newly created HMAC.
           *
           * @param {Hasher} hasher The hash algorithm to use.
           * @param {WordArray|string} key The secret key.
           *
           * @example
           *
           *     var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
           */
          init: function(hasher, key2) {
            hasher = this._hasher = new hasher.init();
            if (typeof key2 == "string") {
              key2 = Utf8.parse(key2);
            }
            var hasherBlockSize = hasher.blockSize;
            var hasherBlockSizeBytes = hasherBlockSize * 4;
            if (key2.sigBytes > hasherBlockSizeBytes) {
              key2 = hasher.finalize(key2);
            }
            key2.clamp();
            var oKey = this._oKey = key2.clone();
            var iKey = this._iKey = key2.clone();
            var oKeyWords = oKey.words;
            var iKeyWords = iKey.words;
            for (var i2 = 0; i2 < hasherBlockSize; i2++) {
              oKeyWords[i2] ^= 1549556828;
              iKeyWords[i2] ^= 909522486;
            }
            oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
            this.reset();
          },
          /**
           * Resets this HMAC to its initial state.
           *
           * @example
           *
           *     hmacHasher.reset();
           */
          reset: function() {
            var hasher = this._hasher;
            hasher.reset();
            hasher.update(this._iKey);
          },
          /**
           * Updates this HMAC with a message.
           *
           * @param {WordArray|string} messageUpdate The message to append.
           *
           * @return {HMAC} This HMAC instance.
           *
           * @example
           *
           *     hmacHasher.update('message');
           *     hmacHasher.update(wordArray);
           */
          update: function(messageUpdate) {
            this._hasher.update(messageUpdate);
            return this;
          },
          /**
           * Finalizes the HMAC computation.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} messageUpdate (Optional) A final message update.
           *
           * @return {WordArray} The HMAC.
           *
           * @example
           *
           *     var hmac = hmacHasher.finalize();
           *     var hmac = hmacHasher.finalize('message');
           *     var hmac = hmacHasher.finalize(wordArray);
           */
          finalize: function(messageUpdate) {
            var hasher = this._hasher;
            var innerHash = hasher.finalize(messageUpdate);
            hasher.reset();
            var hmac2 = hasher.finalize(this._oKey.clone().concat(innerHash));
            return hmac2;
          }
        });
      })();
    });
  })(hmac$1);
  return hmac$1.exports;
}
var pbkdf2$1 = { exports: {} };
var pbkdf2 = pbkdf2$1.exports;
var hasRequiredPbkdf2;
function requirePbkdf2() {
  if (hasRequiredPbkdf2) return pbkdf2$1.exports;
  hasRequiredPbkdf2 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireSha256(), requireHmac());
      }
    })(pbkdf2, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var C_algo = C2.algo;
        var SHA256 = C_algo.SHA256;
        var HMAC = C_algo.HMAC;
        var PBKDF2 = C_algo.PBKDF2 = Base.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hasher to use. Default: SHA256
           * @property {number} iterations The number of iterations to perform. Default: 250000
           */
          cfg: Base.extend({
            keySize: 128 / 32,
            hasher: SHA256,
            iterations: 25e4
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.PBKDF2.create();
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
          },
          /**
           * Computes the Password-Based Key Derivation Function 2.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(password, salt) {
            var cfg = this.cfg;
            var hmac2 = HMAC.create(cfg.hasher, password);
            var derivedKey = WordArray.create();
            var blockIndex = WordArray.create([1]);
            var derivedKeyWords = derivedKey.words;
            var blockIndexWords = blockIndex.words;
            var keySize = cfg.keySize;
            var iterations = cfg.iterations;
            while (derivedKeyWords.length < keySize) {
              var block = hmac2.update(salt).finalize(blockIndex);
              hmac2.reset();
              var blockWords = block.words;
              var blockWordsLength = blockWords.length;
              var intermediate = block;
              for (var i2 = 1; i2 < iterations; i2++) {
                intermediate = hmac2.finalize(intermediate);
                hmac2.reset();
                var intermediateWords = intermediate.words;
                for (var j = 0; j < blockWordsLength; j++) {
                  blockWords[j] ^= intermediateWords[j];
                }
              }
              derivedKey.concat(block);
              blockIndexWords[0]++;
            }
            derivedKey.sigBytes = keySize * 4;
            return derivedKey;
          }
        });
        C2.PBKDF2 = function(password, salt, cfg) {
          return PBKDF2.create(cfg).compute(password, salt);
        };
      })();
      return CryptoJS2.PBKDF2;
    });
  })(pbkdf2$1);
  return pbkdf2$1.exports;
}
var evpkdf$1 = { exports: {} };
var evpkdf = evpkdf$1.exports;
var hasRequiredEvpkdf;
function requireEvpkdf() {
  if (hasRequiredEvpkdf) return evpkdf$1.exports;
  hasRequiredEvpkdf = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireSha1(), requireHmac());
      }
    })(evpkdf, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var C_algo = C2.algo;
        var MD5 = C_algo.MD5;
        var EvpKDF = C_algo.EvpKDF = Base.extend({
          /**
           * Configuration options.
           *
           * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
           * @property {Hasher} hasher The hash algorithm to use. Default: MD5
           * @property {number} iterations The number of iterations to perform. Default: 1
           */
          cfg: Base.extend({
            keySize: 128 / 32,
            hasher: MD5,
            iterations: 1
          }),
          /**
           * Initializes a newly created key derivation function.
           *
           * @param {Object} cfg (Optional) The configuration options to use for the derivation.
           *
           * @example
           *
           *     var kdf = CryptoJS.algo.EvpKDF.create();
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
           *     var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
           */
          init: function(cfg) {
            this.cfg = this.cfg.extend(cfg);
          },
          /**
           * Derives a key from a password.
           *
           * @param {WordArray|string} password The password.
           * @param {WordArray|string} salt A salt.
           *
           * @return {WordArray} The derived key.
           *
           * @example
           *
           *     var key = kdf.compute(password, salt);
           */
          compute: function(password, salt) {
            var block;
            var cfg = this.cfg;
            var hasher = cfg.hasher.create();
            var derivedKey = WordArray.create();
            var derivedKeyWords = derivedKey.words;
            var keySize = cfg.keySize;
            var iterations = cfg.iterations;
            while (derivedKeyWords.length < keySize) {
              if (block) {
                hasher.update(block);
              }
              block = hasher.update(password).finalize(salt);
              hasher.reset();
              for (var i2 = 1; i2 < iterations; i2++) {
                block = hasher.finalize(block);
                hasher.reset();
              }
              derivedKey.concat(block);
            }
            derivedKey.sigBytes = keySize * 4;
            return derivedKey;
          }
        });
        C2.EvpKDF = function(password, salt, cfg) {
          return EvpKDF.create(cfg).compute(password, salt);
        };
      })();
      return CryptoJS2.EvpKDF;
    });
  })(evpkdf$1);
  return evpkdf$1.exports;
}
var cipherCore$1 = { exports: {} };
var cipherCore = cipherCore$1.exports;
var hasRequiredCipherCore;
function requireCipherCore() {
  if (hasRequiredCipherCore) return cipherCore$1.exports;
  hasRequiredCipherCore = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEvpkdf());
      }
    })(cipherCore, function(CryptoJS2) {
      CryptoJS2.lib.Cipher || function(undefined$1) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var Base = C_lib.Base;
        var WordArray = C_lib.WordArray;
        var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
        var C_enc = C2.enc;
        C_enc.Utf8;
        var Base642 = C_enc.Base64;
        var C_algo = C2.algo;
        var EvpKDF = C_algo.EvpKDF;
        var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
          /**
           * Configuration options.
           *
           * @property {WordArray} iv The IV to use for this operation.
           */
          cfg: Base.extend(),
          /**
           * Creates this cipher in encryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
           */
          createEncryptor: function(key2, cfg) {
            return this.create(this._ENC_XFORM_MODE, key2, cfg);
          },
          /**
           * Creates this cipher in decryption mode.
           *
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {Cipher} A cipher instance.
           *
           * @static
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
           */
          createDecryptor: function(key2, cfg) {
            return this.create(this._DEC_XFORM_MODE, key2, cfg);
          },
          /**
           * Initializes a newly created cipher.
           *
           * @param {number} xformMode Either the encryption or decryption transormation mode constant.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @example
           *
           *     var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
           */
          init: function(xformMode, key2, cfg) {
            this.cfg = this.cfg.extend(cfg);
            this._xformMode = xformMode;
            this._key = key2;
            this.reset();
          },
          /**
           * Resets this cipher to its initial state.
           *
           * @example
           *
           *     cipher.reset();
           */
          reset: function() {
            BufferedBlockAlgorithm.reset.call(this);
            this._doReset();
          },
          /**
           * Adds data to be encrypted or decrypted.
           *
           * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
           *
           * @return {WordArray} The data after processing.
           *
           * @example
           *
           *     var encrypted = cipher.process('data');
           *     var encrypted = cipher.process(wordArray);
           */
          process: function(dataUpdate) {
            this._append(dataUpdate);
            return this._process();
          },
          /**
           * Finalizes the encryption or decryption process.
           * Note that the finalize operation is effectively a destructive, read-once operation.
           *
           * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
           *
           * @return {WordArray} The data after final processing.
           *
           * @example
           *
           *     var encrypted = cipher.finalize();
           *     var encrypted = cipher.finalize('data');
           *     var encrypted = cipher.finalize(wordArray);
           */
          finalize: function(dataUpdate) {
            if (dataUpdate) {
              this._append(dataUpdate);
            }
            var finalProcessedData = this._doFinalize();
            return finalProcessedData;
          },
          keySize: 128 / 32,
          ivSize: 128 / 32,
          _ENC_XFORM_MODE: 1,
          _DEC_XFORM_MODE: 2,
          /**
           * Creates shortcut functions to a cipher's object interface.
           *
           * @param {Cipher} cipher The cipher to create a helper for.
           *
           * @return {Object} An object with encrypt and decrypt shortcut functions.
           *
           * @static
           *
           * @example
           *
           *     var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
           */
          _createHelper: /* @__PURE__ */ function() {
            function selectCipherStrategy(key2) {
              if (typeof key2 == "string") {
                return PasswordBasedCipher;
              } else {
                return SerializableCipher;
              }
            }
            return function(cipher2) {
              return {
                encrypt: function(message, key2, cfg) {
                  return selectCipherStrategy(key2).encrypt(cipher2, message, key2, cfg);
                },
                decrypt: function(ciphertext, key2, cfg) {
                  return selectCipherStrategy(key2).decrypt(cipher2, ciphertext, key2, cfg);
                }
              };
            };
          }()
        });
        C_lib.StreamCipher = Cipher.extend({
          _doFinalize: function() {
            var finalProcessedBlocks = this._process(true);
            return finalProcessedBlocks;
          },
          blockSize: 1
        });
        var C_mode = C2.mode = {};
        var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
          /**
           * Creates this mode for encryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
           */
          createEncryptor: function(cipher2, iv) {
            return this.Encryptor.create(cipher2, iv);
          },
          /**
           * Creates this mode for decryption.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @static
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
           */
          createDecryptor: function(cipher2, iv) {
            return this.Decryptor.create(cipher2, iv);
          },
          /**
           * Initializes a newly created mode.
           *
           * @param {Cipher} cipher A block cipher instance.
           * @param {Array} iv The IV words.
           *
           * @example
           *
           *     var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
           */
          init: function(cipher2, iv) {
            this._cipher = cipher2;
            this._iv = iv;
          }
        });
        var CBC = C_mode.CBC = function() {
          var CBC2 = BlockCipherMode.extend();
          CBC2.Encryptor = CBC2.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(words, offset) {
              var cipher2 = this._cipher;
              var blockSize = cipher2.blockSize;
              xorBlock.call(this, words, offset, blockSize);
              cipher2.encryptBlock(words, offset);
              this._prevBlock = words.slice(offset, offset + blockSize);
            }
          });
          CBC2.Decryptor = CBC2.extend({
            /**
             * Processes the data block at offset.
             *
             * @param {Array} words The data words to operate on.
             * @param {number} offset The offset where the block starts.
             *
             * @example
             *
             *     mode.processBlock(data.words, offset);
             */
            processBlock: function(words, offset) {
              var cipher2 = this._cipher;
              var blockSize = cipher2.blockSize;
              var thisBlock = words.slice(offset, offset + blockSize);
              cipher2.decryptBlock(words, offset);
              xorBlock.call(this, words, offset, blockSize);
              this._prevBlock = thisBlock;
            }
          });
          function xorBlock(words, offset, blockSize) {
            var block;
            var iv = this._iv;
            if (iv) {
              block = iv;
              this._iv = undefined$1;
            } else {
              block = this._prevBlock;
            }
            for (var i2 = 0; i2 < blockSize; i2++) {
              words[offset + i2] ^= block[i2];
            }
          }
          return CBC2;
        }();
        var C_pad = C2.pad = {};
        var Pkcs7 = C_pad.Pkcs7 = {
          /**
           * Pads data using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to pad.
           * @param {number} blockSize The multiple that the data should be padded to.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.pad(wordArray, 4);
           */
          pad: function(data2, blockSize) {
            var blockSizeBytes = blockSize * 4;
            var nPaddingBytes = blockSizeBytes - data2.sigBytes % blockSizeBytes;
            var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes;
            var paddingWords = [];
            for (var i2 = 0; i2 < nPaddingBytes; i2 += 4) {
              paddingWords.push(paddingWord);
            }
            var padding = WordArray.create(paddingWords, nPaddingBytes);
            data2.concat(padding);
          },
          /**
           * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
           *
           * @param {WordArray} data The data to unpad.
           *
           * @static
           *
           * @example
           *
           *     CryptoJS.pad.Pkcs7.unpad(wordArray);
           */
          unpad: function(data2) {
            var nPaddingBytes = data2.words[data2.sigBytes - 1 >>> 2] & 255;
            data2.sigBytes -= nPaddingBytes;
          }
        };
        C_lib.BlockCipher = Cipher.extend({
          /**
           * Configuration options.
           *
           * @property {Mode} mode The block mode to use. Default: CBC
           * @property {Padding} padding The padding strategy to use. Default: Pkcs7
           */
          cfg: Cipher.cfg.extend({
            mode: CBC,
            padding: Pkcs7
          }),
          reset: function() {
            var modeCreator;
            Cipher.reset.call(this);
            var cfg = this.cfg;
            var iv = cfg.iv;
            var mode = cfg.mode;
            if (this._xformMode == this._ENC_XFORM_MODE) {
              modeCreator = mode.createEncryptor;
            } else {
              modeCreator = mode.createDecryptor;
              this._minBufferSize = 1;
            }
            if (this._mode && this._mode.__creator == modeCreator) {
              this._mode.init(this, iv && iv.words);
            } else {
              this._mode = modeCreator.call(mode, this, iv && iv.words);
              this._mode.__creator = modeCreator;
            }
          },
          _doProcessBlock: function(words, offset) {
            this._mode.processBlock(words, offset);
          },
          _doFinalize: function() {
            var finalProcessedBlocks;
            var padding = this.cfg.padding;
            if (this._xformMode == this._ENC_XFORM_MODE) {
              padding.pad(this._data, this.blockSize);
              finalProcessedBlocks = this._process(true);
            } else {
              finalProcessedBlocks = this._process(true);
              padding.unpad(finalProcessedBlocks);
            }
            return finalProcessedBlocks;
          },
          blockSize: 128 / 32
        });
        var CipherParams = C_lib.CipherParams = Base.extend({
          /**
           * Initializes a newly created cipher params object.
           *
           * @param {Object} cipherParams An object with any of the possible cipher parameters.
           *
           * @example
           *
           *     var cipherParams = CryptoJS.lib.CipherParams.create({
           *         ciphertext: ciphertextWordArray,
           *         key: keyWordArray,
           *         iv: ivWordArray,
           *         salt: saltWordArray,
           *         algorithm: CryptoJS.algo.AES,
           *         mode: CryptoJS.mode.CBC,
           *         padding: CryptoJS.pad.PKCS7,
           *         blockSize: 4,
           *         formatter: CryptoJS.format.OpenSSL
           *     });
           */
          init: function(cipherParams) {
            this.mixIn(cipherParams);
          },
          /**
           * Converts this cipher params object to a string.
           *
           * @param {Format} formatter (Optional) The formatting strategy to use.
           *
           * @return {string} The stringified cipher params.
           *
           * @throws Error If neither the formatter nor the default formatter is set.
           *
           * @example
           *
           *     var string = cipherParams + '';
           *     var string = cipherParams.toString();
           *     var string = cipherParams.toString(CryptoJS.format.OpenSSL);
           */
          toString: function(formatter) {
            return (formatter || this.formatter).stringify(this);
          }
        });
        var C_format = C2.format = {};
        var OpenSSLFormatter = C_format.OpenSSL = {
          /**
           * Converts a cipher params object to an OpenSSL-compatible string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The OpenSSL-compatible string.
           *
           * @static
           *
           * @example
           *
           *     var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
           */
          stringify: function(cipherParams) {
            var wordArray;
            var ciphertext = cipherParams.ciphertext;
            var salt = cipherParams.salt;
            if (salt) {
              wordArray = WordArray.create([1398893684, 1701076831]).concat(salt).concat(ciphertext);
            } else {
              wordArray = ciphertext;
            }
            return wordArray.toString(Base642);
          },
          /**
           * Converts an OpenSSL-compatible string to a cipher params object.
           *
           * @param {string} openSSLStr The OpenSSL-compatible string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
           */
          parse: function(openSSLStr) {
            var salt;
            var ciphertext = Base642.parse(openSSLStr);
            var ciphertextWords = ciphertext.words;
            if (ciphertextWords[0] == 1398893684 && ciphertextWords[1] == 1701076831) {
              salt = WordArray.create(ciphertextWords.slice(2, 4));
              ciphertextWords.splice(0, 4);
              ciphertext.sigBytes -= 16;
            }
            return CipherParams.create({ ciphertext, salt });
          }
        };
        var SerializableCipher = C_lib.SerializableCipher = Base.extend({
          /**
           * Configuration options.
           *
           * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
           */
          cfg: Base.extend({
            format: OpenSSLFormatter
          }),
          /**
           * Encrypts a message.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(cipher2, message, key2, cfg) {
            cfg = this.cfg.extend(cfg);
            var encryptor = cipher2.createEncryptor(key2, cfg);
            var ciphertext = encryptor.finalize(message);
            var cipherCfg = encryptor.cfg;
            return CipherParams.create({
              ciphertext,
              key: key2,
              iv: cipherCfg.iv,
              algorithm: cipher2,
              mode: cipherCfg.mode,
              padding: cipherCfg.padding,
              blockSize: cipher2.blockSize,
              formatter: cfg.format
            });
          },
          /**
           * Decrypts serialized ciphertext.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {WordArray} key The key.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(cipher2, ciphertext, key2, cfg) {
            cfg = this.cfg.extend(cfg);
            ciphertext = this._parse(ciphertext, cfg.format);
            var plaintext = cipher2.createDecryptor(key2, cfg).finalize(ciphertext.ciphertext);
            return plaintext;
          },
          /**
           * Converts serialized ciphertext to CipherParams,
           * else assumed CipherParams already and returns ciphertext unchanged.
           *
           * @param {CipherParams|string} ciphertext The ciphertext.
           * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
           *
           * @return {CipherParams} The unserialized ciphertext.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
           */
          _parse: function(ciphertext, format2) {
            if (typeof ciphertext == "string") {
              return format2.parse(ciphertext, this);
            } else {
              return ciphertext;
            }
          }
        });
        var C_kdf = C2.kdf = {};
        var OpenSSLKdf = C_kdf.OpenSSL = {
          /**
           * Derives a key and IV from a password.
           *
           * @param {string} password The password to derive from.
           * @param {number} keySize The size in words of the key to generate.
           * @param {number} ivSize The size in words of the IV to generate.
           * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
           *
           * @return {CipherParams} A cipher params object with the key, IV, and salt.
           *
           * @static
           *
           * @example
           *
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
           *     var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
           */
          execute: function(password, keySize, ivSize, salt, hasher) {
            if (!salt) {
              salt = WordArray.random(64 / 8);
            }
            if (!hasher) {
              var key2 = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
            } else {
              var key2 = EvpKDF.create({ keySize: keySize + ivSize, hasher }).compute(password, salt);
            }
            var iv = WordArray.create(key2.words.slice(keySize), ivSize * 4);
            key2.sigBytes = keySize * 4;
            return CipherParams.create({ key: key2, iv, salt });
          }
        };
        var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
          /**
           * Configuration options.
           *
           * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
           */
          cfg: SerializableCipher.cfg.extend({
            kdf: OpenSSLKdf
          }),
          /**
           * Encrypts a message using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {WordArray|string} message The message to encrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {CipherParams} A cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
           *     var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
           */
          encrypt: function(cipher2, message, password, cfg) {
            cfg = this.cfg.extend(cfg);
            var derivedParams = cfg.kdf.execute(password, cipher2.keySize, cipher2.ivSize, cfg.salt, cfg.hasher);
            cfg.iv = derivedParams.iv;
            var ciphertext = SerializableCipher.encrypt.call(this, cipher2, message, derivedParams.key, cfg);
            ciphertext.mixIn(derivedParams);
            return ciphertext;
          },
          /**
           * Decrypts serialized ciphertext using a password.
           *
           * @param {Cipher} cipher The cipher algorithm to use.
           * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
           * @param {string} password The password.
           * @param {Object} cfg (Optional) The configuration options to use for this operation.
           *
           * @return {WordArray} The plaintext.
           *
           * @static
           *
           * @example
           *
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
           *     var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
           */
          decrypt: function(cipher2, ciphertext, password, cfg) {
            cfg = this.cfg.extend(cfg);
            ciphertext = this._parse(ciphertext, cfg.format);
            var derivedParams = cfg.kdf.execute(password, cipher2.keySize, cipher2.ivSize, ciphertext.salt, cfg.hasher);
            cfg.iv = derivedParams.iv;
            var plaintext = SerializableCipher.decrypt.call(this, cipher2, ciphertext, derivedParams.key, cfg);
            return plaintext;
          }
        });
      }();
    });
  })(cipherCore$1);
  return cipherCore$1.exports;
}
var modeCfb$1 = { exports: {} };
var modeCfb = modeCfb$1.exports;
var hasRequiredModeCfb;
function requireModeCfb() {
  if (hasRequiredModeCfb) return modeCfb$1.exports;
  hasRequiredModeCfb = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(modeCfb, function(CryptoJS2) {
      CryptoJS2.mode.CFB = function() {
        var CFB = CryptoJS2.lib.BlockCipherMode.extend();
        CFB.Encryptor = CFB.extend({
          processBlock: function(words, offset) {
            var cipher2 = this._cipher;
            var blockSize = cipher2.blockSize;
            generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher2);
            this._prevBlock = words.slice(offset, offset + blockSize);
          }
        });
        CFB.Decryptor = CFB.extend({
          processBlock: function(words, offset) {
            var cipher2 = this._cipher;
            var blockSize = cipher2.blockSize;
            var thisBlock = words.slice(offset, offset + blockSize);
            generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher2);
            this._prevBlock = thisBlock;
          }
        });
        function generateKeystreamAndEncrypt(words, offset, blockSize, cipher2) {
          var keystream;
          var iv = this._iv;
          if (iv) {
            keystream = iv.slice(0);
            this._iv = void 0;
          } else {
            keystream = this._prevBlock;
          }
          cipher2.encryptBlock(keystream, 0);
          for (var i2 = 0; i2 < blockSize; i2++) {
            words[offset + i2] ^= keystream[i2];
          }
        }
        return CFB;
      }();
      return CryptoJS2.mode.CFB;
    });
  })(modeCfb$1);
  return modeCfb$1.exports;
}
var modeCtr$1 = { exports: {} };
var modeCtr = modeCtr$1.exports;
var hasRequiredModeCtr;
function requireModeCtr() {
  if (hasRequiredModeCtr) return modeCtr$1.exports;
  hasRequiredModeCtr = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(modeCtr, function(CryptoJS2) {
      CryptoJS2.mode.CTR = function() {
        var CTR = CryptoJS2.lib.BlockCipherMode.extend();
        var Encryptor = CTR.Encryptor = CTR.extend({
          processBlock: function(words, offset) {
            var cipher2 = this._cipher;
            var blockSize = cipher2.blockSize;
            var iv = this._iv;
            var counter = this._counter;
            if (iv) {
              counter = this._counter = iv.slice(0);
              this._iv = void 0;
            }
            var keystream = counter.slice(0);
            cipher2.encryptBlock(keystream, 0);
            counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0;
            for (var i2 = 0; i2 < blockSize; i2++) {
              words[offset + i2] ^= keystream[i2];
            }
          }
        });
        CTR.Decryptor = Encryptor;
        return CTR;
      }();
      return CryptoJS2.mode.CTR;
    });
  })(modeCtr$1);
  return modeCtr$1.exports;
}
var modeCtrGladman$1 = { exports: {} };
var modeCtrGladman = modeCtrGladman$1.exports;
var hasRequiredModeCtrGladman;
function requireModeCtrGladman() {
  if (hasRequiredModeCtrGladman) return modeCtrGladman$1.exports;
  hasRequiredModeCtrGladman = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(modeCtrGladman, function(CryptoJS2) {
      /** @preserve
       * Counter block mode compatible with  Dr Brian Gladman fileenc.c
       * derived from CryptoJS.mode.CTR
       * Jan Hruby jhruby.web@gmail.com
       */
      CryptoJS2.mode.CTRGladman = function() {
        var CTRGladman = CryptoJS2.lib.BlockCipherMode.extend();
        function incWord(word) {
          if ((word >> 24 & 255) === 255) {
            var b1 = word >> 16 & 255;
            var b2 = word >> 8 & 255;
            var b3 = word & 255;
            if (b1 === 255) {
              b1 = 0;
              if (b2 === 255) {
                b2 = 0;
                if (b3 === 255) {
                  b3 = 0;
                } else {
                  ++b3;
                }
              } else {
                ++b2;
              }
            } else {
              ++b1;
            }
            word = 0;
            word += b1 << 16;
            word += b2 << 8;
            word += b3;
          } else {
            word += 1 << 24;
          }
          return word;
        }
        function incCounter(counter) {
          if ((counter[0] = incWord(counter[0])) === 0) {
            counter[1] = incWord(counter[1]);
          }
          return counter;
        }
        var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
          processBlock: function(words, offset) {
            var cipher2 = this._cipher;
            var blockSize = cipher2.blockSize;
            var iv = this._iv;
            var counter = this._counter;
            if (iv) {
              counter = this._counter = iv.slice(0);
              this._iv = void 0;
            }
            incCounter(counter);
            var keystream = counter.slice(0);
            cipher2.encryptBlock(keystream, 0);
            for (var i2 = 0; i2 < blockSize; i2++) {
              words[offset + i2] ^= keystream[i2];
            }
          }
        });
        CTRGladman.Decryptor = Encryptor;
        return CTRGladman;
      }();
      return CryptoJS2.mode.CTRGladman;
    });
  })(modeCtrGladman$1);
  return modeCtrGladman$1.exports;
}
var modeOfb$1 = { exports: {} };
var modeOfb = modeOfb$1.exports;
var hasRequiredModeOfb;
function requireModeOfb() {
  if (hasRequiredModeOfb) return modeOfb$1.exports;
  hasRequiredModeOfb = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(modeOfb, function(CryptoJS2) {
      CryptoJS2.mode.OFB = function() {
        var OFB = CryptoJS2.lib.BlockCipherMode.extend();
        var Encryptor = OFB.Encryptor = OFB.extend({
          processBlock: function(words, offset) {
            var cipher2 = this._cipher;
            var blockSize = cipher2.blockSize;
            var iv = this._iv;
            var keystream = this._keystream;
            if (iv) {
              keystream = this._keystream = iv.slice(0);
              this._iv = void 0;
            }
            cipher2.encryptBlock(keystream, 0);
            for (var i2 = 0; i2 < blockSize; i2++) {
              words[offset + i2] ^= keystream[i2];
            }
          }
        });
        OFB.Decryptor = Encryptor;
        return OFB;
      }();
      return CryptoJS2.mode.OFB;
    });
  })(modeOfb$1);
  return modeOfb$1.exports;
}
var modeEcb$1 = { exports: {} };
var modeEcb = modeEcb$1.exports;
var hasRequiredModeEcb;
function requireModeEcb() {
  if (hasRequiredModeEcb) return modeEcb$1.exports;
  hasRequiredModeEcb = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(modeEcb, function(CryptoJS2) {
      CryptoJS2.mode.ECB = function() {
        var ECB = CryptoJS2.lib.BlockCipherMode.extend();
        ECB.Encryptor = ECB.extend({
          processBlock: function(words, offset) {
            this._cipher.encryptBlock(words, offset);
          }
        });
        ECB.Decryptor = ECB.extend({
          processBlock: function(words, offset) {
            this._cipher.decryptBlock(words, offset);
          }
        });
        return ECB;
      }();
      return CryptoJS2.mode.ECB;
    });
  })(modeEcb$1);
  return modeEcb$1.exports;
}
var padAnsix923$1 = { exports: {} };
var padAnsix923 = padAnsix923$1.exports;
var hasRequiredPadAnsix923;
function requirePadAnsix923() {
  if (hasRequiredPadAnsix923) return padAnsix923$1.exports;
  hasRequiredPadAnsix923 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(padAnsix923, function(CryptoJS2) {
      CryptoJS2.pad.AnsiX923 = {
        pad: function(data2, blockSize) {
          var dataSigBytes = data2.sigBytes;
          var blockSizeBytes = blockSize * 4;
          var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
          var lastBytePos = dataSigBytes + nPaddingBytes - 1;
          data2.clamp();
          data2.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8;
          data2.sigBytes += nPaddingBytes;
        },
        unpad: function(data2) {
          var nPaddingBytes = data2.words[data2.sigBytes - 1 >>> 2] & 255;
          data2.sigBytes -= nPaddingBytes;
        }
      };
      return CryptoJS2.pad.Ansix923;
    });
  })(padAnsix923$1);
  return padAnsix923$1.exports;
}
var padIso10126$1 = { exports: {} };
var padIso10126 = padIso10126$1.exports;
var hasRequiredPadIso10126;
function requirePadIso10126() {
  if (hasRequiredPadIso10126) return padIso10126$1.exports;
  hasRequiredPadIso10126 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(padIso10126, function(CryptoJS2) {
      CryptoJS2.pad.Iso10126 = {
        pad: function(data2, blockSize) {
          var blockSizeBytes = blockSize * 4;
          var nPaddingBytes = blockSizeBytes - data2.sigBytes % blockSizeBytes;
          data2.concat(CryptoJS2.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS2.lib.WordArray.create([nPaddingBytes << 24], 1));
        },
        unpad: function(data2) {
          var nPaddingBytes = data2.words[data2.sigBytes - 1 >>> 2] & 255;
          data2.sigBytes -= nPaddingBytes;
        }
      };
      return CryptoJS2.pad.Iso10126;
    });
  })(padIso10126$1);
  return padIso10126$1.exports;
}
var padIso97971$1 = { exports: {} };
var padIso97971 = padIso97971$1.exports;
var hasRequiredPadIso97971;
function requirePadIso97971() {
  if (hasRequiredPadIso97971) return padIso97971$1.exports;
  hasRequiredPadIso97971 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(padIso97971, function(CryptoJS2) {
      CryptoJS2.pad.Iso97971 = {
        pad: function(data2, blockSize) {
          data2.concat(CryptoJS2.lib.WordArray.create([2147483648], 1));
          CryptoJS2.pad.ZeroPadding.pad(data2, blockSize);
        },
        unpad: function(data2) {
          CryptoJS2.pad.ZeroPadding.unpad(data2);
          data2.sigBytes--;
        }
      };
      return CryptoJS2.pad.Iso97971;
    });
  })(padIso97971$1);
  return padIso97971$1.exports;
}
var padZeropadding$1 = { exports: {} };
var padZeropadding = padZeropadding$1.exports;
var hasRequiredPadZeropadding;
function requirePadZeropadding() {
  if (hasRequiredPadZeropadding) return padZeropadding$1.exports;
  hasRequiredPadZeropadding = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(padZeropadding, function(CryptoJS2) {
      CryptoJS2.pad.ZeroPadding = {
        pad: function(data2, blockSize) {
          var blockSizeBytes = blockSize * 4;
          data2.clamp();
          data2.sigBytes += blockSizeBytes - (data2.sigBytes % blockSizeBytes || blockSizeBytes);
        },
        unpad: function(data2) {
          var dataWords = data2.words;
          var i2 = data2.sigBytes - 1;
          for (var i2 = data2.sigBytes - 1; i2 >= 0; i2--) {
            if (dataWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255) {
              data2.sigBytes = i2 + 1;
              break;
            }
          }
        }
      };
      return CryptoJS2.pad.ZeroPadding;
    });
  })(padZeropadding$1);
  return padZeropadding$1.exports;
}
var padNopadding$1 = { exports: {} };
var padNopadding = padNopadding$1.exports;
var hasRequiredPadNopadding;
function requirePadNopadding() {
  if (hasRequiredPadNopadding) return padNopadding$1.exports;
  hasRequiredPadNopadding = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(padNopadding, function(CryptoJS2) {
      CryptoJS2.pad.NoPadding = {
        pad: function() {
        },
        unpad: function() {
        }
      };
      return CryptoJS2.pad.NoPadding;
    });
  })(padNopadding$1);
  return padNopadding$1.exports;
}
var formatHex$1 = { exports: {} };
var formatHex = formatHex$1.exports;
var hasRequiredFormatHex;
function requireFormatHex() {
  if (hasRequiredFormatHex) return formatHex$1.exports;
  hasRequiredFormatHex = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireCipherCore());
      }
    })(formatHex, function(CryptoJS2) {
      (function(undefined$1) {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var CipherParams = C_lib.CipherParams;
        var C_enc = C2.enc;
        var Hex2 = C_enc.Hex;
        var C_format = C2.format;
        C_format.Hex = {
          /**
           * Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
           *
           * @param {CipherParams} cipherParams The cipher params object.
           *
           * @return {string} The hexadecimally encoded string.
           *
           * @static
           *
           * @example
           *
           *     var hexString = CryptoJS.format.Hex.stringify(cipherParams);
           */
          stringify: function(cipherParams) {
            return cipherParams.ciphertext.toString(Hex2);
          },
          /**
           * Converts a hexadecimally encoded ciphertext string to a cipher params object.
           *
           * @param {string} input The hexadecimally encoded string.
           *
           * @return {CipherParams} The cipher params object.
           *
           * @static
           *
           * @example
           *
           *     var cipherParams = CryptoJS.format.Hex.parse(hexString);
           */
          parse: function(input) {
            var ciphertext = Hex2.parse(input);
            return CipherParams.create({ ciphertext });
          }
        };
      })();
      return CryptoJS2.format.Hex;
    });
  })(formatHex$1);
  return formatHex$1.exports;
}
var aes$1 = { exports: {} };
var aes = aes$1.exports;
var hasRequiredAes;
function requireAes() {
  if (hasRequiredAes) return aes$1.exports;
  hasRequiredAes = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(aes, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C2.algo;
        var SBOX = [];
        var INV_SBOX = [];
        var SUB_MIX_0 = [];
        var SUB_MIX_1 = [];
        var SUB_MIX_2 = [];
        var SUB_MIX_3 = [];
        var INV_SUB_MIX_0 = [];
        var INV_SUB_MIX_1 = [];
        var INV_SUB_MIX_2 = [];
        var INV_SUB_MIX_3 = [];
        (function() {
          var d = [];
          for (var i2 = 0; i2 < 256; i2++) {
            if (i2 < 128) {
              d[i2] = i2 << 1;
            } else {
              d[i2] = i2 << 1 ^ 283;
            }
          }
          var x2 = 0;
          var xi = 0;
          for (var i2 = 0; i2 < 256; i2++) {
            var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
            sx = sx >>> 8 ^ sx & 255 ^ 99;
            SBOX[x2] = sx;
            INV_SBOX[sx] = x2;
            var x22 = d[x2];
            var x4 = d[x22];
            var x8 = d[x4];
            var t2 = d[sx] * 257 ^ sx * 16843008;
            SUB_MIX_0[x2] = t2 << 24 | t2 >>> 8;
            SUB_MIX_1[x2] = t2 << 16 | t2 >>> 16;
            SUB_MIX_2[x2] = t2 << 8 | t2 >>> 24;
            SUB_MIX_3[x2] = t2;
            var t2 = x8 * 16843009 ^ x4 * 65537 ^ x22 * 257 ^ x2 * 16843008;
            INV_SUB_MIX_0[sx] = t2 << 24 | t2 >>> 8;
            INV_SUB_MIX_1[sx] = t2 << 16 | t2 >>> 16;
            INV_SUB_MIX_2[sx] = t2 << 8 | t2 >>> 24;
            INV_SUB_MIX_3[sx] = t2;
            if (!x2) {
              x2 = xi = 1;
            } else {
              x2 = x22 ^ d[d[d[x8 ^ x22]]];
              xi ^= d[d[xi]];
            }
          }
        })();
        var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54];
        var AES = C_algo.AES = BlockCipher.extend({
          _doReset: function() {
            var t2;
            if (this._nRounds && this._keyPriorReset === this._key) {
              return;
            }
            var key2 = this._keyPriorReset = this._key;
            var keyWords = key2.words;
            var keySize = key2.sigBytes / 4;
            var nRounds = this._nRounds = keySize + 6;
            var ksRows = (nRounds + 1) * 4;
            var keySchedule = this._keySchedule = [];
            for (var ksRow = 0; ksRow < ksRows; ksRow++) {
              if (ksRow < keySize) {
                keySchedule[ksRow] = keyWords[ksRow];
              } else {
                t2 = keySchedule[ksRow - 1];
                if (!(ksRow % keySize)) {
                  t2 = t2 << 8 | t2 >>> 24;
                  t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
                  t2 ^= RCON[ksRow / keySize | 0] << 24;
                } else if (keySize > 6 && ksRow % keySize == 4) {
                  t2 = SBOX[t2 >>> 24] << 24 | SBOX[t2 >>> 16 & 255] << 16 | SBOX[t2 >>> 8 & 255] << 8 | SBOX[t2 & 255];
                }
                keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t2;
              }
            }
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
              var ksRow = ksRows - invKsRow;
              if (invKsRow % 4) {
                var t2 = keySchedule[ksRow];
              } else {
                var t2 = keySchedule[ksRow - 4];
              }
              if (invKsRow < 4 || ksRow <= 4) {
                invKeySchedule[invKsRow] = t2;
              } else {
                invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t2 >>> 24]] ^ INV_SUB_MIX_1[SBOX[t2 >>> 16 & 255]] ^ INV_SUB_MIX_2[SBOX[t2 >>> 8 & 255]] ^ INV_SUB_MIX_3[SBOX[t2 & 255]];
              }
            }
          },
          encryptBlock: function(M2, offset) {
            this._doCryptBlock(M2, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
          },
          decryptBlock: function(M2, offset) {
            var t2 = M2[offset + 1];
            M2[offset + 1] = M2[offset + 3];
            M2[offset + 3] = t2;
            this._doCryptBlock(M2, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
            var t2 = M2[offset + 1];
            M2[offset + 1] = M2[offset + 3];
            M2[offset + 3] = t2;
          },
          _doCryptBlock: function(M2, offset, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) {
            var nRounds = this._nRounds;
            var s0 = M2[offset] ^ keySchedule[0];
            var s1 = M2[offset + 1] ^ keySchedule[1];
            var s2 = M2[offset + 2] ^ keySchedule[2];
            var s3 = M2[offset + 3] ^ keySchedule[3];
            var ksRow = 4;
            for (var round2 = 1; round2 < nRounds; round2++) {
              var t0 = SUB_MIX_02[s0 >>> 24] ^ SUB_MIX_12[s1 >>> 16 & 255] ^ SUB_MIX_22[s2 >>> 8 & 255] ^ SUB_MIX_32[s3 & 255] ^ keySchedule[ksRow++];
              var t1 = SUB_MIX_02[s1 >>> 24] ^ SUB_MIX_12[s2 >>> 16 & 255] ^ SUB_MIX_22[s3 >>> 8 & 255] ^ SUB_MIX_32[s0 & 255] ^ keySchedule[ksRow++];
              var t2 = SUB_MIX_02[s2 >>> 24] ^ SUB_MIX_12[s3 >>> 16 & 255] ^ SUB_MIX_22[s0 >>> 8 & 255] ^ SUB_MIX_32[s1 & 255] ^ keySchedule[ksRow++];
              var t3 = SUB_MIX_02[s3 >>> 24] ^ SUB_MIX_12[s0 >>> 16 & 255] ^ SUB_MIX_22[s1 >>> 8 & 255] ^ SUB_MIX_32[s2 & 255] ^ keySchedule[ksRow++];
              s0 = t0;
              s1 = t1;
              s2 = t2;
              s3 = t3;
            }
            var t0 = (SBOX2[s0 >>> 24] << 24 | SBOX2[s1 >>> 16 & 255] << 16 | SBOX2[s2 >>> 8 & 255] << 8 | SBOX2[s3 & 255]) ^ keySchedule[ksRow++];
            var t1 = (SBOX2[s1 >>> 24] << 24 | SBOX2[s2 >>> 16 & 255] << 16 | SBOX2[s3 >>> 8 & 255] << 8 | SBOX2[s0 & 255]) ^ keySchedule[ksRow++];
            var t2 = (SBOX2[s2 >>> 24] << 24 | SBOX2[s3 >>> 16 & 255] << 16 | SBOX2[s0 >>> 8 & 255] << 8 | SBOX2[s1 & 255]) ^ keySchedule[ksRow++];
            var t3 = (SBOX2[s3 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s2 & 255]) ^ keySchedule[ksRow++];
            M2[offset] = t0;
            M2[offset + 1] = t1;
            M2[offset + 2] = t2;
            M2[offset + 3] = t3;
          },
          keySize: 256 / 32
        });
        C2.AES = BlockCipher._createHelper(AES);
      })();
      return CryptoJS2.AES;
    });
  })(aes$1);
  return aes$1.exports;
}
var tripledes$1 = { exports: {} };
var tripledes = tripledes$1.exports;
var hasRequiredTripledes;
function requireTripledes() {
  if (hasRequiredTripledes) return tripledes$1.exports;
  hasRequiredTripledes = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(tripledes, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C2.algo;
        var PC1 = [
          57,
          49,
          41,
          33,
          25,
          17,
          9,
          1,
          58,
          50,
          42,
          34,
          26,
          18,
          10,
          2,
          59,
          51,
          43,
          35,
          27,
          19,
          11,
          3,
          60,
          52,
          44,
          36,
          63,
          55,
          47,
          39,
          31,
          23,
          15,
          7,
          62,
          54,
          46,
          38,
          30,
          22,
          14,
          6,
          61,
          53,
          45,
          37,
          29,
          21,
          13,
          5,
          28,
          20,
          12,
          4
        ];
        var PC2 = [
          14,
          17,
          11,
          24,
          1,
          5,
          3,
          28,
          15,
          6,
          21,
          10,
          23,
          19,
          12,
          4,
          26,
          8,
          16,
          7,
          27,
          20,
          13,
          2,
          41,
          52,
          31,
          37,
          47,
          55,
          30,
          40,
          51,
          45,
          33,
          48,
          44,
          49,
          39,
          56,
          34,
          53,
          46,
          42,
          50,
          36,
          29,
          32
        ];
        var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
        var SBOX_P = [
          {
            0: 8421888,
            268435456: 32768,
            536870912: 8421378,
            805306368: 2,
            1073741824: 512,
            1342177280: 8421890,
            1610612736: 8389122,
            1879048192: 8388608,
            2147483648: 514,
            2415919104: 8389120,
            2684354560: 33280,
            2952790016: 8421376,
            3221225472: 32770,
            3489660928: 8388610,
            3758096384: 0,
            4026531840: 33282,
            134217728: 0,
            402653184: 8421890,
            671088640: 33282,
            939524096: 32768,
            1207959552: 8421888,
            1476395008: 512,
            1744830464: 8421378,
            2013265920: 2,
            2281701376: 8389120,
            2550136832: 33280,
            2818572288: 8421376,
            3087007744: 8389122,
            3355443200: 8388610,
            3623878656: 32770,
            3892314112: 514,
            4160749568: 8388608,
            1: 32768,
            268435457: 2,
            536870913: 8421888,
            805306369: 8388608,
            1073741825: 8421378,
            1342177281: 33280,
            1610612737: 512,
            1879048193: 8389122,
            2147483649: 8421890,
            2415919105: 8421376,
            2684354561: 8388610,
            2952790017: 33282,
            3221225473: 514,
            3489660929: 8389120,
            3758096385: 32770,
            4026531841: 0,
            134217729: 8421890,
            402653185: 8421376,
            671088641: 8388608,
            939524097: 512,
            1207959553: 32768,
            1476395009: 8388610,
            1744830465: 2,
            2013265921: 33282,
            2281701377: 32770,
            2550136833: 8389122,
            2818572289: 514,
            3087007745: 8421888,
            3355443201: 8389120,
            3623878657: 0,
            3892314113: 33280,
            4160749569: 8421378
          },
          {
            0: 1074282512,
            16777216: 16384,
            33554432: 524288,
            50331648: 1074266128,
            67108864: 1073741840,
            83886080: 1074282496,
            100663296: 1073758208,
            117440512: 16,
            134217728: 540672,
            150994944: 1073758224,
            167772160: 1073741824,
            184549376: 540688,
            201326592: 524304,
            218103808: 0,
            234881024: 16400,
            251658240: 1074266112,
            8388608: 1073758208,
            25165824: 540688,
            41943040: 16,
            58720256: 1073758224,
            75497472: 1074282512,
            92274688: 1073741824,
            109051904: 524288,
            125829120: 1074266128,
            142606336: 524304,
            159383552: 0,
            176160768: 16384,
            192937984: 1074266112,
            209715200: 1073741840,
            226492416: 540672,
            243269632: 1074282496,
            260046848: 16400,
            268435456: 0,
            285212672: 1074266128,
            301989888: 1073758224,
            318767104: 1074282496,
            335544320: 1074266112,
            352321536: 16,
            369098752: 540688,
            385875968: 16384,
            402653184: 16400,
            419430400: 524288,
            436207616: 524304,
            452984832: 1073741840,
            469762048: 540672,
            486539264: 1073758208,
            503316480: 1073741824,
            520093696: 1074282512,
            276824064: 540688,
            293601280: 524288,
            310378496: 1074266112,
            327155712: 16384,
            343932928: 1073758208,
            360710144: 1074282512,
            377487360: 16,
            394264576: 1073741824,
            411041792: 1074282496,
            427819008: 1073741840,
            444596224: 1073758224,
            461373440: 524304,
            478150656: 0,
            494927872: 16400,
            511705088: 1074266128,
            528482304: 540672
          },
          {
            0: 260,
            1048576: 0,
            2097152: 67109120,
            3145728: 65796,
            4194304: 65540,
            5242880: 67108868,
            6291456: 67174660,
            7340032: 67174400,
            8388608: 67108864,
            9437184: 67174656,
            10485760: 65792,
            11534336: 67174404,
            12582912: 67109124,
            13631488: 65536,
            14680064: 4,
            15728640: 256,
            524288: 67174656,
            1572864: 67174404,
            2621440: 0,
            3670016: 67109120,
            4718592: 67108868,
            5767168: 65536,
            6815744: 65540,
            7864320: 260,
            8912896: 4,
            9961472: 256,
            11010048: 67174400,
            12058624: 65796,
            13107200: 65792,
            14155776: 67109124,
            15204352: 67174660,
            16252928: 67108864,
            16777216: 67174656,
            17825792: 65540,
            18874368: 65536,
            19922944: 67109120,
            20971520: 256,
            22020096: 67174660,
            23068672: 67108868,
            24117248: 0,
            25165824: 67109124,
            26214400: 67108864,
            27262976: 4,
            28311552: 65792,
            29360128: 67174400,
            30408704: 260,
            31457280: 65796,
            32505856: 67174404,
            17301504: 67108864,
            18350080: 260,
            19398656: 67174656,
            20447232: 0,
            21495808: 65540,
            22544384: 67109120,
            23592960: 256,
            24641536: 67174404,
            25690112: 65536,
            26738688: 67174660,
            27787264: 65796,
            28835840: 67108868,
            29884416: 67109124,
            30932992: 67174400,
            31981568: 4,
            33030144: 65792
          },
          {
            0: 2151682048,
            65536: 2147487808,
            131072: 4198464,
            196608: 2151677952,
            262144: 0,
            327680: 4198400,
            393216: 2147483712,
            458752: 4194368,
            524288: 2147483648,
            589824: 4194304,
            655360: 64,
            720896: 2147487744,
            786432: 2151678016,
            851968: 4160,
            917504: 4096,
            983040: 2151682112,
            32768: 2147487808,
            98304: 64,
            163840: 2151678016,
            229376: 2147487744,
            294912: 4198400,
            360448: 2151682112,
            425984: 0,
            491520: 2151677952,
            557056: 4096,
            622592: 2151682048,
            688128: 4194304,
            753664: 4160,
            819200: 2147483648,
            884736: 4194368,
            950272: 4198464,
            1015808: 2147483712,
            1048576: 4194368,
            1114112: 4198400,
            1179648: 2147483712,
            1245184: 0,
            1310720: 4160,
            1376256: 2151678016,
            1441792: 2151682048,
            1507328: 2147487808,
            1572864: 2151682112,
            1638400: 2147483648,
            1703936: 2151677952,
            1769472: 4198464,
            1835008: 2147487744,
            1900544: 4194304,
            1966080: 64,
            2031616: 4096,
            1081344: 2151677952,
            1146880: 2151682112,
            1212416: 0,
            1277952: 4198400,
            1343488: 4194368,
            1409024: 2147483648,
            1474560: 2147487808,
            1540096: 64,
            1605632: 2147483712,
            1671168: 4096,
            1736704: 2147487744,
            1802240: 2151678016,
            1867776: 4160,
            1933312: 2151682048,
            1998848: 4194304,
            2064384: 4198464
          },
          {
            0: 128,
            4096: 17039360,
            8192: 262144,
            12288: 536870912,
            16384: 537133184,
            20480: 16777344,
            24576: 553648256,
            28672: 262272,
            32768: 16777216,
            36864: 537133056,
            40960: 536871040,
            45056: 553910400,
            49152: 553910272,
            53248: 0,
            57344: 17039488,
            61440: 553648128,
            2048: 17039488,
            6144: 553648256,
            10240: 128,
            14336: 17039360,
            18432: 262144,
            22528: 537133184,
            26624: 553910272,
            30720: 536870912,
            34816: 537133056,
            38912: 0,
            43008: 553910400,
            47104: 16777344,
            51200: 536871040,
            55296: 553648128,
            59392: 16777216,
            63488: 262272,
            65536: 262144,
            69632: 128,
            73728: 536870912,
            77824: 553648256,
            81920: 16777344,
            86016: 553910272,
            90112: 537133184,
            94208: 16777216,
            98304: 553910400,
            102400: 553648128,
            106496: 17039360,
            110592: 537133056,
            114688: 262272,
            118784: 536871040,
            122880: 0,
            126976: 17039488,
            67584: 553648256,
            71680: 16777216,
            75776: 17039360,
            79872: 537133184,
            83968: 536870912,
            88064: 17039488,
            92160: 128,
            96256: 553910272,
            100352: 262272,
            104448: 553910400,
            108544: 0,
            112640: 553648128,
            116736: 16777344,
            120832: 262144,
            124928: 537133056,
            129024: 536871040
          },
          {
            0: 268435464,
            256: 8192,
            512: 270532608,
            768: 270540808,
            1024: 268443648,
            1280: 2097152,
            1536: 2097160,
            1792: 268435456,
            2048: 0,
            2304: 268443656,
            2560: 2105344,
            2816: 8,
            3072: 270532616,
            3328: 2105352,
            3584: 8200,
            3840: 270540800,
            128: 270532608,
            384: 270540808,
            640: 8,
            896: 2097152,
            1152: 2105352,
            1408: 268435464,
            1664: 268443648,
            1920: 8200,
            2176: 2097160,
            2432: 8192,
            2688: 268443656,
            2944: 270532616,
            3200: 0,
            3456: 270540800,
            3712: 2105344,
            3968: 268435456,
            4096: 268443648,
            4352: 270532616,
            4608: 270540808,
            4864: 8200,
            5120: 2097152,
            5376: 268435456,
            5632: 268435464,
            5888: 2105344,
            6144: 2105352,
            6400: 0,
            6656: 8,
            6912: 270532608,
            7168: 8192,
            7424: 268443656,
            7680: 270540800,
            7936: 2097160,
            4224: 8,
            4480: 2105344,
            4736: 2097152,
            4992: 268435464,
            5248: 268443648,
            5504: 8200,
            5760: 270540808,
            6016: 270532608,
            6272: 270540800,
            6528: 270532616,
            6784: 8192,
            7040: 2105352,
            7296: 2097160,
            7552: 0,
            7808: 268435456,
            8064: 268443656
          },
          {
            0: 1048576,
            16: 33555457,
            32: 1024,
            48: 1049601,
            64: 34604033,
            80: 0,
            96: 1,
            112: 34603009,
            128: 33555456,
            144: 1048577,
            160: 33554433,
            176: 34604032,
            192: 34603008,
            208: 1025,
            224: 1049600,
            240: 33554432,
            8: 34603009,
            24: 0,
            40: 33555457,
            56: 34604032,
            72: 1048576,
            88: 33554433,
            104: 33554432,
            120: 1025,
            136: 1049601,
            152: 33555456,
            168: 34603008,
            184: 1048577,
            200: 1024,
            216: 34604033,
            232: 1,
            248: 1049600,
            256: 33554432,
            272: 1048576,
            288: 33555457,
            304: 34603009,
            320: 1048577,
            336: 33555456,
            352: 34604032,
            368: 1049601,
            384: 1025,
            400: 34604033,
            416: 1049600,
            432: 1,
            448: 0,
            464: 34603008,
            480: 33554433,
            496: 1024,
            264: 1049600,
            280: 33555457,
            296: 34603009,
            312: 1,
            328: 33554432,
            344: 1048576,
            360: 1025,
            376: 34604032,
            392: 33554433,
            408: 34603008,
            424: 0,
            440: 34604033,
            456: 1049601,
            472: 1024,
            488: 33555456,
            504: 1048577
          },
          {
            0: 134219808,
            1: 131072,
            2: 134217728,
            3: 32,
            4: 131104,
            5: 134350880,
            6: 134350848,
            7: 2048,
            8: 134348800,
            9: 134219776,
            10: 133120,
            11: 134348832,
            12: 2080,
            13: 0,
            14: 134217760,
            15: 133152,
            2147483648: 2048,
            2147483649: 134350880,
            2147483650: 134219808,
            2147483651: 134217728,
            2147483652: 134348800,
            2147483653: 133120,
            2147483654: 133152,
            2147483655: 32,
            2147483656: 134217760,
            2147483657: 2080,
            2147483658: 131104,
            2147483659: 134350848,
            2147483660: 0,
            2147483661: 134348832,
            2147483662: 134219776,
            2147483663: 131072,
            16: 133152,
            17: 134350848,
            18: 32,
            19: 2048,
            20: 134219776,
            21: 134217760,
            22: 134348832,
            23: 131072,
            24: 0,
            25: 131104,
            26: 134348800,
            27: 134219808,
            28: 134350880,
            29: 133120,
            30: 2080,
            31: 134217728,
            2147483664: 131072,
            2147483665: 2048,
            2147483666: 134348832,
            2147483667: 133152,
            2147483668: 32,
            2147483669: 134348800,
            2147483670: 134217728,
            2147483671: 134219808,
            2147483672: 134350880,
            2147483673: 134217760,
            2147483674: 134219776,
            2147483675: 0,
            2147483676: 133120,
            2147483677: 2080,
            2147483678: 131104,
            2147483679: 134350848
          }
        ];
        var SBOX_MASK = [
          4160749569,
          528482304,
          33030144,
          2064384,
          129024,
          8064,
          504,
          2147483679
        ];
        var DES = C_algo.DES = BlockCipher.extend({
          _doReset: function() {
            var key2 = this._key;
            var keyWords = key2.words;
            var keyBits = [];
            for (var i2 = 0; i2 < 56; i2++) {
              var keyBitPos = PC1[i2] - 1;
              keyBits[i2] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1;
            }
            var subKeys = this._subKeys = [];
            for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
              var subKey = subKeys[nSubKey] = [];
              var bitShift = BIT_SHIFTS[nSubKey];
              for (var i2 = 0; i2 < 24; i2++) {
                subKey[i2 / 6 | 0] |= keyBits[(PC2[i2] - 1 + bitShift) % 28] << 31 - i2 % 6;
                subKey[4 + (i2 / 6 | 0)] |= keyBits[28 + (PC2[i2 + 24] - 1 + bitShift) % 28] << 31 - i2 % 6;
              }
              subKey[0] = subKey[0] << 1 | subKey[0] >>> 31;
              for (var i2 = 1; i2 < 7; i2++) {
                subKey[i2] = subKey[i2] >>> (i2 - 1) * 4 + 3;
              }
              subKey[7] = subKey[7] << 5 | subKey[7] >>> 27;
            }
            var invSubKeys = this._invSubKeys = [];
            for (var i2 = 0; i2 < 16; i2++) {
              invSubKeys[i2] = subKeys[15 - i2];
            }
          },
          encryptBlock: function(M2, offset) {
            this._doCryptBlock(M2, offset, this._subKeys);
          },
          decryptBlock: function(M2, offset) {
            this._doCryptBlock(M2, offset, this._invSubKeys);
          },
          _doCryptBlock: function(M2, offset, subKeys) {
            this._lBlock = M2[offset];
            this._rBlock = M2[offset + 1];
            exchangeLR.call(this, 4, 252645135);
            exchangeLR.call(this, 16, 65535);
            exchangeRL.call(this, 2, 858993459);
            exchangeRL.call(this, 8, 16711935);
            exchangeLR.call(this, 1, 1431655765);
            for (var round2 = 0; round2 < 16; round2++) {
              var subKey = subKeys[round2];
              var lBlock = this._lBlock;
              var rBlock = this._rBlock;
              var f2 = 0;
              for (var i2 = 0; i2 < 8; i2++) {
                f2 |= SBOX_P[i2][((rBlock ^ subKey[i2]) & SBOX_MASK[i2]) >>> 0];
              }
              this._lBlock = rBlock;
              this._rBlock = lBlock ^ f2;
            }
            var t2 = this._lBlock;
            this._lBlock = this._rBlock;
            this._rBlock = t2;
            exchangeLR.call(this, 1, 1431655765);
            exchangeRL.call(this, 8, 16711935);
            exchangeRL.call(this, 2, 858993459);
            exchangeLR.call(this, 16, 65535);
            exchangeLR.call(this, 4, 252645135);
            M2[offset] = this._lBlock;
            M2[offset + 1] = this._rBlock;
          },
          keySize: 64 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        function exchangeLR(offset, mask) {
          var t2 = (this._lBlock >>> offset ^ this._rBlock) & mask;
          this._rBlock ^= t2;
          this._lBlock ^= t2 << offset;
        }
        function exchangeRL(offset, mask) {
          var t2 = (this._rBlock >>> offset ^ this._lBlock) & mask;
          this._lBlock ^= t2;
          this._rBlock ^= t2 << offset;
        }
        C2.DES = BlockCipher._createHelper(DES);
        var TripleDES = C_algo.TripleDES = BlockCipher.extend({
          _doReset: function() {
            var key2 = this._key;
            var keyWords = key2.words;
            if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) {
              throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");
            }
            var key1 = keyWords.slice(0, 2);
            var key22 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4);
            var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6);
            this._des1 = DES.createEncryptor(WordArray.create(key1));
            this._des2 = DES.createEncryptor(WordArray.create(key22));
            this._des3 = DES.createEncryptor(WordArray.create(key3));
          },
          encryptBlock: function(M2, offset) {
            this._des1.encryptBlock(M2, offset);
            this._des2.decryptBlock(M2, offset);
            this._des3.encryptBlock(M2, offset);
          },
          decryptBlock: function(M2, offset) {
            this._des3.decryptBlock(M2, offset);
            this._des2.encryptBlock(M2, offset);
            this._des1.decryptBlock(M2, offset);
          },
          keySize: 192 / 32,
          ivSize: 64 / 32,
          blockSize: 64 / 32
        });
        C2.TripleDES = BlockCipher._createHelper(TripleDES);
      })();
      return CryptoJS2.TripleDES;
    });
  })(tripledes$1);
  return tripledes$1.exports;
}
var rc4$1 = { exports: {} };
var rc4 = rc4$1.exports;
var hasRequiredRc4;
function requireRc4() {
  if (hasRequiredRc4) return rc4$1.exports;
  hasRequiredRc4 = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(rc4, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C2.algo;
        var RC4 = C_algo.RC4 = StreamCipher.extend({
          _doReset: function() {
            var key2 = this._key;
            var keyWords = key2.words;
            var keySigBytes = key2.sigBytes;
            var S2 = this._S = [];
            for (var i2 = 0; i2 < 256; i2++) {
              S2[i2] = i2;
            }
            for (var i2 = 0, j = 0; i2 < 256; i2++) {
              var keyByteIndex = i2 % keySigBytes;
              var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255;
              j = (j + S2[i2] + keyByte) % 256;
              var t2 = S2[i2];
              S2[i2] = S2[j];
              S2[j] = t2;
            }
            this._i = this._j = 0;
          },
          _doProcessBlock: function(M2, offset) {
            M2[offset] ^= generateKeystreamWord.call(this);
          },
          keySize: 256 / 32,
          ivSize: 0
        });
        function generateKeystreamWord() {
          var S2 = this._S;
          var i2 = this._i;
          var j = this._j;
          var keystreamWord = 0;
          for (var n2 = 0; n2 < 4; n2++) {
            i2 = (i2 + 1) % 256;
            j = (j + S2[i2]) % 256;
            var t2 = S2[i2];
            S2[i2] = S2[j];
            S2[j] = t2;
            keystreamWord |= S2[(S2[i2] + S2[j]) % 256] << 24 - n2 * 8;
          }
          this._i = i2;
          this._j = j;
          return keystreamWord;
        }
        C2.RC4 = StreamCipher._createHelper(RC4);
        var RC4Drop = C_algo.RC4Drop = RC4.extend({
          /**
           * Configuration options.
           *
           * @property {number} drop The number of keystream words to drop. Default 192
           */
          cfg: RC4.cfg.extend({
            drop: 192
          }),
          _doReset: function() {
            RC4._doReset.call(this);
            for (var i2 = this.cfg.drop; i2 > 0; i2--) {
              generateKeystreamWord.call(this);
            }
          }
        });
        C2.RC4Drop = StreamCipher._createHelper(RC4Drop);
      })();
      return CryptoJS2.RC4;
    });
  })(rc4$1);
  return rc4$1.exports;
}
var rabbit$1 = { exports: {} };
var rabbit = rabbit$1.exports;
var hasRequiredRabbit;
function requireRabbit() {
  if (hasRequiredRabbit) return rabbit$1.exports;
  hasRequiredRabbit = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(rabbit, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C2.algo;
        var S2 = [];
        var C_ = [];
        var G2 = [];
        var Rabbit = C_algo.Rabbit = StreamCipher.extend({
          _doReset: function() {
            var K = this._key.words;
            var iv = this.cfg.iv;
            for (var i2 = 0; i2 < 4; i2++) {
              K[i2] = (K[i2] << 8 | K[i2] >>> 24) & 16711935 | (K[i2] << 24 | K[i2] >>> 8) & 4278255360;
            }
            var X = this._X = [
              K[0],
              K[3] << 16 | K[2] >>> 16,
              K[1],
              K[0] << 16 | K[3] >>> 16,
              K[2],
              K[1] << 16 | K[0] >>> 16,
              K[3],
              K[2] << 16 | K[1] >>> 16
            ];
            var C3 = this._C = [
              K[2] << 16 | K[2] >>> 16,
              K[0] & 4294901760 | K[1] & 65535,
              K[3] << 16 | K[3] >>> 16,
              K[1] & 4294901760 | K[2] & 65535,
              K[0] << 16 | K[0] >>> 16,
              K[2] & 4294901760 | K[3] & 65535,
              K[1] << 16 | K[1] >>> 16,
              K[3] & 4294901760 | K[0] & 65535
            ];
            this._b = 0;
            for (var i2 = 0; i2 < 4; i2++) {
              nextState.call(this);
            }
            for (var i2 = 0; i2 < 8; i2++) {
              C3[i2] ^= X[i2 + 4 & 7];
            }
            if (iv) {
              var IV = iv.words;
              var IV_0 = IV[0];
              var IV_1 = IV[1];
              var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
              var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
              var i1 = i0 >>> 16 | i22 & 4294901760;
              var i3 = i22 << 16 | i0 & 65535;
              C3[0] ^= i0;
              C3[1] ^= i1;
              C3[2] ^= i22;
              C3[3] ^= i3;
              C3[4] ^= i0;
              C3[5] ^= i1;
              C3[6] ^= i22;
              C3[7] ^= i3;
              for (var i2 = 0; i2 < 4; i2++) {
                nextState.call(this);
              }
            }
          },
          _doProcessBlock: function(M2, offset) {
            var X = this._X;
            nextState.call(this);
            S2[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
            S2[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
            S2[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
            S2[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
            for (var i2 = 0; i2 < 4; i2++) {
              S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
              M2[offset + i2] ^= S2[i2];
            }
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function nextState() {
          var X = this._X;
          var C3 = this._C;
          for (var i2 = 0; i2 < 8; i2++) {
            C_[i2] = C3[i2];
          }
          C3[0] = C3[0] + 1295307597 + this._b | 0;
          C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
          C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
          C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
          C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
          C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
          C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
          C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
          this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
          for (var i2 = 0; i2 < 8; i2++) {
            var gx = X[i2] + C3[i2];
            var ga = gx & 65535;
            var gb = gx >>> 16;
            var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
            var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
            G2[i2] = gh ^ gl;
          }
          X[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
          X[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
          X[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
          X[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
          X[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
          X[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
          X[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
          X[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
        }
        C2.Rabbit = StreamCipher._createHelper(Rabbit);
      })();
      return CryptoJS2.Rabbit;
    });
  })(rabbit$1);
  return rabbit$1.exports;
}
var rabbitLegacy$1 = { exports: {} };
var rabbitLegacy = rabbitLegacy$1.exports;
var hasRequiredRabbitLegacy;
function requireRabbitLegacy() {
  if (hasRequiredRabbitLegacy) return rabbitLegacy$1.exports;
  hasRequiredRabbitLegacy = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(rabbitLegacy, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var StreamCipher = C_lib.StreamCipher;
        var C_algo = C2.algo;
        var S2 = [];
        var C_ = [];
        var G2 = [];
        var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
          _doReset: function() {
            var K = this._key.words;
            var iv = this.cfg.iv;
            var X = this._X = [
              K[0],
              K[3] << 16 | K[2] >>> 16,
              K[1],
              K[0] << 16 | K[3] >>> 16,
              K[2],
              K[1] << 16 | K[0] >>> 16,
              K[3],
              K[2] << 16 | K[1] >>> 16
            ];
            var C3 = this._C = [
              K[2] << 16 | K[2] >>> 16,
              K[0] & 4294901760 | K[1] & 65535,
              K[3] << 16 | K[3] >>> 16,
              K[1] & 4294901760 | K[2] & 65535,
              K[0] << 16 | K[0] >>> 16,
              K[2] & 4294901760 | K[3] & 65535,
              K[1] << 16 | K[1] >>> 16,
              K[3] & 4294901760 | K[0] & 65535
            ];
            this._b = 0;
            for (var i2 = 0; i2 < 4; i2++) {
              nextState.call(this);
            }
            for (var i2 = 0; i2 < 8; i2++) {
              C3[i2] ^= X[i2 + 4 & 7];
            }
            if (iv) {
              var IV = iv.words;
              var IV_0 = IV[0];
              var IV_1 = IV[1];
              var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360;
              var i22 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360;
              var i1 = i0 >>> 16 | i22 & 4294901760;
              var i3 = i22 << 16 | i0 & 65535;
              C3[0] ^= i0;
              C3[1] ^= i1;
              C3[2] ^= i22;
              C3[3] ^= i3;
              C3[4] ^= i0;
              C3[5] ^= i1;
              C3[6] ^= i22;
              C3[7] ^= i3;
              for (var i2 = 0; i2 < 4; i2++) {
                nextState.call(this);
              }
            }
          },
          _doProcessBlock: function(M2, offset) {
            var X = this._X;
            nextState.call(this);
            S2[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16;
            S2[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16;
            S2[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16;
            S2[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16;
            for (var i2 = 0; i2 < 4; i2++) {
              S2[i2] = (S2[i2] << 8 | S2[i2] >>> 24) & 16711935 | (S2[i2] << 24 | S2[i2] >>> 8) & 4278255360;
              M2[offset + i2] ^= S2[i2];
            }
          },
          blockSize: 128 / 32,
          ivSize: 64 / 32
        });
        function nextState() {
          var X = this._X;
          var C3 = this._C;
          for (var i2 = 0; i2 < 8; i2++) {
            C_[i2] = C3[i2];
          }
          C3[0] = C3[0] + 1295307597 + this._b | 0;
          C3[1] = C3[1] + 3545052371 + (C3[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0;
          C3[2] = C3[2] + 886263092 + (C3[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0;
          C3[3] = C3[3] + 1295307597 + (C3[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0;
          C3[4] = C3[4] + 3545052371 + (C3[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0;
          C3[5] = C3[5] + 886263092 + (C3[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0;
          C3[6] = C3[6] + 1295307597 + (C3[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0;
          C3[7] = C3[7] + 3545052371 + (C3[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0;
          this._b = C3[7] >>> 0 < C_[7] >>> 0 ? 1 : 0;
          for (var i2 = 0; i2 < 8; i2++) {
            var gx = X[i2] + C3[i2];
            var ga = gx & 65535;
            var gb = gx >>> 16;
            var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb;
            var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0);
            G2[i2] = gh ^ gl;
          }
          X[0] = G2[0] + (G2[7] << 16 | G2[7] >>> 16) + (G2[6] << 16 | G2[6] >>> 16) | 0;
          X[1] = G2[1] + (G2[0] << 8 | G2[0] >>> 24) + G2[7] | 0;
          X[2] = G2[2] + (G2[1] << 16 | G2[1] >>> 16) + (G2[0] << 16 | G2[0] >>> 16) | 0;
          X[3] = G2[3] + (G2[2] << 8 | G2[2] >>> 24) + G2[1] | 0;
          X[4] = G2[4] + (G2[3] << 16 | G2[3] >>> 16) + (G2[2] << 16 | G2[2] >>> 16) | 0;
          X[5] = G2[5] + (G2[4] << 8 | G2[4] >>> 24) + G2[3] | 0;
          X[6] = G2[6] + (G2[5] << 16 | G2[5] >>> 16) + (G2[4] << 16 | G2[4] >>> 16) | 0;
          X[7] = G2[7] + (G2[6] << 8 | G2[6] >>> 24) + G2[5] | 0;
        }
        C2.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
      })();
      return CryptoJS2.RabbitLegacy;
    });
  })(rabbitLegacy$1);
  return rabbitLegacy$1.exports;
}
var blowfish$1 = { exports: {} };
var blowfish = blowfish$1.exports;
var hasRequiredBlowfish;
function requireBlowfish() {
  if (hasRequiredBlowfish) return blowfish$1.exports;
  hasRequiredBlowfish = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireEncBase64(), requireMd5(), requireEvpkdf(), requireCipherCore());
      }
    })(blowfish, function(CryptoJS2) {
      (function() {
        var C2 = CryptoJS2;
        var C_lib = C2.lib;
        var BlockCipher = C_lib.BlockCipher;
        var C_algo = C2.algo;
        const N2 = 16;
        const ORIG_P = [
          608135816,
          2242054355,
          320440878,
          57701188,
          2752067618,
          698298832,
          137296536,
          3964562569,
          1160258022,
          953160567,
          3193202383,
          887688300,
          3232508343,
          3380367581,
          1065670069,
          3041331479,
          2450970073,
          2306472731
        ];
        const ORIG_S = [
          [
            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
          ],
          [
            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
          ],
          [
            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
          ],
          [
            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
          ]
        ];
        var BLOWFISH_CTX = {
          pbox: [],
          sbox: []
        };
        function F(ctx, x2) {
          let a2 = x2 >> 24 & 255;
          let b2 = x2 >> 16 & 255;
          let c2 = x2 >> 8 & 255;
          let d = x2 & 255;
          let y2 = ctx.sbox[0][a2] + ctx.sbox[1][b2];
          y2 = y2 ^ ctx.sbox[2][c2];
          y2 = y2 + ctx.sbox[3][d];
          return y2;
        }
        function BlowFish_Encrypt(ctx, left, right) {
          let Xl = left;
          let Xr = right;
          let temp;
          for (let i2 = 0; i2 < N2; ++i2) {
            Xl = Xl ^ ctx.pbox[i2];
            Xr = F(ctx, Xl) ^ Xr;
            temp = Xl;
            Xl = Xr;
            Xr = temp;
          }
          temp = Xl;
          Xl = Xr;
          Xr = temp;
          Xr = Xr ^ ctx.pbox[N2];
          Xl = Xl ^ ctx.pbox[N2 + 1];
          return { left: Xl, right: Xr };
        }
        function BlowFish_Decrypt(ctx, left, right) {
          let Xl = left;
          let Xr = right;
          let temp;
          for (let i2 = N2 + 1; i2 > 1; --i2) {
            Xl = Xl ^ ctx.pbox[i2];
            Xr = F(ctx, Xl) ^ Xr;
            temp = Xl;
            Xl = Xr;
            Xr = temp;
          }
          temp = Xl;
          Xl = Xr;
          Xr = temp;
          Xr = Xr ^ ctx.pbox[1];
          Xl = Xl ^ ctx.pbox[0];
          return { left: Xl, right: Xr };
        }
        function BlowFishInit(ctx, key2, keysize) {
          for (let Row = 0; Row < 4; Row++) {
            ctx.sbox[Row] = [];
            for (let Col = 0; Col < 256; Col++) {
              ctx.sbox[Row][Col] = ORIG_S[Row][Col];
            }
          }
          let keyIndex = 0;
          for (let index2 = 0; index2 < N2 + 2; index2++) {
            ctx.pbox[index2] = ORIG_P[index2] ^ key2[keyIndex];
            keyIndex++;
            if (keyIndex >= keysize) {
              keyIndex = 0;
            }
          }
          let Data1 = 0;
          let Data2 = 0;
          let res = 0;
          for (let i2 = 0; i2 < N2 + 2; i2 += 2) {
            res = BlowFish_Encrypt(ctx, Data1, Data2);
            Data1 = res.left;
            Data2 = res.right;
            ctx.pbox[i2] = Data1;
            ctx.pbox[i2 + 1] = Data2;
          }
          for (let i2 = 0; i2 < 4; i2++) {
            for (let j = 0; j < 256; j += 2) {
              res = BlowFish_Encrypt(ctx, Data1, Data2);
              Data1 = res.left;
              Data2 = res.right;
              ctx.sbox[i2][j] = Data1;
              ctx.sbox[i2][j + 1] = Data2;
            }
          }
          return true;
        }
        var Blowfish = C_algo.Blowfish = BlockCipher.extend({
          _doReset: function() {
            if (this._keyPriorReset === this._key) {
              return;
            }
            var key2 = this._keyPriorReset = this._key;
            var keyWords = key2.words;
            var keySize = key2.sigBytes / 4;
            BlowFishInit(BLOWFISH_CTX, keyWords, keySize);
          },
          encryptBlock: function(M2, offset) {
            var res = BlowFish_Encrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
            M2[offset] = res.left;
            M2[offset + 1] = res.right;
          },
          decryptBlock: function(M2, offset) {
            var res = BlowFish_Decrypt(BLOWFISH_CTX, M2[offset], M2[offset + 1]);
            M2[offset] = res.left;
            M2[offset + 1] = res.right;
          },
          blockSize: 64 / 32,
          keySize: 128 / 32,
          ivSize: 64 / 32
        });
        C2.Blowfish = BlockCipher._createHelper(Blowfish);
      })();
      return CryptoJS2.Blowfish;
    });
  })(blowfish$1);
  return blowfish$1.exports;
}
var cryptoJs = cryptoJs$1.exports;
var hasRequiredCryptoJs;
function requireCryptoJs() {
  if (hasRequiredCryptoJs) return cryptoJs$1.exports;
  hasRequiredCryptoJs = 1;
  (function(module2, exports) {
    (function(root, factory, undef) {
      {
        module2.exports = factory(requireCore(), requireX64Core(), requireLibTypedarrays(), requireEncUtf16(), requireEncBase64(), requireEncBase64url(), requireMd5(), requireSha1(), requireSha256(), requireSha224(), requireSha512(), requireSha384(), requireSha3(), requireRipemd160(), requireHmac(), requirePbkdf2(), requireEvpkdf(), requireCipherCore(), requireModeCfb(), requireModeCtr(), requireModeCtrGladman(), requireModeOfb(), requireModeEcb(), requirePadAnsix923(), requirePadIso10126(), requirePadIso97971(), requirePadZeropadding(), requirePadNopadding(), requireFormatHex(), requireAes(), requireTripledes(), requireRc4(), requireRabbit(), requireRabbitLegacy(), requireBlowfish());
      }
    })(cryptoJs, function(CryptoJS2) {
      return CryptoJS2;
    });
  })(cryptoJs$1);
  return cryptoJs$1.exports;
}
var cryptoJsExports = requireCryptoJs();
const CryptoJS = /* @__PURE__ */ getDefaultExportFromCjs$1(cryptoJsExports);
var __assign$4 = function() {
  __assign$4 = Object.assign || function __assign2(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$4.apply(this, arguments);
};
function __awaiter$e(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator$e(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
}
function __spreadArray$1(to2, from2, pack) {
  if (pack || arguments.length === 2) for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
    if (ar || !(i2 in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i2);
      ar[i2] = from2[i2];
    }
  }
  return to2.concat(ar || Array.prototype.slice.call(from2));
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e4 = new Error(message);
  return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
};
var version = "3.4.2";
function wait(durationMs, resolveWith) {
  return new Promise(function(resolve2) {
    return setTimeout(resolve2, durationMs, resolveWith);
  });
}
function requestIdleCallbackIfAvailable(fallbackTimeout, deadlineTimeout) {
  if (deadlineTimeout === void 0) {
    deadlineTimeout = Infinity;
  }
  var requestIdleCallback = window.requestIdleCallback;
  if (requestIdleCallback) {
    return new Promise(function(resolve2) {
      return requestIdleCallback.call(window, function() {
        return resolve2();
      }, { timeout: deadlineTimeout });
    });
  } else {
    return wait(Math.min(fallbackTimeout, deadlineTimeout));
  }
}
function isPromise(value) {
  return !!value && typeof value.then === "function";
}
function awaitIfAsync(action, callback) {
  try {
    var returnedValue = action();
    if (isPromise(returnedValue)) {
      returnedValue.then(function(result) {
        return callback(true, result);
      }, function(error) {
        return callback(false, error);
      });
    } else {
      callback(true, returnedValue);
    }
  } catch (error) {
    callback(false, error);
  }
}
function mapWithBreaks(items2, callback, loopReleaseInterval) {
  if (loopReleaseInterval === void 0) {
    loopReleaseInterval = 16;
  }
  return __awaiter$e(this, void 0, void 0, function() {
    var results, lastLoopReleaseTime, i2, now;
    return __generator$e(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          results = Array(items2.length);
          lastLoopReleaseTime = Date.now();
          i2 = 0;
          _a3.label = 1;
        case 1:
          if (!(i2 < items2.length)) return [3, 4];
          results[i2] = callback(items2[i2], i2);
          now = Date.now();
          if (!(now >= lastLoopReleaseTime + loopReleaseInterval)) return [3, 3];
          lastLoopReleaseTime = now;
          return [4, wait(0)];
        case 2:
          _a3.sent();
          _a3.label = 3;
        case 3:
          ++i2;
          return [3, 1];
        case 4:
          return [2, results];
      }
    });
  });
}
function suppressUnhandledRejectionWarning(promise) {
  promise.then(void 0, function() {
    return void 0;
  });
}
function x64Add(m, n2) {
  m = [m[0] >>> 16, m[0] & 65535, m[1] >>> 16, m[1] & 65535];
  n2 = [n2[0] >>> 16, n2[0] & 65535, n2[1] >>> 16, n2[1] & 65535];
  var o2 = [0, 0, 0, 0];
  o2[3] += m[3] + n2[3];
  o2[2] += o2[3] >>> 16;
  o2[3] &= 65535;
  o2[2] += m[2] + n2[2];
  o2[1] += o2[2] >>> 16;
  o2[2] &= 65535;
  o2[1] += m[1] + n2[1];
  o2[0] += o2[1] >>> 16;
  o2[1] &= 65535;
  o2[0] += m[0] + n2[0];
  o2[0] &= 65535;
  return [o2[0] << 16 | o2[1], o2[2] << 16 | o2[3]];
}
function x64Multiply(m, n2) {
  m = [m[0] >>> 16, m[0] & 65535, m[1] >>> 16, m[1] & 65535];
  n2 = [n2[0] >>> 16, n2[0] & 65535, n2[1] >>> 16, n2[1] & 65535];
  var o2 = [0, 0, 0, 0];
  o2[3] += m[3] * n2[3];
  o2[2] += o2[3] >>> 16;
  o2[3] &= 65535;
  o2[2] += m[2] * n2[3];
  o2[1] += o2[2] >>> 16;
  o2[2] &= 65535;
  o2[2] += m[3] * n2[2];
  o2[1] += o2[2] >>> 16;
  o2[2] &= 65535;
  o2[1] += m[1] * n2[3];
  o2[0] += o2[1] >>> 16;
  o2[1] &= 65535;
  o2[1] += m[2] * n2[2];
  o2[0] += o2[1] >>> 16;
  o2[1] &= 65535;
  o2[1] += m[3] * n2[1];
  o2[0] += o2[1] >>> 16;
  o2[1] &= 65535;
  o2[0] += m[0] * n2[3] + m[1] * n2[2] + m[2] * n2[1] + m[3] * n2[0];
  o2[0] &= 65535;
  return [o2[0] << 16 | o2[1], o2[2] << 16 | o2[3]];
}
function x64Rotl(m, n2) {
  n2 %= 64;
  if (n2 === 32) {
    return [m[1], m[0]];
  } else if (n2 < 32) {
    return [m[0] << n2 | m[1] >>> 32 - n2, m[1] << n2 | m[0] >>> 32 - n2];
  } else {
    n2 -= 32;
    return [m[1] << n2 | m[0] >>> 32 - n2, m[0] << n2 | m[1] >>> 32 - n2];
  }
}
function x64LeftShift(m, n2) {
  n2 %= 64;
  if (n2 === 0) {
    return m;
  } else if (n2 < 32) {
    return [m[0] << n2 | m[1] >>> 32 - n2, m[1] << n2];
  } else {
    return [m[1] << n2 - 32, 0];
  }
}
function x64Xor(m, n2) {
  return [m[0] ^ n2[0], m[1] ^ n2[1]];
}
function x64Fmix(h2) {
  h2 = x64Xor(h2, [0, h2[0] >>> 1]);
  h2 = x64Multiply(h2, [4283543511, 3981806797]);
  h2 = x64Xor(h2, [0, h2[0] >>> 1]);
  h2 = x64Multiply(h2, [3301882366, 444984403]);
  h2 = x64Xor(h2, [0, h2[0] >>> 1]);
  return h2;
}
function x64hash128(key2, seed) {
  key2 = key2 || "";
  seed = seed || 0;
  var remainder = key2.length % 16;
  var bytes = key2.length - remainder;
  var h1 = [0, seed];
  var h2 = [0, seed];
  var k1 = [0, 0];
  var k2 = [0, 0];
  var c1 = [2277735313, 289559509];
  var c2 = [1291169091, 658871167];
  var i2;
  for (i2 = 0; i2 < bytes; i2 = i2 + 16) {
    k1 = [
      key2.charCodeAt(i2 + 4) & 255 | (key2.charCodeAt(i2 + 5) & 255) << 8 | (key2.charCodeAt(i2 + 6) & 255) << 16 | (key2.charCodeAt(i2 + 7) & 255) << 24,
      key2.charCodeAt(i2) & 255 | (key2.charCodeAt(i2 + 1) & 255) << 8 | (key2.charCodeAt(i2 + 2) & 255) << 16 | (key2.charCodeAt(i2 + 3) & 255) << 24
    ];
    k2 = [
      key2.charCodeAt(i2 + 12) & 255 | (key2.charCodeAt(i2 + 13) & 255) << 8 | (key2.charCodeAt(i2 + 14) & 255) << 16 | (key2.charCodeAt(i2 + 15) & 255) << 24,
      key2.charCodeAt(i2 + 8) & 255 | (key2.charCodeAt(i2 + 9) & 255) << 8 | (key2.charCodeAt(i2 + 10) & 255) << 16 | (key2.charCodeAt(i2 + 11) & 255) << 24
    ];
    k1 = x64Multiply(k1, c1);
    k1 = x64Rotl(k1, 31);
    k1 = x64Multiply(k1, c2);
    h1 = x64Xor(h1, k1);
    h1 = x64Rotl(h1, 27);
    h1 = x64Add(h1, h2);
    h1 = x64Add(x64Multiply(h1, [0, 5]), [0, 1390208809]);
    k2 = x64Multiply(k2, c2);
    k2 = x64Rotl(k2, 33);
    k2 = x64Multiply(k2, c1);
    h2 = x64Xor(h2, k2);
    h2 = x64Rotl(h2, 31);
    h2 = x64Add(h2, h1);
    h2 = x64Add(x64Multiply(h2, [0, 5]), [0, 944331445]);
  }
  k1 = [0, 0];
  k2 = [0, 0];
  switch (remainder) {
    case 15:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 14)], 48));
    // fallthrough
    case 14:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 13)], 40));
    // fallthrough
    case 13:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 12)], 32));
    // fallthrough
    case 12:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 11)], 24));
    // fallthrough
    case 11:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 10)], 16));
    // fallthrough
    case 10:
      k2 = x64Xor(k2, x64LeftShift([0, key2.charCodeAt(i2 + 9)], 8));
    // fallthrough
    case 9:
      k2 = x64Xor(k2, [0, key2.charCodeAt(i2 + 8)]);
      k2 = x64Multiply(k2, c2);
      k2 = x64Rotl(k2, 33);
      k2 = x64Multiply(k2, c1);
      h2 = x64Xor(h2, k2);
    // fallthrough
    case 8:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 7)], 56));
    // fallthrough
    case 7:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 6)], 48));
    // fallthrough
    case 6:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 5)], 40));
    // fallthrough
    case 5:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 4)], 32));
    // fallthrough
    case 4:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 3)], 24));
    // fallthrough
    case 3:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 2)], 16));
    // fallthrough
    case 2:
      k1 = x64Xor(k1, x64LeftShift([0, key2.charCodeAt(i2 + 1)], 8));
    // fallthrough
    case 1:
      k1 = x64Xor(k1, [0, key2.charCodeAt(i2)]);
      k1 = x64Multiply(k1, c1);
      k1 = x64Rotl(k1, 31);
      k1 = x64Multiply(k1, c2);
      h1 = x64Xor(h1, k1);
  }
  h1 = x64Xor(h1, [0, key2.length]);
  h2 = x64Xor(h2, [0, key2.length]);
  h1 = x64Add(h1, h2);
  h2 = x64Add(h2, h1);
  h1 = x64Fmix(h1);
  h2 = x64Fmix(h2);
  h1 = x64Add(h1, h2);
  h2 = x64Add(h2, h1);
  return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8);
}
function errorToObject(error) {
  var _a3;
  return __assign$4({ name: error.name, message: error.message, stack: (_a3 = error.stack) === null || _a3 === void 0 ? void 0 : _a3.split("\n") }, error);
}
function includes(haystack, needle) {
  for (var i2 = 0, l2 = haystack.length; i2 < l2; ++i2) {
    if (haystack[i2] === needle) {
      return true;
    }
  }
  return false;
}
function excludes(haystack, needle) {
  return !includes(haystack, needle);
}
function toInt(value) {
  return parseInt(value);
}
function toFloat(value) {
  return parseFloat(value);
}
function replaceNaN(value, replacement) {
  return typeof value === "number" && isNaN(value) ? replacement : value;
}
function countTruthy(values) {
  return values.reduce(function(sum, value) {
    return sum + (value ? 1 : 0);
  }, 0);
}
function round(value, base2) {
  if (base2 === void 0) {
    base2 = 1;
  }
  if (Math.abs(base2) >= 1) {
    return Math.round(value / base2) * base2;
  } else {
    var counterBase = 1 / base2;
    return Math.round(value * counterBase) / counterBase;
  }
}
function parseSimpleCssSelector(selector) {
  var _a3, _b2;
  var errorMessage = "Unexpected syntax '".concat(selector, "'");
  var tagMatch = /^\s*([a-z-]*)(.*)$/i.exec(selector);
  var tag = tagMatch[1] || void 0;
  var attributes = {};
  var partsRegex = /([.:#][\w-]+|\[.+?\])/gi;
  var addAttribute = function(name, value) {
    attributes[name] = attributes[name] || [];
    attributes[name].push(value);
  };
  for (; ; ) {
    var match = partsRegex.exec(tagMatch[2]);
    if (!match) {
      break;
    }
    var part = match[0];
    switch (part[0]) {
      case ".":
        addAttribute("class", part.slice(1));
        break;
      case "#":
        addAttribute("id", part.slice(1));
        break;
      case "[": {
        var attributeMatch = /^\[([\w-]+)([~|^$*]?=("(.*?)"|([\w-]+)))?(\s+[is])?\]$/.exec(part);
        if (attributeMatch) {
          addAttribute(attributeMatch[1], (_b2 = (_a3 = attributeMatch[4]) !== null && _a3 !== void 0 ? _a3 : attributeMatch[5]) !== null && _b2 !== void 0 ? _b2 : "");
        } else {
          throw new Error(errorMessage);
        }
        break;
      }
      default:
        throw new Error(errorMessage);
    }
  }
  return [tag, attributes];
}
function ensureErrorWithMessage(error) {
  return error && typeof error === "object" && "message" in error ? error : { message: error };
}
function isFinalResultLoaded(loadResult) {
  return typeof loadResult !== "function";
}
function loadSource(source, sourceOptions) {
  var sourceLoadPromise = new Promise(function(resolveLoad) {
    var loadStartTime = Date.now();
    awaitIfAsync(source.bind(null, sourceOptions), function() {
      var loadArgs = [];
      for (var _i2 = 0; _i2 < arguments.length; _i2++) {
        loadArgs[_i2] = arguments[_i2];
      }
      var loadDuration = Date.now() - loadStartTime;
      if (!loadArgs[0]) {
        return resolveLoad(function() {
          return { error: ensureErrorWithMessage(loadArgs[1]), duration: loadDuration };
        });
      }
      var loadResult = loadArgs[1];
      if (isFinalResultLoaded(loadResult)) {
        return resolveLoad(function() {
          return { value: loadResult, duration: loadDuration };
        });
      }
      resolveLoad(function() {
        return new Promise(function(resolveGet) {
          var getStartTime = Date.now();
          awaitIfAsync(loadResult, function() {
            var getArgs = [];
            for (var _i3 = 0; _i3 < arguments.length; _i3++) {
              getArgs[_i3] = arguments[_i3];
            }
            var duration = loadDuration + Date.now() - getStartTime;
            if (!getArgs[0]) {
              return resolveGet({ error: ensureErrorWithMessage(getArgs[1]), duration });
            }
            resolveGet({ value: getArgs[1], duration });
          });
        });
      });
    });
  });
  suppressUnhandledRejectionWarning(sourceLoadPromise);
  return function getComponent() {
    return sourceLoadPromise.then(function(finalizeSource) {
      return finalizeSource();
    });
  };
}
function loadSources(sources2, sourceOptions, excludeSources) {
  var includedSources = Object.keys(sources2).filter(function(sourceKey) {
    return excludes(excludeSources, sourceKey);
  });
  var sourceGettersPromise = mapWithBreaks(includedSources, function(sourceKey) {
    return loadSource(sources2[sourceKey], sourceOptions);
  });
  suppressUnhandledRejectionWarning(sourceGettersPromise);
  return function getComponents() {
    return __awaiter$e(this, void 0, void 0, function() {
      var sourceGetters, componentPromises, componentArray, components, index2;
      return __generator$e(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            return [4, sourceGettersPromise];
          case 1:
            sourceGetters = _a3.sent();
            return [4, mapWithBreaks(sourceGetters, function(sourceGetter) {
              var componentPromise = sourceGetter();
              suppressUnhandledRejectionWarning(componentPromise);
              return componentPromise;
            })];
          case 2:
            componentPromises = _a3.sent();
            return [
              4,
              Promise.all(componentPromises)
              // Keeping the component keys order the same as the source keys order
            ];
          case 3:
            componentArray = _a3.sent();
            components = {};
            for (index2 = 0; index2 < includedSources.length; ++index2) {
              components[includedSources[index2]] = componentArray[index2];
            }
            return [2, components];
        }
      });
    });
  };
}
function isTrident() {
  var w = window;
  var n2 = navigator;
  return countTruthy([
    "MSCSSMatrix" in w,
    "msSetImmediate" in w,
    "msIndexedDB" in w,
    "msMaxTouchPoints" in n2,
    "msPointerEnabled" in n2
  ]) >= 4;
}
function isEdgeHTML() {
  var w = window;
  var n2 = navigator;
  return countTruthy(["msWriteProfilerMark" in w, "MSStream" in w, "msLaunchUri" in n2, "msSaveBlob" in n2]) >= 3 && !isTrident();
}
function isChromium() {
  var w = window;
  var n2 = navigator;
  return countTruthy([
    "webkitPersistentStorage" in n2,
    "webkitTemporaryStorage" in n2,
    n2.vendor.indexOf("Google") === 0,
    "webkitResolveLocalFileSystemURL" in w,
    "BatteryManager" in w,
    "webkitMediaStream" in w,
    "webkitSpeechGrammar" in w
  ]) >= 5;
}
function isWebKit() {
  var w = window;
  var n2 = navigator;
  return countTruthy([
    "ApplePayError" in w,
    "CSSPrimitiveValue" in w,
    "Counter" in w,
    n2.vendor.indexOf("Apple") === 0,
    "getStorageUpdates" in n2,
    "WebKitMediaKeys" in w
  ]) >= 4;
}
function isDesktopSafari() {
  var w = window;
  return countTruthy([
    "safari" in w,
    !("DeviceMotionEvent" in w),
    !("ongestureend" in w),
    !("standalone" in navigator)
  ]) >= 3;
}
function isGecko() {
  var _a3, _b2;
  var w = window;
  return countTruthy([
    "buildID" in navigator,
    "MozAppearance" in ((_b2 = (_a3 = document.documentElement) === null || _a3 === void 0 ? void 0 : _a3.style) !== null && _b2 !== void 0 ? _b2 : {}),
    "onmozfullscreenchange" in w,
    "mozInnerScreenX" in w,
    "CSSMozDocumentRule" in w,
    "CanvasCaptureMediaStream" in w
  ]) >= 4;
}
function isChromium86OrNewer() {
  var w = window;
  return countTruthy([
    !("MediaSettingsRange" in w),
    "RTCEncodedAudioFrame" in w,
    "" + w.Intl === "[object Intl]",
    "" + w.Reflect === "[object Reflect]"
  ]) >= 3;
}
function isWebKit606OrNewer() {
  var w = window;
  return countTruthy([
    "DOMRectList" in w,
    "RTCPeerConnectionIceEvent" in w,
    "SVGGeometryElement" in w,
    "ontransitioncancel" in w
  ]) >= 3;
}
function isIPad() {
  if (navigator.platform === "iPad") {
    return true;
  }
  var s2 = screen;
  var screenRatio = s2.width / s2.height;
  return countTruthy([
    "MediaSource" in window,
    !!Element.prototype.webkitRequestFullscreen,
    // iPhone 4S that runs iOS 9 matches this. But it won't match the criteria above, so it won't be detected as iPad.
    screenRatio > 0.65 && screenRatio < 1.53
  ]) >= 2;
}
function getFullscreenElement() {
  var d = document;
  return d.fullscreenElement || d.msFullscreenElement || d.mozFullScreenElement || d.webkitFullscreenElement || null;
}
function exitFullscreen() {
  var d = document;
  return (d.exitFullscreen || d.msExitFullscreen || d.mozCancelFullScreen || d.webkitExitFullscreen).call(d);
}
function isAndroid() {
  var isItChromium = isChromium();
  var isItGecko = isGecko();
  if (!isItChromium && !isItGecko) {
    return false;
  }
  var w = window;
  return countTruthy([
    "onorientationchange" in w,
    "orientation" in w,
    isItChromium && !("SharedWorker" in w),
    isItGecko && /android/i.test(navigator.appVersion)
  ]) >= 2;
}
function getAudioFingerprint() {
  var w = window;
  var AudioContext = w.OfflineAudioContext || w.webkitOfflineAudioContext;
  if (!AudioContext) {
    return -2;
  }
  if (doesCurrentBrowserSuspendAudioContext()) {
    return -1;
  }
  var hashFromIndex = 4500;
  var hashToIndex = 5e3;
  var context = new AudioContext(1, hashToIndex, 44100);
  var oscillator = context.createOscillator();
  oscillator.type = "triangle";
  oscillator.frequency.value = 1e4;
  var compressor = context.createDynamicsCompressor();
  compressor.threshold.value = -50;
  compressor.knee.value = 40;
  compressor.ratio.value = 12;
  compressor.attack.value = 0;
  compressor.release.value = 0.25;
  oscillator.connect(compressor);
  compressor.connect(context.destination);
  oscillator.start(0);
  var _a3 = startRenderingAudio(context), renderPromise = _a3[0], finishRendering = _a3[1];
  var fingerprintPromise = renderPromise.then(function(buffer2) {
    return getHash(buffer2.getChannelData(0).subarray(hashFromIndex));
  }, function(error) {
    if (error.name === "timeout" || error.name === "suspended") {
      return -3;
    }
    throw error;
  });
  suppressUnhandledRejectionWarning(fingerprintPromise);
  return function() {
    finishRendering();
    return fingerprintPromise;
  };
}
function doesCurrentBrowserSuspendAudioContext() {
  return isWebKit() && !isDesktopSafari() && !isWebKit606OrNewer();
}
function startRenderingAudio(context) {
  var renderTryMaxCount = 3;
  var renderRetryDelay = 500;
  var runningMaxAwaitTime = 500;
  var runningSufficientTime = 5e3;
  var finalize = function() {
    return void 0;
  };
  var resultPromise = new Promise(function(resolve2, reject2) {
    var isFinalized = false;
    var renderTryCount = 0;
    var startedRunningAt = 0;
    context.oncomplete = function(event) {
      return resolve2(event.renderedBuffer);
    };
    var startRunningTimeout = function() {
      setTimeout(function() {
        return reject2(makeInnerError(
          "timeout"
          /* InnerErrorName.Timeout */
        ));
      }, Math.min(runningMaxAwaitTime, startedRunningAt + runningSufficientTime - Date.now()));
    };
    var tryRender = function() {
      try {
        var renderingPromise = context.startRendering();
        if (isPromise(renderingPromise)) {
          suppressUnhandledRejectionWarning(renderingPromise);
        }
        switch (context.state) {
          case "running":
            startedRunningAt = Date.now();
            if (isFinalized) {
              startRunningTimeout();
            }
            break;
          // Sometimes the audio context doesn't start after calling `startRendering` (in addition to the cases where
          // audio context doesn't start at all). A known case is starting an audio context when the browser tab is in
          // background on iPhone. Retries usually help in this case.
          case "suspended":
            if (!document.hidden) {
              renderTryCount++;
            }
            if (isFinalized && renderTryCount >= renderTryMaxCount) {
              reject2(makeInnerError(
                "suspended"
                /* InnerErrorName.Suspended */
              ));
            } else {
              setTimeout(tryRender, renderRetryDelay);
            }
            break;
        }
      } catch (error) {
        reject2(error);
      }
    };
    tryRender();
    finalize = function() {
      if (!isFinalized) {
        isFinalized = true;
        if (startedRunningAt > 0) {
          startRunningTimeout();
        }
      }
    };
  });
  return [resultPromise, finalize];
}
function getHash(signal) {
  var hash2 = 0;
  for (var i2 = 0; i2 < signal.length; ++i2) {
    hash2 += Math.abs(signal[i2]);
  }
  return hash2;
}
function makeInnerError(name) {
  var error = new Error(name);
  error.name = name;
  return error;
}
function withIframe(action, initialHtml, domPollInterval) {
  var _a3, _b2, _c2;
  if (domPollInterval === void 0) {
    domPollInterval = 50;
  }
  return __awaiter$e(this, void 0, void 0, function() {
    var d, iframe;
    return __generator$e(this, function(_d2) {
      switch (_d2.label) {
        case 0:
          d = document;
          _d2.label = 1;
        case 1:
          if (!!d.body) return [3, 3];
          return [4, wait(domPollInterval)];
        case 2:
          _d2.sent();
          return [3, 1];
        case 3:
          iframe = d.createElement("iframe");
          _d2.label = 4;
        case 4:
          _d2.trys.push([4, , 10, 11]);
          return [4, new Promise(function(_resolve, _reject) {
            var isComplete = false;
            var resolve2 = function() {
              isComplete = true;
              _resolve();
            };
            var reject2 = function(error) {
              isComplete = true;
              _reject(error);
            };
            iframe.onload = resolve2;
            iframe.onerror = reject2;
            var style = iframe.style;
            style.setProperty("display", "block", "important");
            style.position = "absolute";
            style.top = "0";
            style.left = "0";
            style.visibility = "hidden";
            if (initialHtml && "srcdoc" in iframe) {
              iframe.srcdoc = initialHtml;
            } else {
              iframe.src = "about:blank";
            }
            d.body.appendChild(iframe);
            var checkReadyState = function() {
              var _a4, _b3;
              if (isComplete) {
                return;
              }
              if (((_b3 = (_a4 = iframe.contentWindow) === null || _a4 === void 0 ? void 0 : _a4.document) === null || _b3 === void 0 ? void 0 : _b3.readyState) === "complete") {
                resolve2();
              } else {
                setTimeout(checkReadyState, 10);
              }
            };
            checkReadyState();
          })];
        case 5:
          _d2.sent();
          _d2.label = 6;
        case 6:
          if (!!((_b2 = (_a3 = iframe.contentWindow) === null || _a3 === void 0 ? void 0 : _a3.document) === null || _b2 === void 0 ? void 0 : _b2.body)) return [3, 8];
          return [4, wait(domPollInterval)];
        case 7:
          _d2.sent();
          return [3, 6];
        case 8:
          return [4, action(iframe, iframe.contentWindow)];
        case 9:
          return [2, _d2.sent()];
        case 10:
          (_c2 = iframe.parentNode) === null || _c2 === void 0 ? void 0 : _c2.removeChild(iframe);
          return [
            7
            /*endfinally*/
          ];
        case 11:
          return [
            2
            /*return*/
          ];
      }
    });
  });
}
function selectorToElement(selector) {
  var _a3 = parseSimpleCssSelector(selector), tag = _a3[0], attributes = _a3[1];
  var element = document.createElement(tag !== null && tag !== void 0 ? tag : "div");
  for (var _i2 = 0, _b2 = Object.keys(attributes); _i2 < _b2.length; _i2++) {
    var name_1 = _b2[_i2];
    var value = attributes[name_1].join(" ");
    if (name_1 === "style") {
      addStyleString(element.style, value);
    } else {
      element.setAttribute(name_1, value);
    }
  }
  return element;
}
function addStyleString(style, source) {
  for (var _i2 = 0, _a3 = source.split(";"); _i2 < _a3.length; _i2++) {
    var property = _a3[_i2];
    var match = /^\s*([\w-]+)\s*:\s*(.+?)(\s*!([\w-]+))?\s*$/.exec(property);
    if (match) {
      var name_2 = match[1], value = match[2], priority = match[4];
      style.setProperty(name_2, value, priority || "");
    }
  }
}
var testString = "mmMwWLliI0O&1";
var textSize = "48px";
var baseFonts = ["monospace", "sans-serif", "serif"];
var fontList = [
  // This is android-specific font from "Roboto" family
  "sans-serif-thin",
  "ARNO PRO",
  "Agency FB",
  "Arabic Typesetting",
  "Arial Unicode MS",
  "AvantGarde Bk BT",
  "BankGothic Md BT",
  "Batang",
  "Bitstream Vera Sans Mono",
  "Calibri",
  "Century",
  "Century Gothic",
  "Clarendon",
  "EUROSTILE",
  "Franklin Gothic",
  "Futura Bk BT",
  "Futura Md BT",
  "GOTHAM",
  "Gill Sans",
  "HELV",
  "Haettenschweiler",
  "Helvetica Neue",
  "Humanst521 BT",
  "Leelawadee",
  "Letter Gothic",
  "Levenim MT",
  "Lucida Bright",
  "Lucida Sans",
  "Menlo",
  "MS Mincho",
  "MS Outlook",
  "MS Reference Specialty",
  "MS UI Gothic",
  "MT Extra",
  "MYRIAD PRO",
  "Marlett",
  "Meiryo UI",
  "Microsoft Uighur",
  "Minion Pro",
  "Monotype Corsiva",
  "PMingLiU",
  "Pristina",
  "SCRIPTINA",
  "Segoe UI Light",
  "Serifa",
  "SimHei",
  "Small Fonts",
  "Staccato222 BT",
  "TRAJAN PRO",
  "Univers CE 55 Medium",
  "Vrinda",
  "ZWAdobeF"
];
function getFonts() {
  return withIframe(function(_2, _a3) {
    var document2 = _a3.document;
    var holder = document2.body;
    holder.style.fontSize = textSize;
    var spansContainer = document2.createElement("div");
    var defaultWidth = {};
    var defaultHeight = {};
    var createSpan = function(fontFamily) {
      var span = document2.createElement("span");
      var style = span.style;
      style.position = "absolute";
      style.top = "0";
      style.left = "0";
      style.fontFamily = fontFamily;
      span.textContent = testString;
      spansContainer.appendChild(span);
      return span;
    };
    var createSpanWithFonts = function(fontToDetect, baseFont) {
      return createSpan("'".concat(fontToDetect, "',").concat(baseFont));
    };
    var initializeBaseFontsSpans = function() {
      return baseFonts.map(createSpan);
    };
    var initializeFontsSpans = function() {
      var spans = {};
      var _loop_1 = function(font2) {
        spans[font2] = baseFonts.map(function(baseFont) {
          return createSpanWithFonts(font2, baseFont);
        });
      };
      for (var _i2 = 0, fontList_1 = fontList; _i2 < fontList_1.length; _i2++) {
        var font = fontList_1[_i2];
        _loop_1(font);
      }
      return spans;
    };
    var isFontAvailable = function(fontSpans) {
      return baseFonts.some(function(baseFont, baseFontIndex) {
        return fontSpans[baseFontIndex].offsetWidth !== defaultWidth[baseFont] || fontSpans[baseFontIndex].offsetHeight !== defaultHeight[baseFont];
      });
    };
    var baseFontsSpans = initializeBaseFontsSpans();
    var fontsSpans = initializeFontsSpans();
    holder.appendChild(spansContainer);
    for (var index2 = 0; index2 < baseFonts.length; index2++) {
      defaultWidth[baseFonts[index2]] = baseFontsSpans[index2].offsetWidth;
      defaultHeight[baseFonts[index2]] = baseFontsSpans[index2].offsetHeight;
    }
    return fontList.filter(function(font) {
      return isFontAvailable(fontsSpans[font]);
    });
  });
}
function getPlugins() {
  var rawPlugins = navigator.plugins;
  if (!rawPlugins) {
    return void 0;
  }
  var plugins = [];
  for (var i2 = 0; i2 < rawPlugins.length; ++i2) {
    var plugin = rawPlugins[i2];
    if (!plugin) {
      continue;
    }
    var mimeTypes = [];
    for (var j = 0; j < plugin.length; ++j) {
      var mimeType = plugin[j];
      mimeTypes.push({
        type: mimeType.type,
        suffixes: mimeType.suffixes
      });
    }
    plugins.push({
      name: plugin.name,
      description: plugin.description,
      mimeTypes
    });
  }
  return plugins;
}
function getCanvasFingerprint() {
  var winding = false;
  var geometry;
  var text;
  var _a3 = makeCanvasContext(), canvas = _a3[0], context = _a3[1];
  if (!isSupported(canvas, context)) {
    geometry = text = "";
  } else {
    winding = doesSupportWinding(context);
    renderTextImage(canvas, context);
    var textImage1 = canvasToString(canvas);
    var textImage2 = canvasToString(canvas);
    if (textImage1 !== textImage2) {
      geometry = text = "unstable";
    } else {
      text = textImage1;
      renderGeometryImage(canvas, context);
      geometry = canvasToString(canvas);
    }
  }
  return { winding, geometry, text };
}
function makeCanvasContext() {
  var canvas = document.createElement("canvas");
  canvas.width = 1;
  canvas.height = 1;
  return [canvas, canvas.getContext("2d")];
}
function isSupported(canvas, context) {
  return !!(context && canvas.toDataURL);
}
function doesSupportWinding(context) {
  context.rect(0, 0, 10, 10);
  context.rect(2, 2, 6, 6);
  return !context.isPointInPath(5, 5, "evenodd");
}
function renderTextImage(canvas, context) {
  canvas.width = 240;
  canvas.height = 60;
  context.textBaseline = "alphabetic";
  context.fillStyle = "#f60";
  context.fillRect(100, 1, 62, 20);
  context.fillStyle = "#069";
  context.font = '11pt "Times New Roman"';
  var printedText = "Cwm fjordbank gly ".concat(
    String.fromCharCode(55357, 56835)
    /* 😃 */
  );
  context.fillText(printedText, 2, 15);
  context.fillStyle = "rgba(102, 204, 0, 0.2)";
  context.font = "18pt Arial";
  context.fillText(printedText, 4, 45);
}
function renderGeometryImage(canvas, context) {
  canvas.width = 122;
  canvas.height = 110;
  context.globalCompositeOperation = "multiply";
  for (var _i2 = 0, _a3 = [
    ["#f2f", 40, 40],
    ["#2ff", 80, 40],
    ["#ff2", 60, 80]
  ]; _i2 < _a3.length; _i2++) {
    var _b2 = _a3[_i2], color = _b2[0], x2 = _b2[1], y2 = _b2[2];
    context.fillStyle = color;
    context.beginPath();
    context.arc(x2, y2, 40, 0, Math.PI * 2, true);
    context.closePath();
    context.fill();
  }
  context.fillStyle = "#f9c";
  context.arc(60, 60, 60, 0, Math.PI * 2, true);
  context.arc(60, 60, 20, 0, Math.PI * 2, true);
  context.fill("evenodd");
}
function canvasToString(canvas) {
  return canvas.toDataURL();
}
function getTouchSupport() {
  var n2 = navigator;
  var maxTouchPoints = 0;
  var touchEvent;
  if (n2.maxTouchPoints !== void 0) {
    maxTouchPoints = toInt(n2.maxTouchPoints);
  } else if (n2.msMaxTouchPoints !== void 0) {
    maxTouchPoints = n2.msMaxTouchPoints;
  }
  try {
    document.createEvent("TouchEvent");
    touchEvent = true;
  } catch (_a3) {
    touchEvent = false;
  }
  var touchStart = "ontouchstart" in window;
  return {
    maxTouchPoints,
    touchEvent,
    touchStart
  };
}
function getOsCpu() {
  return navigator.oscpu;
}
function getLanguages() {
  var n2 = navigator;
  var result = [];
  var language = n2.language || n2.userLanguage || n2.browserLanguage || n2.systemLanguage;
  if (language !== void 0) {
    result.push([language]);
  }
  if (Array.isArray(n2.languages)) {
    if (!(isChromium() && isChromium86OrNewer())) {
      result.push(n2.languages);
    }
  } else if (typeof n2.languages === "string") {
    var languages = n2.languages;
    if (languages) {
      result.push(languages.split(","));
    }
  }
  return result;
}
function getColorDepth() {
  return window.screen.colorDepth;
}
function getDeviceMemory() {
  return replaceNaN(toFloat(navigator.deviceMemory), void 0);
}
function getScreenResolution() {
  var s2 = screen;
  var parseDimension = function(value) {
    return replaceNaN(toInt(value), null);
  };
  var dimensions = [parseDimension(s2.width), parseDimension(s2.height)];
  dimensions.sort().reverse();
  return dimensions;
}
var screenFrameCheckInterval = 2500;
var roundingPrecision = 10;
var screenFrameBackup;
var screenFrameSizeTimeoutId;
function watchScreenFrame() {
  if (screenFrameSizeTimeoutId !== void 0) {
    return;
  }
  var checkScreenFrame = function() {
    var frameSize = getCurrentScreenFrame();
    if (isFrameSizeNull(frameSize)) {
      screenFrameSizeTimeoutId = setTimeout(checkScreenFrame, screenFrameCheckInterval);
    } else {
      screenFrameBackup = frameSize;
      screenFrameSizeTimeoutId = void 0;
    }
  };
  checkScreenFrame();
}
function getScreenFrame() {
  var _this = this;
  watchScreenFrame();
  return function() {
    return __awaiter$e(_this, void 0, void 0, function() {
      var frameSize;
      return __generator$e(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            frameSize = getCurrentScreenFrame();
            if (!isFrameSizeNull(frameSize)) return [3, 2];
            if (screenFrameBackup) {
              return [2, __spreadArray$1([], screenFrameBackup, true)];
            }
            if (!getFullscreenElement()) return [3, 2];
            return [4, exitFullscreen()];
          case 1:
            _a3.sent();
            frameSize = getCurrentScreenFrame();
            _a3.label = 2;
          case 2:
            if (!isFrameSizeNull(frameSize)) {
              screenFrameBackup = frameSize;
            }
            return [2, frameSize];
        }
      });
    });
  };
}
function getRoundedScreenFrame() {
  var _this = this;
  var screenFrameGetter = getScreenFrame();
  return function() {
    return __awaiter$e(_this, void 0, void 0, function() {
      var frameSize, processSize;
      return __generator$e(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            return [4, screenFrameGetter()];
          case 1:
            frameSize = _a3.sent();
            processSize = function(sideSize) {
              return sideSize === null ? null : round(sideSize, roundingPrecision);
            };
            return [2, [processSize(frameSize[0]), processSize(frameSize[1]), processSize(frameSize[2]), processSize(frameSize[3])]];
        }
      });
    });
  };
}
function getCurrentScreenFrame() {
  var s2 = screen;
  return [
    replaceNaN(toFloat(s2.availTop), null),
    replaceNaN(toFloat(s2.width) - toFloat(s2.availWidth) - replaceNaN(toFloat(s2.availLeft), 0), null),
    replaceNaN(toFloat(s2.height) - toFloat(s2.availHeight) - replaceNaN(toFloat(s2.availTop), 0), null),
    replaceNaN(toFloat(s2.availLeft), null)
  ];
}
function isFrameSizeNull(frameSize) {
  for (var i2 = 0; i2 < 4; ++i2) {
    if (frameSize[i2]) {
      return false;
    }
  }
  return true;
}
function getHardwareConcurrency() {
  return replaceNaN(toInt(navigator.hardwareConcurrency), void 0);
}
function getTimezone() {
  var _a3;
  var DateTimeFormat = (_a3 = window.Intl) === null || _a3 === void 0 ? void 0 : _a3.DateTimeFormat;
  if (DateTimeFormat) {
    var timezone = new DateTimeFormat().resolvedOptions().timeZone;
    if (timezone) {
      return timezone;
    }
  }
  var offset = -getTimezoneOffset();
  return "UTC".concat(offset >= 0 ? "+" : "").concat(Math.abs(offset));
}
function getTimezoneOffset() {
  var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
  return Math.max(
    // `getTimezoneOffset` returns a number as a string in some unidentified cases
    toFloat(new Date(currentYear, 0, 1).getTimezoneOffset()),
    toFloat(new Date(currentYear, 6, 1).getTimezoneOffset())
  );
}
function getSessionStorage() {
  try {
    return !!window.sessionStorage;
  } catch (error) {
    return true;
  }
}
function getLocalStorage() {
  try {
    return !!window.localStorage;
  } catch (e4) {
    return true;
  }
}
function getIndexedDB() {
  if (isTrident() || isEdgeHTML()) {
    return void 0;
  }
  try {
    return !!window.indexedDB;
  } catch (e4) {
    return true;
  }
}
function getOpenDatabase() {
  return !!window.openDatabase;
}
function getCpuClass() {
  return navigator.cpuClass;
}
function getPlatform() {
  var platform2 = navigator.platform;
  if (platform2 === "MacIntel") {
    if (isWebKit() && !isDesktopSafari()) {
      return isIPad() ? "iPad" : "iPhone";
    }
  }
  return platform2;
}
function getVendor() {
  return navigator.vendor || "";
}
function getVendorFlavors() {
  var flavors = [];
  for (var _i2 = 0, _a3 = [
    // Blink and some browsers on iOS
    "chrome",
    // Safari on macOS
    "safari",
    // Chrome on iOS (checked in 85 on 13 and 87 on 14)
    "__crWeb",
    "__gCrWeb",
    // Yandex Browser on iOS, macOS and Android (checked in 21.2 on iOS 14, macOS and Android)
    "yandex",
    // Yandex Browser on iOS (checked in 21.2 on 14)
    "__yb",
    "__ybro",
    // Firefox on iOS (checked in 32 on 14)
    "__firefox__",
    // Edge on iOS (checked in 46 on 14)
    "__edgeTrackingPreventionStatistics",
    "webkit",
    // Opera Touch on iOS (checked in 2.6 on 14)
    "oprt",
    // Samsung Internet on Android (checked in 11.1)
    "samsungAr",
    // UC Browser on Android (checked in 12.10 and 13.0)
    "ucweb",
    "UCShellJava",
    // Puffin on Android (checked in 9.0)
    "puffinDevice"
    // UC on iOS and Opera on Android have no specific global variables
    // Edge for Android isn't checked
  ]; _i2 < _a3.length; _i2++) {
    var key2 = _a3[_i2];
    var value = window[key2];
    if (value && typeof value === "object") {
      flavors.push(key2);
    }
  }
  return flavors.sort();
}
function areCookiesEnabled() {
  var d = document;
  try {
    d.cookie = "cookietest=1; SameSite=Strict;";
    var result = d.cookie.indexOf("cookietest=") !== -1;
    d.cookie = "cookietest=1; SameSite=Strict; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    return result;
  } catch (e4) {
    return false;
  }
}
function getFilters() {
  var fromB64 = atob;
  return {
    abpIndo: [
      "#Iklan-Melayang",
      "#Kolom-Iklan-728",
      "#SidebarIklan-wrapper",
      '[title="ALIENBOLA" i]',
      fromB64("I0JveC1CYW5uZXItYWRz")
    ],
    abpvn: [".quangcao", "#mobileCatfish", fromB64("LmNsb3NlLWFkcw=="), '[id^="bn_bottom_fixed_"]', "#pmadv"],
    adBlockFinland: [
      ".mainostila",
      fromB64("LnNwb25zb3JpdA=="),
      ".ylamainos",
      fromB64("YVtocmVmKj0iL2NsaWNrdGhyZ2guYXNwPyJd"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9hcHAucmVhZHBlYWsuY29tL2FkcyJd")
    ],
    adBlockPersian: [
      "#navbar_notice_50",
      ".kadr",
      'TABLE[width="140px"]',
      "#divAgahi",
      fromB64("YVtocmVmXj0iaHR0cDovL2cxLnYuZndtcm0ubmV0L2FkLyJd")
    ],
    adBlockWarningRemoval: [
      "#adblock-honeypot",
      ".adblocker-root",
      ".wp_adblock_detect",
      fromB64("LmhlYWRlci1ibG9ja2VkLWFk"),
      fromB64("I2FkX2Jsb2NrZXI=")
    ],
    adGuardAnnoyances: [
      ".hs-sosyal",
      "#cookieconsentdiv",
      'div[class^="app_gdpr"]',
      ".as-oil",
      '[data-cypress="soft-push-notification-modal"]'
    ],
    adGuardBase: [
      ".BetterJsPopOverlay",
      fromB64("I2FkXzMwMFgyNTA="),
      fromB64("I2Jhbm5lcmZsb2F0MjI="),
      fromB64("I2NhbXBhaWduLWJhbm5lcg=="),
      fromB64("I0FkLUNvbnRlbnQ=")
    ],
    adGuardChinese: [
      fromB64("LlppX2FkX2FfSA=="),
      fromB64("YVtocmVmKj0iLmh0aGJldDM0LmNvbSJd"),
      "#widget-quan",
      fromB64("YVtocmVmKj0iLzg0OTkyMDIwLnh5eiJd"),
      fromB64("YVtocmVmKj0iLjE5NTZobC5jb20vIl0=")
    ],
    adGuardFrench: [
      "#pavePub",
      fromB64("LmFkLWRlc2t0b3AtcmVjdGFuZ2xl"),
      ".mobile_adhesion",
      ".widgetadv",
      fromB64("LmFkc19iYW4=")
    ],
    adGuardGerman: ['aside[data-portal-id="leaderboard"]'],
    adGuardJapanese: [
      "#kauli_yad_1",
      fromB64("YVtocmVmXj0iaHR0cDovL2FkMi50cmFmZmljZ2F0ZS5uZXQvIl0="),
      fromB64("Ll9wb3BJbl9pbmZpbml0ZV9hZA=="),
      fromB64("LmFkZ29vZ2xl"),
      fromB64("Ll9faXNib29zdFJldHVybkFk")
    ],
    adGuardMobile: [
      fromB64("YW1wLWF1dG8tYWRz"),
      fromB64("LmFtcF9hZA=="),
      'amp-embed[type="24smi"]',
      "#mgid_iframe1",
      fromB64("I2FkX2ludmlld19hcmVh")
    ],
    adGuardRussian: [
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9hZC5sZXRtZWFkcy5jb20vIl0="),
      fromB64("LnJlY2xhbWE="),
      'div[id^="smi2adblock"]',
      fromB64("ZGl2W2lkXj0iQWRGb3hfYmFubmVyXyJd"),
      "#psyduckpockeball"
    ],
    adGuardSocial: [
      fromB64("YVtocmVmXj0iLy93d3cuc3R1bWJsZXVwb24uY29tL3N1Ym1pdD91cmw9Il0="),
      fromB64("YVtocmVmXj0iLy90ZWxlZ3JhbS5tZS9zaGFyZS91cmw/Il0="),
      ".etsy-tweet",
      "#inlineShare",
      ".popup-social"
    ],
    adGuardSpanishPortuguese: ["#barraPublicidade", "#Publicidade", "#publiEspecial", "#queTooltip", ".cnt-publi"],
    adGuardTrackingProtection: [
      "#qoo-counter",
      fromB64("YVtocmVmXj0iaHR0cDovL2NsaWNrLmhvdGxvZy5ydS8iXQ=="),
      fromB64("YVtocmVmXj0iaHR0cDovL2hpdGNvdW50ZXIucnUvdG9wL3N0YXQucGhwIl0="),
      fromB64("YVtocmVmXj0iaHR0cDovL3RvcC5tYWlsLnJ1L2p1bXAiXQ=="),
      "#top100counter"
    ],
    adGuardTurkish: [
      "#backkapat",
      fromB64("I3Jla2xhbWk="),
      fromB64("YVtocmVmXj0iaHR0cDovL2Fkc2Vydi5vbnRlay5jb20udHIvIl0="),
      fromB64("YVtocmVmXj0iaHR0cDovL2l6bGVuemkuY29tL2NhbXBhaWduLyJd"),
      fromB64("YVtocmVmXj0iaHR0cDovL3d3dy5pbnN0YWxsYWRzLm5ldC8iXQ==")
    ],
    bulgarian: [fromB64("dGQjZnJlZW5ldF90YWJsZV9hZHM="), "#ea_intext_div", ".lapni-pop-over", "#xenium_hot_offers"],
    easyList: [
      ".yb-floorad",
      fromB64("LndpZGdldF9wb19hZHNfd2lkZ2V0"),
      fromB64("LnRyYWZmaWNqdW5reS1hZA=="),
      ".textad_headline",
      fromB64("LnNwb25zb3JlZC10ZXh0LWxpbmtz")
    ],
    easyListChina: [
      fromB64("LmFwcGd1aWRlLXdyYXBbb25jbGljayo9ImJjZWJvcy5jb20iXQ=="),
      fromB64("LmZyb250cGFnZUFkdk0="),
      "#taotaole",
      "#aafoot.top_box",
      ".cfa_popup"
    ],
    easyListCookie: [
      ".ezmob-footer",
      ".cc-CookieWarning",
      "[data-cookie-number]",
      fromB64("LmF3LWNvb2tpZS1iYW5uZXI="),
      ".sygnal24-gdpr-modal-wrap"
    ],
    easyListCzechSlovak: [
      "#onlajny-stickers",
      fromB64("I3Jla2xhbW5pLWJveA=="),
      fromB64("LnJla2xhbWEtbWVnYWJvYXJk"),
      ".sklik",
      fromB64("W2lkXj0ic2tsaWtSZWtsYW1hIl0=")
    ],
    easyListDutch: [
      fromB64("I2FkdmVydGVudGll"),
      fromB64("I3ZpcEFkbWFya3RCYW5uZXJCbG9jaw=="),
      ".adstekst",
      fromB64("YVtocmVmXj0iaHR0cHM6Ly94bHR1YmUubmwvY2xpY2svIl0="),
      "#semilo-lrectangle"
    ],
    easyListGermany: [
      "#SSpotIMPopSlider",
      fromB64("LnNwb25zb3JsaW5rZ3J1ZW4="),
      fromB64("I3dlcmJ1bmdza3k="),
      fromB64("I3Jla2xhbWUtcmVjaHRzLW1pdHRl"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9iZDc0Mi5jb20vIl0=")
    ],
    easyListItaly: [
      fromB64("LmJveF9hZHZfYW5udW5jaQ=="),
      ".sb-box-pubbliredazionale",
      fromB64("YVtocmVmXj0iaHR0cDovL2FmZmlsaWF6aW9uaWFkcy5zbmFpLml0LyJd"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9hZHNlcnZlci5odG1sLml0LyJd"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9hZmZpbGlhemlvbmlhZHMuc25haS5pdC8iXQ==")
    ],
    easyListLithuania: [
      fromB64("LnJla2xhbW9zX3RhcnBhcw=="),
      fromB64("LnJla2xhbW9zX251b3JvZG9z"),
      fromB64("aW1nW2FsdD0iUmVrbGFtaW5pcyBza3lkZWxpcyJd"),
      fromB64("aW1nW2FsdD0iRGVkaWt1b3RpLmx0IHNlcnZlcmlhaSJd"),
      fromB64("aW1nW2FsdD0iSG9zdGluZ2FzIFNlcnZlcmlhaS5sdCJd")
    ],
    estonian: [fromB64("QVtocmVmKj0iaHR0cDovL3BheTRyZXN1bHRzMjQuZXUiXQ==")],
    fanboyAnnoyances: ["#ac-lre-player", ".navigate-to-top", "#subscribe_popup", ".newsletter_holder", "#back-top"],
    fanboyAntiFacebook: [".util-bar-module-firefly-visible"],
    fanboyEnhancedTrackers: [
      ".open.pushModal",
      "#issuem-leaky-paywall-articles-zero-remaining-nag",
      "#sovrn_container",
      'div[class$="-hide"][zoompage-fontsize][style="display: block;"]',
      ".BlockNag__Card"
    ],
    fanboySocial: ["#FollowUs", "#meteored_share", "#social_follow", ".article-sharer", ".community__social-desc"],
    frellwitSwedish: [
      fromB64("YVtocmVmKj0iY2FzaW5vcHJvLnNlIl1bdGFyZ2V0PSJfYmxhbmsiXQ=="),
      fromB64("YVtocmVmKj0iZG9rdG9yLXNlLm9uZWxpbmsubWUiXQ=="),
      "article.category-samarbete",
      fromB64("ZGl2LmhvbGlkQWRz"),
      "ul.adsmodern"
    ],
    greekAdBlock: [
      fromB64("QVtocmVmKj0iYWRtYW4ub3RlbmV0LmdyL2NsaWNrPyJd"),
      fromB64("QVtocmVmKj0iaHR0cDovL2F4aWFiYW5uZXJzLmV4b2R1cy5nci8iXQ=="),
      fromB64("QVtocmVmKj0iaHR0cDovL2ludGVyYWN0aXZlLmZvcnRobmV0LmdyL2NsaWNrPyJd"),
      "DIV.agores300",
      "TABLE.advright"
    ],
    hungarian: [
      "#cemp_doboz",
      ".optimonk-iframe-container",
      fromB64("LmFkX19tYWlu"),
      fromB64("W2NsYXNzKj0iR29vZ2xlQWRzIl0="),
      "#hirdetesek_box"
    ],
    iDontCareAboutCookies: [
      '.alert-info[data-block-track*="CookieNotice"]',
      ".ModuleTemplateCookieIndicator",
      ".o--cookies--container",
      "#cookies-policy-sticky",
      "#stickyCookieBar"
    ],
    icelandicAbp: [fromB64("QVtocmVmXj0iL2ZyYW1ld29yay9yZXNvdXJjZXMvZm9ybXMvYWRzLmFzcHgiXQ==")],
    latvian: [
      fromB64("YVtocmVmPSJodHRwOi8vd3d3LnNhbGlkemluaS5sdi8iXVtzdHlsZT0iZGlzcGxheTogYmxvY2s7IHdpZHRoOiAxMjBweDsgaGVpZ2h0OiA0MHB4OyBvdmVyZmxvdzogaGlkZGVuOyBwb3NpdGlvbjogcmVsYXRpdmU7Il0="),
      fromB64("YVtocmVmPSJodHRwOi8vd3d3LnNhbGlkemluaS5sdi8iXVtzdHlsZT0iZGlzcGxheTogYmxvY2s7IHdpZHRoOiA4OHB4OyBoZWlnaHQ6IDMxcHg7IG92ZXJmbG93OiBoaWRkZW47IHBvc2l0aW9uOiByZWxhdGl2ZTsiXQ==")
    ],
    listKr: [
      fromB64("YVtocmVmKj0iLy9hZC5wbGFuYnBsdXMuY28ua3IvIl0="),
      fromB64("I2xpdmVyZUFkV3JhcHBlcg=="),
      fromB64("YVtocmVmKj0iLy9hZHYuaW1hZHJlcC5jby5rci8iXQ=="),
      fromB64("aW5zLmZhc3R2aWV3LWFk"),
      ".revenue_unit_item.dable"
    ],
    listeAr: [
      fromB64("LmdlbWluaUxCMUFk"),
      ".right-and-left-sponsers",
      fromB64("YVtocmVmKj0iLmFmbGFtLmluZm8iXQ=="),
      fromB64("YVtocmVmKj0iYm9vcmFxLm9yZyJd"),
      fromB64("YVtocmVmKj0iZHViaXp6bGUuY29tL2FyLz91dG1fc291cmNlPSJd")
    ],
    listeFr: [
      fromB64("YVtocmVmXj0iaHR0cDovL3Byb21vLnZhZG9yLmNvbS8iXQ=="),
      fromB64("I2FkY29udGFpbmVyX3JlY2hlcmNoZQ=="),
      fromB64("YVtocmVmKj0id2Vib3JhbWEuZnIvZmNnaS1iaW4vIl0="),
      ".site-pub-interstitiel",
      'div[id^="crt-"][data-criteo-id]'
    ],
    officialPolish: [
      "#ceneo-placeholder-ceneo-12",
      fromB64("W2hyZWZePSJodHRwczovL2FmZi5zZW5kaHViLnBsLyJd"),
      fromB64("YVtocmVmXj0iaHR0cDovL2Fkdm1hbmFnZXIudGVjaGZ1bi5wbC9yZWRpcmVjdC8iXQ=="),
      fromB64("YVtocmVmXj0iaHR0cDovL3d3dy50cml6ZXIucGwvP3V0bV9zb3VyY2UiXQ=="),
      fromB64("ZGl2I3NrYXBpZWNfYWQ=")
    ],
    ro: [
      fromB64("YVtocmVmXj0iLy9hZmZ0cmsuYWx0ZXgucm8vQ291bnRlci9DbGljayJd"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9ibGFja2ZyaWRheXNhbGVzLnJvL3Ryay9zaG9wLyJd"),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9ldmVudC4ycGVyZm9ybWFudC5jb20vZXZlbnRzL2NsaWNrIl0="),
      fromB64("YVtocmVmXj0iaHR0cHM6Ly9sLnByb2ZpdHNoYXJlLnJvLyJd"),
      'a[href^="/url/"]'
    ],
    ruAd: [
      fromB64("YVtocmVmKj0iLy9mZWJyYXJlLnJ1LyJd"),
      fromB64("YVtocmVmKj0iLy91dGltZy5ydS8iXQ=="),
      fromB64("YVtocmVmKj0iOi8vY2hpa2lkaWtpLnJ1Il0="),
      "#pgeldiz",
      ".yandex-rtb-block"
    ],
    thaiAds: [
      "a[href*=macau-uta-popup]",
      fromB64("I2Fkcy1nb29nbGUtbWlkZGxlX3JlY3RhbmdsZS1ncm91cA=="),
      fromB64("LmFkczMwMHM="),
      ".bumq",
      ".img-kosana"
    ],
    webAnnoyancesUltralist: [
      "#mod-social-share-2",
      "#social-tools",
      fromB64("LmN0cGwtZnVsbGJhbm5lcg=="),
      ".zergnet-recommend",
      ".yt.btn-link.btn-md.btn"
    ]
  };
}
function getDomBlockers(_a3) {
  var _b2 = _a3 === void 0 ? {} : _a3, debug2 = _b2.debug;
  return __awaiter$e(this, void 0, void 0, function() {
    var filters, filterNames, allSelectors, blockedSelectors, activeBlockers;
    var _c2;
    return __generator$e(this, function(_d2) {
      switch (_d2.label) {
        case 0:
          if (!isApplicable()) {
            return [2, void 0];
          }
          filters = getFilters();
          filterNames = Object.keys(filters);
          allSelectors = (_c2 = []).concat.apply(_c2, filterNames.map(function(filterName) {
            return filters[filterName];
          }));
          return [4, getBlockedSelectors(allSelectors)];
        case 1:
          blockedSelectors = _d2.sent();
          if (debug2) {
            printDebug(filters, blockedSelectors);
          }
          activeBlockers = filterNames.filter(function(filterName) {
            var selectors = filters[filterName];
            var blockedCount = countTruthy(selectors.map(function(selector) {
              return blockedSelectors[selector];
            }));
            return blockedCount > selectors.length * 0.6;
          });
          activeBlockers.sort();
          return [2, activeBlockers];
      }
    });
  });
}
function isApplicable() {
  return isWebKit() || isAndroid();
}
function getBlockedSelectors(selectors) {
  var _a3;
  return __awaiter$e(this, void 0, void 0, function() {
    var d, root, elements, blockedSelectors, i2, element, holder, i2;
    return __generator$e(this, function(_b2) {
      switch (_b2.label) {
        case 0:
          d = document;
          root = d.createElement("div");
          elements = new Array(selectors.length);
          blockedSelectors = {};
          forceShow(root);
          for (i2 = 0; i2 < selectors.length; ++i2) {
            element = selectorToElement(selectors[i2]);
            if (element.tagName === "DIALOG") {
              element.show();
            }
            holder = d.createElement("div");
            forceShow(holder);
            holder.appendChild(element);
            root.appendChild(holder);
            elements[i2] = element;
          }
          _b2.label = 1;
        case 1:
          if (!!d.body) return [3, 3];
          return [4, wait(50)];
        case 2:
          _b2.sent();
          return [3, 1];
        case 3:
          d.body.appendChild(root);
          try {
            for (i2 = 0; i2 < selectors.length; ++i2) {
              if (!elements[i2].offsetParent) {
                blockedSelectors[selectors[i2]] = true;
              }
            }
          } finally {
            (_a3 = root.parentNode) === null || _a3 === void 0 ? void 0 : _a3.removeChild(root);
          }
          return [2, blockedSelectors];
      }
    });
  });
}
function forceShow(element) {
  element.style.setProperty("display", "block", "important");
}
function printDebug(filters, blockedSelectors) {
  var message = "DOM blockers debug:\n```";
  for (var _i2 = 0, _a3 = Object.keys(filters); _i2 < _a3.length; _i2++) {
    var filterName = _a3[_i2];
    message += "\n".concat(filterName, ":");
    for (var _b2 = 0, _c2 = filters[filterName]; _b2 < _c2.length; _b2++) {
      var selector = _c2[_b2];
      message += "\n  ".concat(blockedSelectors[selector] ? "🚫" : "➡️", " ").concat(selector);
    }
  }
  console.log("".concat(message, "\n```"));
}
function getColorGamut() {
  for (var _i2 = 0, _a3 = ["rec2020", "p3", "srgb"]; _i2 < _a3.length; _i2++) {
    var gamut = _a3[_i2];
    if (matchMedia("(color-gamut: ".concat(gamut, ")")).matches) {
      return gamut;
    }
  }
  return void 0;
}
function areColorsInverted() {
  if (doesMatch$4("inverted")) {
    return true;
  }
  if (doesMatch$4("none")) {
    return false;
  }
  return void 0;
}
function doesMatch$4(value) {
  return matchMedia("(inverted-colors: ".concat(value, ")")).matches;
}
function areColorsForced() {
  if (doesMatch$3("active")) {
    return true;
  }
  if (doesMatch$3("none")) {
    return false;
  }
  return void 0;
}
function doesMatch$3(value) {
  return matchMedia("(forced-colors: ".concat(value, ")")).matches;
}
var maxValueToCheck = 100;
function getMonochromeDepth() {
  if (!matchMedia("(min-monochrome: 0)").matches) {
    return void 0;
  }
  for (var i2 = 0; i2 <= maxValueToCheck; ++i2) {
    if (matchMedia("(max-monochrome: ".concat(i2, ")")).matches) {
      return i2;
    }
  }
  throw new Error("Too high value");
}
function getContrastPreference() {
  if (doesMatch$2("no-preference")) {
    return 0;
  }
  if (doesMatch$2("high") || doesMatch$2("more")) {
    return 1;
  }
  if (doesMatch$2("low") || doesMatch$2("less")) {
    return -1;
  }
  if (doesMatch$2("forced")) {
    return 10;
  }
  return void 0;
}
function doesMatch$2(value) {
  return matchMedia("(prefers-contrast: ".concat(value, ")")).matches;
}
function isMotionReduced() {
  if (doesMatch$1("reduce")) {
    return true;
  }
  if (doesMatch$1("no-preference")) {
    return false;
  }
  return void 0;
}
function doesMatch$1(value) {
  return matchMedia("(prefers-reduced-motion: ".concat(value, ")")).matches;
}
function isHDR() {
  if (doesMatch("high")) {
    return true;
  }
  if (doesMatch("standard")) {
    return false;
  }
  return void 0;
}
function doesMatch(value) {
  return matchMedia("(dynamic-range: ".concat(value, ")")).matches;
}
var M$1 = Math;
var fallbackFn = function() {
  return 0;
};
function getMathFingerprint() {
  var acos = M$1.acos || fallbackFn;
  var acosh = M$1.acosh || fallbackFn;
  var asin = M$1.asin || fallbackFn;
  var asinh = M$1.asinh || fallbackFn;
  var atanh = M$1.atanh || fallbackFn;
  var atan = M$1.atan || fallbackFn;
  var sin = M$1.sin || fallbackFn;
  var sinh = M$1.sinh || fallbackFn;
  var cos = M$1.cos || fallbackFn;
  var cosh = M$1.cosh || fallbackFn;
  var tan = M$1.tan || fallbackFn;
  var tanh = M$1.tanh || fallbackFn;
  var exp = M$1.exp || fallbackFn;
  var expm1 = M$1.expm1 || fallbackFn;
  var log1p = M$1.log1p || fallbackFn;
  var powPI = function(value) {
    return M$1.pow(M$1.PI, value);
  };
  var acoshPf = function(value) {
    return M$1.log(value + M$1.sqrt(value * value - 1));
  };
  var asinhPf = function(value) {
    return M$1.log(value + M$1.sqrt(value * value + 1));
  };
  var atanhPf = function(value) {
    return M$1.log((1 + value) / (1 - value)) / 2;
  };
  var sinhPf = function(value) {
    return M$1.exp(value) - 1 / M$1.exp(value) / 2;
  };
  var coshPf = function(value) {
    return (M$1.exp(value) + 1 / M$1.exp(value)) / 2;
  };
  var expm1Pf = function(value) {
    return M$1.exp(value) - 1;
  };
  var tanhPf = function(value) {
    return (M$1.exp(2 * value) - 1) / (M$1.exp(2 * value) + 1);
  };
  var log1pPf = function(value) {
    return M$1.log(1 + value);
  };
  return {
    acos: acos(0.12312423423423424),
    acosh: acosh(1e308),
    acoshPf: acoshPf(1e154),
    asin: asin(0.12312423423423424),
    asinh: asinh(1),
    asinhPf: asinhPf(1),
    atanh: atanh(0.5),
    atanhPf: atanhPf(0.5),
    atan: atan(0.5),
    sin: sin(-1e300),
    sinh: sinh(1),
    sinhPf: sinhPf(1),
    cos: cos(10.000000000123),
    cosh: cosh(1),
    coshPf: coshPf(1),
    tan: tan(-1e300),
    tanh: tanh(1),
    tanhPf: tanhPf(1),
    exp: exp(1),
    expm1: expm1(1),
    expm1Pf: expm1Pf(1),
    log1p: log1p(10),
    log1pPf: log1pPf(10),
    powPI: powPI(-100)
  };
}
var defaultText = "mmMwWLliI0fiflO&1";
var presets = {
  /**
   * The default font. User can change it in desktop Chrome, desktop Firefox, IE 11,
   * Android Chrome (but only when the size is ≥ than the default) and Android Firefox.
   */
  default: [],
  /** OS font on macOS. User can change its size and weight. Applies after Safari restart. */
  apple: [{ font: "-apple-system-body" }],
  /** User can change it in desktop Chrome and desktop Firefox. */
  serif: [{ fontFamily: "serif" }],
  /** User can change it in desktop Chrome and desktop Firefox. */
  sans: [{ fontFamily: "sans-serif" }],
  /** User can change it in desktop Chrome and desktop Firefox. */
  mono: [{ fontFamily: "monospace" }],
  /**
   * Check the smallest allowed font size. User can change it in desktop Chrome, desktop Firefox and desktop Safari.
   * The height can be 0 in Chrome on a retina display.
   */
  min: [{ fontSize: "1px" }],
  /** Tells one OS from another in desktop Chrome. */
  system: [{ fontFamily: "system-ui" }]
};
function getFontPreferences() {
  return withNaturalFonts(function(document2, container) {
    var elements = {};
    var sizes = {};
    for (var _i2 = 0, _a3 = Object.keys(presets); _i2 < _a3.length; _i2++) {
      var key2 = _a3[_i2];
      var _b2 = presets[key2], _c2 = _b2[0], style = _c2 === void 0 ? {} : _c2, _d2 = _b2[1], text = _d2 === void 0 ? defaultText : _d2;
      var element = document2.createElement("span");
      element.textContent = text;
      element.style.whiteSpace = "nowrap";
      for (var _e2 = 0, _f2 = Object.keys(style); _e2 < _f2.length; _e2++) {
        var name_1 = _f2[_e2];
        var value = style[name_1];
        if (value !== void 0) {
          element.style[name_1] = value;
        }
      }
      elements[key2] = element;
      container.appendChild(document2.createElement("br"));
      container.appendChild(element);
    }
    for (var _g2 = 0, _h2 = Object.keys(presets); _g2 < _h2.length; _g2++) {
      var key2 = _h2[_g2];
      sizes[key2] = elements[key2].getBoundingClientRect().width;
    }
    return sizes;
  });
}
function withNaturalFonts(action, containerWidthPx) {
  if (containerWidthPx === void 0) {
    containerWidthPx = 4e3;
  }
  return withIframe(function(_2, iframeWindow) {
    var iframeDocument = iframeWindow.document;
    var iframeBody = iframeDocument.body;
    var bodyStyle = iframeBody.style;
    bodyStyle.width = "".concat(containerWidthPx, "px");
    bodyStyle.webkitTextSizeAdjust = bodyStyle.textSizeAdjust = "none";
    if (isChromium()) {
      iframeBody.style.zoom = "".concat(1 / iframeWindow.devicePixelRatio);
    } else if (isWebKit()) {
      iframeBody.style.zoom = "reset";
    }
    var linesOfText = iframeDocument.createElement("div");
    linesOfText.textContent = __spreadArray$1([], Array(containerWidthPx / 20 << 0), true).map(function() {
      return "word";
    }).join(" ");
    iframeBody.appendChild(linesOfText);
    return action(iframeDocument, iframeBody);
  }, '<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">');
}
function getVideoCard() {
  var _a3;
  var canvas = document.createElement("canvas");
  var gl = (_a3 = canvas.getContext("webgl")) !== null && _a3 !== void 0 ? _a3 : canvas.getContext("experimental-webgl");
  if (gl && "getExtension" in gl) {
    var debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
    if (debugInfo) {
      return {
        vendor: (gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) || "").toString(),
        renderer: (gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || "").toString()
      };
    }
  }
  return void 0;
}
function isPdfViewerEnabled() {
  return navigator.pdfViewerEnabled;
}
function getArchitecture() {
  var f2 = new Float32Array(1);
  var u8 = new Uint8Array(f2.buffer);
  f2[0] = Infinity;
  f2[0] = f2[0] - f2[0];
  return u8[3];
}
var sources = {
  // READ FIRST:
  // See https://github.com/fingerprintjs/fingerprintjs/blob/master/contributing.md#how-to-make-an-entropy-source
  // to learn how entropy source works and how to make your own.
  // The sources run in this exact order.
  // The asynchronous sources are at the start to run in parallel with other sources.
  fonts: getFonts,
  domBlockers: getDomBlockers,
  fontPreferences: getFontPreferences,
  audio: getAudioFingerprint,
  screenFrame: getRoundedScreenFrame,
  osCpu: getOsCpu,
  languages: getLanguages,
  colorDepth: getColorDepth,
  deviceMemory: getDeviceMemory,
  screenResolution: getScreenResolution,
  hardwareConcurrency: getHardwareConcurrency,
  timezone: getTimezone,
  sessionStorage: getSessionStorage,
  localStorage: getLocalStorage,
  indexedDB: getIndexedDB,
  openDatabase: getOpenDatabase,
  cpuClass: getCpuClass,
  platform: getPlatform,
  plugins: getPlugins,
  canvas: getCanvasFingerprint,
  touchSupport: getTouchSupport,
  vendor: getVendor,
  vendorFlavors: getVendorFlavors,
  cookiesEnabled: areCookiesEnabled,
  colorGamut: getColorGamut,
  invertedColors: areColorsInverted,
  forcedColors: areColorsForced,
  monochrome: getMonochromeDepth,
  contrast: getContrastPreference,
  reducedMotion: isMotionReduced,
  hdr: isHDR,
  math: getMathFingerprint,
  videoCard: getVideoCard,
  pdfViewerEnabled: isPdfViewerEnabled,
  architecture: getArchitecture
};
function loadBuiltinSources(options2) {
  return loadSources(sources, options2, []);
}
var commentTemplate = "$ if upgrade to Pro: https://fpjs.dev/pro";
function getConfidence(components) {
  var openConfidenceScore = getOpenConfidenceScore(components);
  var proConfidenceScore = deriveProConfidenceScore(openConfidenceScore);
  return { score: openConfidenceScore, comment: commentTemplate.replace(/\$/g, "".concat(proConfidenceScore)) };
}
function getOpenConfidenceScore(components) {
  if (isAndroid()) {
    return 0.4;
  }
  if (isWebKit()) {
    return isDesktopSafari() ? 0.5 : 0.3;
  }
  var platform2 = components.platform.value || "";
  if (/^Win/.test(platform2)) {
    return 0.6;
  }
  if (/^Mac/.test(platform2)) {
    return 0.5;
  }
  return 0.7;
}
function deriveProConfidenceScore(openConfidenceScore) {
  return round(0.99 + 0.01 * openConfidenceScore, 1e-4);
}
function componentsToCanonicalString(components) {
  var result = "";
  for (var _i2 = 0, _a3 = Object.keys(components).sort(); _i2 < _a3.length; _i2++) {
    var componentKey = _a3[_i2];
    var component = components[componentKey];
    var value = component.error ? "error" : JSON.stringify(component.value);
    result += "".concat(result ? "|" : "").concat(componentKey.replace(/([:|\\])/g, "\\$1"), ":").concat(value);
  }
  return result;
}
function componentsToDebugString(components) {
  return JSON.stringify(components, function(_key, value) {
    if (value instanceof Error) {
      return errorToObject(value);
    }
    return value;
  }, 2);
}
function hashComponents(components) {
  return x64hash128(componentsToCanonicalString(components));
}
function makeLazyGetResult(components) {
  var visitorIdCache;
  var confidence = getConfidence(components);
  return {
    get visitorId() {
      if (visitorIdCache === void 0) {
        visitorIdCache = hashComponents(this.components);
      }
      return visitorIdCache;
    },
    set visitorId(visitorId) {
      visitorIdCache = visitorId;
    },
    confidence,
    components,
    version
  };
}
function prepareForSources(delayFallback) {
  if (delayFallback === void 0) {
    delayFallback = 50;
  }
  return requestIdleCallbackIfAvailable(delayFallback, delayFallback * 2);
}
function makeAgent(getComponents, debug2) {
  var creationTime = Date.now();
  return {
    get: function(options2) {
      return __awaiter$e(this, void 0, void 0, function() {
        var startTime, components, result;
        return __generator$e(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              startTime = Date.now();
              return [4, getComponents()];
            case 1:
              components = _a3.sent();
              result = makeLazyGetResult(components);
              if (debug2 || (options2 === null || options2 === void 0 ? void 0 : options2.debug)) {
                console.log("Copy the text below to get the debug data:\n\n```\nversion: ".concat(result.version, "\nuserAgent: ").concat(navigator.userAgent, "\ntimeBetweenLoadAndGet: ").concat(startTime - creationTime, "\nvisitorId: ").concat(result.visitorId, "\ncomponents: ").concat(componentsToDebugString(components), "\n```"));
              }
              return [2, result];
          }
        });
      });
    }
  };
}
function monitor() {
  if (window.__fpjs_d_m || Math.random() >= 1e-3) {
    return;
  }
  try {
    var request = new XMLHttpRequest();
    request.open("get", "https://m1.openfpcdn.io/fingerprintjs/v".concat(version, "/npm-monitoring"), true);
    request.send();
  } catch (error) {
    console.error(error);
  }
}
function load(_a3) {
  var _b2 = _a3 === void 0 ? {} : _a3, delayFallback = _b2.delayFallback, debug2 = _b2.debug, _c2 = _b2.monitoring, monitoring = _c2 === void 0 ? true : _c2;
  return __awaiter$e(this, void 0, void 0, function() {
    var getComponents;
    return __generator$e(this, function(_d2) {
      switch (_d2.label) {
        case 0:
          if (monitoring) {
            monitor();
          }
          return [4, prepareForSources(delayFallback)];
        case 1:
          _d2.sent();
          getComponents = loadBuiltinSources({ debug: debug2 });
          return [2, makeAgent(getComponents, debug2)];
      }
    });
  });
}
var index$1 = { load, hashComponents, componentsToDebugString };
var navigator2 = {
  appName: "Netscape",
  userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"
};
var window2 = {
  ASN1: null,
  Base64: null,
  Hex: null,
  crypto: null,
  href: null
};
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
function int2char(n2) {
  return BI_RM.charAt(n2);
}
function op_and(x2, y2) {
  return x2 & y2;
}
function op_or(x2, y2) {
  return x2 | y2;
}
function op_xor(x2, y2) {
  return x2 ^ y2;
}
function op_andnot(x2, y2) {
  return x2 & ~y2;
}
function lbit(x2) {
  if (x2 == 0) {
    return -1;
  }
  var r2 = 0;
  if ((x2 & 65535) == 0) {
    x2 >>= 16;
    r2 += 16;
  }
  if ((x2 & 255) == 0) {
    x2 >>= 8;
    r2 += 8;
  }
  if ((x2 & 15) == 0) {
    x2 >>= 4;
    r2 += 4;
  }
  if ((x2 & 3) == 0) {
    x2 >>= 2;
    r2 += 2;
  }
  if ((x2 & 1) == 0) {
    ++r2;
  }
  return r2;
}
function cbit(x2) {
  var r2 = 0;
  while (x2 != 0) {
    x2 &= x2 - 1;
    ++r2;
  }
  return r2;
}
var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64pad = "=";
function hex2b64(h2) {
  var i2;
  var c2;
  var ret = "";
  for (i2 = 0; i2 + 3 <= h2.length; i2 += 3) {
    c2 = parseInt(h2.substring(i2, i2 + 3), 16);
    ret += b64map.charAt(c2 >> 6) + b64map.charAt(c2 & 63);
  }
  if (i2 + 1 == h2.length) {
    c2 = parseInt(h2.substring(i2, i2 + 1), 16);
    ret += b64map.charAt(c2 << 2);
  } else if (i2 + 2 == h2.length) {
    c2 = parseInt(h2.substring(i2, i2 + 2), 16);
    ret += b64map.charAt(c2 >> 2) + b64map.charAt((c2 & 3) << 4);
  }
  while ((ret.length & 3) > 0) {
    ret += b64pad;
  }
  return ret;
}
function b64tohex(s2) {
  var ret = "";
  var i2;
  var k2 = 0;
  var slop = 0;
  for (i2 = 0; i2 < s2.length; ++i2) {
    if (s2.charAt(i2) == b64pad) {
      break;
    }
    var v2 = b64map.indexOf(s2.charAt(i2));
    if (v2 < 0) {
      continue;
    }
    if (k2 == 0) {
      ret += int2char(v2 >> 2);
      slop = v2 & 3;
      k2 = 1;
    } else if (k2 == 1) {
      ret += int2char(slop << 2 | v2 >> 4);
      slop = v2 & 15;
      k2 = 2;
    } else if (k2 == 2) {
      ret += int2char(slop);
      ret += int2char(v2 >> 2);
      slop = v2 & 3;
      k2 = 3;
    } else {
      ret += int2char(slop << 2 | v2 >> 4);
      ret += int2char(v2 & 15);
      k2 = 0;
    }
  }
  if (k2 == 1) {
    ret += int2char(slop << 2);
  }
  return ret;
}
var extendStatics = function(d, b2) {
  extendStatics = Object.setPrototypeOf || {
    __proto__: []
  } instanceof Array && function(d2, b3) {
    d2.__proto__ = b3;
  } || function(d2, b3) {
    for (var p2 in b3)
      if (b3.hasOwnProperty(p2))
        d2[p2] = b3[p2];
  };
  return extendStatics(d, b2);
};
function __extends$1(d, b2) {
  extendStatics(d, b2);
  function __() {
    this.constructor = d;
  }
  d.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
}
var decoder$1;
var Hex = {
  decode: function(a2) {
    var i2;
    if (decoder$1 === void 0) {
      var hex = "0123456789ABCDEF";
      var ignore = " \f\n\r	 \u2028\u2029";
      decoder$1 = {};
      for (i2 = 0; i2 < 16; ++i2) {
        decoder$1[hex.charAt(i2)] = i2;
      }
      hex = hex.toLowerCase();
      for (i2 = 10; i2 < 16; ++i2) {
        decoder$1[hex.charAt(i2)] = i2;
      }
      for (i2 = 0; i2 < ignore.length; ++i2) {
        decoder$1[ignore.charAt(i2)] = -1;
      }
    }
    var out = [];
    var bits = 0;
    var char_count = 0;
    for (i2 = 0; i2 < a2.length; ++i2) {
      var c2 = a2.charAt(i2);
      if (c2 == "=") {
        break;
      }
      c2 = decoder$1[c2];
      if (c2 == -1) {
        continue;
      }
      if (c2 === void 0) {
        throw new Error("Illegal character at offset " + i2);
      }
      bits |= c2;
      if (++char_count >= 2) {
        out[out.length] = bits;
        bits = 0;
        char_count = 0;
      } else {
        bits <<= 4;
      }
    }
    if (char_count) {
      throw new Error("Hex encoding incomplete: 4 bits missing");
    }
    return out;
  }
};
var decoder$1$1;
var Base64 = {
  decode: function(a2) {
    var i2;
    if (decoder$1$1 === void 0) {
      var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      var ignore = "= \f\n\r	 \u2028\u2029";
      decoder$1$1 = /* @__PURE__ */ Object.create(null);
      for (i2 = 0; i2 < 64; ++i2) {
        decoder$1$1[b64.charAt(i2)] = i2;
      }
      for (i2 = 0; i2 < ignore.length; ++i2) {
        decoder$1$1[ignore.charAt(i2)] = -1;
      }
    }
    var out = [];
    var bits = 0;
    var char_count = 0;
    for (i2 = 0; i2 < a2.length; ++i2) {
      var c2 = a2.charAt(i2);
      if (c2 == "=") {
        break;
      }
      c2 = decoder$1$1[c2];
      if (c2 == -1) {
        continue;
      }
      if (c2 === void 0) {
        throw new Error("Illegal character at offset " + i2);
      }
      bits |= c2;
      if (++char_count >= 4) {
        out[out.length] = bits >> 16;
        out[out.length] = bits >> 8 & 255;
        out[out.length] = bits & 255;
        bits = 0;
        char_count = 0;
      } else {
        bits <<= 6;
      }
    }
    switch (char_count) {
      case 1:
        throw new Error("Base64 encoding incomplete: at least 2 bits missing");
      case 2:
        out[out.length] = bits >> 10;
        break;
      case 3:
        out[out.length] = bits >> 16;
        out[out.length] = bits >> 8 & 255;
        break;
    }
    return out;
  },
  re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
  unarmor: function(a2) {
    var m = Base64.re.exec(a2);
    if (m) {
      if (m[1]) {
        a2 = m[1];
      } else if (m[2]) {
        a2 = m[2];
      } else {
        throw new Error("RegExp out of sync");
      }
    }
    return Base64.decode(a2);
  }
};
var max = 1e13;
var Int10 = function() {
  function Int102(value) {
    this.buf = [+value || 0];
  }
  Int102.prototype.mulAdd = function(m, c2) {
    var b2 = this.buf;
    var l2 = b2.length;
    var i2;
    var t2;
    for (i2 = 0; i2 < l2; ++i2) {
      t2 = b2[i2] * m + c2;
      if (t2 < max) {
        c2 = 0;
      } else {
        c2 = 0 | t2 / max;
        t2 -= c2 * max;
      }
      b2[i2] = t2;
    }
    if (c2 > 0) {
      b2[i2] = c2;
    }
  };
  Int102.prototype.sub = function(c2) {
    var b2 = this.buf;
    var l2 = b2.length;
    var i2;
    var t2;
    for (i2 = 0; i2 < l2; ++i2) {
      t2 = b2[i2] - c2;
      if (t2 < 0) {
        t2 += max;
        c2 = 1;
      } else {
        c2 = 0;
      }
      b2[i2] = t2;
    }
    while (b2[b2.length - 1] === 0) {
      b2.pop();
    }
  };
  Int102.prototype.toString = function(base2) {
    if ((base2 || 10) != 10) {
      throw new Error("only base 10 is supported");
    }
    var b2 = this.buf;
    var s2 = b2[b2.length - 1].toString();
    for (var i2 = b2.length - 2; i2 >= 0; --i2) {
      s2 += (max + b2[i2]).toString().substring(1);
    }
    return s2;
  };
  Int102.prototype.valueOf = function() {
    var b2 = this.buf;
    var v2 = 0;
    for (var i2 = b2.length - 1; i2 >= 0; --i2) {
      v2 = v2 * max + b2[i2];
    }
    return v2;
  };
  Int102.prototype.simplify = function() {
    var b2 = this.buf;
    return b2.length == 1 ? b2[0] : this;
  };
  return Int102;
}();
var ellipsis = "…";
var reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
var reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
function stringCut(str, len) {
  if (str.length > len) {
    str = str.substring(0, len) + ellipsis;
  }
  return str;
}
var Stream = function() {
  function Stream2(enc, pos) {
    this.hexDigits = "0123456789ABCDEF";
    if (enc instanceof Stream2) {
      this.enc = enc.enc;
      this.pos = enc.pos;
    } else {
      this.enc = enc;
      this.pos = pos;
    }
  }
  Stream2.prototype.get = function(pos) {
    if (pos === void 0) {
      pos = this.pos++;
    }
    if (pos >= this.enc.length) {
      throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
    }
    return "string" === typeof this.enc ? this.enc.charCodeAt(pos) : this.enc[pos];
  };
  Stream2.prototype.hexByte = function(b2) {
    return this.hexDigits.charAt(b2 >> 4 & 15) + this.hexDigits.charAt(b2 & 15);
  };
  Stream2.prototype.hexDump = function(start, end, raw) {
    var s2 = "";
    for (var i2 = start; i2 < end; ++i2) {
      s2 += this.hexByte(this.get(i2));
      if (raw !== true) {
        switch (i2 & 15) {
          case 7:
            s2 += "  ";
            break;
          case 15:
            s2 += "\n";
            break;
          default:
            s2 += " ";
        }
      }
    }
    return s2;
  };
  Stream2.prototype.isASCII = function(start, end) {
    for (var i2 = start; i2 < end; ++i2) {
      var c2 = this.get(i2);
      if (c2 < 32 || c2 > 176) {
        return false;
      }
    }
    return true;
  };
  Stream2.prototype.parseStringISO = function(start, end) {
    var s2 = "";
    for (var i2 = start; i2 < end; ++i2) {
      s2 += String.fromCharCode(this.get(i2));
    }
    return s2;
  };
  Stream2.prototype.parseStringUTF = function(start, end) {
    var s2 = "";
    for (var i2 = start; i2 < end; ) {
      var c2 = this.get(i2++);
      if (c2 < 128) {
        s2 += String.fromCharCode(c2);
      } else if (c2 > 191 && c2 < 224) {
        s2 += String.fromCharCode((c2 & 31) << 6 | this.get(i2++) & 63);
      } else {
        s2 += String.fromCharCode((c2 & 15) << 12 | (this.get(i2++) & 63) << 6 | this.get(i2++) & 63);
      }
    }
    return s2;
  };
  Stream2.prototype.parseStringBMP = function(start, end) {
    var str = "";
    var hi;
    var lo;
    for (var i2 = start; i2 < end; ) {
      hi = this.get(i2++);
      lo = this.get(i2++);
      str += String.fromCharCode(hi << 8 | lo);
    }
    return str;
  };
  Stream2.prototype.parseTime = function(start, end, shortYear) {
    var s2 = this.parseStringISO(start, end);
    var m = (shortYear ? reTimeS : reTimeL).exec(s2);
    if (!m) {
      return "Unrecognized time: " + s2;
    }
    if (shortYear) {
      m[1] = +m[1];
      m[1] += +m[1] < 70 ? 2e3 : 1900;
    }
    s2 = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
    if (m[5]) {
      s2 += ":" + m[5];
      if (m[6]) {
        s2 += ":" + m[6];
        if (m[7]) {
          s2 += "." + m[7];
        }
      }
    }
    if (m[8]) {
      s2 += " UTC";
      if (m[8] != "Z") {
        s2 += m[8];
        if (m[9]) {
          s2 += ":" + m[9];
        }
      }
    }
    return s2;
  };
  Stream2.prototype.parseInteger = function(start, end) {
    var v2 = this.get(start);
    var neg = v2 > 127;
    var pad = neg ? 255 : 0;
    var len;
    var s2 = "";
    while (v2 == pad && ++start < end) {
      v2 = this.get(start);
    }
    len = end - start;
    if (len === 0) {
      return neg ? -1 : 0;
    }
    if (len > 4) {
      s2 = v2;
      len <<= 3;
      while (((+s2 ^ pad) & 128) == 0) {
        s2 = +s2 << 1;
        --len;
      }
      s2 = "(" + len + " bit)\n";
    }
    if (neg) {
      v2 = v2 - 256;
    }
    var n2 = new Int10(v2);
    for (var i2 = start + 1; i2 < end; ++i2) {
      n2.mulAdd(256, this.get(i2));
    }
    return s2 + n2.toString();
  };
  Stream2.prototype.parseBitString = function(start, end, maxLength) {
    var unusedBit = this.get(start);
    var lenBit = (end - start - 1 << 3) - unusedBit;
    var intro = "(" + lenBit + " bit)\n";
    var s2 = "";
    for (var i2 = start + 1; i2 < end; ++i2) {
      var b2 = this.get(i2);
      var skip = i2 == end - 1 ? unusedBit : 0;
      for (var j = 7; j >= skip; --j) {
        s2 += b2 >> j & 1 ? "1" : "0";
      }
      if (s2.length > maxLength) {
        return intro + stringCut(s2, maxLength);
      }
    }
    return intro + s2;
  };
  Stream2.prototype.parseOctetString = function(start, end, maxLength) {
    if (this.isASCII(start, end)) {
      return stringCut(this.parseStringISO(start, end), maxLength);
    }
    var len = end - start;
    var s2 = "(" + len + " byte)\n";
    maxLength /= 2;
    if (len > maxLength) {
      end = start + maxLength;
    }
    for (var i2 = start; i2 < end; ++i2) {
      s2 += this.hexByte(this.get(i2));
    }
    if (len > maxLength) {
      s2 += ellipsis;
    }
    return s2;
  };
  Stream2.prototype.parseOID = function(start, end, maxLength) {
    var s2 = "";
    var n2 = new Int10();
    var bits = 0;
    for (var i2 = start; i2 < end; ++i2) {
      var v2 = this.get(i2);
      n2.mulAdd(128, v2 & 127);
      bits += 7;
      if (!(v2 & 128)) {
        if (s2 === "") {
          n2 = n2.simplify();
          if (n2 instanceof Int10) {
            n2.sub(80);
            s2 = "2." + n2.toString();
          } else {
            var m = n2 < 80 ? n2 < 40 ? 0 : 1 : 2;
            s2 = m + "." + (n2 - m * 40);
          }
        } else {
          s2 += "." + n2.toString();
        }
        if (s2.length > maxLength) {
          return stringCut(s2, maxLength);
        }
        n2 = new Int10();
        bits = 0;
      }
    }
    if (bits > 0) {
      s2 += ".incomplete";
    }
    return s2;
  };
  return Stream2;
}();
var ASN1 = function() {
  function ASN12(stream2, header, length, tag, sub) {
    if (!(tag instanceof ASN1Tag)) {
      throw new Error("Invalid tag value.");
    }
    this.stream = stream2;
    this.header = header;
    this.length = length;
    this.tag = tag;
    this.sub = sub;
  }
  ASN12.prototype.typeName = function() {
    switch (this.tag.tagClass) {
      case 0:
        switch (this.tag.tagNumber) {
          case 0:
            return "EOC";
          case 1:
            return "BOOLEAN";
          case 2:
            return "INTEGER";
          case 3:
            return "BIT_STRING";
          case 4:
            return "OCTET_STRING";
          case 5:
            return "NULL";
          case 6:
            return "OBJECT_IDENTIFIER";
          case 7:
            return "ObjectDescriptor";
          case 8:
            return "EXTERNAL";
          case 9:
            return "REAL";
          case 10:
            return "ENUMERATED";
          case 11:
            return "EMBEDDED_PDV";
          case 12:
            return "UTF8String";
          case 16:
            return "SEQUENCE";
          case 17:
            return "SET";
          case 18:
            return "NumericString";
          case 19:
            return "PrintableString";
          case 20:
            return "TeletexString";
          case 21:
            return "VideotexString";
          case 22:
            return "IA5String";
          case 23:
            return "UTCTime";
          case 24:
            return "GeneralizedTime";
          case 25:
            return "GraphicString";
          case 26:
            return "VisibleString";
          case 27:
            return "GeneralString";
          case 28:
            return "UniversalString";
          case 30:
            return "BMPString";
        }
        return "Universal_" + this.tag.tagNumber.toString();
      case 1:
        return "Application_" + this.tag.tagNumber.toString();
      case 2:
        return "[" + this.tag.tagNumber.toString() + "]";
      case 3:
        return "Private_" + this.tag.tagNumber.toString();
    }
  };
  ASN12.prototype.content = function(maxLength) {
    if (this.tag === void 0) {
      return null;
    }
    if (maxLength === void 0) {
      maxLength = Infinity;
    }
    var content = this.posContent();
    var len = Math.abs(this.length);
    if (!this.tag.isUniversal()) {
      if (this.sub !== null) {
        return "(" + this.sub.length + " elem)";
      }
      return this.stream.parseOctetString(content, content + len, maxLength);
    }
    switch (this.tag.tagNumber) {
      case 1:
        return this.stream.get(content) === 0 ? "false" : "true";
      case 2:
        return this.stream.parseInteger(content, content + len);
      case 3:
        return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseBitString(content, content + len, maxLength);
      case 4:
        return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseOctetString(content, content + len, maxLength);
      case 6:
        return this.stream.parseOID(content, content + len, maxLength);
      case 16:
      case 17:
        if (this.sub !== null) {
          return "(" + this.sub.length + " elem)";
        } else {
          return "(no elem)";
        }
      case 12:
        return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
      case 18:
      case 19:
      case 20:
      case 21:
      case 22:
      case 26:
        return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
      case 30:
        return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
      case 23:
      case 24:
        return this.stream.parseTime(content, content + len, this.tag.tagNumber == 23);
    }
    return null;
  };
  ASN12.prototype.toString = function() {
    return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + (this.sub === null ? "null" : this.sub.length) + "]";
  };
  ASN12.prototype.toPrettyString = function(indent) {
    if (indent === void 0) {
      indent = "";
    }
    var s2 = indent + this.typeName() + " @" + this.stream.pos;
    if (this.length >= 0) {
      s2 += "+";
    }
    s2 += this.length;
    if (this.tag.tagConstructed) {
      s2 += " (constructed)";
    } else if (this.tag.isUniversal() && (this.tag.tagNumber == 3 || this.tag.tagNumber == 4) && this.sub !== null) {
      s2 += " (encapsulates)";
    }
    s2 += "\n";
    if (this.sub !== null) {
      indent += "  ";
      for (var i2 = 0, max2 = this.sub.length; i2 < max2; ++i2) {
        s2 += this.sub[i2].toPrettyString(indent);
      }
    }
    return s2;
  };
  ASN12.prototype.posStart = function() {
    return this.stream.pos;
  };
  ASN12.prototype.posContent = function() {
    return this.stream.pos + this.header;
  };
  ASN12.prototype.posEnd = function() {
    return this.stream.pos + this.header + Math.abs(this.length);
  };
  ASN12.prototype.toHexString = function() {
    return this.stream.hexDump(this.posStart(), this.posEnd(), true);
  };
  ASN12.decodeLength = function(stream2) {
    var buf = stream2.get();
    var len = buf & 127;
    if (len == buf) {
      return len;
    }
    if (len > 6) {
      throw new Error("Length over 48 bits not supported at position " + (stream2.pos - 1));
    }
    if (len === 0) {
      return null;
    }
    buf = 0;
    for (var i2 = 0; i2 < len; ++i2) {
      buf = buf * 256 + stream2.get();
    }
    return buf;
  };
  ASN12.prototype.getHexStringValue = function() {
    var hexString = this.toHexString();
    var offset = this.header * 2;
    var length = this.length * 2;
    return hexString.substr(offset, length);
  };
  ASN12.decode = function(str) {
    var stream2;
    if (!(str instanceof Stream)) {
      stream2 = new Stream(str, 0);
    } else {
      stream2 = str;
    }
    var streamStart = new Stream(stream2);
    var tag = new ASN1Tag(stream2);
    var len = ASN12.decodeLength(stream2);
    var start = stream2.pos;
    var header = start - streamStart.pos;
    var sub = null;
    var getSub = function() {
      var ret = [];
      if (len !== null) {
        var end = start + len;
        while (stream2.pos < end) {
          ret[ret.length] = ASN12.decode(stream2);
        }
        if (stream2.pos != end) {
          throw new Error("Content size is not correct for container starting at offset " + start);
        }
      } else {
        try {
          for (; ; ) {
            var s2 = ASN12.decode(stream2);
            if (s2.tag.isEOC()) {
              break;
            }
            ret[ret.length] = s2;
          }
          len = start - stream2.pos;
        } catch (e4) {
          throw new Error("Exception while decoding undefined length content: " + e4);
        }
      }
      return ret;
    };
    if (tag.tagConstructed) {
      sub = getSub();
    } else if (tag.isUniversal() && (tag.tagNumber == 3 || tag.tagNumber == 4)) {
      try {
        if (tag.tagNumber == 3) {
          if (stream2.get() != 0) {
            throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
          }
        }
        sub = getSub();
        for (var i2 = 0; i2 < sub.length; ++i2) {
          if (sub[i2].tag.isEOC()) {
            throw new Error("EOC is not supposed to be actual content.");
          }
        }
      } catch (e4) {
        sub = null;
      }
    }
    if (sub === null) {
      if (len === null) {
        throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
      }
      stream2.pos = start + Math.abs(len);
    }
    return new ASN12(streamStart, header, len, tag, sub);
  };
  return ASN12;
}();
var ASN1Tag = function() {
  function ASN1Tag2(stream2) {
    var buf = stream2.get();
    this.tagClass = buf >> 6;
    this.tagConstructed = (buf & 32) !== 0;
    this.tagNumber = buf & 31;
    if (this.tagNumber == 31) {
      var n2 = new Int10();
      do {
        buf = stream2.get();
        n2.mulAdd(128, buf & 127);
      } while (buf & 128);
      this.tagNumber = n2.simplify();
    }
  }
  ASN1Tag2.prototype.isUniversal = function() {
    return this.tagClass === 0;
  };
  ASN1Tag2.prototype.isEOC = function() {
    return this.tagClass === 0 && this.tagNumber === 0;
  };
  return ASN1Tag2;
}();
var dbits;
var lowprimes = [
  2,
  3,
  5,
  7,
  11,
  13,
  17,
  19,
  23,
  29,
  31,
  37,
  41,
  43,
  47,
  53,
  59,
  61,
  67,
  71,
  73,
  79,
  83,
  89,
  97,
  101,
  103,
  107,
  109,
  113,
  127,
  131,
  137,
  139,
  149,
  151,
  157,
  163,
  167,
  173,
  179,
  181,
  191,
  193,
  197,
  199,
  211,
  223,
  227,
  229,
  233,
  239,
  241,
  251,
  257,
  263,
  269,
  271,
  277,
  281,
  283,
  293,
  307,
  311,
  313,
  317,
  331,
  337,
  347,
  349,
  353,
  359,
  367,
  373,
  379,
  383,
  389,
  397,
  401,
  409,
  419,
  421,
  431,
  433,
  439,
  443,
  449,
  457,
  461,
  463,
  467,
  479,
  487,
  491,
  499,
  503,
  509,
  521,
  523,
  541,
  547,
  557,
  563,
  569,
  571,
  577,
  587,
  593,
  599,
  601,
  607,
  613,
  617,
  619,
  631,
  641,
  643,
  647,
  653,
  659,
  661,
  673,
  677,
  683,
  691,
  701,
  709,
  719,
  727,
  733,
  739,
  743,
  751,
  757,
  761,
  769,
  773,
  787,
  797,
  809,
  811,
  821,
  823,
  827,
  829,
  839,
  853,
  857,
  859,
  863,
  877,
  881,
  883,
  887,
  907,
  911,
  919,
  929,
  937,
  941,
  947,
  953,
  967,
  971,
  977,
  983,
  991,
  997
];
var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
var BigInteger = function() {
  function BigInteger2(a2, b2, c2) {
    if (a2 != null) {
      if ("number" == typeof a2) {
        this.fromNumber(a2, b2, c2);
      } else if (b2 == null && "string" != typeof a2) {
        this.fromString(a2, 256);
      } else {
        this.fromString(a2, b2);
      }
    }
  }
  BigInteger2.prototype.toString = function(b2) {
    if (this.s < 0) {
      return "-" + this.negate().toString(b2);
    }
    var k2;
    if (b2 == 16) {
      k2 = 4;
    } else if (b2 == 8) {
      k2 = 3;
    } else if (b2 == 2) {
      k2 = 1;
    } else if (b2 == 32) {
      k2 = 5;
    } else if (b2 == 4) {
      k2 = 2;
    } else {
      return this.toRadix(b2);
    }
    var km = (1 << k2) - 1;
    var d;
    var m = false;
    var r2 = "";
    var i2 = this.t;
    var p2 = this.DB - i2 * this.DB % k2;
    if (i2-- > 0) {
      if (p2 < this.DB && (d = this[i2] >> p2) > 0) {
        m = true;
        r2 = int2char(d);
      }
      while (i2 >= 0) {
        if (p2 < k2) {
          d = (this[i2] & (1 << p2) - 1) << k2 - p2;
          d |= this[--i2] >> (p2 += this.DB - k2);
        } else {
          d = this[i2] >> (p2 -= k2) & km;
          if (p2 <= 0) {
            p2 += this.DB;
            --i2;
          }
        }
        if (d > 0) {
          m = true;
        }
        if (m) {
          r2 += int2char(d);
        }
      }
    }
    return m ? r2 : "0";
  };
  BigInteger2.prototype.negate = function() {
    var r2 = nbi();
    BigInteger2.ZERO.subTo(this, r2);
    return r2;
  };
  BigInteger2.prototype.abs = function() {
    return this.s < 0 ? this.negate() : this;
  };
  BigInteger2.prototype.compareTo = function(a2) {
    var r2 = this.s - a2.s;
    if (r2 != 0) {
      return r2;
    }
    var i2 = this.t;
    r2 = i2 - a2.t;
    if (r2 != 0) {
      return this.s < 0 ? -r2 : r2;
    }
    while (--i2 >= 0) {
      if ((r2 = this[i2] - a2[i2]) != 0) {
        return r2;
      }
    }
    return 0;
  };
  BigInteger2.prototype.bitLength = function() {
    if (this.t <= 0) {
      return 0;
    }
    return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ this.s & this.DM);
  };
  BigInteger2.prototype.mod = function(a2) {
    var r2 = nbi();
    this.abs().divRemTo(a2, null, r2);
    if (this.s < 0 && r2.compareTo(BigInteger2.ZERO) > 0) {
      a2.subTo(r2, r2);
    }
    return r2;
  };
  BigInteger2.prototype.modPowInt = function(e4, m) {
    var z2;
    if (e4 < 256 || m.isEven()) {
      z2 = new Classic(m);
    } else {
      z2 = new Montgomery(m);
    }
    return this.exp(e4, z2);
  };
  BigInteger2.prototype.clone = function() {
    var r2 = nbi();
    this.copyTo(r2);
    return r2;
  };
  BigInteger2.prototype.intValue = function() {
    if (this.s < 0) {
      if (this.t == 1) {
        return this[0] - this.DV;
      } else if (this.t == 0) {
        return -1;
      }
    } else if (this.t == 1) {
      return this[0];
    } else if (this.t == 0) {
      return 0;
    }
    return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
  };
  BigInteger2.prototype.byteValue = function() {
    return this.t == 0 ? this.s : this[0] << 24 >> 24;
  };
  BigInteger2.prototype.shortValue = function() {
    return this.t == 0 ? this.s : this[0] << 16 >> 16;
  };
  BigInteger2.prototype.signum = function() {
    if (this.s < 0) {
      return -1;
    } else if (this.t <= 0 || this.t == 1 && this[0] <= 0) {
      return 0;
    } else {
      return 1;
    }
  };
  BigInteger2.prototype.toByteArray = function() {
    var i2 = this.t;
    var r2 = [];
    r2[0] = this.s;
    var p2 = this.DB - i2 * this.DB % 8;
    var d;
    var k2 = 0;
    if (i2-- > 0) {
      if (p2 < this.DB && (d = this[i2] >> p2) != (this.s & this.DM) >> p2) {
        r2[k2++] = d | this.s << this.DB - p2;
      }
      while (i2 >= 0) {
        if (p2 < 8) {
          d = (this[i2] & (1 << p2) - 1) << 8 - p2;
          d |= this[--i2] >> (p2 += this.DB - 8);
        } else {
          d = this[i2] >> (p2 -= 8) & 255;
          if (p2 <= 0) {
            p2 += this.DB;
            --i2;
          }
        }
        if ((d & 128) != 0) {
          d |= -256;
        }
        if (k2 == 0 && (this.s & 128) != (d & 128)) {
          ++k2;
        }
        if (k2 > 0 || d != this.s) {
          r2[k2++] = d;
        }
      }
    }
    return r2;
  };
  BigInteger2.prototype.equals = function(a2) {
    return this.compareTo(a2) == 0;
  };
  BigInteger2.prototype.min = function(a2) {
    return this.compareTo(a2) < 0 ? this : a2;
  };
  BigInteger2.prototype.max = function(a2) {
    return this.compareTo(a2) > 0 ? this : a2;
  };
  BigInteger2.prototype.and = function(a2) {
    var r2 = nbi();
    this.bitwiseTo(a2, op_and, r2);
    return r2;
  };
  BigInteger2.prototype.or = function(a2) {
    var r2 = nbi();
    this.bitwiseTo(a2, op_or, r2);
    return r2;
  };
  BigInteger2.prototype.xor = function(a2) {
    var r2 = nbi();
    this.bitwiseTo(a2, op_xor, r2);
    return r2;
  };
  BigInteger2.prototype.andNot = function(a2) {
    var r2 = nbi();
    this.bitwiseTo(a2, op_andnot, r2);
    return r2;
  };
  BigInteger2.prototype.not = function() {
    var r2 = nbi();
    for (var i2 = 0; i2 < this.t; ++i2) {
      r2[i2] = this.DM & ~this[i2];
    }
    r2.t = this.t;
    r2.s = ~this.s;
    return r2;
  };
  BigInteger2.prototype.shiftLeft = function(n2) {
    var r2 = nbi();
    if (n2 < 0) {
      this.rShiftTo(-n2, r2);
    } else {
      this.lShiftTo(n2, r2);
    }
    return r2;
  };
  BigInteger2.prototype.shiftRight = function(n2) {
    var r2 = nbi();
    if (n2 < 0) {
      this.lShiftTo(-n2, r2);
    } else {
      this.rShiftTo(n2, r2);
    }
    return r2;
  };
  BigInteger2.prototype.getLowestSetBit = function() {
    for (var i2 = 0; i2 < this.t; ++i2) {
      if (this[i2] != 0) {
        return i2 * this.DB + lbit(this[i2]);
      }
    }
    if (this.s < 0) {
      return this.t * this.DB;
    }
    return -1;
  };
  BigInteger2.prototype.bitCount = function() {
    var r2 = 0;
    var x2 = this.s & this.DM;
    for (var i2 = 0; i2 < this.t; ++i2) {
      r2 += cbit(this[i2] ^ x2);
    }
    return r2;
  };
  BigInteger2.prototype.testBit = function(n2) {
    var j = Math.floor(n2 / this.DB);
    if (j >= this.t) {
      return this.s != 0;
    }
    return (this[j] & 1 << n2 % this.DB) != 0;
  };
  BigInteger2.prototype.setBit = function(n2) {
    return this.changeBit(n2, op_or);
  };
  BigInteger2.prototype.clearBit = function(n2) {
    return this.changeBit(n2, op_andnot);
  };
  BigInteger2.prototype.flipBit = function(n2) {
    return this.changeBit(n2, op_xor);
  };
  BigInteger2.prototype.add = function(a2) {
    var r2 = nbi();
    this.addTo(a2, r2);
    return r2;
  };
  BigInteger2.prototype.subtract = function(a2) {
    var r2 = nbi();
    this.subTo(a2, r2);
    return r2;
  };
  BigInteger2.prototype.multiply = function(a2) {
    var r2 = nbi();
    this.multiplyTo(a2, r2);
    return r2;
  };
  BigInteger2.prototype.divide = function(a2) {
    var r2 = nbi();
    this.divRemTo(a2, r2, null);
    return r2;
  };
  BigInteger2.prototype.remainder = function(a2) {
    var r2 = nbi();
    this.divRemTo(a2, null, r2);
    return r2;
  };
  BigInteger2.prototype.divideAndRemainder = function(a2) {
    var q = nbi();
    var r2 = nbi();
    this.divRemTo(a2, q, r2);
    return [q, r2];
  };
  BigInteger2.prototype.modPow = function(e4, m) {
    var i2 = e4.bitLength();
    var k2;
    var r2 = nbv(1);
    var z2;
    if (i2 <= 0) {
      return r2;
    } else if (i2 < 18) {
      k2 = 1;
    } else if (i2 < 48) {
      k2 = 3;
    } else if (i2 < 144) {
      k2 = 4;
    } else if (i2 < 768) {
      k2 = 5;
    } else {
      k2 = 6;
    }
    if (i2 < 8) {
      z2 = new Classic(m);
    } else if (m.isEven()) {
      z2 = new Barrett(m);
    } else {
      z2 = new Montgomery(m);
    }
    var g = [];
    var n2 = 3;
    var k1 = k2 - 1;
    var km = (1 << k2) - 1;
    g[1] = z2.convert(this);
    if (k2 > 1) {
      var g2 = nbi();
      z2.sqrTo(g[1], g2);
      while (n2 <= km) {
        g[n2] = nbi();
        z2.mulTo(g2, g[n2 - 2], g[n2]);
        n2 += 2;
      }
    }
    var j = e4.t - 1;
    var w;
    var is1 = true;
    var r22 = nbi();
    var t2;
    i2 = nbits(e4[j]) - 1;
    while (j >= 0) {
      if (i2 >= k1) {
        w = e4[j] >> i2 - k1 & km;
      } else {
        w = (e4[j] & (1 << i2 + 1) - 1) << k1 - i2;
        if (j > 0) {
          w |= e4[j - 1] >> this.DB + i2 - k1;
        }
      }
      n2 = k2;
      while ((w & 1) == 0) {
        w >>= 1;
        --n2;
      }
      if ((i2 -= n2) < 0) {
        i2 += this.DB;
        --j;
      }
      if (is1) {
        g[w].copyTo(r2);
        is1 = false;
      } else {
        while (n2 > 1) {
          z2.sqrTo(r2, r22);
          z2.sqrTo(r22, r2);
          n2 -= 2;
        }
        if (n2 > 0) {
          z2.sqrTo(r2, r22);
        } else {
          t2 = r2;
          r2 = r22;
          r22 = t2;
        }
        z2.mulTo(r22, g[w], r2);
      }
      while (j >= 0 && (e4[j] & 1 << i2) == 0) {
        z2.sqrTo(r2, r22);
        t2 = r2;
        r2 = r22;
        r22 = t2;
        if (--i2 < 0) {
          i2 = this.DB - 1;
          --j;
        }
      }
    }
    return z2.revert(r2);
  };
  BigInteger2.prototype.modInverse = function(m) {
    var ac = m.isEven();
    if (this.isEven() && ac || m.signum() == 0) {
      return BigInteger2.ZERO;
    }
    var u2 = m.clone();
    var v2 = this.clone();
    var a2 = nbv(1);
    var b2 = nbv(0);
    var c2 = nbv(0);
    var d = nbv(1);
    while (u2.signum() != 0) {
      while (u2.isEven()) {
        u2.rShiftTo(1, u2);
        if (ac) {
          if (!a2.isEven() || !b2.isEven()) {
            a2.addTo(this, a2);
            b2.subTo(m, b2);
          }
          a2.rShiftTo(1, a2);
        } else if (!b2.isEven()) {
          b2.subTo(m, b2);
        }
        b2.rShiftTo(1, b2);
      }
      while (v2.isEven()) {
        v2.rShiftTo(1, v2);
        if (ac) {
          if (!c2.isEven() || !d.isEven()) {
            c2.addTo(this, c2);
            d.subTo(m, d);
          }
          c2.rShiftTo(1, c2);
        } else if (!d.isEven()) {
          d.subTo(m, d);
        }
        d.rShiftTo(1, d);
      }
      if (u2.compareTo(v2) >= 0) {
        u2.subTo(v2, u2);
        if (ac) {
          a2.subTo(c2, a2);
        }
        b2.subTo(d, b2);
      } else {
        v2.subTo(u2, v2);
        if (ac) {
          c2.subTo(a2, c2);
        }
        d.subTo(b2, d);
      }
    }
    if (v2.compareTo(BigInteger2.ONE) != 0) {
      return BigInteger2.ZERO;
    }
    if (d.compareTo(m) >= 0) {
      return d.subtract(m);
    }
    if (d.signum() < 0) {
      d.addTo(m, d);
    } else {
      return d;
    }
    if (d.signum() < 0) {
      return d.add(m);
    } else {
      return d;
    }
  };
  BigInteger2.prototype.pow = function(e4) {
    return this.exp(e4, new NullExp());
  };
  BigInteger2.prototype.gcd = function(a2) {
    var x2 = this.s < 0 ? this.negate() : this.clone();
    var y2 = a2.s < 0 ? a2.negate() : a2.clone();
    if (x2.compareTo(y2) < 0) {
      var t2 = x2;
      x2 = y2;
      y2 = t2;
    }
    var i2 = x2.getLowestSetBit();
    var g = y2.getLowestSetBit();
    if (g < 0) {
      return x2;
    }
    if (i2 < g) {
      g = i2;
    }
    if (g > 0) {
      x2.rShiftTo(g, x2);
      y2.rShiftTo(g, y2);
    }
    while (x2.signum() > 0) {
      if ((i2 = x2.getLowestSetBit()) > 0) {
        x2.rShiftTo(i2, x2);
      }
      if ((i2 = y2.getLowestSetBit()) > 0) {
        y2.rShiftTo(i2, y2);
      }
      if (x2.compareTo(y2) >= 0) {
        x2.subTo(y2, x2);
        x2.rShiftTo(1, x2);
      } else {
        y2.subTo(x2, y2);
        y2.rShiftTo(1, y2);
      }
    }
    if (g > 0) {
      y2.lShiftTo(g, y2);
    }
    return y2;
  };
  BigInteger2.prototype.isProbablePrime = function(t2) {
    var i2;
    var x2 = this.abs();
    if (x2.t == 1 && x2[0] <= lowprimes[lowprimes.length - 1]) {
      for (i2 = 0; i2 < lowprimes.length; ++i2) {
        if (x2[0] == lowprimes[i2]) {
          return true;
        }
      }
      return false;
    }
    if (x2.isEven()) {
      return false;
    }
    i2 = 1;
    while (i2 < lowprimes.length) {
      var m = lowprimes[i2];
      var j = i2 + 1;
      while (j < lowprimes.length && m < lplim) {
        m *= lowprimes[j++];
      }
      m = x2.modInt(m);
      while (i2 < j) {
        if (m % lowprimes[i2++] == 0) {
          return false;
        }
      }
    }
    return x2.millerRabin(t2);
  };
  BigInteger2.prototype.copyTo = function(r2) {
    for (var i2 = this.t - 1; i2 >= 0; --i2) {
      r2[i2] = this[i2];
    }
    r2.t = this.t;
    r2.s = this.s;
  };
  BigInteger2.prototype.fromInt = function(x2) {
    this.t = 1;
    this.s = x2 < 0 ? -1 : 0;
    if (x2 > 0) {
      this[0] = x2;
    } else if (x2 < -1) {
      this[0] = x2 + this.DV;
    } else {
      this.t = 0;
    }
  };
  BigInteger2.prototype.fromString = function(s2, b2) {
    var k2;
    if (b2 == 16) {
      k2 = 4;
    } else if (b2 == 8) {
      k2 = 3;
    } else if (b2 == 256) {
      k2 = 8;
    } else if (b2 == 2) {
      k2 = 1;
    } else if (b2 == 32) {
      k2 = 5;
    } else if (b2 == 4) {
      k2 = 2;
    } else {
      this.fromRadix(s2, b2);
      return;
    }
    this.t = 0;
    this.s = 0;
    var i2 = s2.length;
    var mi = false;
    var sh = 0;
    while (--i2 >= 0) {
      var x2 = k2 == 8 ? +s2[i2] & 255 : intAt(s2, i2);
      if (x2 < 0) {
        if (s2.charAt(i2) == "-") {
          mi = true;
        }
        continue;
      }
      mi = false;
      if (sh == 0) {
        this[this.t++] = x2;
      } else if (sh + k2 > this.DB) {
        this[this.t - 1] |= (x2 & (1 << this.DB - sh) - 1) << sh;
        this[this.t++] = x2 >> this.DB - sh;
      } else {
        this[this.t - 1] |= x2 << sh;
      }
      sh += k2;
      if (sh >= this.DB) {
        sh -= this.DB;
      }
    }
    if (k2 == 8 && (+s2[0] & 128) != 0) {
      this.s = -1;
      if (sh > 0) {
        this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
      }
    }
    this.clamp();
    if (mi) {
      BigInteger2.ZERO.subTo(this, this);
    }
  };
  BigInteger2.prototype.clamp = function() {
    var c2 = this.s & this.DM;
    while (this.t > 0 && this[this.t - 1] == c2) {
      --this.t;
    }
  };
  BigInteger2.prototype.dlShiftTo = function(n2, r2) {
    var i2;
    for (i2 = this.t - 1; i2 >= 0; --i2) {
      r2[i2 + n2] = this[i2];
    }
    for (i2 = n2 - 1; i2 >= 0; --i2) {
      r2[i2] = 0;
    }
    r2.t = this.t + n2;
    r2.s = this.s;
  };
  BigInteger2.prototype.drShiftTo = function(n2, r2) {
    for (var i2 = n2; i2 < this.t; ++i2) {
      r2[i2 - n2] = this[i2];
    }
    r2.t = Math.max(this.t - n2, 0);
    r2.s = this.s;
  };
  BigInteger2.prototype.lShiftTo = function(n2, r2) {
    var bs = n2 % this.DB;
    var cbs = this.DB - bs;
    var bm = (1 << cbs) - 1;
    var ds = Math.floor(n2 / this.DB);
    var c2 = this.s << bs & this.DM;
    for (var i2 = this.t - 1; i2 >= 0; --i2) {
      r2[i2 + ds + 1] = this[i2] >> cbs | c2;
      c2 = (this[i2] & bm) << bs;
    }
    for (var i2 = ds - 1; i2 >= 0; --i2) {
      r2[i2] = 0;
    }
    r2[ds] = c2;
    r2.t = this.t + ds + 1;
    r2.s = this.s;
    r2.clamp();
  };
  BigInteger2.prototype.rShiftTo = function(n2, r2) {
    r2.s = this.s;
    var ds = Math.floor(n2 / this.DB);
    if (ds >= this.t) {
      r2.t = 0;
      return;
    }
    var bs = n2 % this.DB;
    var cbs = this.DB - bs;
    var bm = (1 << bs) - 1;
    r2[0] = this[ds] >> bs;
    for (var i2 = ds + 1; i2 < this.t; ++i2) {
      r2[i2 - ds - 1] |= (this[i2] & bm) << cbs;
      r2[i2 - ds] = this[i2] >> bs;
    }
    if (bs > 0) {
      r2[this.t - ds - 1] |= (this.s & bm) << cbs;
    }
    r2.t = this.t - ds;
    r2.clamp();
  };
  BigInteger2.prototype.subTo = function(a2, r2) {
    var i2 = 0;
    var c2 = 0;
    var m = Math.min(a2.t, this.t);
    while (i2 < m) {
      c2 += this[i2] - a2[i2];
      r2[i2++] = c2 & this.DM;
      c2 >>= this.DB;
    }
    if (a2.t < this.t) {
      c2 -= a2.s;
      while (i2 < this.t) {
        c2 += this[i2];
        r2[i2++] = c2 & this.DM;
        c2 >>= this.DB;
      }
      c2 += this.s;
    } else {
      c2 += this.s;
      while (i2 < a2.t) {
        c2 -= a2[i2];
        r2[i2++] = c2 & this.DM;
        c2 >>= this.DB;
      }
      c2 -= a2.s;
    }
    r2.s = c2 < 0 ? -1 : 0;
    if (c2 < -1) {
      r2[i2++] = this.DV + c2;
    } else if (c2 > 0) {
      r2[i2++] = c2;
    }
    r2.t = i2;
    r2.clamp();
  };
  BigInteger2.prototype.multiplyTo = function(a2, r2) {
    var x2 = this.abs();
    var y2 = a2.abs();
    var i2 = x2.t;
    r2.t = i2 + y2.t;
    while (--i2 >= 0) {
      r2[i2] = 0;
    }
    for (i2 = 0; i2 < y2.t; ++i2) {
      r2[i2 + x2.t] = x2.am(0, y2[i2], r2, i2, 0, x2.t);
    }
    r2.s = 0;
    r2.clamp();
    if (this.s != a2.s) {
      BigInteger2.ZERO.subTo(r2, r2);
    }
  };
  BigInteger2.prototype.squareTo = function(r2) {
    var x2 = this.abs();
    var i2 = r2.t = 2 * x2.t;
    while (--i2 >= 0) {
      r2[i2] = 0;
    }
    for (i2 = 0; i2 < x2.t - 1; ++i2) {
      var c2 = x2.am(i2, x2[i2], r2, 2 * i2, 0, 1);
      if ((r2[i2 + x2.t] += x2.am(i2 + 1, 2 * x2[i2], r2, 2 * i2 + 1, c2, x2.t - i2 - 1)) >= x2.DV) {
        r2[i2 + x2.t] -= x2.DV;
        r2[i2 + x2.t + 1] = 1;
      }
    }
    if (r2.t > 0) {
      r2[r2.t - 1] += x2.am(i2, x2[i2], r2, 2 * i2, 0, 1);
    }
    r2.s = 0;
    r2.clamp();
  };
  BigInteger2.prototype.divRemTo = function(m, q, r2) {
    var pm = m.abs();
    if (pm.t <= 0) {
      return;
    }
    var pt = this.abs();
    if (pt.t < pm.t) {
      if (q != null) {
        q.fromInt(0);
      }
      if (r2 != null) {
        this.copyTo(r2);
      }
      return;
    }
    if (r2 == null) {
      r2 = nbi();
    }
    var y2 = nbi();
    var ts = this.s;
    var ms2 = m.s;
    var nsh = this.DB - nbits(pm[pm.t - 1]);
    if (nsh > 0) {
      pm.lShiftTo(nsh, y2);
      pt.lShiftTo(nsh, r2);
    } else {
      pm.copyTo(y2);
      pt.copyTo(r2);
    }
    var ys = y2.t;
    var y0 = y2[ys - 1];
    if (y0 == 0) {
      return;
    }
    var yt = y0 * (1 << this.F1) + (ys > 1 ? y2[ys - 2] >> this.F2 : 0);
    var d1 = this.FV / yt;
    var d2 = (1 << this.F1) / yt;
    var e4 = 1 << this.F2;
    var i2 = r2.t;
    var j = i2 - ys;
    var t2 = q == null ? nbi() : q;
    y2.dlShiftTo(j, t2);
    if (r2.compareTo(t2) >= 0) {
      r2[r2.t++] = 1;
      r2.subTo(t2, r2);
    }
    BigInteger2.ONE.dlShiftTo(ys, t2);
    t2.subTo(y2, y2);
    while (y2.t < ys) {
      y2[y2.t++] = 0;
    }
    while (--j >= 0) {
      var qd = r2[--i2] == y0 ? this.DM : Math.floor(r2[i2] * d1 + (r2[i2 - 1] + e4) * d2);
      if ((r2[i2] += y2.am(0, qd, r2, j, 0, ys)) < qd) {
        y2.dlShiftTo(j, t2);
        r2.subTo(t2, r2);
        while (r2[i2] < --qd) {
          r2.subTo(t2, r2);
        }
      }
    }
    if (q != null) {
      r2.drShiftTo(ys, q);
      if (ts != ms2) {
        BigInteger2.ZERO.subTo(q, q);
      }
    }
    r2.t = ys;
    r2.clamp();
    if (nsh > 0) {
      r2.rShiftTo(nsh, r2);
    }
    if (ts < 0) {
      BigInteger2.ZERO.subTo(r2, r2);
    }
  };
  BigInteger2.prototype.invDigit = function() {
    if (this.t < 1) {
      return 0;
    }
    var x2 = this[0];
    if ((x2 & 1) == 0) {
      return 0;
    }
    var y2 = x2 & 3;
    y2 = y2 * (2 - (x2 & 15) * y2) & 15;
    y2 = y2 * (2 - (x2 & 255) * y2) & 255;
    y2 = y2 * (2 - ((x2 & 65535) * y2 & 65535)) & 65535;
    y2 = y2 * (2 - x2 * y2 % this.DV) % this.DV;
    return y2 > 0 ? this.DV - y2 : -y2;
  };
  BigInteger2.prototype.isEven = function() {
    return (this.t > 0 ? this[0] & 1 : this.s) == 0;
  };
  BigInteger2.prototype.exp = function(e4, z2) {
    if (e4 > 4294967295 || e4 < 1) {
      return BigInteger2.ONE;
    }
    var r2 = nbi();
    var r22 = nbi();
    var g = z2.convert(this);
    var i2 = nbits(e4) - 1;
    g.copyTo(r2);
    while (--i2 >= 0) {
      z2.sqrTo(r2, r22);
      if ((e4 & 1 << i2) > 0) {
        z2.mulTo(r22, g, r2);
      } else {
        var t2 = r2;
        r2 = r22;
        r22 = t2;
      }
    }
    return z2.revert(r2);
  };
  BigInteger2.prototype.chunkSize = function(r2) {
    return Math.floor(Math.LN2 * this.DB / Math.log(r2));
  };
  BigInteger2.prototype.toRadix = function(b2) {
    if (b2 == null) {
      b2 = 10;
    }
    if (this.signum() == 0 || b2 < 2 || b2 > 36) {
      return "0";
    }
    var cs = this.chunkSize(b2);
    var a2 = Math.pow(b2, cs);
    var d = nbv(a2);
    var y2 = nbi();
    var z2 = nbi();
    var r2 = "";
    this.divRemTo(d, y2, z2);
    while (y2.signum() > 0) {
      r2 = (a2 + z2.intValue()).toString(b2).substr(1) + r2;
      y2.divRemTo(d, y2, z2);
    }
    return z2.intValue().toString(b2) + r2;
  };
  BigInteger2.prototype.fromRadix = function(s2, b2) {
    this.fromInt(0);
    if (b2 == null) {
      b2 = 10;
    }
    var cs = this.chunkSize(b2);
    var d = Math.pow(b2, cs);
    var mi = false;
    var j = 0;
    var w = 0;
    for (var i2 = 0; i2 < s2.length; ++i2) {
      var x2 = intAt(s2, i2);
      if (x2 < 0) {
        if (s2.charAt(i2) == "-" && this.signum() == 0) {
          mi = true;
        }
        continue;
      }
      w = b2 * w + x2;
      if (++j >= cs) {
        this.dMultiply(d);
        this.dAddOffset(w, 0);
        j = 0;
        w = 0;
      }
    }
    if (j > 0) {
      this.dMultiply(Math.pow(b2, j));
      this.dAddOffset(w, 0);
    }
    if (mi) {
      BigInteger2.ZERO.subTo(this, this);
    }
  };
  BigInteger2.prototype.fromNumber = function(a2, b2, c2) {
    if ("number" == typeof b2) {
      if (a2 < 2) {
        this.fromInt(1);
      } else {
        this.fromNumber(a2, c2);
        if (!this.testBit(a2 - 1)) {
          this.bitwiseTo(BigInteger2.ONE.shiftLeft(a2 - 1), op_or, this);
        }
        if (this.isEven()) {
          this.dAddOffset(1, 0);
        }
        while (!this.isProbablePrime(b2)) {
          this.dAddOffset(2, 0);
          if (this.bitLength() > a2) {
            this.subTo(BigInteger2.ONE.shiftLeft(a2 - 1), this);
          }
        }
      }
    } else {
      var x2 = [];
      var t2 = a2 & 7;
      x2.length = (a2 >> 3) + 1;
      b2.nextBytes(x2);
      if (t2 > 0) {
        x2[0] &= (1 << t2) - 1;
      } else {
        x2[0] = 0;
      }
      this.fromString(x2, 256);
    }
  };
  BigInteger2.prototype.bitwiseTo = function(a2, op, r2) {
    var i2;
    var f2;
    var m = Math.min(a2.t, this.t);
    for (i2 = 0; i2 < m; ++i2) {
      r2[i2] = op(this[i2], a2[i2]);
    }
    if (a2.t < this.t) {
      f2 = a2.s & this.DM;
      for (i2 = m; i2 < this.t; ++i2) {
        r2[i2] = op(this[i2], f2);
      }
      r2.t = this.t;
    } else {
      f2 = this.s & this.DM;
      for (i2 = m; i2 < a2.t; ++i2) {
        r2[i2] = op(f2, a2[i2]);
      }
      r2.t = a2.t;
    }
    r2.s = op(this.s, a2.s);
    r2.clamp();
  };
  BigInteger2.prototype.changeBit = function(n2, op) {
    var r2 = BigInteger2.ONE.shiftLeft(n2);
    this.bitwiseTo(r2, op, r2);
    return r2;
  };
  BigInteger2.prototype.addTo = function(a2, r2) {
    var i2 = 0;
    var c2 = 0;
    var m = Math.min(a2.t, this.t);
    while (i2 < m) {
      c2 += this[i2] + a2[i2];
      r2[i2++] = c2 & this.DM;
      c2 >>= this.DB;
    }
    if (a2.t < this.t) {
      c2 += a2.s;
      while (i2 < this.t) {
        c2 += this[i2];
        r2[i2++] = c2 & this.DM;
        c2 >>= this.DB;
      }
      c2 += this.s;
    } else {
      c2 += this.s;
      while (i2 < a2.t) {
        c2 += a2[i2];
        r2[i2++] = c2 & this.DM;
        c2 >>= this.DB;
      }
      c2 += a2.s;
    }
    r2.s = c2 < 0 ? -1 : 0;
    if (c2 > 0) {
      r2[i2++] = c2;
    } else if (c2 < -1) {
      r2[i2++] = this.DV + c2;
    }
    r2.t = i2;
    r2.clamp();
  };
  BigInteger2.prototype.dMultiply = function(n2) {
    this[this.t] = this.am(0, n2 - 1, this, 0, 0, this.t);
    ++this.t;
    this.clamp();
  };
  BigInteger2.prototype.dAddOffset = function(n2, w) {
    if (n2 == 0) {
      return;
    }
    while (this.t <= w) {
      this[this.t++] = 0;
    }
    this[w] += n2;
    while (this[w] >= this.DV) {
      this[w] -= this.DV;
      if (++w >= this.t) {
        this[this.t++] = 0;
      }
      ++this[w];
    }
  };
  BigInteger2.prototype.multiplyLowerTo = function(a2, n2, r2) {
    var i2 = Math.min(this.t + a2.t, n2);
    r2.s = 0;
    r2.t = i2;
    while (i2 > 0) {
      r2[--i2] = 0;
    }
    for (var j = r2.t - this.t; i2 < j; ++i2) {
      r2[i2 + this.t] = this.am(0, a2[i2], r2, i2, 0, this.t);
    }
    for (var j = Math.min(a2.t, n2); i2 < j; ++i2) {
      this.am(0, a2[i2], r2, i2, 0, n2 - i2);
    }
    r2.clamp();
  };
  BigInteger2.prototype.multiplyUpperTo = function(a2, n2, r2) {
    --n2;
    var i2 = r2.t = this.t + a2.t - n2;
    r2.s = 0;
    while (--i2 >= 0) {
      r2[i2] = 0;
    }
    for (i2 = Math.max(n2 - this.t, 0); i2 < a2.t; ++i2) {
      r2[this.t + i2 - n2] = this.am(n2 - i2, a2[i2], r2, 0, 0, this.t + i2 - n2);
    }
    r2.clamp();
    r2.drShiftTo(1, r2);
  };
  BigInteger2.prototype.modInt = function(n2) {
    if (n2 <= 0) {
      return 0;
    }
    var d = this.DV % n2;
    var r2 = this.s < 0 ? n2 - 1 : 0;
    if (this.t > 0) {
      if (d == 0) {
        r2 = this[0] % n2;
      } else {
        for (var i2 = this.t - 1; i2 >= 0; --i2) {
          r2 = (d * r2 + this[i2]) % n2;
        }
      }
    }
    return r2;
  };
  BigInteger2.prototype.millerRabin = function(t2) {
    var n1 = this.subtract(BigInteger2.ONE);
    var k2 = n1.getLowestSetBit();
    if (k2 <= 0) {
      return false;
    }
    var r2 = n1.shiftRight(k2);
    t2 = t2 + 1 >> 1;
    if (t2 > lowprimes.length) {
      t2 = lowprimes.length;
    }
    var a2 = nbi();
    for (var i2 = 0; i2 < t2; ++i2) {
      a2.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
      var y2 = a2.modPow(r2, this);
      if (y2.compareTo(BigInteger2.ONE) != 0 && y2.compareTo(n1) != 0) {
        var j = 1;
        while (j++ < k2 && y2.compareTo(n1) != 0) {
          y2 = y2.modPowInt(2, this);
          if (y2.compareTo(BigInteger2.ONE) == 0) {
            return false;
          }
        }
        if (y2.compareTo(n1) != 0) {
          return false;
        }
      }
    }
    return true;
  };
  BigInteger2.prototype.square = function() {
    var r2 = nbi();
    this.squareTo(r2);
    return r2;
  };
  BigInteger2.prototype.gcda = function(a2, callback) {
    var x2 = this.s < 0 ? this.negate() : this.clone();
    var y2 = a2.s < 0 ? a2.negate() : a2.clone();
    if (x2.compareTo(y2) < 0) {
      var t2 = x2;
      x2 = y2;
      y2 = t2;
    }
    var i2 = x2.getLowestSetBit();
    var g = y2.getLowestSetBit();
    if (g < 0) {
      callback(x2);
      return;
    }
    if (i2 < g) {
      g = i2;
    }
    if (g > 0) {
      x2.rShiftTo(g, x2);
      y2.rShiftTo(g, y2);
    }
    var gcda1 = function() {
      if ((i2 = x2.getLowestSetBit()) > 0) {
        x2.rShiftTo(i2, x2);
      }
      if ((i2 = y2.getLowestSetBit()) > 0) {
        y2.rShiftTo(i2, y2);
      }
      if (x2.compareTo(y2) >= 0) {
        x2.subTo(y2, x2);
        x2.rShiftTo(1, x2);
      } else {
        y2.subTo(x2, y2);
        y2.rShiftTo(1, y2);
      }
      if (!(x2.signum() > 0)) {
        if (g > 0) {
          y2.lShiftTo(g, y2);
        }
        setTimeout(function() {
          callback(y2);
        }, 0);
      } else {
        setTimeout(gcda1, 0);
      }
    };
    setTimeout(gcda1, 10);
  };
  BigInteger2.prototype.fromNumberAsync = function(a2, b2, c2, callback) {
    if ("number" == typeof b2) {
      if (a2 < 2) {
        this.fromInt(1);
      } else {
        this.fromNumber(a2, c2);
        if (!this.testBit(a2 - 1)) {
          this.bitwiseTo(BigInteger2.ONE.shiftLeft(a2 - 1), op_or, this);
        }
        if (this.isEven()) {
          this.dAddOffset(1, 0);
        }
        var bnp_1 = this;
        var bnpfn1_1 = function() {
          bnp_1.dAddOffset(2, 0);
          if (bnp_1.bitLength() > a2) {
            bnp_1.subTo(BigInteger2.ONE.shiftLeft(a2 - 1), bnp_1);
          }
          if (bnp_1.isProbablePrime(b2)) {
            setTimeout(function() {
              callback();
            }, 0);
          } else {
            setTimeout(bnpfn1_1, 0);
          }
        };
        setTimeout(bnpfn1_1, 0);
      }
    } else {
      var x2 = [];
      var t2 = a2 & 7;
      x2.length = (a2 >> 3) + 1;
      b2.nextBytes(x2);
      if (t2 > 0) {
        x2[0] &= (1 << t2) - 1;
      } else {
        x2[0] = 0;
      }
      this.fromString(x2, 256);
    }
  };
  return BigInteger2;
}();
var NullExp = function() {
  function NullExp2() {
  }
  NullExp2.prototype.convert = function(x2) {
    return x2;
  };
  NullExp2.prototype.revert = function(x2) {
    return x2;
  };
  NullExp2.prototype.mulTo = function(x2, y2, r2) {
    x2.multiplyTo(y2, r2);
  };
  NullExp2.prototype.sqrTo = function(x2, r2) {
    x2.squareTo(r2);
  };
  return NullExp2;
}();
var Classic = function() {
  function Classic2(m) {
    this.m = m;
  }
  Classic2.prototype.convert = function(x2) {
    if (x2.s < 0 || x2.compareTo(this.m) >= 0) {
      return x2.mod(this.m);
    } else {
      return x2;
    }
  };
  Classic2.prototype.revert = function(x2) {
    return x2;
  };
  Classic2.prototype.reduce = function(x2) {
    x2.divRemTo(this.m, null, x2);
  };
  Classic2.prototype.mulTo = function(x2, y2, r2) {
    x2.multiplyTo(y2, r2);
    this.reduce(r2);
  };
  Classic2.prototype.sqrTo = function(x2, r2) {
    x2.squareTo(r2);
    this.reduce(r2);
  };
  return Classic2;
}();
var Montgomery = function() {
  function Montgomery2(m) {
    this.m = m;
    this.mp = m.invDigit();
    this.mpl = this.mp & 32767;
    this.mph = this.mp >> 15;
    this.um = (1 << m.DB - 15) - 1;
    this.mt2 = 2 * m.t;
  }
  Montgomery2.prototype.convert = function(x2) {
    var r2 = nbi();
    x2.abs().dlShiftTo(this.m.t, r2);
    r2.divRemTo(this.m, null, r2);
    if (x2.s < 0 && r2.compareTo(BigInteger.ZERO) > 0) {
      this.m.subTo(r2, r2);
    }
    return r2;
  };
  Montgomery2.prototype.revert = function(x2) {
    var r2 = nbi();
    x2.copyTo(r2);
    this.reduce(r2);
    return r2;
  };
  Montgomery2.prototype.reduce = function(x2) {
    while (x2.t <= this.mt2) {
      x2[x2.t++] = 0;
    }
    for (var i2 = 0; i2 < this.m.t; ++i2) {
      var j = x2[i2] & 32767;
      var u0 = j * this.mpl + ((j * this.mph + (x2[i2] >> 15) * this.mpl & this.um) << 15) & x2.DM;
      j = i2 + this.m.t;
      x2[j] += this.m.am(0, u0, x2, i2, 0, this.m.t);
      while (x2[j] >= x2.DV) {
        x2[j] -= x2.DV;
        x2[++j]++;
      }
    }
    x2.clamp();
    x2.drShiftTo(this.m.t, x2);
    if (x2.compareTo(this.m) >= 0) {
      x2.subTo(this.m, x2);
    }
  };
  Montgomery2.prototype.mulTo = function(x2, y2, r2) {
    x2.multiplyTo(y2, r2);
    this.reduce(r2);
  };
  Montgomery2.prototype.sqrTo = function(x2, r2) {
    x2.squareTo(r2);
    this.reduce(r2);
  };
  return Montgomery2;
}();
var Barrett = function() {
  function Barrett2(m) {
    this.m = m;
    this.r2 = nbi();
    this.q3 = nbi();
    BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
    this.mu = this.r2.divide(m);
  }
  Barrett2.prototype.convert = function(x2) {
    if (x2.s < 0 || x2.t > 2 * this.m.t) {
      return x2.mod(this.m);
    } else if (x2.compareTo(this.m) < 0) {
      return x2;
    } else {
      var r2 = nbi();
      x2.copyTo(r2);
      this.reduce(r2);
      return r2;
    }
  };
  Barrett2.prototype.revert = function(x2) {
    return x2;
  };
  Barrett2.prototype.reduce = function(x2) {
    x2.drShiftTo(this.m.t - 1, this.r2);
    if (x2.t > this.m.t + 1) {
      x2.t = this.m.t + 1;
      x2.clamp();
    }
    this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
    this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
    while (x2.compareTo(this.r2) < 0) {
      x2.dAddOffset(1, this.m.t + 1);
    }
    x2.subTo(this.r2, x2);
    while (x2.compareTo(this.m) >= 0) {
      x2.subTo(this.m, x2);
    }
  };
  Barrett2.prototype.mulTo = function(x2, y2, r2) {
    x2.multiplyTo(y2, r2);
    this.reduce(r2);
  };
  Barrett2.prototype.sqrTo = function(x2, r2) {
    x2.squareTo(r2);
    this.reduce(r2);
  };
  return Barrett2;
}();
function nbi() {
  return new BigInteger(null);
}
function parseBigInt(str, r2) {
  return new BigInteger(str, r2);
}
function am3(i2, x2, w, j, c2, n2) {
  var xl = x2 & 16383;
  var xh = x2 >> 14;
  while (--n2 >= 0) {
    var l2 = this[i2] & 16383;
    var h2 = this[i2++] >> 14;
    var m = xh * l2 + h2 * xl;
    l2 = xl * l2 + ((m & 16383) << 14) + w[j] + c2;
    c2 = (l2 >> 28) + (m >> 14) + xh * h2;
    w[j++] = l2 & 268435455;
  }
  return c2;
}
{
  BigInteger.prototype.am = am3;
  dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = (1 << dbits) - 1;
BigInteger.prototype.DV = 1 << dbits;
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2, BI_FP);
BigInteger.prototype.F1 = BI_FP - dbits;
BigInteger.prototype.F2 = 2 * dbits - BI_FP;
var BI_RC = [];
var rr;
var vv;
rr = "0".charCodeAt(0);
for (vv = 0; vv <= 9; ++vv) {
  BI_RC[rr++] = vv;
}
rr = "a".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
  BI_RC[rr++] = vv;
}
rr = "A".charCodeAt(0);
for (vv = 10; vv < 36; ++vv) {
  BI_RC[rr++] = vv;
}
function intAt(s2, i2) {
  var c2 = BI_RC[s2.charCodeAt(i2)];
  return c2 == null ? -1 : c2;
}
function nbv(i2) {
  var r2 = nbi();
  r2.fromInt(i2);
  return r2;
}
function nbits(x2) {
  var r2 = 1;
  var t2;
  if ((t2 = x2 >>> 16) != 0) {
    x2 = t2;
    r2 += 16;
  }
  if ((t2 = x2 >> 8) != 0) {
    x2 = t2;
    r2 += 8;
  }
  if ((t2 = x2 >> 4) != 0) {
    x2 = t2;
    r2 += 4;
  }
  if ((t2 = x2 >> 2) != 0) {
    x2 = t2;
    r2 += 2;
  }
  if ((t2 = x2 >> 1) != 0) {
    x2 = t2;
    r2 += 1;
  }
  return r2;
}
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
var Arcfour = function() {
  function Arcfour2() {
    this.i = 0;
    this.j = 0;
    this.S = [];
  }
  Arcfour2.prototype.init = function(key2) {
    var i2;
    var j;
    var t2;
    for (i2 = 0; i2 < 256; ++i2) {
      this.S[i2] = i2;
    }
    j = 0;
    for (i2 = 0; i2 < 256; ++i2) {
      j = j + this.S[i2] + key2[i2 % key2.length] & 255;
      t2 = this.S[i2];
      this.S[i2] = this.S[j];
      this.S[j] = t2;
    }
    this.i = 0;
    this.j = 0;
  };
  Arcfour2.prototype.next = function() {
    var t2;
    this.i = this.i + 1 & 255;
    this.j = this.j + this.S[this.i] & 255;
    t2 = this.S[this.i];
    this.S[this.i] = this.S[this.j];
    this.S[this.j] = t2;
    return this.S[t2 + this.S[this.i] & 255];
  };
  return Arcfour2;
}();
function prng_newstate() {
  return new Arcfour();
}
var rng_psize = 256;
var rng_state;
var rng_pool = null;
var rng_pptr;
if (rng_pool == null) {
  rng_pool = [];
  rng_pptr = 0;
  var t$2 = void 0;
  if (window2.crypto && window2.crypto.getRandomValues) {
    var z$1 = new Uint32Array(256);
    window2.crypto.getRandomValues(z$1);
    for (t$2 = 0; t$2 < z$1.length; ++t$2) {
      rng_pool[rng_pptr++] = z$1[t$2] & 255;
    }
  }
  var onMouseMoveListener_1 = function(ev) {
    this.count = this.count || 0;
    if (this.count >= 256 || rng_pptr >= rng_psize) {
      if (window2.removeEventListener) {
        window2.removeEventListener("mousemove", onMouseMoveListener_1, false);
      } else if (window2.detachEvent) {
        window2.detachEvent("onmousemove", onMouseMoveListener_1);
      }
      return;
    }
    try {
      var mouseCoordinates = ev.x + ev.y;
      rng_pool[rng_pptr++] = mouseCoordinates & 255;
      this.count += 1;
    } catch (e4) {
    }
  };
  if (window2.addEventListener) {
    window2.addEventListener("mousemove", onMouseMoveListener_1, false);
  } else if (window2.attachEvent) {
    window2.attachEvent("onmousemove", onMouseMoveListener_1);
  }
}
function rng_get_byte() {
  if (rng_state == null) {
    rng_state = prng_newstate();
    while (rng_pptr < rng_psize) {
      var random = Math.floor(65536 * Math.random());
      rng_pool[rng_pptr++] = random & 255;
    }
    rng_state.init(rng_pool);
    for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
      rng_pool[rng_pptr] = 0;
    }
    rng_pptr = 0;
  }
  return rng_state.next();
}
var SecureRandom = function() {
  function SecureRandom2() {
  }
  SecureRandom2.prototype.nextBytes = function(ba) {
    for (var i2 = 0; i2 < ba.length; ++i2) {
      ba[i2] = rng_get_byte();
    }
  };
  return SecureRandom2;
}();
function pkcs1pad1(s2, n2) {
  if (n2 < s2.length + 22) {
    console.error("Message too long for RSA");
    return null;
  }
  var len = n2 - s2.length - 6;
  var filler = "";
  for (var f2 = 0; f2 < len; f2 += 2) {
    filler += "ff";
  }
  var m = "0001" + filler + "00" + s2;
  return parseBigInt(m, 16);
}
function pkcs1pad2(s2, n2) {
  if (n2 < s2.length + 11) {
    console.error("Message too long for RSA");
    return null;
  }
  var ba = [];
  var i2 = s2.length - 1;
  while (i2 >= 0 && n2 > 0) {
    var c2 = s2.charCodeAt(i2--);
    if (c2 < 128) {
      ba[--n2] = c2;
    } else if (c2 > 127 && c2 < 2048) {
      ba[--n2] = c2 & 63 | 128;
      ba[--n2] = c2 >> 6 | 192;
    } else {
      ba[--n2] = c2 & 63 | 128;
      ba[--n2] = c2 >> 6 & 63 | 128;
      ba[--n2] = c2 >> 12 | 224;
    }
  }
  ba[--n2] = 0;
  var rng2 = new SecureRandom();
  var x2 = [];
  while (n2 > 2) {
    x2[0] = 0;
    while (x2[0] == 0) {
      rng2.nextBytes(x2);
    }
    ba[--n2] = x2[0];
  }
  ba[--n2] = 2;
  ba[--n2] = 0;
  return new BigInteger(ba);
}
var RSAKey = function() {
  function RSAKey2() {
    this.n = null;
    this.e = 0;
    this.d = null;
    this.p = null;
    this.q = null;
    this.dmp1 = null;
    this.dmq1 = null;
    this.coeff = null;
  }
  RSAKey2.prototype.doPublic = function(x2) {
    return x2.modPowInt(this.e, this.n);
  };
  RSAKey2.prototype.doPrivate = function(x2) {
    if (this.p == null || this.q == null) {
      return x2.modPow(this.d, this.n);
    }
    var xp = x2.mod(this.p).modPow(this.dmp1, this.p);
    var xq = x2.mod(this.q).modPow(this.dmq1, this.q);
    while (xp.compareTo(xq) < 0) {
      xp = xp.add(this.p);
    }
    return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  };
  RSAKey2.prototype.setPublic = function(N2, E2) {
    if (N2 != null && E2 != null && N2.length > 0 && E2.length > 0) {
      this.n = parseBigInt(N2, 16);
      this.e = parseInt(E2, 16);
    } else {
      console.error("Invalid RSA public key");
    }
  };
  RSAKey2.prototype.encrypt = function(text) {
    var m = pkcs1pad2(text, this.n.bitLength() + 7 >> 3);
    if (m == null) {
      return null;
    }
    var c2 = this.doPublic(m);
    if (c2 == null) {
      return null;
    }
    var h2 = c2.toString(16);
    if ((h2.length & 1) == 0) {
      return h2;
    } else {
      return "0" + h2;
    }
  };
  RSAKey2.prototype.setPrivate = function(N2, E2, D) {
    if (N2 != null && E2 != null && N2.length > 0 && E2.length > 0) {
      this.n = parseBigInt(N2, 16);
      this.e = parseInt(E2, 16);
      this.d = parseBigInt(D, 16);
    } else {
      console.error("Invalid RSA private key");
    }
  };
  RSAKey2.prototype.setPrivateEx = function(N2, E2, D, P, Q, DP, DQ, C2) {
    if (N2 != null && E2 != null && N2.length > 0 && E2.length > 0) {
      this.n = parseBigInt(N2, 16);
      this.e = parseInt(E2, 16);
      this.d = parseBigInt(D, 16);
      this.p = parseBigInt(P, 16);
      this.q = parseBigInt(Q, 16);
      this.dmp1 = parseBigInt(DP, 16);
      this.dmq1 = parseBigInt(DQ, 16);
      this.coeff = parseBigInt(C2, 16);
    } else {
      console.error("Invalid RSA private key");
    }
  };
  RSAKey2.prototype.generate = function(B2, E2) {
    var rng2 = new SecureRandom();
    var qs = B2 >> 1;
    this.e = parseInt(E2, 16);
    var ee = new BigInteger(E2, 16);
    for (; ; ) {
      for (; ; ) {
        this.p = new BigInteger(B2 - qs, 1, rng2);
        if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
          break;
        }
      }
      for (; ; ) {
        this.q = new BigInteger(qs, 1, rng2);
        if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
          break;
        }
      }
      if (this.p.compareTo(this.q) <= 0) {
        var t2 = this.p;
        this.p = this.q;
        this.q = t2;
      }
      var p1 = this.p.subtract(BigInteger.ONE);
      var q1 = this.q.subtract(BigInteger.ONE);
      var phi = p1.multiply(q1);
      if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
        this.n = this.p.multiply(this.q);
        this.d = ee.modInverse(phi);
        this.dmp1 = this.d.mod(p1);
        this.dmq1 = this.d.mod(q1);
        this.coeff = this.q.modInverse(this.p);
        break;
      }
    }
  };
  RSAKey2.prototype.decrypt = function(ctext) {
    var c2 = parseBigInt(ctext, 16);
    var m = this.doPrivate(c2);
    if (m == null) {
      return null;
    }
    return pkcs1unpad2(m, this.n.bitLength() + 7 >> 3);
  };
  RSAKey2.prototype.generateAsync = function(B2, E2, callback) {
    var rng2 = new SecureRandom();
    var qs = B2 >> 1;
    this.e = parseInt(E2, 16);
    var ee = new BigInteger(E2, 16);
    var rsa = this;
    var loop1 = function() {
      var loop4 = function() {
        if (rsa.p.compareTo(rsa.q) <= 0) {
          var t2 = rsa.p;
          rsa.p = rsa.q;
          rsa.q = t2;
        }
        var p1 = rsa.p.subtract(BigInteger.ONE);
        var q1 = rsa.q.subtract(BigInteger.ONE);
        var phi = p1.multiply(q1);
        if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
          rsa.n = rsa.p.multiply(rsa.q);
          rsa.d = ee.modInverse(phi);
          rsa.dmp1 = rsa.d.mod(p1);
          rsa.dmq1 = rsa.d.mod(q1);
          rsa.coeff = rsa.q.modInverse(rsa.p);
          setTimeout(function() {
            callback();
          }, 0);
        } else {
          setTimeout(loop1, 0);
        }
      };
      var loop3 = function() {
        rsa.q = nbi();
        rsa.q.fromNumberAsync(qs, 1, rng2, function() {
          rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r2) {
            if (r2.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
              setTimeout(loop4, 0);
            } else {
              setTimeout(loop3, 0);
            }
          });
        });
      };
      var loop2 = function() {
        rsa.p = nbi();
        rsa.p.fromNumberAsync(B2 - qs, 1, rng2, function() {
          rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r2) {
            if (r2.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
              setTimeout(loop3, 0);
            } else {
              setTimeout(loop2, 0);
            }
          });
        });
      };
      setTimeout(loop2, 0);
    };
    setTimeout(loop1, 0);
  };
  RSAKey2.prototype.sign = function(text, digestMethod, digestName) {
    var header = getDigestHeader(digestName);
    var digest = header + digestMethod(text).toString();
    var m = pkcs1pad1(digest, this.n.bitLength() / 4);
    if (m == null) {
      return null;
    }
    var c2 = this.doPrivate(m);
    if (c2 == null) {
      return null;
    }
    var h2 = c2.toString(16);
    if ((h2.length & 1) == 0) {
      return h2;
    } else {
      return "0" + h2;
    }
  };
  RSAKey2.prototype.verify = function(text, signature2, digestMethod) {
    var c2 = parseBigInt(signature2, 16);
    var m = this.doPublic(c2);
    if (m == null) {
      return null;
    }
    var unpadded = m.toString(16).replace(/^1f+00/, "");
    var digest = removeDigestHeader(unpadded);
    return digest == digestMethod(text).toString();
  };
  return RSAKey2;
}();
function pkcs1unpad2(d, n2) {
  var b2 = d.toByteArray();
  var i2 = 0;
  while (i2 < b2.length && b2[i2] == 0) {
    ++i2;
  }
  if (b2.length - i2 != n2 - 1 || b2[i2] != 2) {
    return null;
  }
  ++i2;
  while (b2[i2] != 0) {
    if (++i2 >= b2.length) {
      return null;
    }
  }
  var ret = "";
  while (++i2 < b2.length) {
    var c2 = b2[i2] & 255;
    if (c2 < 128) {
      ret += String.fromCharCode(c2);
    } else if (c2 > 191 && c2 < 224) {
      ret += String.fromCharCode((c2 & 31) << 6 | b2[i2 + 1] & 63);
      ++i2;
    } else {
      ret += String.fromCharCode((c2 & 15) << 12 | (b2[i2 + 1] & 63) << 6 | b2[i2 + 2] & 63);
      i2 += 2;
    }
  }
  return ret;
}
var DIGEST_HEADERS = {
  md2: "3020300c06082a864886f70d020205000410",
  md5: "3020300c06082a864886f70d020505000410",
  sha1: "3021300906052b0e03021a05000414",
  sha224: "302d300d06096086480165030402040500041c",
  sha256: "3031300d060960864801650304020105000420",
  sha384: "3041300d060960864801650304020205000430",
  sha512: "3051300d060960864801650304020305000440",
  ripemd160: "3021300906052b2403020105000414"
};
function getDigestHeader(name) {
  return DIGEST_HEADERS[name] || "";
}
function removeDigestHeader(str) {
  for (var name_1 in DIGEST_HEADERS) {
    if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
      var header = DIGEST_HEADERS[name_1];
      var len = header.length;
      if (str.substr(0, len) == header) {
        return str.substr(len);
      }
    }
  }
  return str;
}
var YAHOO = {};
YAHOO.lang = {
  extend: function(subc, superc, overrides) {
    if (!superc || !subc) {
      throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");
    }
    var F = function() {
    };
    F.prototype = superc.prototype;
    subc.prototype = new F();
    subc.prototype.constructor = subc;
    subc.superclass = superc.prototype;
    if (superc.prototype.constructor == Object.prototype.constructor) {
      superc.prototype.constructor = superc;
    }
    if (overrides) {
      var i2;
      for (i2 in overrides) {
        subc.prototype[i2] = overrides[i2];
      }
      var _IEEnumFix = function() {
      }, ADD = ["toString", "valueOf"];
      try {
        if (/MSIE/.test(navigator2.userAgent)) {
          _IEEnumFix = function(r2, s2) {
            for (i2 = 0; i2 < ADD.length; i2 = i2 + 1) {
              var fname = ADD[i2], f2 = s2[fname];
              if (typeof f2 === "function" && f2 != Object.prototype[fname]) {
                r2[fname] = f2;
              }
            }
          };
        }
      } catch (ex) {
      }
      _IEEnumFix(subc.prototype, overrides);
    }
  }
};
var KJUR = {};
if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1)
  KJUR.asn1 = {};
KJUR.asn1.ASN1Util = new function() {
  this.integerToByteHex = function(i2) {
    var h2 = i2.toString(16);
    if (h2.length % 2 == 1)
      h2 = "0" + h2;
    return h2;
  };
  this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
    var h2 = bigIntegerValue.toString(16);
    if (h2.substr(0, 1) != "-") {
      if (h2.length % 2 == 1) {
        h2 = "0" + h2;
      } else {
        if (!h2.match(/^[0-7]/)) {
          h2 = "00" + h2;
        }
      }
    } else {
      var hPos = h2.substr(1);
      var xorLen = hPos.length;
      if (xorLen % 2 == 1) {
        xorLen += 1;
      } else {
        if (!h2.match(/^[0-7]/)) {
          xorLen += 2;
        }
      }
      var hMask = "";
      for (var i2 = 0; i2 < xorLen; i2++) {
        hMask += "f";
      }
      var biMask = new BigInteger(hMask, 16);
      var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
      h2 = biNeg.toString(16).replace(/^-/, "");
    }
    return h2;
  };
  this.getPEMStringFromHex = function(dataHex, pemHeader) {
    return hextopem(dataHex, pemHeader);
  };
  this.newObject = function(param) {
    var _KJUR = KJUR, _KJUR_asn1 = _KJUR.asn1, _DERBoolean = _KJUR_asn1.DERBoolean, _DERInteger = _KJUR_asn1.DERInteger, _DERBitString = _KJUR_asn1.DERBitString, _DEROctetString = _KJUR_asn1.DEROctetString, _DERNull = _KJUR_asn1.DERNull, _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, _DEREnumerated = _KJUR_asn1.DEREnumerated, _DERUTF8String = _KJUR_asn1.DERUTF8String, _DERNumericString = _KJUR_asn1.DERNumericString, _DERPrintableString = _KJUR_asn1.DERPrintableString, _DERTeletexString = _KJUR_asn1.DERTeletexString, _DERIA5String = _KJUR_asn1.DERIA5String, _DERUTCTime = _KJUR_asn1.DERUTCTime, _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, _DERSequence = _KJUR_asn1.DERSequence, _DERSet = _KJUR_asn1.DERSet, _DERTaggedObject = _KJUR_asn1.DERTaggedObject, _newObject = _KJUR_asn1.ASN1Util.newObject;
    var keys = Object.keys(param);
    if (keys.length != 1)
      throw "key of param shall be only one.";
    var key2 = keys[0];
    if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key2 + ":") == -1)
      throw "undefined key: " + key2;
    if (key2 == "bool")
      return new _DERBoolean(param[key2]);
    if (key2 == "int")
      return new _DERInteger(param[key2]);
    if (key2 == "bitstr")
      return new _DERBitString(param[key2]);
    if (key2 == "octstr")
      return new _DEROctetString(param[key2]);
    if (key2 == "null")
      return new _DERNull(param[key2]);
    if (key2 == "oid")
      return new _DERObjectIdentifier(param[key2]);
    if (key2 == "enum")
      return new _DEREnumerated(param[key2]);
    if (key2 == "utf8str")
      return new _DERUTF8String(param[key2]);
    if (key2 == "numstr")
      return new _DERNumericString(param[key2]);
    if (key2 == "prnstr")
      return new _DERPrintableString(param[key2]);
    if (key2 == "telstr")
      return new _DERTeletexString(param[key2]);
    if (key2 == "ia5str")
      return new _DERIA5String(param[key2]);
    if (key2 == "utctime")
      return new _DERUTCTime(param[key2]);
    if (key2 == "gentime")
      return new _DERGeneralizedTime(param[key2]);
    if (key2 == "seq") {
      var paramList = param[key2];
      var a2 = [];
      for (var i2 = 0; i2 < paramList.length; i2++) {
        var asn1Obj = _newObject(paramList[i2]);
        a2.push(asn1Obj);
      }
      return new _DERSequence({
        array: a2
      });
    }
    if (key2 == "set") {
      var paramList = param[key2];
      var a2 = [];
      for (var i2 = 0; i2 < paramList.length; i2++) {
        var asn1Obj = _newObject(paramList[i2]);
        a2.push(asn1Obj);
      }
      return new _DERSet({
        array: a2
      });
    }
    if (key2 == "tag") {
      var tagParam = param[key2];
      if (Object.prototype.toString.call(tagParam) === "[object Array]" && tagParam.length == 3) {
        var obj = _newObject(tagParam[2]);
        return new _DERTaggedObject({
          tag: tagParam[0],
          explicit: tagParam[1],
          obj
        });
      } else {
        var newParam = {};
        if (tagParam.explicit !== void 0)
          newParam.explicit = tagParam.explicit;
        if (tagParam.tag !== void 0)
          newParam.tag = tagParam.tag;
        if (tagParam.obj === void 0)
          throw "obj shall be specified for 'tag'.";
        newParam.obj = _newObject(tagParam.obj);
        return new _DERTaggedObject(newParam);
      }
    }
  };
  this.jsonToASN1HEX = function(param) {
    var asn1Obj = this.newObject(param);
    return asn1Obj.getEncodedHex();
  };
}();
KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
  var s2 = "";
  var i01 = parseInt(hex.substr(0, 2), 16);
  var i0 = Math.floor(i01 / 40);
  var i1 = i01 % 40;
  var s2 = i0 + "." + i1;
  var binbuf = "";
  for (var i2 = 2; i2 < hex.length; i2 += 2) {
    var value = parseInt(hex.substr(i2, 2), 16);
    var bin = ("00000000" + value.toString(2)).slice(-8);
    binbuf = binbuf + bin.substr(1, 7);
    if (bin.substr(0, 1) == "0") {
      var bi = new BigInteger(binbuf, 2);
      s2 = s2 + "." + bi.toString(10);
      binbuf = "";
    }
  }
  return s2;
};
KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
  var itox = function(i3) {
    var h3 = i3.toString(16);
    if (h3.length == 1)
      h3 = "0" + h3;
    return h3;
  };
  var roidtox = function(roid) {
    var h3 = "";
    var bi = new BigInteger(roid, 10);
    var b2 = bi.toString(2);
    var padLen = 7 - b2.length % 7;
    if (padLen == 7)
      padLen = 0;
    var bPad = "";
    for (var i3 = 0; i3 < padLen; i3++)
      bPad += "0";
    b2 = bPad + b2;
    for (var i3 = 0; i3 < b2.length - 1; i3 += 7) {
      var b8 = b2.substr(i3, 7);
      if (i3 != b2.length - 7)
        b8 = "1" + b8;
      h3 += itox(parseInt(b8, 2));
    }
    return h3;
  };
  if (!oidString.match(/^[0-9.]+$/)) {
    throw "malformed oid string: " + oidString;
  }
  var h2 = "";
  var a2 = oidString.split(".");
  var i0 = parseInt(a2[0]) * 40 + parseInt(a2[1]);
  h2 += itox(i0);
  a2.splice(0, 2);
  for (var i2 = 0; i2 < a2.length; i2++) {
    h2 += roidtox(a2[i2]);
  }
  return h2;
};
KJUR.asn1.ASN1Object = function() {
  var hV = "";
  this.getLengthHexFromValue = function() {
    if (typeof this.hV == "undefined" || this.hV == null) {
      throw "this.hV is null or undefined.";
    }
    if (this.hV.length % 2 == 1) {
      throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
    }
    var n2 = this.hV.length / 2;
    var hN = n2.toString(16);
    if (hN.length % 2 == 1) {
      hN = "0" + hN;
    }
    if (n2 < 128) {
      return hN;
    } else {
      var hNlen = hN.length / 2;
      if (hNlen > 15) {
        throw "ASN.1 length too long to represent by 8x: n = " + n2.toString(16);
      }
      var head = 128 + hNlen;
      return head.toString(16) + hN;
    }
  };
  this.getEncodedHex = function() {
    if (this.hTLV == null || this.isModified) {
      this.hV = this.getFreshValueHex();
      this.hL = this.getLengthHexFromValue();
      this.hTLV = this.hT + this.hL + this.hV;
      this.isModified = false;
    }
    return this.hTLV;
  };
  this.getValueHex = function() {
    this.getEncodedHex();
    return this.hV;
  };
  this.getFreshValueHex = function() {
    return "";
  };
};
KJUR.asn1.DERAbstractString = function(params) {
  KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  this.getString = function() {
    return this.s;
  };
  this.setString = function(newS) {
    this.hTLV = null;
    this.isModified = true;
    this.s = newS;
    this.hV = stohex(this.s);
  };
  this.setStringHex = function(newHexString) {
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = newHexString;
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params == "string") {
      this.setString(params);
    } else if (typeof params["str"] != "undefined") {
      this.setString(params["str"]);
    } else if (typeof params["hex"] != "undefined") {
      this.setStringHex(params["hex"]);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractTime = function(params) {
  KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  this.localDateToUTC = function(d) {
    utc = d.getTime() + d.getTimezoneOffset() * 6e4;
    var utcDate = new Date(utc);
    return utcDate;
  };
  this.formatDate = function(dateObject, type2, withMillis) {
    var pad = this.zeroPadding;
    var d = this.localDateToUTC(dateObject);
    var year = String(d.getFullYear());
    if (type2 == "utc")
      year = year.substr(2, 2);
    var month = pad(String(d.getMonth() + 1), 2);
    var day = pad(String(d.getDate()), 2);
    var hour = pad(String(d.getHours()), 2);
    var min2 = pad(String(d.getMinutes()), 2);
    var sec = pad(String(d.getSeconds()), 2);
    var s2 = year + month + day + hour + min2 + sec;
    if (withMillis === true) {
      var millis = d.getMilliseconds();
      if (millis != 0) {
        var sMillis = pad(String(millis), 3);
        sMillis = sMillis.replace(/[0]+$/, "");
        s2 = s2 + "." + sMillis;
      }
    }
    return s2 + "Z";
  };
  this.zeroPadding = function(s2, len) {
    if (s2.length >= len)
      return s2;
    return new Array(len - s2.length + 1).join("0") + s2;
  };
  this.getString = function() {
    return this.s;
  };
  this.setString = function(newS) {
    this.hTLV = null;
    this.isModified = true;
    this.s = newS;
    this.hV = stohex(newS);
  };
  this.setByDateValue = function(year, month, day, hour, min2, sec) {
    var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min2, sec, 0));
    this.setByDate(dateObject);
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
KJUR.asn1.DERAbstractStructured = function(params) {
  KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  this.setByASN1ObjectArray = function(asn1ObjectArray) {
    this.hTLV = null;
    this.isModified = true;
    this.asn1Array = asn1ObjectArray;
  };
  this.appendASN1Object = function(asn1Object) {
    this.hTLV = null;
    this.isModified = true;
    this.asn1Array.push(asn1Object);
  };
  this.asn1Array = new Array();
  if (typeof params != "undefined") {
    if (typeof params["array"] != "undefined") {
      this.asn1Array = params["array"];
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBoolean = function() {
  KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  this.hT = "01";
  this.hTLV = "0101ff";
};
YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
KJUR.asn1.DERInteger = function(params) {
  KJUR.asn1.DERInteger.superclass.constructor.call(this);
  this.hT = "02";
  this.setByBigInteger = function(bigIntegerValue) {
    this.hTLV = null;
    this.isModified = true;
    this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  };
  this.setByInteger = function(intValue) {
    var bi = new BigInteger(String(intValue), 10);
    this.setByBigInteger(bi);
  };
  this.setValueHex = function(newHexString) {
    this.hV = newHexString;
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params["bigint"] != "undefined") {
      this.setByBigInteger(params["bigint"]);
    } else if (typeof params["int"] != "undefined") {
      this.setByInteger(params["int"]);
    } else if (typeof params == "number") {
      this.setByInteger(params);
    } else if (typeof params["hex"] != "undefined") {
      this.setValueHex(params["hex"]);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
KJUR.asn1.DERBitString = function(params) {
  if (params !== void 0 && typeof params.obj !== "undefined") {
    var o2 = KJUR.asn1.ASN1Util.newObject(params.obj);
    params.hex = "00" + o2.getEncodedHex();
  }
  KJUR.asn1.DERBitString.superclass.constructor.call(this);
  this.hT = "03";
  this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
    this.hTLV = null;
    this.isModified = true;
    this.hV = newHexStringIncludingUnusedBits;
  };
  this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
    if (unusedBits < 0 || 7 < unusedBits) {
      throw "unused bits shall be from 0 to 7: u = " + unusedBits;
    }
    var hUnusedBits = "0" + unusedBits;
    this.hTLV = null;
    this.isModified = true;
    this.hV = hUnusedBits + hValue;
  };
  this.setByBinaryString = function(binaryString) {
    binaryString = binaryString.replace(/0+$/, "");
    var unusedBits = 8 - binaryString.length % 8;
    if (unusedBits == 8)
      unusedBits = 0;
    for (var i2 = 0; i2 <= unusedBits; i2++) {
      binaryString += "0";
    }
    var h2 = "";
    for (var i2 = 0; i2 < binaryString.length - 1; i2 += 8) {
      var b2 = binaryString.substr(i2, 8);
      var x2 = parseInt(b2, 2).toString(16);
      if (x2.length == 1)
        x2 = "0" + x2;
      h2 += x2;
    }
    this.hTLV = null;
    this.isModified = true;
    this.hV = "0" + unusedBits + h2;
  };
  this.setByBooleanArray = function(booleanArray) {
    var s2 = "";
    for (var i2 = 0; i2 < booleanArray.length; i2++) {
      if (booleanArray[i2] == true) {
        s2 += "1";
      } else {
        s2 += "0";
      }
    }
    this.setByBinaryString(s2);
  };
  this.newFalseArray = function(nLength) {
    var a2 = new Array(nLength);
    for (var i2 = 0; i2 < nLength; i2++) {
      a2[i2] = false;
    }
    return a2;
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
      this.setHexValueIncludingUnusedBits(params);
    } else if (typeof params["hex"] != "undefined") {
      this.setHexValueIncludingUnusedBits(params["hex"]);
    } else if (typeof params["bin"] != "undefined") {
      this.setByBinaryString(params["bin"]);
    } else if (typeof params["array"] != "undefined") {
      this.setByBooleanArray(params["array"]);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
KJUR.asn1.DEROctetString = function(params) {
  if (params !== void 0 && typeof params.obj !== "undefined") {
    var o2 = KJUR.asn1.ASN1Util.newObject(params.obj);
    params.hex = o2.getEncodedHex();
  }
  KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  this.hT = "04";
};
YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNull = function() {
  KJUR.asn1.DERNull.superclass.constructor.call(this);
  this.hT = "05";
  this.hTLV = "0500";
};
YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
KJUR.asn1.DERObjectIdentifier = function(params) {
  var itox = function(i2) {
    var h2 = i2.toString(16);
    if (h2.length == 1)
      h2 = "0" + h2;
    return h2;
  };
  var roidtox = function(roid) {
    var h2 = "";
    var bi = new BigInteger(roid, 10);
    var b2 = bi.toString(2);
    var padLen = 7 - b2.length % 7;
    if (padLen == 7)
      padLen = 0;
    var bPad = "";
    for (var i2 = 0; i2 < padLen; i2++)
      bPad += "0";
    b2 = bPad + b2;
    for (var i2 = 0; i2 < b2.length - 1; i2 += 7) {
      var b8 = b2.substr(i2, 7);
      if (i2 != b2.length - 7)
        b8 = "1" + b8;
      h2 += itox(parseInt(b8, 2));
    }
    return h2;
  };
  KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  this.hT = "06";
  this.setValueHex = function(newHexString) {
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = newHexString;
  };
  this.setValueOidString = function(oidString) {
    if (!oidString.match(/^[0-9.]+$/)) {
      throw "malformed oid string: " + oidString;
    }
    var h2 = "";
    var a2 = oidString.split(".");
    var i0 = parseInt(a2[0]) * 40 + parseInt(a2[1]);
    h2 += itox(i0);
    a2.splice(0, 2);
    for (var i2 = 0; i2 < a2.length; i2++) {
      h2 += roidtox(a2[i2]);
    }
    this.hTLV = null;
    this.isModified = true;
    this.s = null;
    this.hV = h2;
  };
  this.setValueName = function(oidName) {
    var oid = KJUR.asn1.x509.OID.name2oid(oidName);
    if (oid !== "") {
      this.setValueOidString(oid);
    } else {
      throw "DERObjectIdentifier oidName undefined: " + oidName;
    }
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (params !== void 0) {
    if (typeof params === "string") {
      if (params.match(/^[0-2].[0-9.]+$/)) {
        this.setValueOidString(params);
      } else {
        this.setValueName(params);
      }
    } else if (params.oid !== void 0) {
      this.setValueOidString(params.oid);
    } else if (params.hex !== void 0) {
      this.setValueHex(params.hex);
    } else if (params.name !== void 0) {
      this.setValueName(params.name);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
KJUR.asn1.DEREnumerated = function(params) {
  KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
  this.hT = "0a";
  this.setByBigInteger = function(bigIntegerValue) {
    this.hTLV = null;
    this.isModified = true;
    this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  };
  this.setByInteger = function(intValue) {
    var bi = new BigInteger(String(intValue), 10);
    this.setByBigInteger(bi);
  };
  this.setValueHex = function(newHexString) {
    this.hV = newHexString;
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params["int"] != "undefined") {
      this.setByInteger(params["int"]);
    } else if (typeof params == "number") {
      this.setByInteger(params);
    } else if (typeof params["hex"] != "undefined") {
      this.setValueHex(params["hex"]);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
KJUR.asn1.DERUTF8String = function(params) {
  KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  this.hT = "0c";
};
YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERNumericString = function(params) {
  KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  this.hT = "12";
};
YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERPrintableString = function(params) {
  KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  this.hT = "13";
};
YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERTeletexString = function(params) {
  KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  this.hT = "14";
};
YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERIA5String = function(params) {
  KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  this.hT = "16";
};
YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
KJUR.asn1.DERUTCTime = function(params) {
  KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  this.hT = "17";
  this.setByDate = function(dateObject) {
    this.hTLV = null;
    this.isModified = true;
    this.date = dateObject;
    this.s = this.formatDate(this.date, "utc");
    this.hV = stohex(this.s);
  };
  this.getFreshValueHex = function() {
    if (typeof this.date == "undefined" && typeof this.s == "undefined") {
      this.date = /* @__PURE__ */ new Date();
      this.s = this.formatDate(this.date, "utc");
      this.hV = stohex(this.s);
    }
    return this.hV;
  };
  if (params !== void 0) {
    if (params.str !== void 0) {
      this.setString(params.str);
    } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
      this.setString(params);
    } else if (params.hex !== void 0) {
      this.setStringHex(params.hex);
    } else if (params.date !== void 0) {
      this.setByDate(params.date);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERGeneralizedTime = function(params) {
  KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  this.hT = "18";
  this.withMillis = false;
  this.setByDate = function(dateObject) {
    this.hTLV = null;
    this.isModified = true;
    this.date = dateObject;
    this.s = this.formatDate(this.date, "gen", this.withMillis);
    this.hV = stohex(this.s);
  };
  this.getFreshValueHex = function() {
    if (this.date === void 0 && this.s === void 0) {
      this.date = /* @__PURE__ */ new Date();
      this.s = this.formatDate(this.date, "gen", this.withMillis);
      this.hV = stohex(this.s);
    }
    return this.hV;
  };
  if (params !== void 0) {
    if (params.str !== void 0) {
      this.setString(params.str);
    } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
      this.setString(params);
    } else if (params.hex !== void 0) {
      this.setStringHex(params.hex);
    } else if (params.date !== void 0) {
      this.setByDate(params.date);
    }
    if (params.millis === true) {
      this.withMillis = true;
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
KJUR.asn1.DERSequence = function(params) {
  KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  this.hT = "30";
  this.getFreshValueHex = function() {
    var h2 = "";
    for (var i2 = 0; i2 < this.asn1Array.length; i2++) {
      var asn1Obj = this.asn1Array[i2];
      h2 += asn1Obj.getEncodedHex();
    }
    this.hV = h2;
    return this.hV;
  };
};
YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERSet = function(params) {
  KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  this.hT = "31";
  this.sortFlag = true;
  this.getFreshValueHex = function() {
    var a2 = new Array();
    for (var i2 = 0; i2 < this.asn1Array.length; i2++) {
      var asn1Obj = this.asn1Array[i2];
      a2.push(asn1Obj.getEncodedHex());
    }
    if (this.sortFlag == true)
      a2.sort();
    this.hV = a2.join("");
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params.sortflag != "undefined" && params.sortflag == false)
      this.sortFlag = false;
  }
};
YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
KJUR.asn1.DERTaggedObject = function(params) {
  KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  this.hT = "a0";
  this.hV = "";
  this.isExplicit = true;
  this.asn1Object = null;
  this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
    this.hT = tagNoHex;
    this.isExplicit = isExplicitFlag;
    this.asn1Object = asn1Object;
    if (this.isExplicit) {
      this.hV = this.asn1Object.getEncodedHex();
      this.hTLV = null;
      this.isModified = true;
    } else {
      this.hV = null;
      this.hTLV = asn1Object.getEncodedHex();
      this.hTLV = this.hTLV.replace(/^../, tagNoHex);
      this.isModified = false;
    }
  };
  this.getFreshValueHex = function() {
    return this.hV;
  };
  if (typeof params != "undefined") {
    if (typeof params["tag"] != "undefined") {
      this.hT = params["tag"];
    }
    if (typeof params["explicit"] != "undefined") {
      this.isExplicit = params["explicit"];
    }
    if (typeof params["obj"] != "undefined") {
      this.asn1Object = params["obj"];
      this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
    }
  }
};
YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
__extends$1(JSEncryptRSAKey, RSAKey);
function JSEncryptRSAKey(key2) {
  var _this = RSAKey.call(this) || this;
  if (key2) {
    if (typeof key2 === "string") {
      _this.parseKey(key2);
    } else if (JSEncryptRSAKey.hasPrivateKeyProperty(key2) || JSEncryptRSAKey.hasPublicKeyProperty(key2)) {
      _this.parsePropertiesFrom(key2);
    }
  }
  return _this;
}
JSEncryptRSAKey.prototype.parseKey = function(pem2) {
  try {
    var modulus = 0;
    var public_exponent = 0;
    var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
    var der2 = reHex.test(pem2) ? Hex.decode(pem2) : Base64.unarmor(pem2);
    var asn12 = ASN1.decode(der2);
    if (asn12.sub.length === 3) {
      asn12 = asn12.sub[2].sub[0];
    }
    if (asn12.sub.length === 9) {
      modulus = asn12.sub[1].getHexStringValue();
      this.n = parseBigInt(modulus, 16);
      public_exponent = asn12.sub[2].getHexStringValue();
      this.e = parseInt(public_exponent, 16);
      var private_exponent = asn12.sub[3].getHexStringValue();
      this.d = parseBigInt(private_exponent, 16);
      var prime1 = asn12.sub[4].getHexStringValue();
      this.p = parseBigInt(prime1, 16);
      var prime2 = asn12.sub[5].getHexStringValue();
      this.q = parseBigInt(prime2, 16);
      var exponent1 = asn12.sub[6].getHexStringValue();
      this.dmp1 = parseBigInt(exponent1, 16);
      var exponent2 = asn12.sub[7].getHexStringValue();
      this.dmq1 = parseBigInt(exponent2, 16);
      var coefficient = asn12.sub[8].getHexStringValue();
      this.coeff = parseBigInt(coefficient, 16);
    } else if (asn12.sub.length === 2) {
      var bit_string = asn12.sub[1];
      var sequence = bit_string.sub[0];
      modulus = sequence.sub[0].getHexStringValue();
      this.n = parseBigInt(modulus, 16);
      public_exponent = sequence.sub[1].getHexStringValue();
      this.e = parseInt(public_exponent, 16);
    } else {
      return false;
    }
    return true;
  } catch (ex) {
    return false;
  }
};
JSEncryptRSAKey.prototype.getPrivateBaseKey = function() {
  var options2 = {
    array: [new KJUR.asn1.DERInteger({
      int: 0
    }), new KJUR.asn1.DERInteger({
      bigint: this.n
    }), new KJUR.asn1.DERInteger({
      int: this.e
    }), new KJUR.asn1.DERInteger({
      bigint: this.d
    }), new KJUR.asn1.DERInteger({
      bigint: this.p
    }), new KJUR.asn1.DERInteger({
      bigint: this.q
    }), new KJUR.asn1.DERInteger({
      bigint: this.dmp1
    }), new KJUR.asn1.DERInteger({
      bigint: this.dmq1
    }), new KJUR.asn1.DERInteger({
      bigint: this.coeff
    })]
  };
  var seq = new KJUR.asn1.DERSequence(options2);
  return seq.getEncodedHex();
};
JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function() {
  return hex2b64(this.getPrivateBaseKey());
};
JSEncryptRSAKey.prototype.getPublicBaseKey = function() {
  var first_sequence = new KJUR.asn1.DERSequence({
    array: [new KJUR.asn1.DERObjectIdentifier({
      oid: "1.2.840.113549.1.1.1"
    }), new KJUR.asn1.DERNull()]
  });
  var second_sequence = new KJUR.asn1.DERSequence({
    array: [new KJUR.asn1.DERInteger({
      bigint: this.n
    }), new KJUR.asn1.DERInteger({
      int: this.e
    })]
  });
  var bit_string = new KJUR.asn1.DERBitString({
    hex: "00" + second_sequence.getEncodedHex()
  });
  var seq = new KJUR.asn1.DERSequence({
    array: [first_sequence, bit_string]
  });
  return seq.getEncodedHex();
};
JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function() {
  return hex2b64(this.getPublicBaseKey());
};
JSEncryptRSAKey.wordwrap = function(str, width) {
  width = width || 64;
  if (!str) {
    return str;
  }
  var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  return str.match(RegExp(regex, "g")).join("\n");
};
JSEncryptRSAKey.prototype.getPrivateKey = function() {
  var key2 = "-----BEGIN RSA PRIVATE KEY-----\n";
  key2 += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  key2 += "-----END RSA PRIVATE KEY-----";
  return key2;
};
JSEncryptRSAKey.prototype.getPublicKey = function() {
  var key2 = "-----BEGIN PUBLIC KEY-----\n";
  key2 += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  key2 += "-----END PUBLIC KEY-----";
  return key2;
};
JSEncryptRSAKey.hasPublicKeyProperty = function(obj) {
  obj = obj || {};
  return obj.hasOwnProperty("n") && obj.hasOwnProperty("e");
};
JSEncryptRSAKey.hasPrivateKeyProperty = function(obj) {
  obj = obj || {};
  return obj.hasOwnProperty("n") && obj.hasOwnProperty("e") && obj.hasOwnProperty("d") && obj.hasOwnProperty("p") && obj.hasOwnProperty("q") && obj.hasOwnProperty("dmp1") && obj.hasOwnProperty("dmq1") && obj.hasOwnProperty("coeff");
};
JSEncryptRSAKey.prototype.parsePropertiesFrom = function(obj) {
  this.n = obj.n;
  this.e = obj.e;
  if (obj.hasOwnProperty("d")) {
    this.d = obj.d;
    this.p = obj.p;
    this.q = obj.q;
    this.dmp1 = obj.dmp1;
    this.dmq1 = obj.dmq1;
    this.coeff = obj.coeff;
  }
};
function JSEncrypt(options2) {
  options2 = options2 || {};
  this.default_key_size = parseInt(options2.default_key_size, 10) || 1024;
  this.default_public_exponent = options2.default_public_exponent || "010001";
  this.log = options2.log || false;
  this.key = null;
}
JSEncrypt.prototype.setKey = function(key2) {
  if (this.log && this.key) {
    console.warn("A key was already set, overriding existing.");
  }
  this.key = new JSEncryptRSAKey(key2);
};
JSEncrypt.prototype.setPrivateKey = function(privkey) {
  this.setKey(privkey);
};
JSEncrypt.prototype.setPublicKey = function(pubkey) {
  this.setKey(pubkey);
};
JSEncrypt.prototype.decrypt = function(str) {
  try {
    return this.getKey().decrypt(b64tohex(str));
  } catch (ex) {
    return false;
  }
};
JSEncrypt.prototype.encrypt = function(str) {
  try {
    return hex2b64(this.getKey().encrypt(str));
  } catch (ex) {
    return false;
  }
};
JSEncrypt.prototype.sign = function(str, digestMethod, digestName) {
  try {
    return hex2b64(this.getKey().sign(str, digestMethod, digestName));
  } catch (ex) {
    return false;
  }
};
JSEncrypt.prototype.verify = function(str, signature2, digestMethod) {
  try {
    return this.getKey().verify(str, b64tohex(signature2), digestMethod);
  } catch (ex) {
    return false;
  }
};
JSEncrypt.prototype.getKey = function(cb) {
  if (!this.key) {
    this.key = new JSEncryptRSAKey();
    if (cb && {}.toString.call(cb) === "[object Function]") {
      this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
      return;
    }
    this.key.generate(this.default_key_size, this.default_public_exponent);
  }
  return this.key;
};
JSEncrypt.prototype.getPrivateKey = function() {
  return this.getKey().getPrivateKey();
};
JSEncrypt.prototype.getPrivateKeyB64 = function() {
  return this.getKey().getPrivateBaseKeyB64();
};
JSEncrypt.prototype.getPublicKey = function() {
  return this.getKey().getPublicKey();
};
JSEncrypt.prototype.getPublicKeyB64 = function() {
  return this.getKey().getPublicBaseKeyB64();
};
JSEncrypt.version = "3.0.0-rc.1";
var jsbn$1 = { exports: {} };
var jsbn = jsbn$1.exports;
var hasRequiredJsbn;
function requireJsbn() {
  if (hasRequiredJsbn) return jsbn$1.exports;
  hasRequiredJsbn = 1;
  (function(module2, exports) {
    (function() {
      var dbits2;
      var canary = 244837814094590;
      var j_lm = (canary & 16777215) == 15715070;
      function BigInteger2(a2, b2, c2) {
        if (a2 != null)
          if ("number" == typeof a2) this.fromNumber(a2, b2, c2);
          else if (b2 == null && "string" != typeof a2) this.fromString(a2, 256);
          else this.fromString(a2, b2);
      }
      function nbi2() {
        return new BigInteger2(null);
      }
      function am1(i2, x2, w, j, c2, n2) {
        while (--n2 >= 0) {
          var v2 = x2 * this[i2++] + w[j] + c2;
          c2 = Math.floor(v2 / 67108864);
          w[j++] = v2 & 67108863;
        }
        return c2;
      }
      function am2(i2, x2, w, j, c2, n2) {
        var xl = x2 & 32767, xh = x2 >> 15;
        while (--n2 >= 0) {
          var l2 = this[i2] & 32767;
          var h2 = this[i2++] >> 15;
          var m = xh * l2 + h2 * xl;
          l2 = xl * l2 + ((m & 32767) << 15) + w[j] + (c2 & 1073741823);
          c2 = (l2 >>> 30) + (m >>> 15) + xh * h2 + (c2 >>> 30);
          w[j++] = l2 & 1073741823;
        }
        return c2;
      }
      function am32(i2, x2, w, j, c2, n2) {
        var xl = x2 & 16383, xh = x2 >> 14;
        while (--n2 >= 0) {
          var l2 = this[i2] & 16383;
          var h2 = this[i2++] >> 14;
          var m = xh * l2 + h2 * xl;
          l2 = xl * l2 + ((m & 16383) << 14) + w[j] + c2;
          c2 = (l2 >> 28) + (m >> 14) + xh * h2;
          w[j++] = l2 & 268435455;
        }
        return c2;
      }
      var inBrowser = typeof navigator !== "undefined";
      if (inBrowser && j_lm && navigator.appName == "Microsoft Internet Explorer") {
        BigInteger2.prototype.am = am2;
        dbits2 = 30;
      } else if (inBrowser && j_lm && navigator.appName != "Netscape") {
        BigInteger2.prototype.am = am1;
        dbits2 = 26;
      } else {
        BigInteger2.prototype.am = am32;
        dbits2 = 28;
      }
      BigInteger2.prototype.DB = dbits2;
      BigInteger2.prototype.DM = (1 << dbits2) - 1;
      BigInteger2.prototype.DV = 1 << dbits2;
      var BI_FP2 = 52;
      BigInteger2.prototype.FV = Math.pow(2, BI_FP2);
      BigInteger2.prototype.F1 = BI_FP2 - dbits2;
      BigInteger2.prototype.F2 = 2 * dbits2 - BI_FP2;
      var BI_RM2 = "0123456789abcdefghijklmnopqrstuvwxyz";
      var BI_RC2 = new Array();
      var rr2, vv2;
      rr2 = "0".charCodeAt(0);
      for (vv2 = 0; vv2 <= 9; ++vv2) BI_RC2[rr2++] = vv2;
      rr2 = "a".charCodeAt(0);
      for (vv2 = 10; vv2 < 36; ++vv2) BI_RC2[rr2++] = vv2;
      rr2 = "A".charCodeAt(0);
      for (vv2 = 10; vv2 < 36; ++vv2) BI_RC2[rr2++] = vv2;
      function int2char2(n2) {
        return BI_RM2.charAt(n2);
      }
      function intAt2(s2, i2) {
        var c2 = BI_RC2[s2.charCodeAt(i2)];
        return c2 == null ? -1 : c2;
      }
      function bnpCopyTo(r2) {
        for (var i2 = this.t - 1; i2 >= 0; --i2) r2[i2] = this[i2];
        r2.t = this.t;
        r2.s = this.s;
      }
      function bnpFromInt(x2) {
        this.t = 1;
        this.s = x2 < 0 ? -1 : 0;
        if (x2 > 0) this[0] = x2;
        else if (x2 < -1) this[0] = x2 + this.DV;
        else this.t = 0;
      }
      function nbv2(i2) {
        var r2 = nbi2();
        r2.fromInt(i2);
        return r2;
      }
      function bnpFromString(s2, b2) {
        var k2;
        if (b2 == 16) k2 = 4;
        else if (b2 == 8) k2 = 3;
        else if (b2 == 256) k2 = 8;
        else if (b2 == 2) k2 = 1;
        else if (b2 == 32) k2 = 5;
        else if (b2 == 4) k2 = 2;
        else {
          this.fromRadix(s2, b2);
          return;
        }
        this.t = 0;
        this.s = 0;
        var i2 = s2.length, mi = false, sh = 0;
        while (--i2 >= 0) {
          var x2 = k2 == 8 ? s2[i2] & 255 : intAt2(s2, i2);
          if (x2 < 0) {
            if (s2.charAt(i2) == "-") mi = true;
            continue;
          }
          mi = false;
          if (sh == 0)
            this[this.t++] = x2;
          else if (sh + k2 > this.DB) {
            this[this.t - 1] |= (x2 & (1 << this.DB - sh) - 1) << sh;
            this[this.t++] = x2 >> this.DB - sh;
          } else
            this[this.t - 1] |= x2 << sh;
          sh += k2;
          if (sh >= this.DB) sh -= this.DB;
        }
        if (k2 == 8 && (s2[0] & 128) != 0) {
          this.s = -1;
          if (sh > 0) this[this.t - 1] |= (1 << this.DB - sh) - 1 << sh;
        }
        this.clamp();
        if (mi) BigInteger2.ZERO.subTo(this, this);
      }
      function bnpClamp() {
        var c2 = this.s & this.DM;
        while (this.t > 0 && this[this.t - 1] == c2) --this.t;
      }
      function bnToString(b2) {
        if (this.s < 0) return "-" + this.negate().toString(b2);
        var k2;
        if (b2 == 16) k2 = 4;
        else if (b2 == 8) k2 = 3;
        else if (b2 == 2) k2 = 1;
        else if (b2 == 32) k2 = 5;
        else if (b2 == 4) k2 = 2;
        else return this.toRadix(b2);
        var km = (1 << k2) - 1, d, m = false, r2 = "", i2 = this.t;
        var p2 = this.DB - i2 * this.DB % k2;
        if (i2-- > 0) {
          if (p2 < this.DB && (d = this[i2] >> p2) > 0) {
            m = true;
            r2 = int2char2(d);
          }
          while (i2 >= 0) {
            if (p2 < k2) {
              d = (this[i2] & (1 << p2) - 1) << k2 - p2;
              d |= this[--i2] >> (p2 += this.DB - k2);
            } else {
              d = this[i2] >> (p2 -= k2) & km;
              if (p2 <= 0) {
                p2 += this.DB;
                --i2;
              }
            }
            if (d > 0) m = true;
            if (m) r2 += int2char2(d);
          }
        }
        return m ? r2 : "0";
      }
      function bnNegate() {
        var r2 = nbi2();
        BigInteger2.ZERO.subTo(this, r2);
        return r2;
      }
      function bnAbs() {
        return this.s < 0 ? this.negate() : this;
      }
      function bnCompareTo(a2) {
        var r2 = this.s - a2.s;
        if (r2 != 0) return r2;
        var i2 = this.t;
        r2 = i2 - a2.t;
        if (r2 != 0) return this.s < 0 ? -r2 : r2;
        while (--i2 >= 0) if ((r2 = this[i2] - a2[i2]) != 0) return r2;
        return 0;
      }
      function nbits2(x2) {
        var r2 = 1, t3;
        if ((t3 = x2 >>> 16) != 0) {
          x2 = t3;
          r2 += 16;
        }
        if ((t3 = x2 >> 8) != 0) {
          x2 = t3;
          r2 += 8;
        }
        if ((t3 = x2 >> 4) != 0) {
          x2 = t3;
          r2 += 4;
        }
        if ((t3 = x2 >> 2) != 0) {
          x2 = t3;
          r2 += 2;
        }
        if ((t3 = x2 >> 1) != 0) {
          x2 = t3;
          r2 += 1;
        }
        return r2;
      }
      function bnBitLength() {
        if (this.t <= 0) return 0;
        return this.DB * (this.t - 1) + nbits2(this[this.t - 1] ^ this.s & this.DM);
      }
      function bnpDLShiftTo(n2, r2) {
        var i2;
        for (i2 = this.t - 1; i2 >= 0; --i2) r2[i2 + n2] = this[i2];
        for (i2 = n2 - 1; i2 >= 0; --i2) r2[i2] = 0;
        r2.t = this.t + n2;
        r2.s = this.s;
      }
      function bnpDRShiftTo(n2, r2) {
        for (var i2 = n2; i2 < this.t; ++i2) r2[i2 - n2] = this[i2];
        r2.t = Math.max(this.t - n2, 0);
        r2.s = this.s;
      }
      function bnpLShiftTo(n2, r2) {
        var bs = n2 % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << cbs) - 1;
        var ds = Math.floor(n2 / this.DB), c2 = this.s << bs & this.DM, i2;
        for (i2 = this.t - 1; i2 >= 0; --i2) {
          r2[i2 + ds + 1] = this[i2] >> cbs | c2;
          c2 = (this[i2] & bm) << bs;
        }
        for (i2 = ds - 1; i2 >= 0; --i2) r2[i2] = 0;
        r2[ds] = c2;
        r2.t = this.t + ds + 1;
        r2.s = this.s;
        r2.clamp();
      }
      function bnpRShiftTo(n2, r2) {
        r2.s = this.s;
        var ds = Math.floor(n2 / this.DB);
        if (ds >= this.t) {
          r2.t = 0;
          return;
        }
        var bs = n2 % this.DB;
        var cbs = this.DB - bs;
        var bm = (1 << bs) - 1;
        r2[0] = this[ds] >> bs;
        for (var i2 = ds + 1; i2 < this.t; ++i2) {
          r2[i2 - ds - 1] |= (this[i2] & bm) << cbs;
          r2[i2 - ds] = this[i2] >> bs;
        }
        if (bs > 0) r2[this.t - ds - 1] |= (this.s & bm) << cbs;
        r2.t = this.t - ds;
        r2.clamp();
      }
      function bnpSubTo(a2, r2) {
        var i2 = 0, c2 = 0, m = Math.min(a2.t, this.t);
        while (i2 < m) {
          c2 += this[i2] - a2[i2];
          r2[i2++] = c2 & this.DM;
          c2 >>= this.DB;
        }
        if (a2.t < this.t) {
          c2 -= a2.s;
          while (i2 < this.t) {
            c2 += this[i2];
            r2[i2++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += this.s;
        } else {
          c2 += this.s;
          while (i2 < a2.t) {
            c2 -= a2[i2];
            r2[i2++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 -= a2.s;
        }
        r2.s = c2 < 0 ? -1 : 0;
        if (c2 < -1) r2[i2++] = this.DV + c2;
        else if (c2 > 0) r2[i2++] = c2;
        r2.t = i2;
        r2.clamp();
      }
      function bnpMultiplyTo(a2, r2) {
        var x2 = this.abs(), y2 = a2.abs();
        var i2 = x2.t;
        r2.t = i2 + y2.t;
        while (--i2 >= 0) r2[i2] = 0;
        for (i2 = 0; i2 < y2.t; ++i2) r2[i2 + x2.t] = x2.am(0, y2[i2], r2, i2, 0, x2.t);
        r2.s = 0;
        r2.clamp();
        if (this.s != a2.s) BigInteger2.ZERO.subTo(r2, r2);
      }
      function bnpSquareTo(r2) {
        var x2 = this.abs();
        var i2 = r2.t = 2 * x2.t;
        while (--i2 >= 0) r2[i2] = 0;
        for (i2 = 0; i2 < x2.t - 1; ++i2) {
          var c2 = x2.am(i2, x2[i2], r2, 2 * i2, 0, 1);
          if ((r2[i2 + x2.t] += x2.am(i2 + 1, 2 * x2[i2], r2, 2 * i2 + 1, c2, x2.t - i2 - 1)) >= x2.DV) {
            r2[i2 + x2.t] -= x2.DV;
            r2[i2 + x2.t + 1] = 1;
          }
        }
        if (r2.t > 0) r2[r2.t - 1] += x2.am(i2, x2[i2], r2, 2 * i2, 0, 1);
        r2.s = 0;
        r2.clamp();
      }
      function bnpDivRemTo(m, q, r2) {
        var pm = m.abs();
        if (pm.t <= 0) return;
        var pt = this.abs();
        if (pt.t < pm.t) {
          if (q != null) q.fromInt(0);
          if (r2 != null) this.copyTo(r2);
          return;
        }
        if (r2 == null) r2 = nbi2();
        var y2 = nbi2(), ts = this.s, ms2 = m.s;
        var nsh = this.DB - nbits2(pm[pm.t - 1]);
        if (nsh > 0) {
          pm.lShiftTo(nsh, y2);
          pt.lShiftTo(nsh, r2);
        } else {
          pm.copyTo(y2);
          pt.copyTo(r2);
        }
        var ys = y2.t;
        var y0 = y2[ys - 1];
        if (y0 == 0) return;
        var yt = y0 * (1 << this.F1) + (ys > 1 ? y2[ys - 2] >> this.F2 : 0);
        var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e4 = 1 << this.F2;
        var i2 = r2.t, j = i2 - ys, t3 = q == null ? nbi2() : q;
        y2.dlShiftTo(j, t3);
        if (r2.compareTo(t3) >= 0) {
          r2[r2.t++] = 1;
          r2.subTo(t3, r2);
        }
        BigInteger2.ONE.dlShiftTo(ys, t3);
        t3.subTo(y2, y2);
        while (y2.t < ys) y2[y2.t++] = 0;
        while (--j >= 0) {
          var qd = r2[--i2] == y0 ? this.DM : Math.floor(r2[i2] * d1 + (r2[i2 - 1] + e4) * d2);
          if ((r2[i2] += y2.am(0, qd, r2, j, 0, ys)) < qd) {
            y2.dlShiftTo(j, t3);
            r2.subTo(t3, r2);
            while (r2[i2] < --qd) r2.subTo(t3, r2);
          }
        }
        if (q != null) {
          r2.drShiftTo(ys, q);
          if (ts != ms2) BigInteger2.ZERO.subTo(q, q);
        }
        r2.t = ys;
        r2.clamp();
        if (nsh > 0) r2.rShiftTo(nsh, r2);
        if (ts < 0) BigInteger2.ZERO.subTo(r2, r2);
      }
      function bnMod(a2) {
        var r2 = nbi2();
        this.abs().divRemTo(a2, null, r2);
        if (this.s < 0 && r2.compareTo(BigInteger2.ZERO) > 0) a2.subTo(r2, r2);
        return r2;
      }
      function Classic2(m) {
        this.m = m;
      }
      function cConvert(x2) {
        if (x2.s < 0 || x2.compareTo(this.m) >= 0) return x2.mod(this.m);
        else return x2;
      }
      function cRevert(x2) {
        return x2;
      }
      function cReduce(x2) {
        x2.divRemTo(this.m, null, x2);
      }
      function cMulTo(x2, y2, r2) {
        x2.multiplyTo(y2, r2);
        this.reduce(r2);
      }
      function cSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      Classic2.prototype.convert = cConvert;
      Classic2.prototype.revert = cRevert;
      Classic2.prototype.reduce = cReduce;
      Classic2.prototype.mulTo = cMulTo;
      Classic2.prototype.sqrTo = cSqrTo;
      function bnpInvDigit() {
        if (this.t < 1) return 0;
        var x2 = this[0];
        if ((x2 & 1) == 0) return 0;
        var y2 = x2 & 3;
        y2 = y2 * (2 - (x2 & 15) * y2) & 15;
        y2 = y2 * (2 - (x2 & 255) * y2) & 255;
        y2 = y2 * (2 - ((x2 & 65535) * y2 & 65535)) & 65535;
        y2 = y2 * (2 - x2 * y2 % this.DV) % this.DV;
        return y2 > 0 ? this.DV - y2 : -y2;
      }
      function Montgomery2(m) {
        this.m = m;
        this.mp = m.invDigit();
        this.mpl = this.mp & 32767;
        this.mph = this.mp >> 15;
        this.um = (1 << m.DB - 15) - 1;
        this.mt2 = 2 * m.t;
      }
      function montConvert(x2) {
        var r2 = nbi2();
        x2.abs().dlShiftTo(this.m.t, r2);
        r2.divRemTo(this.m, null, r2);
        if (x2.s < 0 && r2.compareTo(BigInteger2.ZERO) > 0) this.m.subTo(r2, r2);
        return r2;
      }
      function montRevert(x2) {
        var r2 = nbi2();
        x2.copyTo(r2);
        this.reduce(r2);
        return r2;
      }
      function montReduce(x2) {
        while (x2.t <= this.mt2)
          x2[x2.t++] = 0;
        for (var i2 = 0; i2 < this.m.t; ++i2) {
          var j = x2[i2] & 32767;
          var u0 = j * this.mpl + ((j * this.mph + (x2[i2] >> 15) * this.mpl & this.um) << 15) & x2.DM;
          j = i2 + this.m.t;
          x2[j] += this.m.am(0, u0, x2, i2, 0, this.m.t);
          while (x2[j] >= x2.DV) {
            x2[j] -= x2.DV;
            x2[++j]++;
          }
        }
        x2.clamp();
        x2.drShiftTo(this.m.t, x2);
        if (x2.compareTo(this.m) >= 0) x2.subTo(this.m, x2);
      }
      function montSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      function montMulTo(x2, y2, r2) {
        x2.multiplyTo(y2, r2);
        this.reduce(r2);
      }
      Montgomery2.prototype.convert = montConvert;
      Montgomery2.prototype.revert = montRevert;
      Montgomery2.prototype.reduce = montReduce;
      Montgomery2.prototype.mulTo = montMulTo;
      Montgomery2.prototype.sqrTo = montSqrTo;
      function bnpIsEven() {
        return (this.t > 0 ? this[0] & 1 : this.s) == 0;
      }
      function bnpExp(e4, z3) {
        if (e4 > 4294967295 || e4 < 1) return BigInteger2.ONE;
        var r2 = nbi2(), r22 = nbi2(), g = z3.convert(this), i2 = nbits2(e4) - 1;
        g.copyTo(r2);
        while (--i2 >= 0) {
          z3.sqrTo(r2, r22);
          if ((e4 & 1 << i2) > 0) z3.mulTo(r22, g, r2);
          else {
            var t3 = r2;
            r2 = r22;
            r22 = t3;
          }
        }
        return z3.revert(r2);
      }
      function bnModPowInt(e4, m) {
        var z3;
        if (e4 < 256 || m.isEven()) z3 = new Classic2(m);
        else z3 = new Montgomery2(m);
        return this.exp(e4, z3);
      }
      BigInteger2.prototype.copyTo = bnpCopyTo;
      BigInteger2.prototype.fromInt = bnpFromInt;
      BigInteger2.prototype.fromString = bnpFromString;
      BigInteger2.prototype.clamp = bnpClamp;
      BigInteger2.prototype.dlShiftTo = bnpDLShiftTo;
      BigInteger2.prototype.drShiftTo = bnpDRShiftTo;
      BigInteger2.prototype.lShiftTo = bnpLShiftTo;
      BigInteger2.prototype.rShiftTo = bnpRShiftTo;
      BigInteger2.prototype.subTo = bnpSubTo;
      BigInteger2.prototype.multiplyTo = bnpMultiplyTo;
      BigInteger2.prototype.squareTo = bnpSquareTo;
      BigInteger2.prototype.divRemTo = bnpDivRemTo;
      BigInteger2.prototype.invDigit = bnpInvDigit;
      BigInteger2.prototype.isEven = bnpIsEven;
      BigInteger2.prototype.exp = bnpExp;
      BigInteger2.prototype.toString = bnToString;
      BigInteger2.prototype.negate = bnNegate;
      BigInteger2.prototype.abs = bnAbs;
      BigInteger2.prototype.compareTo = bnCompareTo;
      BigInteger2.prototype.bitLength = bnBitLength;
      BigInteger2.prototype.mod = bnMod;
      BigInteger2.prototype.modPowInt = bnModPowInt;
      BigInteger2.ZERO = nbv2(0);
      BigInteger2.ONE = nbv2(1);
      function bnClone() {
        var r2 = nbi2();
        this.copyTo(r2);
        return r2;
      }
      function bnIntValue() {
        if (this.s < 0) {
          if (this.t == 1) return this[0] - this.DV;
          else if (this.t == 0) return -1;
        } else if (this.t == 1) return this[0];
        else if (this.t == 0) return 0;
        return (this[1] & (1 << 32 - this.DB) - 1) << this.DB | this[0];
      }
      function bnByteValue() {
        return this.t == 0 ? this.s : this[0] << 24 >> 24;
      }
      function bnShortValue() {
        return this.t == 0 ? this.s : this[0] << 16 >> 16;
      }
      function bnpChunkSize(r2) {
        return Math.floor(Math.LN2 * this.DB / Math.log(r2));
      }
      function bnSigNum() {
        if (this.s < 0) return -1;
        else if (this.t <= 0 || this.t == 1 && this[0] <= 0) return 0;
        else return 1;
      }
      function bnpToRadix(b2) {
        if (b2 == null) b2 = 10;
        if (this.signum() == 0 || b2 < 2 || b2 > 36) return "0";
        var cs = this.chunkSize(b2);
        var a2 = Math.pow(b2, cs);
        var d = nbv2(a2), y2 = nbi2(), z3 = nbi2(), r2 = "";
        this.divRemTo(d, y2, z3);
        while (y2.signum() > 0) {
          r2 = (a2 + z3.intValue()).toString(b2).substr(1) + r2;
          y2.divRemTo(d, y2, z3);
        }
        return z3.intValue().toString(b2) + r2;
      }
      function bnpFromRadix(s2, b2) {
        this.fromInt(0);
        if (b2 == null) b2 = 10;
        var cs = this.chunkSize(b2);
        var d = Math.pow(b2, cs), mi = false, j = 0, w = 0;
        for (var i2 = 0; i2 < s2.length; ++i2) {
          var x2 = intAt2(s2, i2);
          if (x2 < 0) {
            if (s2.charAt(i2) == "-" && this.signum() == 0) mi = true;
            continue;
          }
          w = b2 * w + x2;
          if (++j >= cs) {
            this.dMultiply(d);
            this.dAddOffset(w, 0);
            j = 0;
            w = 0;
          }
        }
        if (j > 0) {
          this.dMultiply(Math.pow(b2, j));
          this.dAddOffset(w, 0);
        }
        if (mi) BigInteger2.ZERO.subTo(this, this);
      }
      function bnpFromNumber(a2, b2, c2) {
        if ("number" == typeof b2) {
          if (a2 < 2) this.fromInt(1);
          else {
            this.fromNumber(a2, c2);
            if (!this.testBit(a2 - 1))
              this.bitwiseTo(BigInteger2.ONE.shiftLeft(a2 - 1), op_or2, this);
            if (this.isEven()) this.dAddOffset(1, 0);
            while (!this.isProbablePrime(b2)) {
              this.dAddOffset(2, 0);
              if (this.bitLength() > a2) this.subTo(BigInteger2.ONE.shiftLeft(a2 - 1), this);
            }
          }
        } else {
          var x2 = new Array(), t3 = a2 & 7;
          x2.length = (a2 >> 3) + 1;
          b2.nextBytes(x2);
          if (t3 > 0) x2[0] &= (1 << t3) - 1;
          else x2[0] = 0;
          this.fromString(x2, 256);
        }
      }
      function bnToByteArray() {
        var i2 = this.t, r2 = new Array();
        r2[0] = this.s;
        var p2 = this.DB - i2 * this.DB % 8, d, k2 = 0;
        if (i2-- > 0) {
          if (p2 < this.DB && (d = this[i2] >> p2) != (this.s & this.DM) >> p2)
            r2[k2++] = d | this.s << this.DB - p2;
          while (i2 >= 0) {
            if (p2 < 8) {
              d = (this[i2] & (1 << p2) - 1) << 8 - p2;
              d |= this[--i2] >> (p2 += this.DB - 8);
            } else {
              d = this[i2] >> (p2 -= 8) & 255;
              if (p2 <= 0) {
                p2 += this.DB;
                --i2;
              }
            }
            if ((d & 128) != 0) d |= -256;
            if (k2 == 0 && (this.s & 128) != (d & 128)) ++k2;
            if (k2 > 0 || d != this.s) r2[k2++] = d;
          }
        }
        return r2;
      }
      function bnEquals(a2) {
        return this.compareTo(a2) == 0;
      }
      function bnMin(a2) {
        return this.compareTo(a2) < 0 ? this : a2;
      }
      function bnMax(a2) {
        return this.compareTo(a2) > 0 ? this : a2;
      }
      function bnpBitwiseTo(a2, op, r2) {
        var i2, f2, m = Math.min(a2.t, this.t);
        for (i2 = 0; i2 < m; ++i2) r2[i2] = op(this[i2], a2[i2]);
        if (a2.t < this.t) {
          f2 = a2.s & this.DM;
          for (i2 = m; i2 < this.t; ++i2) r2[i2] = op(this[i2], f2);
          r2.t = this.t;
        } else {
          f2 = this.s & this.DM;
          for (i2 = m; i2 < a2.t; ++i2) r2[i2] = op(f2, a2[i2]);
          r2.t = a2.t;
        }
        r2.s = op(this.s, a2.s);
        r2.clamp();
      }
      function op_and2(x2, y2) {
        return x2 & y2;
      }
      function bnAnd(a2) {
        var r2 = nbi2();
        this.bitwiseTo(a2, op_and2, r2);
        return r2;
      }
      function op_or2(x2, y2) {
        return x2 | y2;
      }
      function bnOr(a2) {
        var r2 = nbi2();
        this.bitwiseTo(a2, op_or2, r2);
        return r2;
      }
      function op_xor2(x2, y2) {
        return x2 ^ y2;
      }
      function bnXor(a2) {
        var r2 = nbi2();
        this.bitwiseTo(a2, op_xor2, r2);
        return r2;
      }
      function op_andnot2(x2, y2) {
        return x2 & ~y2;
      }
      function bnAndNot(a2) {
        var r2 = nbi2();
        this.bitwiseTo(a2, op_andnot2, r2);
        return r2;
      }
      function bnNot() {
        var r2 = nbi2();
        for (var i2 = 0; i2 < this.t; ++i2) r2[i2] = this.DM & ~this[i2];
        r2.t = this.t;
        r2.s = ~this.s;
        return r2;
      }
      function bnShiftLeft(n2) {
        var r2 = nbi2();
        if (n2 < 0) this.rShiftTo(-n2, r2);
        else this.lShiftTo(n2, r2);
        return r2;
      }
      function bnShiftRight(n2) {
        var r2 = nbi2();
        if (n2 < 0) this.lShiftTo(-n2, r2);
        else this.rShiftTo(n2, r2);
        return r2;
      }
      function lbit2(x2) {
        if (x2 == 0) return -1;
        var r2 = 0;
        if ((x2 & 65535) == 0) {
          x2 >>= 16;
          r2 += 16;
        }
        if ((x2 & 255) == 0) {
          x2 >>= 8;
          r2 += 8;
        }
        if ((x2 & 15) == 0) {
          x2 >>= 4;
          r2 += 4;
        }
        if ((x2 & 3) == 0) {
          x2 >>= 2;
          r2 += 2;
        }
        if ((x2 & 1) == 0) ++r2;
        return r2;
      }
      function bnGetLowestSetBit() {
        for (var i2 = 0; i2 < this.t; ++i2)
          if (this[i2] != 0) return i2 * this.DB + lbit2(this[i2]);
        if (this.s < 0) return this.t * this.DB;
        return -1;
      }
      function cbit2(x2) {
        var r2 = 0;
        while (x2 != 0) {
          x2 &= x2 - 1;
          ++r2;
        }
        return r2;
      }
      function bnBitCount() {
        var r2 = 0, x2 = this.s & this.DM;
        for (var i2 = 0; i2 < this.t; ++i2) r2 += cbit2(this[i2] ^ x2);
        return r2;
      }
      function bnTestBit(n2) {
        var j = Math.floor(n2 / this.DB);
        if (j >= this.t) return this.s != 0;
        return (this[j] & 1 << n2 % this.DB) != 0;
      }
      function bnpChangeBit(n2, op) {
        var r2 = BigInteger2.ONE.shiftLeft(n2);
        this.bitwiseTo(r2, op, r2);
        return r2;
      }
      function bnSetBit(n2) {
        return this.changeBit(n2, op_or2);
      }
      function bnClearBit(n2) {
        return this.changeBit(n2, op_andnot2);
      }
      function bnFlipBit(n2) {
        return this.changeBit(n2, op_xor2);
      }
      function bnpAddTo(a2, r2) {
        var i2 = 0, c2 = 0, m = Math.min(a2.t, this.t);
        while (i2 < m) {
          c2 += this[i2] + a2[i2];
          r2[i2++] = c2 & this.DM;
          c2 >>= this.DB;
        }
        if (a2.t < this.t) {
          c2 += a2.s;
          while (i2 < this.t) {
            c2 += this[i2];
            r2[i2++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += this.s;
        } else {
          c2 += this.s;
          while (i2 < a2.t) {
            c2 += a2[i2];
            r2[i2++] = c2 & this.DM;
            c2 >>= this.DB;
          }
          c2 += a2.s;
        }
        r2.s = c2 < 0 ? -1 : 0;
        if (c2 > 0) r2[i2++] = c2;
        else if (c2 < -1) r2[i2++] = this.DV + c2;
        r2.t = i2;
        r2.clamp();
      }
      function bnAdd(a2) {
        var r2 = nbi2();
        this.addTo(a2, r2);
        return r2;
      }
      function bnSubtract(a2) {
        var r2 = nbi2();
        this.subTo(a2, r2);
        return r2;
      }
      function bnMultiply(a2) {
        var r2 = nbi2();
        this.multiplyTo(a2, r2);
        return r2;
      }
      function bnSquare() {
        var r2 = nbi2();
        this.squareTo(r2);
        return r2;
      }
      function bnDivide(a2) {
        var r2 = nbi2();
        this.divRemTo(a2, r2, null);
        return r2;
      }
      function bnRemainder(a2) {
        var r2 = nbi2();
        this.divRemTo(a2, null, r2);
        return r2;
      }
      function bnDivideAndRemainder(a2) {
        var q = nbi2(), r2 = nbi2();
        this.divRemTo(a2, q, r2);
        return new Array(q, r2);
      }
      function bnpDMultiply(n2) {
        this[this.t] = this.am(0, n2 - 1, this, 0, 0, this.t);
        ++this.t;
        this.clamp();
      }
      function bnpDAddOffset(n2, w) {
        if (n2 == 0) return;
        while (this.t <= w) this[this.t++] = 0;
        this[w] += n2;
        while (this[w] >= this.DV) {
          this[w] -= this.DV;
          if (++w >= this.t) this[this.t++] = 0;
          ++this[w];
        }
      }
      function NullExp2() {
      }
      function nNop(x2) {
        return x2;
      }
      function nMulTo(x2, y2, r2) {
        x2.multiplyTo(y2, r2);
      }
      function nSqrTo(x2, r2) {
        x2.squareTo(r2);
      }
      NullExp2.prototype.convert = nNop;
      NullExp2.prototype.revert = nNop;
      NullExp2.prototype.mulTo = nMulTo;
      NullExp2.prototype.sqrTo = nSqrTo;
      function bnPow(e4) {
        return this.exp(e4, new NullExp2());
      }
      function bnpMultiplyLowerTo(a2, n2, r2) {
        var i2 = Math.min(this.t + a2.t, n2);
        r2.s = 0;
        r2.t = i2;
        while (i2 > 0) r2[--i2] = 0;
        var j;
        for (j = r2.t - this.t; i2 < j; ++i2) r2[i2 + this.t] = this.am(0, a2[i2], r2, i2, 0, this.t);
        for (j = Math.min(a2.t, n2); i2 < j; ++i2) this.am(0, a2[i2], r2, i2, 0, n2 - i2);
        r2.clamp();
      }
      function bnpMultiplyUpperTo(a2, n2, r2) {
        --n2;
        var i2 = r2.t = this.t + a2.t - n2;
        r2.s = 0;
        while (--i2 >= 0) r2[i2] = 0;
        for (i2 = Math.max(n2 - this.t, 0); i2 < a2.t; ++i2)
          r2[this.t + i2 - n2] = this.am(n2 - i2, a2[i2], r2, 0, 0, this.t + i2 - n2);
        r2.clamp();
        r2.drShiftTo(1, r2);
      }
      function Barrett2(m) {
        this.r2 = nbi2();
        this.q3 = nbi2();
        BigInteger2.ONE.dlShiftTo(2 * m.t, this.r2);
        this.mu = this.r2.divide(m);
        this.m = m;
      }
      function barrettConvert(x2) {
        if (x2.s < 0 || x2.t > 2 * this.m.t) return x2.mod(this.m);
        else if (x2.compareTo(this.m) < 0) return x2;
        else {
          var r2 = nbi2();
          x2.copyTo(r2);
          this.reduce(r2);
          return r2;
        }
      }
      function barrettRevert(x2) {
        return x2;
      }
      function barrettReduce(x2) {
        x2.drShiftTo(this.m.t - 1, this.r2);
        if (x2.t > this.m.t + 1) {
          x2.t = this.m.t + 1;
          x2.clamp();
        }
        this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
        this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
        while (x2.compareTo(this.r2) < 0) x2.dAddOffset(1, this.m.t + 1);
        x2.subTo(this.r2, x2);
        while (x2.compareTo(this.m) >= 0) x2.subTo(this.m, x2);
      }
      function barrettSqrTo(x2, r2) {
        x2.squareTo(r2);
        this.reduce(r2);
      }
      function barrettMulTo(x2, y2, r2) {
        x2.multiplyTo(y2, r2);
        this.reduce(r2);
      }
      Barrett2.prototype.convert = barrettConvert;
      Barrett2.prototype.revert = barrettRevert;
      Barrett2.prototype.reduce = barrettReduce;
      Barrett2.prototype.mulTo = barrettMulTo;
      Barrett2.prototype.sqrTo = barrettSqrTo;
      function bnModPow(e4, m) {
        var i2 = e4.bitLength(), k2, r2 = nbv2(1), z3;
        if (i2 <= 0) return r2;
        else if (i2 < 18) k2 = 1;
        else if (i2 < 48) k2 = 3;
        else if (i2 < 144) k2 = 4;
        else if (i2 < 768) k2 = 5;
        else k2 = 6;
        if (i2 < 8)
          z3 = new Classic2(m);
        else if (m.isEven())
          z3 = new Barrett2(m);
        else
          z3 = new Montgomery2(m);
        var g = new Array(), n2 = 3, k1 = k2 - 1, km = (1 << k2) - 1;
        g[1] = z3.convert(this);
        if (k2 > 1) {
          var g2 = nbi2();
          z3.sqrTo(g[1], g2);
          while (n2 <= km) {
            g[n2] = nbi2();
            z3.mulTo(g2, g[n2 - 2], g[n2]);
            n2 += 2;
          }
        }
        var j = e4.t - 1, w, is1 = true, r22 = nbi2(), t3;
        i2 = nbits2(e4[j]) - 1;
        while (j >= 0) {
          if (i2 >= k1) w = e4[j] >> i2 - k1 & km;
          else {
            w = (e4[j] & (1 << i2 + 1) - 1) << k1 - i2;
            if (j > 0) w |= e4[j - 1] >> this.DB + i2 - k1;
          }
          n2 = k2;
          while ((w & 1) == 0) {
            w >>= 1;
            --n2;
          }
          if ((i2 -= n2) < 0) {
            i2 += this.DB;
            --j;
          }
          if (is1) {
            g[w].copyTo(r2);
            is1 = false;
          } else {
            while (n2 > 1) {
              z3.sqrTo(r2, r22);
              z3.sqrTo(r22, r2);
              n2 -= 2;
            }
            if (n2 > 0) z3.sqrTo(r2, r22);
            else {
              t3 = r2;
              r2 = r22;
              r22 = t3;
            }
            z3.mulTo(r22, g[w], r2);
          }
          while (j >= 0 && (e4[j] & 1 << i2) == 0) {
            z3.sqrTo(r2, r22);
            t3 = r2;
            r2 = r22;
            r22 = t3;
            if (--i2 < 0) {
              i2 = this.DB - 1;
              --j;
            }
          }
        }
        return z3.revert(r2);
      }
      function bnGCD(a2) {
        var x2 = this.s < 0 ? this.negate() : this.clone();
        var y2 = a2.s < 0 ? a2.negate() : a2.clone();
        if (x2.compareTo(y2) < 0) {
          var t3 = x2;
          x2 = y2;
          y2 = t3;
        }
        var i2 = x2.getLowestSetBit(), g = y2.getLowestSetBit();
        if (g < 0) return x2;
        if (i2 < g) g = i2;
        if (g > 0) {
          x2.rShiftTo(g, x2);
          y2.rShiftTo(g, y2);
        }
        while (x2.signum() > 0) {
          if ((i2 = x2.getLowestSetBit()) > 0) x2.rShiftTo(i2, x2);
          if ((i2 = y2.getLowestSetBit()) > 0) y2.rShiftTo(i2, y2);
          if (x2.compareTo(y2) >= 0) {
            x2.subTo(y2, x2);
            x2.rShiftTo(1, x2);
          } else {
            y2.subTo(x2, y2);
            y2.rShiftTo(1, y2);
          }
        }
        if (g > 0) y2.lShiftTo(g, y2);
        return y2;
      }
      function bnpModInt(n2) {
        if (n2 <= 0) return 0;
        var d = this.DV % n2, r2 = this.s < 0 ? n2 - 1 : 0;
        if (this.t > 0)
          if (d == 0) r2 = this[0] % n2;
          else for (var i2 = this.t - 1; i2 >= 0; --i2) r2 = (d * r2 + this[i2]) % n2;
        return r2;
      }
      function bnModInverse(m) {
        var ac = m.isEven();
        if (this.isEven() && ac || m.signum() == 0) return BigInteger2.ZERO;
        var u2 = m.clone(), v2 = this.clone();
        var a2 = nbv2(1), b2 = nbv2(0), c2 = nbv2(0), d = nbv2(1);
        while (u2.signum() != 0) {
          while (u2.isEven()) {
            u2.rShiftTo(1, u2);
            if (ac) {
              if (!a2.isEven() || !b2.isEven()) {
                a2.addTo(this, a2);
                b2.subTo(m, b2);
              }
              a2.rShiftTo(1, a2);
            } else if (!b2.isEven()) b2.subTo(m, b2);
            b2.rShiftTo(1, b2);
          }
          while (v2.isEven()) {
            v2.rShiftTo(1, v2);
            if (ac) {
              if (!c2.isEven() || !d.isEven()) {
                c2.addTo(this, c2);
                d.subTo(m, d);
              }
              c2.rShiftTo(1, c2);
            } else if (!d.isEven()) d.subTo(m, d);
            d.rShiftTo(1, d);
          }
          if (u2.compareTo(v2) >= 0) {
            u2.subTo(v2, u2);
            if (ac) a2.subTo(c2, a2);
            b2.subTo(d, b2);
          } else {
            v2.subTo(u2, v2);
            if (ac) c2.subTo(a2, c2);
            d.subTo(b2, d);
          }
        }
        if (v2.compareTo(BigInteger2.ONE) != 0) return BigInteger2.ZERO;
        if (d.compareTo(m) >= 0) return d.subtract(m);
        if (d.signum() < 0) d.addTo(m, d);
        else return d;
        if (d.signum() < 0) return d.add(m);
        else return d;
      }
      var lowprimes2 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997];
      var lplim2 = (1 << 26) / lowprimes2[lowprimes2.length - 1];
      function bnIsProbablePrime(t3) {
        var i2, x2 = this.abs();
        if (x2.t == 1 && x2[0] <= lowprimes2[lowprimes2.length - 1]) {
          for (i2 = 0; i2 < lowprimes2.length; ++i2)
            if (x2[0] == lowprimes2[i2]) return true;
          return false;
        }
        if (x2.isEven()) return false;
        i2 = 1;
        while (i2 < lowprimes2.length) {
          var m = lowprimes2[i2], j = i2 + 1;
          while (j < lowprimes2.length && m < lplim2) m *= lowprimes2[j++];
          m = x2.modInt(m);
          while (i2 < j) if (m % lowprimes2[i2++] == 0) return false;
        }
        return x2.millerRabin(t3);
      }
      function bnpMillerRabin(t3) {
        var n1 = this.subtract(BigInteger2.ONE);
        var k2 = n1.getLowestSetBit();
        if (k2 <= 0) return false;
        var r2 = n1.shiftRight(k2);
        t3 = t3 + 1 >> 1;
        if (t3 > lowprimes2.length) t3 = lowprimes2.length;
        var a2 = nbi2();
        for (var i2 = 0; i2 < t3; ++i2) {
          a2.fromInt(lowprimes2[Math.floor(Math.random() * lowprimes2.length)]);
          var y2 = a2.modPow(r2, this);
          if (y2.compareTo(BigInteger2.ONE) != 0 && y2.compareTo(n1) != 0) {
            var j = 1;
            while (j++ < k2 && y2.compareTo(n1) != 0) {
              y2 = y2.modPowInt(2, this);
              if (y2.compareTo(BigInteger2.ONE) == 0) return false;
            }
            if (y2.compareTo(n1) != 0) return false;
          }
        }
        return true;
      }
      BigInteger2.prototype.chunkSize = bnpChunkSize;
      BigInteger2.prototype.toRadix = bnpToRadix;
      BigInteger2.prototype.fromRadix = bnpFromRadix;
      BigInteger2.prototype.fromNumber = bnpFromNumber;
      BigInteger2.prototype.bitwiseTo = bnpBitwiseTo;
      BigInteger2.prototype.changeBit = bnpChangeBit;
      BigInteger2.prototype.addTo = bnpAddTo;
      BigInteger2.prototype.dMultiply = bnpDMultiply;
      BigInteger2.prototype.dAddOffset = bnpDAddOffset;
      BigInteger2.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
      BigInteger2.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
      BigInteger2.prototype.modInt = bnpModInt;
      BigInteger2.prototype.millerRabin = bnpMillerRabin;
      BigInteger2.prototype.clone = bnClone;
      BigInteger2.prototype.intValue = bnIntValue;
      BigInteger2.prototype.byteValue = bnByteValue;
      BigInteger2.prototype.shortValue = bnShortValue;
      BigInteger2.prototype.signum = bnSigNum;
      BigInteger2.prototype.toByteArray = bnToByteArray;
      BigInteger2.prototype.equals = bnEquals;
      BigInteger2.prototype.min = bnMin;
      BigInteger2.prototype.max = bnMax;
      BigInteger2.prototype.and = bnAnd;
      BigInteger2.prototype.or = bnOr;
      BigInteger2.prototype.xor = bnXor;
      BigInteger2.prototype.andNot = bnAndNot;
      BigInteger2.prototype.not = bnNot;
      BigInteger2.prototype.shiftLeft = bnShiftLeft;
      BigInteger2.prototype.shiftRight = bnShiftRight;
      BigInteger2.prototype.getLowestSetBit = bnGetLowestSetBit;
      BigInteger2.prototype.bitCount = bnBitCount;
      BigInteger2.prototype.testBit = bnTestBit;
      BigInteger2.prototype.setBit = bnSetBit;
      BigInteger2.prototype.clearBit = bnClearBit;
      BigInteger2.prototype.flipBit = bnFlipBit;
      BigInteger2.prototype.add = bnAdd;
      BigInteger2.prototype.subtract = bnSubtract;
      BigInteger2.prototype.multiply = bnMultiply;
      BigInteger2.prototype.divide = bnDivide;
      BigInteger2.prototype.remainder = bnRemainder;
      BigInteger2.prototype.divideAndRemainder = bnDivideAndRemainder;
      BigInteger2.prototype.modPow = bnModPow;
      BigInteger2.prototype.modInverse = bnModInverse;
      BigInteger2.prototype.pow = bnPow;
      BigInteger2.prototype.gcd = bnGCD;
      BigInteger2.prototype.isProbablePrime = bnIsProbablePrime;
      BigInteger2.prototype.square = bnSquare;
      BigInteger2.prototype.Barrett = Barrett2;
      var rng_state2;
      var rng_pool2;
      var rng_pptr2;
      function rng_seed_int(x2) {
        rng_pool2[rng_pptr2++] ^= x2 & 255;
        rng_pool2[rng_pptr2++] ^= x2 >> 8 & 255;
        rng_pool2[rng_pptr2++] ^= x2 >> 16 & 255;
        rng_pool2[rng_pptr2++] ^= x2 >> 24 & 255;
        if (rng_pptr2 >= rng_psize2) rng_pptr2 -= rng_psize2;
      }
      function rng_seed_time() {
        rng_seed_int((/* @__PURE__ */ new Date()).getTime());
      }
      if (rng_pool2 == null) {
        rng_pool2 = new Array();
        rng_pptr2 = 0;
        var t2;
        if (typeof window !== "undefined" && window.crypto) {
          if (window.crypto.getRandomValues) {
            var ua = new Uint8Array(32);
            window.crypto.getRandomValues(ua);
            for (t2 = 0; t2 < 32; ++t2)
              rng_pool2[rng_pptr2++] = ua[t2];
          } else if (navigator.appName == "Netscape" && navigator.appVersion < "5") {
            var z2 = window.crypto.random(32);
            for (t2 = 0; t2 < z2.length; ++t2)
              rng_pool2[rng_pptr2++] = z2.charCodeAt(t2) & 255;
          }
        }
        while (rng_pptr2 < rng_psize2) {
          t2 = Math.floor(65536 * Math.random());
          rng_pool2[rng_pptr2++] = t2 >>> 8;
          rng_pool2[rng_pptr2++] = t2 & 255;
        }
        rng_pptr2 = 0;
        rng_seed_time();
      }
      function rng_get_byte2() {
        if (rng_state2 == null) {
          rng_seed_time();
          rng_state2 = prng_newstate2();
          rng_state2.init(rng_pool2);
          for (rng_pptr2 = 0; rng_pptr2 < rng_pool2.length; ++rng_pptr2)
            rng_pool2[rng_pptr2] = 0;
          rng_pptr2 = 0;
        }
        return rng_state2.next();
      }
      function rng_get_bytes(ba) {
        var i2;
        for (i2 = 0; i2 < ba.length; ++i2) ba[i2] = rng_get_byte2();
      }
      function SecureRandom2() {
      }
      SecureRandom2.prototype.nextBytes = rng_get_bytes;
      function Arcfour2() {
        this.i = 0;
        this.j = 0;
        this.S = new Array();
      }
      function ARC4init(key2) {
        var i2, j, t3;
        for (i2 = 0; i2 < 256; ++i2)
          this.S[i2] = i2;
        j = 0;
        for (i2 = 0; i2 < 256; ++i2) {
          j = j + this.S[i2] + key2[i2 % key2.length] & 255;
          t3 = this.S[i2];
          this.S[i2] = this.S[j];
          this.S[j] = t3;
        }
        this.i = 0;
        this.j = 0;
      }
      function ARC4next() {
        var t3;
        this.i = this.i + 1 & 255;
        this.j = this.j + this.S[this.i] & 255;
        t3 = this.S[this.i];
        this.S[this.i] = this.S[this.j];
        this.S[this.j] = t3;
        return this.S[t3 + this.S[this.i] & 255];
      }
      Arcfour2.prototype.init = ARC4init;
      Arcfour2.prototype.next = ARC4next;
      function prng_newstate2() {
        return new Arcfour2();
      }
      var rng_psize2 = 256;
      {
        module2.exports = {
          default: BigInteger2,
          BigInteger: BigInteger2,
          SecureRandom: SecureRandom2
        };
      }
    }).call(jsbn);
  })(jsbn$1);
  return jsbn$1.exports;
}
var jsbnExports = requireJsbn();
var THREE = new jsbnExports.BigInteger("3");
var ECFieldElementFp = (
  /** @class */
  function() {
    function ECFieldElementFp2(q, x2) {
      this.x = x2;
      this.q = q;
    }
    ECFieldElementFp2.prototype.equals = function(other) {
      if (other === this)
        return true;
      return this.q.equals(other.q) && this.x.equals(other.x);
    };
    ECFieldElementFp2.prototype.toBigInteger = function() {
      return this.x;
    };
    ECFieldElementFp2.prototype.negate = function() {
      return new ECFieldElementFp2(this.q, this.x.negate().mod(this.q));
    };
    ECFieldElementFp2.prototype.add = function(b2) {
      return new ECFieldElementFp2(this.q, this.x.add(b2.toBigInteger()).mod(this.q));
    };
    ECFieldElementFp2.prototype.subtract = function(b2) {
      return new ECFieldElementFp2(this.q, this.x.subtract(b2.toBigInteger()).mod(this.q));
    };
    ECFieldElementFp2.prototype.multiply = function(b2) {
      return new ECFieldElementFp2(this.q, this.x.multiply(b2.toBigInteger()).mod(this.q));
    };
    ECFieldElementFp2.prototype.divide = function(b2) {
      return new ECFieldElementFp2(this.q, this.x.multiply(b2.toBigInteger().modInverse(this.q)).mod(this.q));
    };
    ECFieldElementFp2.prototype.square = function() {
      return new ECFieldElementFp2(this.q, this.x.square().mod(this.q));
    };
    return ECFieldElementFp2;
  }()
);
var ECPointFp = (
  /** @class */
  function() {
    function ECPointFp2(curve2, x2, y2, z2) {
      this.curve = curve2;
      this.x = x2;
      this.y = y2;
      this.z = z2 == null ? jsbnExports.BigInteger.ONE : z2;
      this.zinv = null;
    }
    ECPointFp2.prototype.getX = function() {
      if (this.zinv === null)
        this.zinv = this.z.modInverse(this.curve.q);
      return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
    };
    ECPointFp2.prototype.getY = function() {
      if (this.zinv === null)
        this.zinv = this.z.modInverse(this.curve.q);
      return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
    };
    ECPointFp2.prototype.equals = function(other) {
      if (other === this)
        return true;
      if (this.isInfinity())
        return other.isInfinity();
      if (other.isInfinity())
        return this.isInfinity();
      var u2 = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
      if (!u2.equals(jsbnExports.BigInteger.ZERO))
        return false;
      var v2 = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
      return v2.equals(jsbnExports.BigInteger.ZERO);
    };
    ECPointFp2.prototype.isInfinity = function() {
      if (this.x === null && this.y === null)
        return true;
      return this.z.equals(jsbnExports.BigInteger.ZERO) && !this.y.toBigInteger().equals(jsbnExports.BigInteger.ZERO);
    };
    ECPointFp2.prototype.negate = function() {
      return new ECPointFp2(this.curve, this.x, this.y.negate(), this.z);
    };
    ECPointFp2.prototype.add = function(b2) {
      if (this.isInfinity())
        return b2;
      if (b2.isInfinity())
        return this;
      var x1 = this.x.toBigInteger();
      var y1 = this.y.toBigInteger();
      var z1 = this.z;
      var x2 = b2.x.toBigInteger();
      var y2 = b2.y.toBigInteger();
      var z2 = b2.z;
      var q = this.curve.q;
      var w1 = x1.multiply(z2).mod(q);
      var w2 = x2.multiply(z1).mod(q);
      var w3 = w1.subtract(w2);
      var w4 = y1.multiply(z2).mod(q);
      var w5 = y2.multiply(z1).mod(q);
      var w6 = w4.subtract(w5);
      if (jsbnExports.BigInteger.ZERO.equals(w3)) {
        if (jsbnExports.BigInteger.ZERO.equals(w6)) {
          return this.twice();
        }
        return this.curve.infinity;
      }
      var w7 = w1.add(w2);
      var w8 = z1.multiply(z2).mod(q);
      var w9 = w3.square().mod(q);
      var w10 = w3.multiply(w9).mod(q);
      var w11 = w8.multiply(w6.square()).subtract(w7.multiply(w9)).mod(q);
      var x3 = w3.multiply(w11).mod(q);
      var y3 = w6.multiply(w9.multiply(w1).subtract(w11)).subtract(w4.multiply(w10)).mod(q);
      var z3 = w10.multiply(w8).mod(q);
      return new ECPointFp2(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
    };
    ECPointFp2.prototype.twice = function() {
      if (this.isInfinity())
        return this;
      if (!this.y.toBigInteger().signum())
        return this.curve.infinity;
      var x1 = this.x.toBigInteger();
      var y1 = this.y.toBigInteger();
      var z1 = this.z;
      var q = this.curve.q;
      var a2 = this.curve.a.toBigInteger();
      var w1 = x1.square().multiply(THREE).add(a2.multiply(z1.square())).mod(q);
      var w2 = y1.shiftLeft(1).multiply(z1).mod(q);
      var w3 = y1.square().mod(q);
      var w4 = w3.multiply(x1).multiply(z1).mod(q);
      var w5 = w2.square().mod(q);
      var w6 = w1.square().subtract(w4.shiftLeft(3)).mod(q);
      var x3 = w2.multiply(w6).mod(q);
      var y3 = w1.multiply(w4.shiftLeft(2).subtract(w6)).subtract(w5.shiftLeft(1).multiply(w3)).mod(q);
      var z3 = w2.multiply(w5).mod(q);
      return new ECPointFp2(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
    };
    ECPointFp2.prototype.multiply = function(k2) {
      if (this.isInfinity())
        return this;
      if (!k2.signum())
        return this.curve.infinity;
      var k3 = k2.multiply(THREE);
      var neg = this.negate();
      var Q = this;
      for (var i2 = k3.bitLength() - 2; i2 > 0; i2--) {
        Q = Q.twice();
        var k3Bit = k3.testBit(i2);
        var kBit = k2.testBit(i2);
        if (k3Bit !== kBit) {
          Q = Q.add(k3Bit ? this : neg);
        }
      }
      return Q;
    };
    return ECPointFp2;
  }()
);
var ECCurveFp = (
  /** @class */
  function() {
    function ECCurveFp2(q, a2, b2) {
      this.q = q;
      this.a = this.fromBigInteger(a2);
      this.b = this.fromBigInteger(b2);
      this.infinity = new ECPointFp(this, null, null);
    }
    ECCurveFp2.prototype.equals = function(other) {
      if (other === this)
        return true;
      return this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b);
    };
    ECCurveFp2.prototype.fromBigInteger = function(x2) {
      return new ECFieldElementFp(this.q, x2);
    };
    ECCurveFp2.prototype.decodePointHex = function(s2) {
      switch (parseInt(s2.substr(0, 2), 16)) {
        // 第一个字节
        case 0:
          return this.infinity;
        case 2:
        case 3:
          return null;
        case 4:
        case 6:
        case 7:
          var len = (s2.length - 2) / 2;
          var xHex = s2.substr(2, len);
          var yHex = s2.substr(len + 2, len);
          return new ECPointFp(this, this.fromBigInteger(new jsbnExports.BigInteger(xHex, 16)), this.fromBigInteger(new jsbnExports.BigInteger(yHex, 16)));
        default:
          return null;
      }
    };
    return ECCurveFp2;
  }()
);
var rng$1 = new jsbnExports.SecureRandom();
var _a = generateEcparam(), curve = _a.curve, G = _a.G, n$1 = _a.n;
function getGlobalCurve() {
  return curve;
}
function generateEcparam() {
  var p2 = new jsbnExports.BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
  var a2 = new jsbnExports.BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
  var b2 = new jsbnExports.BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
  var curve2 = new ECCurveFp(p2, a2, b2);
  var gxHex = "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7";
  var gyHex = "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0";
  var G2 = curve2.decodePointHex("04" + gxHex + gyHex);
  var n2 = new jsbnExports.BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
  return { curve: curve2, G: G2, n: n2 };
}
function generateKeyPairHex(a2, b2, c2) {
  var random = a2 ? new jsbnExports.BigInteger(a2, b2, c2) : new jsbnExports.BigInteger(n$1.bitLength(), rng$1);
  var d = random.mod(n$1.subtract(jsbnExports.BigInteger.ONE)).add(jsbnExports.BigInteger.ONE);
  var privateKey = leftPad(d.toString(16), 64);
  var P = G.multiply(d);
  var Px = leftPad(P.getX().toBigInteger().toString(16), 64);
  var Py = leftPad(P.getY().toBigInteger().toString(16), 64);
  var publicKey2 = "04" + Px + Py;
  return { privateKey, publicKey: publicKey2 };
}
function utf8ToHex(input) {
  input = unescape(encodeURIComponent(input));
  var length = input.length;
  var words = [];
  for (var i2 = 0; i2 < length; i2++) {
    words[i2 >>> 2] |= (input.charCodeAt(i2) & 255) << 24 - i2 % 4 * 8;
  }
  var hexChars = [];
  for (var i2 = 0; i2 < length; i2++) {
    var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
    hexChars.push((bite >>> 4).toString(16));
    hexChars.push((bite & 15).toString(16));
  }
  return hexChars.join("");
}
function leftPad(input, num) {
  if (input.length >= num)
    return input;
  return new Array(num - input.length + 1).join("0") + input;
}
function arrayToHex(arr) {
  return arr.map(function(item) {
    item = item.toString(16);
    return item.length === 1 ? "0" + item : item;
  }).join("");
}
function hexToArray(hexStr) {
  var words = [];
  var hexStrLength = hexStr.length;
  if (hexStrLength % 2 !== 0) {
    hexStr = leftPad(hexStr, hexStrLength + 1);
  }
  hexStrLength = hexStr.length;
  for (var i2 = 0; i2 < hexStrLength; i2 += 2) {
    words.push(parseInt(hexStr.substr(i2, 2), 16));
  }
  return words;
}
function rotl(x2, n2) {
  var result = [];
  var a2 = ~~(n2 / 8);
  var b2 = n2 % 8;
  for (var i2 = 0, len = x2.length; i2 < len; i2++) {
    result[i2] = (x2[(i2 + a2) % len] << b2 & 255) + (x2[(i2 + a2 + 1) % len] >>> 8 - b2 & 255);
  }
  return result;
}
function xor(x2, y2) {
  var result = [];
  for (var i2 = x2.length - 1; i2 >= 0; i2--)
    result[i2] = (x2[i2] ^ y2[i2]) & 255;
  return result;
}
function and(x2, y2) {
  var result = [];
  for (var i2 = x2.length - 1; i2 >= 0; i2--)
    result[i2] = x2[i2] & y2[i2] & 255;
  return result;
}
function or(x2, y2) {
  var result = [];
  for (var i2 = x2.length - 1; i2 >= 0; i2--)
    result[i2] = (x2[i2] | y2[i2]) & 255;
  return result;
}
function add$1(x2, y2) {
  var result = [];
  var temp = 0;
  for (var i2 = x2.length - 1; i2 >= 0; i2--) {
    var sum = x2[i2] + y2[i2] + temp;
    if (sum > 255) {
      temp = 1;
      result[i2] = sum & 255;
    } else {
      temp = 0;
      result[i2] = sum & 255;
    }
  }
  return result;
}
function not$1(x2) {
  var result = [];
  for (var i2 = x2.length - 1; i2 >= 0; i2--)
    result[i2] = ~x2[i2] & 255;
  return result;
}
function P0(X) {
  return xor(xor(X, rotl(X, 9)), rotl(X, 17));
}
function P1(X) {
  return xor(xor(X, rotl(X, 15)), rotl(X, 23));
}
function FF(X, Y2, Z, j) {
  return j >= 0 && j <= 15 ? xor(xor(X, Y2), Z) : or(or(and(X, Y2), and(X, Z)), and(Y2, Z));
}
function GG(X, Y2, Z, j) {
  return j >= 0 && j <= 15 ? xor(xor(X, Y2), Z) : or(and(X, Y2), and(not$1(X), Z));
}
function CF(V, Bi) {
  var W = [];
  var M2 = [];
  for (var i2 = 0; i2 < 16; i2++) {
    var start = i2 * 4;
    W.push(Bi.slice(start, start + 4));
  }
  for (var j = 16; j < 68; j++) {
    W.push(xor(xor(P1(xor(xor(W[j - 16], W[j - 9]), rotl(W[j - 3], 15))), rotl(W[j - 13], 7)), W[j - 6]));
  }
  for (var j = 0; j < 64; j++) {
    M2.push(xor(W[j], W[j + 4]));
  }
  var T1 = [121, 204, 69, 25];
  var T2 = [122, 135, 157, 138];
  var A2 = V.slice(0, 4);
  var B2 = V.slice(4, 8);
  var C2 = V.slice(8, 12);
  var D = V.slice(12, 16);
  var E2 = V.slice(16, 20);
  var F = V.slice(20, 24);
  var G2 = V.slice(24, 28);
  var H = V.slice(28, 32);
  var SS1;
  var SS2;
  var TT1;
  var TT2;
  for (var j = 0; j < 64; j++) {
    var T3 = j >= 0 && j <= 15 ? T1 : T2;
    SS1 = rotl(add$1(add$1(rotl(A2, 12), E2), rotl(T3, j)), 7);
    SS2 = xor(SS1, rotl(A2, 12));
    TT1 = add$1(add$1(add$1(FF(A2, B2, C2, j), D), SS2), M2[j]);
    TT2 = add$1(add$1(add$1(GG(E2, F, G2, j), H), SS1), W[j]);
    D = C2;
    C2 = rotl(B2, 9);
    B2 = A2;
    A2 = TT1;
    H = G2;
    G2 = rotl(F, 19);
    F = E2;
    E2 = P0(TT2);
  }
  return xor([].concat(A2, B2, C2, D, E2, F, G2, H), V);
}
function sm3(array) {
  var len = array.length * 8;
  var k2 = len % 512;
  k2 = k2 >= 448 ? 512 - k2 % 448 - 1 : 448 - k2 - 1;
  var kArr = new Array((k2 - 7) / 8);
  for (var i2 = 0, len_1 = kArr.length; i2 < len_1; i2++)
    kArr[i2] = 0;
  var lenArr = [];
  len = len.toString(2);
  for (var i2 = 7; i2 >= 0; i2--) {
    if (len.length > 8) {
      var start = len.length - 8;
      lenArr[i2] = parseInt(len.substr(start), 2);
      len = len.substr(0, start);
    } else if (len.length > 0) {
      lenArr[i2] = parseInt(len, 2);
      len = "";
    } else {
      lenArr[i2] = 0;
    }
  }
  var m = [].concat(array, [128], kArr, lenArr);
  var n2 = m.length / 64;
  var V = [115, 128, 22, 111, 73, 20, 178, 185, 23, 36, 66, 215, 218, 138, 6, 0, 169, 111, 48, 188, 22, 49, 56, 170, 227, 141, 238, 77, 176, 251, 14, 78];
  for (var i2 = 0; i2 < n2; i2++) {
    var start = 64 * i2;
    var B2 = m.slice(start, start + 64);
    V = CF(V, B2);
  }
  return V;
}
var __spreadArray = function(to2, from2, pack) {
  if (pack || arguments.length === 2) for (var i2 = 0, l2 = from2.length, ar; i2 < l2; i2++) {
    if (ar || !(i2 in from2)) {
      if (!ar) ar = Array.prototype.slice.call(from2, 0, i2);
      ar[i2] = from2[i2];
    }
  }
  return to2.concat(ar || Array.prototype.slice.call(from2));
};
generateEcparam();
var C1C2C3 = 0;
function doEncrypt(msg, publicKey2, cipherMode) {
  if (cipherMode === void 0) {
    cipherMode = 1;
  }
  msg = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Array.prototype.slice.call(msg);
  publicKey2 = getGlobalCurve().decodePointHex(publicKey2);
  var keypair = generateKeyPairHex();
  var k2 = new jsbnExports.BigInteger(keypair.privateKey, 16);
  var c1 = keypair.publicKey;
  if (c1.length > 128)
    c1 = c1.substr(c1.length - 128);
  var p2 = publicKey2.multiply(k2);
  var x2 = hexToArray(leftPad(p2.getX().toBigInteger().toRadix(16), 64));
  var y2 = hexToArray(leftPad(p2.getY().toBigInteger().toRadix(16), 64));
  var c3 = arrayToHex(sm3([].concat(x2, msg, y2)));
  var ct = 1;
  var offset = 0;
  var t2 = [];
  var z2 = [].concat(x2, y2);
  var nextT = function() {
    t2 = sm3(__spreadArray(__spreadArray([], z2, true), [
      ct >> 24 & 255,
      ct >> 16 & 255,
      ct >> 8 & 255,
      ct & 255
    ], false));
    ct++;
    offset = 0;
  };
  nextT();
  for (var i2 = 0, len = msg.length; i2 < len; i2++) {
    if (offset === t2.length)
      nextT();
    msg[i2] ^= t2[offset++] & 255;
  }
  var c2 = arrayToHex(msg);
  return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
}
var __awaiter$d = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$d = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var BrowserInfoFun = function() {
  return __awaiter$d(void 0, void 0, void 0, function() {
    var _a3, pluginCount2, pluginList;
    return __generator$d(this, function(_b2) {
      switch (_b2.label) {
        case 0:
          return [4, getInstalledPlugins()];
        case 1:
          _a3 = _b2.sent(), pluginCount2 = _a3.pluginCount, pluginList = _a3.pluginList;
          return [2, {
            //客户端系统
            os: getUserOsInfo(),
            //浏览器版本信息
            version: getBrowserVersion(),
            //浏览器代码名称
            appCodeName: getAppCodeName(),
            //浏览器厂家信息
            vendor: getBrowserVendor(),
            //显示器高度
            screenHeight: getScreenHeight(),
            //显示器宽度
            screenWidth: getScreenWidth(),
            //屏幕设置色彩位数
            colorDepth: getScreenColorDepth(),
            //浏览器产品名称
            product: getBrowserProduct(),
            //浏览器默认语言
            language: navigator.language,
            //浏览器是否连接到网络
            onLine: getBrowserOnline(),
            //浏览器MIME支持类型列表
            mimeTypes: getBrowserMimeTypes(),
            //浏览器的MIME类型数量
            mimeTypesLength: getBrowserMimeTypesLength(),
            //浏览器产品其他信息
            productSub: getBrowserProductSub(),
            //浏览器是否开启cookie
            cookie: getBrowserCookieEnabled(),
            //浏览器安装插件数量
            pluginsLength: pluginCount2,
            //浏览器安装插件信息列表
            plugins: pluginList,
            //浏览器 userAgent
            userAgent: navigator.userAgent,
            //设备类型
            type: "Browser"
          }];
      }
    });
  });
};
function getBrowserMimeTypes() {
  var mimeTypes = navigator.mimeTypes;
  var supportedTypes = [];
  for (var i2 = 0; i2 < mimeTypes.length; i2++) {
    var mimeType = mimeTypes[i2];
    supportedTypes.push({
      type: mimeType.type,
      description: mimeType.description,
      suffixes: mimeType.suffixes
    });
  }
  return JSON.stringify(supportedTypes);
}
function getBrowserMimeTypesLength() {
  if (navigator.mimeTypes.length) {
    return navigator.mimeTypes.length;
  }
  return 0;
}
function getBrowserCookieEnabled() {
  if (navigator.cookieEnabled) {
    return navigator.cookieEnabled;
  }
  document.cookie = "__testAuthingCookie=1";
  var cookieEnabled = document.cookie.indexOf("__testAuthingCookie=") !== -1;
  document.cookie = "__testAuthingCookie=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  return cookieEnabled;
}
function getBrowserOnline() {
  if (navigator.onLine) {
    return navigator.onLine;
  }
  return true;
}
function getBrowserVendor() {
  var userAgent = navigator.userAgent;
  var browserVendor = "Unknown";
  if (userAgent.includes("Chrome")) {
    browserVendor = "Google";
  } else if (userAgent.includes("Firefox")) {
    browserVendor = "Mozilla";
  } else if (userAgent.includes("Trident") || userAgent.includes("MSIE")) {
    browserVendor = "Microsoft";
  } else if (userAgent.includes("Edge")) {
    browserVendor = "Microsoft (EdgeHTML)";
  } else if (userAgent.includes("Edg")) {
    browserVendor = "Microsoft (Chromium)";
  } else if (userAgent.includes("Safari")) {
    browserVendor = "Apple";
  }
  return browserVendor;
}
var getInstalledPlugins = function() {
  return new Promise(function(resolve2) {
    return __awaiter$d(void 0, void 0, void 0, function() {
      var fp, result, pluginCount2, pluginList;
      return __generator$d(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            return [4, index$1.load()];
          case 1:
            fp = _a3.sent();
            return [4, fp.get()];
          case 2:
            result = _a3.sent();
            pluginCount2 = result.components.plugins.value.length;
            pluginList = result.components.plugins.value;
            resolve2({ pluginCount: pluginCount2, pluginList: JSON.stringify(pluginList) });
            return [
              2
              /*return*/
            ];
        }
      });
    });
  });
};
function getBrowserProduct() {
  var userAgent = navigator.userAgent;
  var browserProduct = "Unknown";
  if (userAgent.indexOf("Trident") !== -1) {
    browserProduct = "Trident";
  } else if (userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1) {
    browserProduct = "Gecko";
  } else if (userAgent.indexOf("WebKit") !== -1) {
    browserProduct = "WebKit";
  } else if (userAgent.indexOf("Blink") !== -1) {
    browserProduct = "Blink";
  }
  return browserProduct;
}
function getBrowserProductSub() {
  var userAgent = navigator.userAgent;
  if (userAgent.includes("Firefox")) {
    return "20030107";
  } else if (userAgent.includes("Chrome")) {
    return "20030107";
  } else if (userAgent.includes("Trident") || userAgent.includes("MSIE")) {
    return "20000101";
  } else {
    return "0";
  }
}
function getScreenColorDepth() {
  var colorDepth = window.screen.colorDepth || window.screen.pixelDepth;
  if (navigator.userAgent.indexOf("Chrome") !== -1) {
    return colorDepth * window.devicePixelRatio;
  } else if (navigator.userAgent.indexOf("Firefox") !== -1) {
    return colorDepth;
  } else if (navigator.userAgent.indexOf("Trident") !== -1) {
    return screen.deviceXDPI;
  } else {
    return colorDepth;
  }
}
function getScreenWidth() {
  var screenWidth = 0;
  if (typeof window.innerWidth === "number") {
    screenWidth = window.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth) {
    screenWidth = document.documentElement.clientWidth;
  } else if (document.body && document.body.clientWidth) {
    screenWidth = document.body.clientWidth;
  }
  return screenWidth;
}
function getScreenHeight() {
  if (navigator.userAgent.indexOf("Chrome") !== -1) {
    return window.screen.height;
  } else if (navigator.userAgent.indexOf("Firefox") !== -1) {
    return window.screen.height;
  } else if (navigator.userAgent.indexOf("Trident") !== -1 || navigator.userAgent.indexOf("MSIE") !== -1) {
    return screen.height;
  } else {
    return window.innerHeight;
  }
}
function getUserOsInfo() {
  var userAgent = navigator.userAgent;
  if (userAgent.indexOf("Windows NT 10.0") !== -1)
    return "Windows 10";
  if (userAgent.indexOf("Windows NT 6.2") !== -1)
    return "Windows 8";
  if (userAgent.indexOf("Windows NT 6.1") !== -1)
    return "Windows 7";
  if (userAgent.indexOf("Windows NT 6.0") !== -1)
    return "Windows Vista";
  if (userAgent.indexOf("Windows NT 5.1") !== -1)
    return "Windows XP";
  if (userAgent.indexOf("Windows NT 5.0") !== -1)
    return "Windows 2000";
  if (userAgent.indexOf("Mac") !== -1)
    return "Mac OS";
  if (userAgent.indexOf("X11") !== -1)
    return "UNIX";
  if (userAgent.indexOf("Linux") !== -1)
    return "Linux";
  return "Other";
}
function getBrowserVersion() {
  var userAgent = navigator.userAgent;
  var version2 = "Unknown";
  if (/Chrome\/([\d.]+)/.test(userAgent)) {
    version2 = userAgent.match(/Chrome\/([\d.]+)/)[1];
  } else if (/Firefox\/([\d.]+)/.test(userAgent)) {
    version2 = userAgent.match(/Firefox\/([\d.]+)/)[1];
  } else if (/MSIE ([\d.]+)/.test(userAgent)) {
    version2 = userAgent.match(/MSIE ([\d.]+)/)[1];
  } else if (/Trident\/[\d](?:[\d.]+)?; rv:([0-9.]+)/.test(userAgent)) {
    version2 = userAgent.match(/Trident\/[\d](?:[\d.]+)?; rv:([0-9.]+)/)[1];
  }
  return version2;
}
function getAppCodeName() {
  var userAgent = navigator.userAgent;
  var browserCodeName = "Unknown";
  if (userAgent.indexOf("Chrome") !== -1) {
    browserCodeName = "Chrome";
  } else if (userAgent.indexOf("Firefox") !== -1) {
    browserCodeName = "Firefox";
  } else if (userAgent.indexOf("Safari") !== -1) {
    browserCodeName = "Safari";
  } else if (userAgent.indexOf("Edge") !== -1) {
    browserCodeName = "Edge";
  } else if (userAgent.indexOf("Trident") !== -1) {
    browserCodeName = "Internet Explorer";
  }
  return browserCodeName;
}
var handleFingerprint = function(localDeviceFingersObj) {
  var fingerObj = {
    userAgentFingerprint: localDeviceFingersObj.userAgent,
    audioFingerprint: localDeviceFingersObj.audio,
    canvasFingerprint: localDeviceFingersObj.canvas,
    screenResolutionFingerprint: localDeviceFingersObj.screenResolution,
    webglFingerprint: localDeviceFingersObj.webgl,
    fontsFingerprint: localDeviceFingersObj.fonts,
    pluginsFingerprint: localDeviceFingersObj.plugins
  };
  return fingerObj;
};
var getBrowserInfo = function() {
  var agent = navigator.userAgent.toLowerCase();
  var regStr_ie = /msie [\d.]+;/gi;
  var regStr_ff = /firefox\/[\d.]+/gi;
  var regStr_chrome = /chrome\/[\d.]+/gi;
  var regStr_Edg = /edg\/[\d.]+/gi;
  var regStr_saf = /safari\/[\d.]+/gi;
  var regStr_safVersion = /version\/[\d.]+/gi;
  if (agent.indexOf("msie") > 0) {
    return agent.match(regStr_ie);
  }
  if (agent.indexOf("firefox") > 0) {
    return agent.match(regStr_ff);
  }
  if (agent.indexOf("edg") > 0) {
    return agent.match(regStr_Edg);
  }
  if (agent.indexOf("chrome") > 0) {
    return agent.match(regStr_chrome);
  }
  if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
    var bro = agent.match(regStr_saf)[0].split("/")[0];
    var ver = agent.match(regStr_safVersion)[0].split("/")[1];
    var user2 = bro + "/" + ver;
    return [user2];
  }
};
var getWebGLValues = function() {
  var canvas = document.createElement("canvas");
  var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
  if (!gl) {
    return "";
  }
  var webGLValues = {
    // @ts-ignore
    renderer: gl.getParameter(gl.RENDERER),
    // @ts-ignore
    vendor: gl.getParameter(gl.VENDOR),
    // @ts-ignore
    version: gl.getParameter(gl.VERSION),
    // @ts-ignore
    shadingLanguageVersion: gl.getParameter(gl.SHADING_LANGUAGE_VERSION),
    // @ts-ignore
    maxVertexAttributes: gl.getParameter(gl.MAX_VERTEX_ATTRIBS),
    // @ts-ignore
    maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE)
    // 可根据需要添加其他属性
  };
  return webGLValues;
};
var __awaiter$c = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$c = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var encrypt = function(plainText, publicKey2, encryption) {
  return __awaiter$c(void 0, void 0, void 0, function() {
    return __generator$c(this, function(_a3) {
      return [2, new Promise(function(resolve2, reject2) {
        if (encryption && (encryption === null || encryption === void 0 ? void 0 : encryption.type) === "sm2") {
          if (!encryption.publicKey) {
            throw new Error("未配置: encryption.publicKey");
          }
          var encrypted_1 = doEncrypt(plainText, encryption.publicKey);
          return resolve2("sm2:".concat(encrypted_1));
        }
        var jsencrypt = new JSEncrypt({});
        jsencrypt.setPublicKey(publicKey2);
        var encrypted = jsencrypt.encrypt(plainText);
        if (encrypted !== false) {
          resolve2(encrypted);
        } else {
          reject2(encrypted);
        }
      })];
    });
  });
};
var popupCenter = function(url, _a3) {
  var _b2 = _a3 === void 0 ? { w: 585, h: 649 } : _a3, w = _b2.w, h2 = _b2.h;
  var dualScreenLeft = window.screenLeft !== void 0 ? window.screenLeft : window.screenX;
  var dualScreenTop = window.screenTop !== void 0 ? window.screenTop : window.screenY;
  var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : window.screen.width;
  var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : window.screen.height;
  var systemZoom = width / window.screen.availWidth;
  var left = (width - w) / 2 / systemZoom + dualScreenLeft;
  var top = (height - h2) / 2 / systemZoom + dualScreenTop;
  var newWindow = window.open(url, "_blank", "\n      toolbar=no,\n      menubar=no,\n      scrollbars=no,\n      resizable=no,\n      location=no,\n      status=no\n      width=".concat(w / systemZoom, ",\n      height=").concat(h2 / systemZoom, ",\n      top=").concat(top, ",\n      left=").concat(left, "\n      "));
  newWindow === null || newWindow === void 0 ? void 0 : newWindow.focus();
  return newWindow;
};
var createCssClassStyleSheet = function(className, styleSheet) {
  var styleTag = document.createElement("style");
  var styleText = "\n    .".concat(className, " {\n      ").concat(styleSheet, "\n    }\n  ");
  var textNode = document.createTextNode(styleText);
  styleTag.appendChild(textNode);
  document.head.appendChild(styleTag);
};
var serialize = function(obj) {
  var str = [];
  for (var p2 in obj)
    if (obj.hasOwnProperty(p2)) {
      if (obj[p2] !== void 0) {
        str.push(encodeURIComponent(p2) + "=" + encodeURIComponent(obj[p2]));
      }
    }
  return str.join("&");
};
var convertUdv = function(data2) {
  for (var _i2 = 0, data_1 = data2; _i2 < data_1.length; _i2++) {
    var item = data_1[_i2];
    var dataType = item.dataType, value = item.value;
    if (dataType === UdfDataType.Number) {
      item.value = JSON.parse(value);
    } else if (dataType === UdfDataType.Boolean) {
      item.value = JSON.parse(value);
    } else if (dataType === UdfDataType.Datetime) {
      item.value = new Date(parseInt(value));
    } else if (dataType === UdfDataType.Object) {
      item.value = JSON.parse(value);
    }
  }
  return data2;
};
var isNumeric = function(str) {
  if (typeof str != "string")
    return false;
  return (
    // @ts-ignore
    !isNaN(str) && !isNaN(parseFloat(str))
  );
};
var convertUdvToKeyValuePair = function(data2) {
  data2 = data2 || [];
  for (var _i2 = 0, data_2 = data2; _i2 < data_2.length; _i2++) {
    var item = data_2[_i2];
    var dataType = item.dataType, value = item.value;
    if (dataType === UdfDataType.Number) {
      item.value = JSON.parse(value);
    } else if (dataType === UdfDataType.Boolean) {
      item.value = JSON.parse(value);
    } else if (dataType === UdfDataType.Datetime) {
      item.value = isNumeric(value) ? new Date(parseInt(value)) : new Date(value);
    } else if (dataType === UdfDataType.Object) {
      item.value = JSON.parse(value);
    }
  }
  var ret = {};
  for (var _a3 = 0, data_3 = data2; _a3 < data_3.length; _a3++) {
    var item = data_3[_a3];
    ret[item.key] = item.value;
  }
  return ret;
};
var isWechatBrowser = function() {
  return typeof navigator !== "undefined" && /MicroMessenger/i.test(navigator === null || navigator === void 0 ? void 0 : navigator.userAgent);
};
var isLarkBrowser = function() {
  return typeof navigator !== "undefined" && /Lark/i.test(navigator.userAgent);
};
var isMobileBrowser = function() {
  return isWechatBrowser() || isLarkBrowser();
};
var formatAuthorizedResources = function(resources) {
  return resources.map(function(resource) {
    for (var key2 in resource) {
      if (!resource[key2]) {
        delete resource[key2];
      }
    }
    return resource;
  });
};
function generateUidKey(number) {
  var map = [];
  for (var i2 = 97; i2 < 123; i2++) {
    map.push(String.fromCharCode(i2));
  }
  var arr = [];
  while (number--) {
    var rand = Math.floor(Math.random() * 16);
    arr.push(map[rand]);
  }
  return arr.join("");
}
var xhrUpload = function(file, url) {
  return new Promise(function(resolve2, reject2) {
    var formData = new FormData();
    formData.append("file", file, file instanceof Blob ? "personal.jpeg" : void 0);
    var xhr2 = new XMLHttpRequest();
    xhr2.onreadystatechange = function() {
      if (this.readyState === 4) {
        try {
          var res = JSON.parse(this.responseText);
          var code = res.code, message = res.message, data2 = res.data;
          if (code !== 200) {
            reject2({
              code,
              message
            });
          }
          resolve2(data2);
        } catch (error) {
          var code = 500;
          var message = "上传图片失败, error = ".concat(error.message);
          reject2({
            code,
            message
          });
        }
      }
    };
    xhr2.open("POST", url);
    xhr2.send(formData);
  });
};
function uploadFile(opts) {
  var url = opts.url, accept = opts.accept, multiple = opts.multiple;
  return new Promise(function(resolve2, reject2) {
    var inputElem = document.createElement("input");
    inputElem.type = "file";
    inputElem.accept = accept;
    inputElem.multiple = multiple;
    inputElem.onchange = function() {
      var files = inputElem.files;
      if (!multiple) {
        var file = files[0];
        xhrUpload(file, url).then(function(res) {
          return resolve2(res);
        }).catch(function(error) {
          return reject2(error);
        });
      } else {
        var promises = [];
        var i2 = 0;
        while (i2 < files.length) {
          promises.push(xhrUpload(files[i2], url));
          i2++;
        }
        Promise.all(promises).then(function(res) {
          return resolve2(res);
        }).catch(function(error) {
          return reject2(error);
        });
      }
    };
    inputElem.click();
  });
}
var convertObjectToKeyValueList = function(data2) {
  var ret = [];
  for (var _i2 = 0, _a3 = Object.keys(data2); _i2 < _a3.length; _i2++) {
    var key2 = _a3[_i2];
    ret.push({
      key: key2,
      value: data2[key2]
    });
  }
  return ret;
};
var createFingerprint = function() {
  return new Promise(function(resolve2) {
    return __awaiter$c(void 0, void 0, void 0, function() {
      var fp, result, fingerParamsObj, browserId;
      return __generator$c(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            return [4, index$1.load()];
          case 1:
            fp = _a3.sent();
            return [4, fp.get()];
          case 2:
            result = _a3.sent();
            fingerParamsObj = {
              canvas: "",
              webgl: "",
              plugins: "",
              audio: "",
              fonts: "",
              userAgent: "",
              screenResolution: ""
            };
            fingerParamsObj.canvas = sha256WithLengthControl(result.components.canvas.value.toString());
            fingerParamsObj.webgl = getWebGLValues() ? sha256WithLengthControl(getWebGLValues().toString()) : "";
            fingerParamsObj.plugins = sha256WithLengthControl(result.components.plugins.value.toString());
            fingerParamsObj.audio = sha256WithLengthControl(result.components.audio.value.toString());
            fingerParamsObj.fonts = sha256WithLengthControl(result.components.fonts.value.toString());
            fingerParamsObj.userAgent = sha256WithLengthControl(navigator.userAgent.toString());
            fingerParamsObj.screenResolution = sha256WithLengthControl(result.components.screenResolution.value.toString());
            browserId = result.visitorId;
            localStorage.setItem("deviceFingers", JSON.stringify(fingerParamsObj));
            localStorage.setItem("browserId", browserId);
            resolve2({ deviceFingers: fingerParamsObj, browserId });
            return [
              2
              /*return*/
            ];
        }
      });
    });
  });
};
function sha256WithLengthControl(input, outputLength) {
  if (outputLength === void 0) {
    outputLength = 32;
  }
  var hash2 = CryptoJS.SHA256(input);
  var hashSubstring = hash2.toString(CryptoJS.enc.Hex).substring(0, outputLength);
  return hashSubstring;
}
function generateRandomString(length) {
  if (length === void 0) {
    length = 30;
  }
  var result = "";
  var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  var charactersLength = characters.length;
  for (var i2 = 0; i2 < length; i2++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
var pickBy = function(obj, predicate) {
  var ret = {};
  for (var _i2 = 0, _a3 = Object.keys(obj); _i2 < _a3.length; _i2++) {
    var key2 = _a3[_i2];
    if (predicate(obj[key2], key2)) {
      ret[key2] = obj[key2];
    }
  }
  return ret;
};
var __awaiter$b = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$b = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var user = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UserDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [4, garpqhlClient.request({
            query,
            token,
            variables
          })];
        case 2:
          return [2, _a3.sent()];
      }
    });
  });
};
var checkPasswordStrength = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = CheckPasswordStrengthDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var registerByEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = RegisterByEmailDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var loginByEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = LoginByEmailDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var loginByUsername = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = LoginByUsernameDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var loginByPhoneCode = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = LoginByPhoneCodeDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var loginByPhonePassword = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = LoginByPhonePasswordDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var loginBySubAccount = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = LoginBySubAccountDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var registerByUsername = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = RegisterByUsernameDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var registerByPhoneCode = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      query = RegisterByPhoneCodeDocument;
      token = tokenProvider.getToken();
      return [2, garpqhlClient.request({
        query,
        token,
        variables
      })];
    });
  });
};
var sendEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = SendEmailDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [4, garpqhlClient.request({
            query,
            token,
            variables
          })];
        case 2:
          return [2, _a3.sent()];
      }
    });
  });
};
var resetPassword = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = ResetPasswordDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var resetPasswordByFirstLoginToken = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = ResetPasswordByFirstLoginTokenDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var resetPasswordByForceResetToken = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = ResetPasswordByForceResetTokenDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var updateUser = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UpdateUserDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var refreshToken = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = RefreshTokenDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var isUserExists = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = IsUserExistsDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var updatePassword = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UpdatePasswordDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var updatePhone = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UpdatePhoneDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var updateEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UpdateEmailDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var bindPhone = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = BindPhoneDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var bindEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = BindEmailDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var unbindPhone = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UnbindPhoneDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var getUserRoles = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = GetUserRolesDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var getUserDepartments = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = GetUserDepartmentsDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var udv = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UdvDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var setUdv = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = SetUdvDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var setUdvBatch = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = SetUdvBatchDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var removeUdv = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = RemoveUdvDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var checkLoginStatus = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = CheckLoginStatusDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var unbindEmail = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = UnbindEmailDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var listUserAuthorizedResources = function(garpqhlClient, tokenProvider, variables) {
  return __awaiter$b(void 0, void 0, void 0, function() {
    var query, token;
    return __generator$b(this, function(_a3) {
      switch (_a3.label) {
        case 0:
          query = ListUserAuthorizedResourcesDocument;
          return [4, tokenProvider.getToken()];
        case 1:
          token = _a3.sent();
          return [2, garpqhlClient.request({
            query,
            token,
            variables
          })];
      }
    });
  });
};
var SDK_VERSION$1 = "4.21.8";
var axios$1 = { exports: {} };
var bind;
var hasRequiredBind;
function requireBind() {
  if (hasRequiredBind) return bind;
  hasRequiredBind = 1;
  bind = function bind2(fn, thisArg) {
    return function wrap() {
      return fn.apply(thisArg, arguments);
    };
  };
  return bind;
}
var utils;
var hasRequiredUtils;
function requireUtils() {
  if (hasRequiredUtils) return utils;
  hasRequiredUtils = 1;
  var bind2 = requireBind();
  var toString2 = Object.prototype.toString;
  var kindOf = /* @__PURE__ */ function(cache2) {
    return function(thing) {
      var str = toString2.call(thing);
      return cache2[str] || (cache2[str] = str.slice(8, -1).toLowerCase());
    };
  }(/* @__PURE__ */ Object.create(null));
  function kindOfTest(type2) {
    type2 = type2.toLowerCase();
    return function isKindOf(thing) {
      return kindOf(thing) === type2;
    };
  }
  function isArray2(val) {
    return Array.isArray(val);
  }
  function isUndefined(val) {
    return typeof val === "undefined";
  }
  function isBuffer2(val) {
    return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val);
  }
  var isArrayBuffer = kindOfTest("ArrayBuffer");
  function isArrayBufferView(val) {
    var result;
    if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
      result = ArrayBuffer.isView(val);
    } else {
      result = val && val.buffer && isArrayBuffer(val.buffer);
    }
    return result;
  }
  function isString2(val) {
    return typeof val === "string";
  }
  function isNumber(val) {
    return typeof val === "number";
  }
  function isObject(val) {
    return val !== null && typeof val === "object";
  }
  function isPlainObject2(val) {
    if (kindOf(val) !== "object") {
      return false;
    }
    var prototype = Object.getPrototypeOf(val);
    return prototype === null || prototype === Object.prototype;
  }
  function isEmptyObject(val) {
    return val && Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  }
  var isDate = kindOfTest("Date");
  var isFile = kindOfTest("File");
  var isBlob = kindOfTest("Blob");
  var isFileList = kindOfTest("FileList");
  function isFunction(val) {
    return toString2.call(val) === "[object Function]";
  }
  function isStream(val) {
    return isObject(val) && isFunction(val.pipe);
  }
  function isFormData(thing) {
    var pattern2 = "[object FormData]";
    return thing && (typeof FormData === "function" && thing instanceof FormData || toString2.call(thing) === pattern2 || isFunction(thing.toString) && thing.toString() === pattern2);
  }
  var isURLSearchParams = kindOfTest("URLSearchParams");
  function trim(str) {
    return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
  }
  function isStandardBrowserEnv() {
    var product;
    if (typeof navigator !== "undefined" && ((product = navigator.product) === "ReactNative" || product === "NativeScript" || product === "NS")) {
      return false;
    }
    return typeof window !== "undefined" && typeof document !== "undefined";
  }
  function forEach2(obj, fn) {
    if (obj === null || typeof obj === "undefined") {
      return;
    }
    if (typeof obj !== "object") {
      obj = [obj];
    }
    if (isArray2(obj)) {
      for (var i2 = 0, l2 = obj.length; i2 < l2; i2++) {
        fn.call(null, obj[i2], i2, obj);
      }
    } else {
      for (var key2 in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key2)) {
          fn.call(null, obj[key2], key2, obj);
        }
      }
    }
  }
  function merge() {
    var result = {};
    function assignValue(val, key2) {
      if (isPlainObject2(result[key2]) && isPlainObject2(val)) {
        result[key2] = merge(result[key2], val);
      } else if (isPlainObject2(val)) {
        result[key2] = merge({}, val);
      } else if (isArray2(val)) {
        result[key2] = val.slice();
      } else {
        result[key2] = val;
      }
    }
    for (var i2 = 0, l2 = arguments.length; i2 < l2; i2++) {
      forEach2(arguments[i2], assignValue);
    }
    return result;
  }
  function extend(a2, b2, thisArg) {
    forEach2(b2, function assignValue(val, key2) {
      if (thisArg && typeof val === "function") {
        a2[key2] = bind2(val, thisArg);
      } else {
        a2[key2] = val;
      }
    });
    return a2;
  }
  function stripBOM(content) {
    if (content.charCodeAt(0) === 65279) {
      content = content.slice(1);
    }
    return content;
  }
  function inherits(constructor, superConstructor, props, descriptors) {
    constructor.prototype = Object.create(superConstructor.prototype, descriptors);
    constructor.prototype.constructor = constructor;
    props && Object.assign(constructor.prototype, props);
  }
  function toFlatObject(sourceObj, destObj, filter, propFilter) {
    var props;
    var i2;
    var prop;
    var merged = {};
    destObj = destObj || {};
    if (sourceObj == null) return destObj;
    do {
      props = Object.getOwnPropertyNames(sourceObj);
      i2 = props.length;
      while (i2-- > 0) {
        prop = props[i2];
        if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
          destObj[prop] = sourceObj[prop];
          merged[prop] = true;
        }
      }
      sourceObj = filter !== false && Object.getPrototypeOf(sourceObj);
    } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
    return destObj;
  }
  function endsWith(str, searchString, position) {
    str = String(str);
    if (position === void 0 || position > str.length) {
      position = str.length;
    }
    position -= searchString.length;
    var lastIndex = str.indexOf(searchString, position);
    return lastIndex !== -1 && lastIndex === position;
  }
  function toArray(thing) {
    if (!thing) return null;
    if (isArray2(thing)) return thing;
    var i2 = thing.length;
    if (!isNumber(i2)) return null;
    var arr = new Array(i2);
    while (i2-- > 0) {
      arr[i2] = thing[i2];
    }
    return arr;
  }
  var isTypedArray2 = /* @__PURE__ */ function(TypedArray) {
    return function(thing) {
      return TypedArray && thing instanceof TypedArray;
    };
  }(typeof Uint8Array !== "undefined" && Object.getPrototypeOf(Uint8Array));
  function forEachEntry(obj, fn) {
    var generator = obj && obj[Symbol.iterator];
    var iterator = generator.call(obj);
    var result;
    while ((result = iterator.next()) && !result.done) {
      var pair = result.value;
      fn.call(obj, pair[0], pair[1]);
    }
  }
  function matchAll(regExp, str) {
    var matches;
    var arr = [];
    while ((matches = regExp.exec(str)) !== null) {
      arr.push(matches);
    }
    return arr;
  }
  var isHTMLForm = kindOfTest("HTMLFormElement");
  var hasOwnProperty = /* @__PURE__ */ function resolver(_hasOwnProperty) {
    return function(obj, prop) {
      return _hasOwnProperty.call(obj, prop);
    };
  }(Object.prototype.hasOwnProperty);
  utils = {
    isArray: isArray2,
    isArrayBuffer,
    isBuffer: isBuffer2,
    isFormData,
    isArrayBufferView,
    isString: isString2,
    isNumber,
    isObject,
    isPlainObject: isPlainObject2,
    isEmptyObject,
    isUndefined,
    isDate,
    isFile,
    isBlob,
    isFunction,
    isStream,
    isURLSearchParams,
    isStandardBrowserEnv,
    forEach: forEach2,
    merge,
    extend,
    trim,
    stripBOM,
    inherits,
    toFlatObject,
    kindOf,
    kindOfTest,
    endsWith,
    toArray,
    isTypedArray: isTypedArray2,
    isFileList,
    forEachEntry,
    matchAll,
    isHTMLForm,
    hasOwnProperty
  };
  return utils;
}
var AxiosError_1;
var hasRequiredAxiosError;
function requireAxiosError() {
  if (hasRequiredAxiosError) return AxiosError_1;
  hasRequiredAxiosError = 1;
  var utils2 = requireUtils();
  function AxiosError(message, code, config, request, response) {
    Error.call(this);
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    } else {
      this.stack = new Error().stack;
    }
    this.message = message;
    this.name = "AxiosError";
    code && (this.code = code);
    config && (this.config = config);
    request && (this.request = request);
    response && (this.response = response);
  }
  utils2.inherits(AxiosError, Error, {
    toJSON: function toJSON() {
      return {
        // Standard
        message: this.message,
        name: this.name,
        // Microsoft
        description: this.description,
        number: this.number,
        // Mozilla
        fileName: this.fileName,
        lineNumber: this.lineNumber,
        columnNumber: this.columnNumber,
        stack: this.stack,
        // Axios
        config: this.config,
        code: this.code,
        status: this.response && this.response.status ? this.response.status : null
      };
    }
  });
  var prototype = AxiosError.prototype;
  var descriptors = {};
  [
    "ERR_BAD_OPTION_VALUE",
    "ERR_BAD_OPTION",
    "ECONNABORTED",
    "ETIMEDOUT",
    "ERR_NETWORK",
    "ERR_FR_TOO_MANY_REDIRECTS",
    "ERR_DEPRECATED",
    "ERR_BAD_RESPONSE",
    "ERR_BAD_REQUEST",
    "ERR_CANCELED",
    "ERR_NOT_SUPPORT",
    "ERR_INVALID_URL"
    // eslint-disable-next-line func-names
  ].forEach(function(code) {
    descriptors[code] = { value: code };
  });
  Object.defineProperties(AxiosError, descriptors);
  Object.defineProperty(prototype, "isAxiosError", { value: true });
  AxiosError.from = function(error, code, config, request, response, customProps) {
    var axiosError = Object.create(prototype);
    utils2.toFlatObject(error, axiosError, function filter(obj) {
      return obj !== Error.prototype;
    });
    AxiosError.call(axiosError, error.message, code, config, request, response);
    axiosError.cause = error;
    axiosError.name = error.name;
    customProps && Object.assign(axiosError, customProps);
    return axiosError;
  };
  AxiosError_1 = AxiosError;
  return AxiosError_1;
}
var browser$4;
var hasRequiredBrowser$2;
function requireBrowser$2() {
  if (hasRequiredBrowser$2) return browser$4;
  hasRequiredBrowser$2 = 1;
  browser$4 = typeof self === "object" ? self.FormData : window.FormData;
  return browser$4;
}
var FormData$1;
var hasRequiredFormData$1;
function requireFormData$1() {
  if (hasRequiredFormData$1) return FormData$1;
  hasRequiredFormData$1 = 1;
  FormData$1 = requireBrowser$2();
  return FormData$1;
}
var toFormData_1;
var hasRequiredToFormData;
function requireToFormData() {
  if (hasRequiredToFormData) return toFormData_1;
  hasRequiredToFormData = 1;
  var utils2 = requireUtils();
  var AxiosError = requireAxiosError();
  var envFormData = requireFormData$1();
  function isVisitable(thing) {
    return utils2.isPlainObject(thing) || utils2.isArray(thing);
  }
  function removeBrackets(key2) {
    return utils2.endsWith(key2, "[]") ? key2.slice(0, -2) : key2;
  }
  function renderKey(path, key2, dots) {
    if (!path) return key2;
    return path.concat(key2).map(function each(token, i2) {
      token = removeBrackets(token);
      return !dots && i2 ? "[" + token + "]" : token;
    }).join(dots ? "." : "");
  }
  function isFlatArray(arr) {
    return utils2.isArray(arr) && !arr.some(isVisitable);
  }
  var predicates = utils2.toFlatObject(utils2, {}, null, function filter(prop) {
    return /^is[A-Z]/.test(prop);
  });
  function isSpecCompliant(thing) {
    return thing && utils2.isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator];
  }
  function toFormData(obj, formData, options2) {
    if (!utils2.isObject(obj)) {
      throw new TypeError("target must be an object");
    }
    formData = formData || new (envFormData || FormData)();
    options2 = utils2.toFlatObject(options2, {
      metaTokens: true,
      dots: false,
      indexes: false
    }, false, function defined(option, source) {
      return !utils2.isUndefined(source[option]);
    });
    var metaTokens = options2.metaTokens;
    var visitor = options2.visitor || defaultVisitor;
    var dots = options2.dots;
    var indexes = options2.indexes;
    var _Blob = options2.Blob || typeof Blob !== "undefined" && Blob;
    var useBlob = _Blob && isSpecCompliant(formData);
    if (!utils2.isFunction(visitor)) {
      throw new TypeError("visitor must be a function");
    }
    function convertValue(value) {
      if (value === null) return "";
      if (utils2.isDate(value)) {
        return value.toISOString();
      }
      if (!useBlob && utils2.isBlob(value)) {
        throw new AxiosError("Blob is not supported. Use a Buffer instead.");
      }
      if (utils2.isArrayBuffer(value) || utils2.isTypedArray(value)) {
        return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
      }
      return value;
    }
    function defaultVisitor(value, key2, path) {
      var arr = value;
      if (value && !path && typeof value === "object") {
        if (utils2.endsWith(key2, "{}")) {
          key2 = metaTokens ? key2 : key2.slice(0, -2);
          value = JSON.stringify(value);
        } else if (utils2.isArray(value) && isFlatArray(value) || (utils2.isFileList(value) || utils2.endsWith(key2, "[]") && (arr = utils2.toArray(value)))) {
          key2 = removeBrackets(key2);
          arr.forEach(function each(el, index2) {
            !utils2.isUndefined(el) && formData.append(
              // eslint-disable-next-line no-nested-ternary
              indexes === true ? renderKey([key2], index2, dots) : indexes === null ? key2 : key2 + "[]",
              convertValue(el)
            );
          });
          return false;
        }
      }
      if (isVisitable(value)) {
        return true;
      }
      formData.append(renderKey(path, key2, dots), convertValue(value));
      return false;
    }
    var stack = [];
    var exposedHelpers = Object.assign(predicates, {
      defaultVisitor,
      convertValue,
      isVisitable
    });
    function build(value, path) {
      if (utils2.isUndefined(value)) return;
      if (stack.indexOf(value) !== -1) {
        throw Error("Circular reference detected in " + path.join("."));
      }
      stack.push(value);
      utils2.forEach(value, function each(el, key2) {
        var result = !utils2.isUndefined(el) && visitor.call(
          formData,
          el,
          utils2.isString(key2) ? key2.trim() : key2,
          path,
          exposedHelpers
        );
        if (result === true) {
          build(el, path ? path.concat(key2) : [key2]);
        }
      });
      stack.pop();
    }
    if (!utils2.isObject(obj)) {
      throw new TypeError("data must be an object");
    }
    build(obj);
    return formData;
  }
  toFormData_1 = toFormData;
  return toFormData_1;
}
var AxiosURLSearchParams_1;
var hasRequiredAxiosURLSearchParams;
function requireAxiosURLSearchParams() {
  if (hasRequiredAxiosURLSearchParams) return AxiosURLSearchParams_1;
  hasRequiredAxiosURLSearchParams = 1;
  var toFormData = requireToFormData();
  function encode2(str) {
    var charMap = {
      "!": "%21",
      "'": "%27",
      "(": "%28",
      ")": "%29",
      "~": "%7E",
      "%20": "+",
      "%00": "\0"
    };
    return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function replacer(match) {
      return charMap[match];
    });
  }
  function AxiosURLSearchParams(params, options2) {
    this._pairs = [];
    params && toFormData(params, this, options2);
  }
  var prototype = AxiosURLSearchParams.prototype;
  prototype.append = function append(name, value) {
    this._pairs.push([name, value]);
  };
  prototype.toString = function toString2(encoder2) {
    var _encode = encoder2 ? function(value) {
      return encoder2.call(this, value, encode2);
    } : encode2;
    return this._pairs.map(function each(pair) {
      return _encode(pair[0]) + "=" + _encode(pair[1]);
    }, "").join("&");
  };
  AxiosURLSearchParams_1 = AxiosURLSearchParams;
  return AxiosURLSearchParams_1;
}
var buildURL;
var hasRequiredBuildURL;
function requireBuildURL() {
  if (hasRequiredBuildURL) return buildURL;
  hasRequiredBuildURL = 1;
  var utils2 = requireUtils();
  var AxiosURLSearchParams = requireAxiosURLSearchParams();
  function encode2(val) {
    return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
  }
  buildURL = function buildURL2(url, params, options2) {
    if (!params) {
      return url;
    }
    var hashmarkIndex = url.indexOf("#");
    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    var _encode = options2 && options2.encode || encode2;
    var serializerParams = utils2.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options2).toString(_encode);
    if (serializerParams) {
      url += (url.indexOf("?") === -1 ? "?" : "&") + serializerParams;
    }
    return url;
  };
  return buildURL;
}
var InterceptorManager_1;
var hasRequiredInterceptorManager;
function requireInterceptorManager() {
  if (hasRequiredInterceptorManager) return InterceptorManager_1;
  hasRequiredInterceptorManager = 1;
  var utils2 = requireUtils();
  function InterceptorManager() {
    this.handlers = [];
  }
  InterceptorManager.prototype.use = function use(fulfilled, rejected, options2) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options2 ? options2.synchronous : false,
      runWhen: options2 ? options2.runWhen : null
    });
    return this.handlers.length - 1;
  };
  InterceptorManager.prototype.eject = function eject(id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  };
  InterceptorManager.prototype.clear = function clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  };
  InterceptorManager.prototype.forEach = function forEach2(fn) {
    utils2.forEach(this.handlers, function forEachHandler(h2) {
      if (h2 !== null) {
        fn(h2);
      }
    });
  };
  InterceptorManager_1 = InterceptorManager;
  return InterceptorManager_1;
}
var normalizeHeaderName;
var hasRequiredNormalizeHeaderName;
function requireNormalizeHeaderName() {
  if (hasRequiredNormalizeHeaderName) return normalizeHeaderName;
  hasRequiredNormalizeHeaderName = 1;
  var utils2 = requireUtils();
  normalizeHeaderName = function normalizeHeaderName2(headers, normalizedName) {
    utils2.forEach(headers, function processHeader(value, name) {
      if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
        headers[normalizedName] = value;
        delete headers[name];
      }
    });
  };
  return normalizeHeaderName;
}
var transitional;
var hasRequiredTransitional;
function requireTransitional() {
  if (hasRequiredTransitional) return transitional;
  hasRequiredTransitional = 1;
  transitional = {
    silentJSONParsing: true,
    forcedJSONParsing: true,
    clarifyTimeoutError: false
  };
  return transitional;
}
var URLSearchParams_1;
var hasRequiredURLSearchParams;
function requireURLSearchParams() {
  if (hasRequiredURLSearchParams) return URLSearchParams_1;
  hasRequiredURLSearchParams = 1;
  var AxiosURLSearchParams = requireAxiosURLSearchParams();
  URLSearchParams_1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
  return URLSearchParams_1;
}
var FormData_1;
var hasRequiredFormData;
function requireFormData() {
  if (hasRequiredFormData) return FormData_1;
  hasRequiredFormData = 1;
  FormData_1 = FormData;
  return FormData_1;
}
var browser$3;
var hasRequiredBrowser$1;
function requireBrowser$1() {
  if (hasRequiredBrowser$1) return browser$3;
  hasRequiredBrowser$1 = 1;
  browser$3 = {
    isBrowser: true,
    classes: {
      URLSearchParams: requireURLSearchParams(),
      FormData: requireFormData(),
      Blob
    },
    protocols: ["http", "https", "file", "blob", "url", "data"]
  };
  return browser$3;
}
var platform;
var hasRequiredPlatform;
function requirePlatform() {
  if (hasRequiredPlatform) return platform;
  hasRequiredPlatform = 1;
  platform = requireBrowser$1();
  return platform;
}
var toURLEncodedForm;
var hasRequiredToURLEncodedForm;
function requireToURLEncodedForm() {
  if (hasRequiredToURLEncodedForm) return toURLEncodedForm;
  hasRequiredToURLEncodedForm = 1;
  var utils2 = requireUtils();
  var toFormData = requireToFormData();
  var platform2 = requirePlatform();
  toURLEncodedForm = function toURLEncodedForm2(data2, options2) {
    return toFormData(data2, new platform2.classes.URLSearchParams(), Object.assign({
      visitor: function(value, key2, path, helpers) {
        if (platform2.isNode && utils2.isBuffer(value)) {
          this.append(key2, value.toString("base64"));
          return false;
        }
        return helpers.defaultVisitor.apply(this, arguments);
      }
    }, options2));
  };
  return toURLEncodedForm;
}
var formDataToJSON_1;
var hasRequiredFormDataToJSON;
function requireFormDataToJSON() {
  if (hasRequiredFormDataToJSON) return formDataToJSON_1;
  hasRequiredFormDataToJSON = 1;
  var utils2 = requireUtils();
  function parsePropPath(name) {
    return utils2.matchAll(/\w+|\[(\w*)]/g, name).map(function(match) {
      return match[0] === "[]" ? "" : match[1] || match[0];
    });
  }
  function arrayToObject(arr) {
    var obj = {};
    var keys = Object.keys(arr);
    var i2;
    var len = keys.length;
    var key2;
    for (i2 = 0; i2 < len; i2++) {
      key2 = keys[i2];
      obj[key2] = arr[key2];
    }
    return obj;
  }
  function formDataToJSON(formData) {
    function buildPath(path, value, target, index2) {
      var name = path[index2++];
      var isNumericKey = Number.isFinite(+name);
      var isLast = index2 >= path.length;
      name = !name && utils2.isArray(target) ? target.length : name;
      if (isLast) {
        if (utils2.hasOwnProperty(target, name)) {
          target[name] = [target[name], value];
        } else {
          target[name] = value;
        }
        return !isNumericKey;
      }
      if (!target[name] || !utils2.isObject(target[name])) {
        target[name] = [];
      }
      var result = buildPath(path, value, target[name], index2);
      if (result && utils2.isArray(target[name])) {
        target[name] = arrayToObject(target[name]);
      }
      return !isNumericKey;
    }
    if (utils2.isFormData(formData) && utils2.isFunction(formData.entries)) {
      var obj = {};
      utils2.forEachEntry(formData, function(name, value) {
        buildPath(parsePropPath(name), value, obj, 0);
      });
      return obj;
    }
    return null;
  }
  formDataToJSON_1 = formDataToJSON;
  return formDataToJSON_1;
}
var settle;
var hasRequiredSettle;
function requireSettle() {
  if (hasRequiredSettle) return settle;
  hasRequiredSettle = 1;
  var AxiosError = requireAxiosError();
  settle = function settle2(resolve2, reject2, response) {
    var validateStatus = response.config.validateStatus;
    if (!response.status || !validateStatus || validateStatus(response.status)) {
      resolve2(response);
    } else {
      reject2(new AxiosError(
        "Request failed with status code " + response.status,
        [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
        response.config,
        response.request,
        response
      ));
    }
  };
  return settle;
}
var cookies;
var hasRequiredCookies;
function requireCookies() {
  if (hasRequiredCookies) return cookies;
  hasRequiredCookies = 1;
  var utils2 = requireUtils();
  cookies = utils2.isStandardBrowserEnv() ? (
    // Standard browser envs support document.cookie
    /* @__PURE__ */ function standardBrowserEnv() {
      return {
        write: function write2(name, value, expires, path, domain, secure) {
          var cookie = [];
          cookie.push(name + "=" + encodeURIComponent(value));
          if (utils2.isNumber(expires)) {
            cookie.push("expires=" + new Date(expires).toGMTString());
          }
          if (utils2.isString(path)) {
            cookie.push("path=" + path);
          }
          if (utils2.isString(domain)) {
            cookie.push("domain=" + domain);
          }
          if (secure === true) {
            cookie.push("secure");
          }
          document.cookie = cookie.join("; ");
        },
        read: function read2(name) {
          var match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
          return match ? decodeURIComponent(match[3]) : null;
        },
        remove: function remove(name) {
          this.write(name, "", Date.now() - 864e5);
        }
      };
    }()
  ) : (
    // Non standard browser env (web workers, react-native) lack needed support.
    /* @__PURE__ */ function nonStandardBrowserEnv() {
      return {
        write: function write2() {
        },
        read: function read2() {
          return null;
        },
        remove: function remove() {
        }
      };
    }()
  );
  return cookies;
}
var isAbsoluteURL;
var hasRequiredIsAbsoluteURL;
function requireIsAbsoluteURL() {
  if (hasRequiredIsAbsoluteURL) return isAbsoluteURL;
  hasRequiredIsAbsoluteURL = 1;
  isAbsoluteURL = function isAbsoluteURL2(url) {
    return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  };
  return isAbsoluteURL;
}
var combineURLs;
var hasRequiredCombineURLs;
function requireCombineURLs() {
  if (hasRequiredCombineURLs) return combineURLs;
  hasRequiredCombineURLs = 1;
  combineURLs = function combineURLs2(baseURL, relativeURL) {
    return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
  };
  return combineURLs;
}
var buildFullPath;
var hasRequiredBuildFullPath;
function requireBuildFullPath() {
  if (hasRequiredBuildFullPath) return buildFullPath;
  hasRequiredBuildFullPath = 1;
  var isAbsoluteURL2 = requireIsAbsoluteURL();
  var combineURLs2 = requireCombineURLs();
  buildFullPath = function buildFullPath2(baseURL, requestedURL) {
    if (baseURL && !isAbsoluteURL2(requestedURL)) {
      return combineURLs2(baseURL, requestedURL);
    }
    return requestedURL;
  };
  return buildFullPath;
}
var parseHeaders;
var hasRequiredParseHeaders;
function requireParseHeaders() {
  if (hasRequiredParseHeaders) return parseHeaders;
  hasRequiredParseHeaders = 1;
  var utils2 = requireUtils();
  var ignoreDuplicateOf = [
    "age",
    "authorization",
    "content-length",
    "content-type",
    "etag",
    "expires",
    "from",
    "host",
    "if-modified-since",
    "if-unmodified-since",
    "last-modified",
    "location",
    "max-forwards",
    "proxy-authorization",
    "referer",
    "retry-after",
    "user-agent"
  ];
  parseHeaders = function parseHeaders2(headers) {
    var parsed = {};
    var key2;
    var val;
    var i2;
    if (!headers) {
      return parsed;
    }
    utils2.forEach(headers.split("\n"), function parser2(line) {
      i2 = line.indexOf(":");
      key2 = utils2.trim(line.slice(0, i2)).toLowerCase();
      val = utils2.trim(line.slice(i2 + 1));
      if (key2) {
        if (parsed[key2] && ignoreDuplicateOf.indexOf(key2) >= 0) {
          return;
        }
        if (key2 === "set-cookie") {
          parsed[key2] = (parsed[key2] ? parsed[key2] : []).concat([val]);
        } else {
          parsed[key2] = parsed[key2] ? parsed[key2] + ", " + val : val;
        }
      }
    });
    return parsed;
  };
  return parseHeaders;
}
var isURLSameOrigin;
var hasRequiredIsURLSameOrigin;
function requireIsURLSameOrigin() {
  if (hasRequiredIsURLSameOrigin) return isURLSameOrigin;
  hasRequiredIsURLSameOrigin = 1;
  var utils2 = requireUtils();
  isURLSameOrigin = utils2.isStandardBrowserEnv() ? (
    // Standard browser envs have full support of the APIs needed to test
    // whether the request URL is of the same origin as current location.
    function standardBrowserEnv() {
      var msie = /(msie|trident)/i.test(navigator.userAgent);
      var urlParsingNode = document.createElement("a");
      var originURL;
      function resolveURL(url) {
        var href = url;
        if (msie) {
          urlParsingNode.setAttribute("href", href);
          href = urlParsingNode.href;
        }
        urlParsingNode.setAttribute("href", href);
        return {
          href: urlParsingNode.href,
          protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "",
          host: urlParsingNode.host,
          search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "",
          hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "",
          hostname: urlParsingNode.hostname,
          port: urlParsingNode.port,
          pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname
        };
      }
      originURL = resolveURL(window.location.href);
      return function isURLSameOrigin2(requestURL) {
        var parsed = utils2.isString(requestURL) ? resolveURL(requestURL) : requestURL;
        return parsed.protocol === originURL.protocol && parsed.host === originURL.host;
      };
    }()
  ) : (
    // Non standard browser envs (web workers, react-native) lack needed support.
    /* @__PURE__ */ function nonStandardBrowserEnv() {
      return function isURLSameOrigin2() {
        return true;
      };
    }()
  );
  return isURLSameOrigin;
}
var CanceledError_1;
var hasRequiredCanceledError;
function requireCanceledError() {
  if (hasRequiredCanceledError) return CanceledError_1;
  hasRequiredCanceledError = 1;
  var AxiosError = requireAxiosError();
  var utils2 = requireUtils();
  function CanceledError(message, config, request) {
    AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request);
    this.name = "CanceledError";
  }
  utils2.inherits(CanceledError, AxiosError, {
    __CANCEL__: true
  });
  CanceledError_1 = CanceledError;
  return CanceledError_1;
}
var parseProtocol;
var hasRequiredParseProtocol;
function requireParseProtocol() {
  if (hasRequiredParseProtocol) return parseProtocol;
  hasRequiredParseProtocol = 1;
  parseProtocol = function parseProtocol2(url) {
    var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
    return match && match[1] || "";
  };
  return parseProtocol;
}
var xhr;
var hasRequiredXhr;
function requireXhr() {
  if (hasRequiredXhr) return xhr;
  hasRequiredXhr = 1;
  var utils2 = requireUtils();
  var settle2 = requireSettle();
  var cookies2 = requireCookies();
  var buildURL2 = requireBuildURL();
  var buildFullPath2 = requireBuildFullPath();
  var parseHeaders2 = requireParseHeaders();
  var isURLSameOrigin2 = requireIsURLSameOrigin();
  var transitionalDefaults = requireTransitional();
  var AxiosError = requireAxiosError();
  var CanceledError = requireCanceledError();
  var parseProtocol2 = requireParseProtocol();
  var platform2 = requirePlatform();
  xhr = function xhrAdapter(config) {
    return new Promise(function dispatchXhrRequest(resolve2, reject2) {
      var requestData = config.data;
      var requestHeaders = config.headers;
      var responseType = config.responseType;
      var withXSRFToken = config.withXSRFToken;
      var onCanceled;
      function done() {
        if (config.cancelToken) {
          config.cancelToken.unsubscribe(onCanceled);
        }
        if (config.signal) {
          config.signal.removeEventListener("abort", onCanceled);
        }
      }
      if (utils2.isFormData(requestData) && utils2.isStandardBrowserEnv()) {
        delete requestHeaders["Content-Type"];
      }
      var request = new XMLHttpRequest();
      if (config.auth) {
        var username = config.auth.username || "";
        var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : "";
        requestHeaders.Authorization = "Basic " + btoa(username + ":" + password);
      }
      var fullPath = buildFullPath2(config.baseURL, config.url);
      request.open(config.method.toUpperCase(), buildURL2(fullPath, config.params, config.paramsSerializer), true);
      request.timeout = config.timeout;
      function onloadend() {
        if (!request) {
          return;
        }
        var responseHeaders = "getAllResponseHeaders" in request ? parseHeaders2(request.getAllResponseHeaders()) : null;
        var responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
        var response = {
          data: responseData,
          status: request.status,
          statusText: request.statusText,
          headers: responseHeaders,
          config,
          request
        };
        settle2(function _resolve(value) {
          resolve2(value);
          done();
        }, function _reject(err) {
          reject2(err);
          done();
        }, response);
        request = null;
      }
      if ("onloadend" in request) {
        request.onloadend = onloadend;
      } else {
        request.onreadystatechange = function handleLoad() {
          if (!request || request.readyState !== 4) {
            return;
          }
          if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
            return;
          }
          setTimeout(onloadend);
        };
      }
      request.onabort = function handleAbort() {
        if (!request) {
          return;
        }
        reject2(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request));
        request = null;
      };
      request.onerror = function handleError() {
        reject2(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request));
        request = null;
      };
      request.ontimeout = function handleTimeout() {
        var timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded";
        var transitional2 = config.transitional || transitionalDefaults;
        if (config.timeoutErrorMessage) {
          timeoutErrorMessage = config.timeoutErrorMessage;
        }
        reject2(new AxiosError(
          timeoutErrorMessage,
          transitional2.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
          config,
          request
        ));
        request = null;
      };
      if (utils2.isStandardBrowserEnv()) {
        withXSRFToken && utils2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));
        if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin2(fullPath)) {
          var xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies2.read(config.xsrfCookieName);
          if (xsrfValue) {
            requestHeaders[config.xsrfHeaderName] = xsrfValue;
          }
        }
      }
      if ("setRequestHeader" in request) {
        utils2.forEach(requestHeaders, function setRequestHeader(val, key2) {
          if (typeof requestData === "undefined" && key2.toLowerCase() === "content-type") {
            delete requestHeaders[key2];
          } else {
            request.setRequestHeader(key2, val);
          }
        });
      }
      if (!utils2.isUndefined(config.withCredentials)) {
        request.withCredentials = !!config.withCredentials;
      }
      if (responseType && responseType !== "json") {
        request.responseType = config.responseType;
      }
      if (typeof config.onDownloadProgress === "function") {
        request.addEventListener("progress", config.onDownloadProgress);
      }
      if (typeof config.onUploadProgress === "function" && request.upload) {
        request.upload.addEventListener("progress", config.onUploadProgress);
      }
      if (config.cancelToken || config.signal) {
        onCanceled = function(cancel) {
          if (!request) {
            return;
          }
          reject2(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
          request.abort();
          request = null;
        };
        config.cancelToken && config.cancelToken.subscribe(onCanceled);
        if (config.signal) {
          config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled);
        }
      }
      if (!requestData && requestData !== false && requestData !== 0 && requestData !== "") {
        requestData = null;
      }
      var protocol = parseProtocol2(fullPath);
      if (protocol && platform2.protocols.indexOf(protocol) === -1) {
        reject2(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config));
        return;
      }
      request.send(requestData);
    });
  };
  return xhr;
}
var defaults_1;
var hasRequiredDefaults;
function requireDefaults() {
  if (hasRequiredDefaults) return defaults_1;
  hasRequiredDefaults = 1;
  var utils2 = requireUtils();
  var normalizeHeaderName2 = requireNormalizeHeaderName();
  var AxiosError = requireAxiosError();
  var transitionalDefaults = requireTransitional();
  var toFormData = requireToFormData();
  var toURLEncodedForm2 = requireToURLEncodedForm();
  var platform2 = requirePlatform();
  var formDataToJSON = requireFormDataToJSON();
  var DEFAULT_CONTENT_TYPE = {
    "Content-Type": "application/x-www-form-urlencoded"
  };
  function setContentTypeIfUnset(headers, value) {
    if (!utils2.isUndefined(headers) && utils2.isUndefined(headers["Content-Type"])) {
      headers["Content-Type"] = value;
    }
  }
  function getDefaultAdapter() {
    var adapter;
    if (typeof XMLHttpRequest !== "undefined") {
      adapter = requireXhr();
    } else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
      adapter = requireXhr();
    }
    return adapter;
  }
  function stringifySafely(rawValue, parser2, encoder2) {
    if (utils2.isString(rawValue)) {
      try {
        (parser2 || JSON.parse)(rawValue);
        return utils2.trim(rawValue);
      } catch (e4) {
        if (e4.name !== "SyntaxError") {
          throw e4;
        }
      }
    }
    return (encoder2 || JSON.stringify)(rawValue);
  }
  var defaults = {
    transitional: transitionalDefaults,
    adapter: getDefaultAdapter(),
    transformRequest: [function transformRequest(data2, headers) {
      normalizeHeaderName2(headers, "Accept");
      normalizeHeaderName2(headers, "Content-Type");
      var contentType = headers && headers["Content-Type"] || "";
      var hasJSONContentType = contentType.indexOf("application/json") > -1;
      var isObjectPayload = utils2.isObject(data2);
      if (isObjectPayload && utils2.isHTMLForm(data2)) {
        data2 = new FormData(data2);
      }
      var isFormData = utils2.isFormData(data2);
      if (isFormData) {
        return hasJSONContentType ? JSON.stringify(formDataToJSON(data2)) : data2;
      }
      if (utils2.isArrayBuffer(data2) || utils2.isBuffer(data2) || utils2.isStream(data2) || utils2.isFile(data2) || utils2.isBlob(data2)) {
        return data2;
      }
      if (utils2.isArrayBufferView(data2)) {
        return data2.buffer;
      }
      if (utils2.isURLSearchParams(data2)) {
        setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8");
        return data2.toString();
      }
      var isFileList;
      if (isObjectPayload) {
        if (contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
          return toURLEncodedForm2(data2, this.formSerializer).toString();
        }
        if ((isFileList = utils2.isFileList(data2)) || contentType.indexOf("multipart/form-data") > -1) {
          var _FormData = this.env && this.env.FormData;
          return toFormData(
            isFileList ? { "files[]": data2 } : data2,
            _FormData && new _FormData(),
            this.formSerializer
          );
        }
      }
      if (isObjectPayload || hasJSONContentType) {
        setContentTypeIfUnset(headers, "application/json");
        return stringifySafely(data2);
      }
      return data2;
    }],
    transformResponse: [function transformResponse(data2) {
      var transitional2 = this.transitional || defaults.transitional;
      var forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
      var JSONRequested = this.responseType === "json";
      if (data2 && utils2.isString(data2) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
        var silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
        var strictJSONParsing = !silentJSONParsing && JSONRequested;
        try {
          return JSON.parse(data2);
        } catch (e4) {
          if (strictJSONParsing) {
            if (e4.name === "SyntaxError") {
              throw AxiosError.from(e4, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
            }
            throw e4;
          }
        }
      }
      return data2;
    }],
    /**
     * A timeout in milliseconds to abort a request. If set to 0 (default) a
     * timeout is not created.
     */
    timeout: 0,
    xsrfCookieName: "XSRF-TOKEN",
    xsrfHeaderName: "X-XSRF-TOKEN",
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: platform2.classes.FormData,
      Blob: platform2.classes.Blob
    },
    validateStatus: function validateStatus(status) {
      return status >= 200 && status < 300;
    },
    headers: {
      common: {
        "Accept": "application/json, text/plain, */*"
      }
    }
  };
  utils2.forEach(["delete", "get", "head"], function forEachMethodNoData(method) {
    defaults.headers[method] = {};
  });
  utils2.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
    defaults.headers[method] = utils2.merge(DEFAULT_CONTENT_TYPE);
  });
  defaults_1 = defaults;
  return defaults_1;
}
var transformData;
var hasRequiredTransformData;
function requireTransformData() {
  if (hasRequiredTransformData) return transformData;
  hasRequiredTransformData = 1;
  var utils2 = requireUtils();
  var defaults = requireDefaults();
  transformData = function transformData2(data2, headers, status, fns) {
    var context = this || defaults;
    utils2.forEach(fns, function transform(fn) {
      data2 = fn.call(context, data2, headers, status);
    });
    return data2;
  };
  return transformData;
}
var isCancel;
var hasRequiredIsCancel;
function requireIsCancel() {
  if (hasRequiredIsCancel) return isCancel;
  hasRequiredIsCancel = 1;
  isCancel = function isCancel2(value) {
    return !!(value && value.__CANCEL__);
  };
  return isCancel;
}
var dispatchRequest;
var hasRequiredDispatchRequest;
function requireDispatchRequest() {
  if (hasRequiredDispatchRequest) return dispatchRequest;
  hasRequiredDispatchRequest = 1;
  var utils2 = requireUtils();
  var transformData2 = requireTransformData();
  var isCancel2 = requireIsCancel();
  var defaults = requireDefaults();
  var CanceledError = requireCanceledError();
  var normalizeHeaderName2 = requireNormalizeHeaderName();
  function throwIfCancellationRequested(config) {
    if (config.cancelToken) {
      config.cancelToken.throwIfRequested();
    }
    if (config.signal && config.signal.aborted) {
      throw new CanceledError();
    }
  }
  dispatchRequest = function dispatchRequest2(config) {
    throwIfCancellationRequested(config);
    config.headers = config.headers || {};
    config.data = transformData2.call(
      config,
      config.data,
      config.headers,
      null,
      config.transformRequest
    );
    normalizeHeaderName2(config.headers, "Accept");
    normalizeHeaderName2(config.headers, "Content-Type");
    config.headers = utils2.merge(
      config.headers.common || {},
      config.headers[config.method] || {},
      config.headers
    );
    utils2.forEach(
      ["delete", "get", "head", "post", "put", "patch", "common"],
      function cleanHeaderConfig(method) {
        delete config.headers[method];
      }
    );
    var adapter = config.adapter || defaults.adapter;
    return adapter(config).then(function onAdapterResolution(response) {
      throwIfCancellationRequested(config);
      response.data = transformData2.call(
        config,
        response.data,
        response.headers,
        response.status,
        config.transformResponse
      );
      return response;
    }, function onAdapterRejection(reason) {
      if (!isCancel2(reason)) {
        throwIfCancellationRequested(config);
        if (reason && reason.response) {
          reason.response.data = transformData2.call(
            config,
            reason.response.data,
            reason.response.headers,
            reason.response.status,
            config.transformResponse
          );
        }
      }
      return Promise.reject(reason);
    });
  };
  return dispatchRequest;
}
var mergeConfig;
var hasRequiredMergeConfig;
function requireMergeConfig() {
  if (hasRequiredMergeConfig) return mergeConfig;
  hasRequiredMergeConfig = 1;
  var utils2 = requireUtils();
  mergeConfig = function mergeConfig2(config1, config2) {
    config2 = config2 || {};
    var config = {};
    function getMergedValue(target, source) {
      if (utils2.isPlainObject(target) && utils2.isPlainObject(source)) {
        return utils2.merge(target, source);
      } else if (utils2.isEmptyObject(source)) {
        return utils2.merge({}, target);
      } else if (utils2.isPlainObject(source)) {
        return utils2.merge({}, source);
      } else if (utils2.isArray(source)) {
        return source.slice();
      }
      return source;
    }
    function mergeDeepProperties(prop) {
      if (!utils2.isUndefined(config2[prop])) {
        return getMergedValue(config1[prop], config2[prop]);
      } else if (!utils2.isUndefined(config1[prop])) {
        return getMergedValue(void 0, config1[prop]);
      }
    }
    function valueFromConfig2(prop) {
      if (!utils2.isUndefined(config2[prop])) {
        return getMergedValue(void 0, config2[prop]);
      }
    }
    function defaultToConfig2(prop) {
      if (!utils2.isUndefined(config2[prop])) {
        return getMergedValue(void 0, config2[prop]);
      } else if (!utils2.isUndefined(config1[prop])) {
        return getMergedValue(void 0, config1[prop]);
      }
    }
    function mergeDirectKeys(prop) {
      if (prop in config2) {
        return getMergedValue(config1[prop], config2[prop]);
      } else if (prop in config1) {
        return getMergedValue(void 0, config1[prop]);
      }
    }
    var mergeMap = {
      "url": valueFromConfig2,
      "method": valueFromConfig2,
      "data": valueFromConfig2,
      "baseURL": defaultToConfig2,
      "transformRequest": defaultToConfig2,
      "transformResponse": defaultToConfig2,
      "paramsSerializer": defaultToConfig2,
      "timeout": defaultToConfig2,
      "timeoutMessage": defaultToConfig2,
      "withCredentials": defaultToConfig2,
      "withXSRFToken": defaultToConfig2,
      "adapter": defaultToConfig2,
      "responseType": defaultToConfig2,
      "xsrfCookieName": defaultToConfig2,
      "xsrfHeaderName": defaultToConfig2,
      "onUploadProgress": defaultToConfig2,
      "onDownloadProgress": defaultToConfig2,
      "decompress": defaultToConfig2,
      "maxContentLength": defaultToConfig2,
      "maxBodyLength": defaultToConfig2,
      "beforeRedirect": defaultToConfig2,
      "transport": defaultToConfig2,
      "httpAgent": defaultToConfig2,
      "httpsAgent": defaultToConfig2,
      "cancelToken": defaultToConfig2,
      "socketPath": defaultToConfig2,
      "responseEncoding": defaultToConfig2,
      "validateStatus": mergeDirectKeys
    };
    utils2.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
      var merge = mergeMap[prop] || mergeDeepProperties;
      var configValue = merge(prop);
      utils2.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
    });
    return config;
  };
  return mergeConfig;
}
var data$1;
var hasRequiredData$1;
function requireData$1() {
  if (hasRequiredData$1) return data$1;
  hasRequiredData$1 = 1;
  data$1 = {
    "version": "0.28.0"
  };
  return data$1;
}
var validator;
var hasRequiredValidator;
function requireValidator() {
  if (hasRequiredValidator) return validator;
  hasRequiredValidator = 1;
  var VERSION = requireData$1().version;
  var AxiosError = requireAxiosError();
  var validators = {};
  ["object", "boolean", "number", "function", "string", "symbol"].forEach(function(type2, i2) {
    validators[type2] = function validator2(thing) {
      return typeof thing === type2 || "a" + (i2 < 1 ? "n " : " ") + type2;
    };
  });
  var deprecatedWarnings = {};
  validators.transitional = function transitional2(validator2, version2, message) {
    function formatMessage(opt, desc) {
      return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
    }
    return function(value, opt, opts) {
      if (validator2 === false) {
        throw new AxiosError(
          formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")),
          AxiosError.ERR_DEPRECATED
        );
      }
      if (version2 && !deprecatedWarnings[opt]) {
        deprecatedWarnings[opt] = true;
        console.warn(
          formatMessage(
            opt,
            " has been deprecated since v" + version2 + " and will be removed in the near future"
          )
        );
      }
      return validator2 ? validator2(value, opt, opts) : true;
    };
  };
  function assertOptions(options2, schema, allowUnknown) {
    if (typeof options2 !== "object") {
      throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE);
    }
    var keys = Object.keys(options2);
    var i2 = keys.length;
    while (i2-- > 0) {
      var opt = keys[i2];
      var validator2 = schema[opt];
      if (validator2) {
        var value = options2[opt];
        var result = value === void 0 || validator2(value, opt, options2);
        if (result !== true) {
          throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
        }
        continue;
      }
      if (allowUnknown !== true) {
        throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION);
      }
    }
  }
  validator = {
    assertOptions,
    validators
  };
  return validator;
}
var Axios_1;
var hasRequiredAxios$2;
function requireAxios$2() {
  if (hasRequiredAxios$2) return Axios_1;
  hasRequiredAxios$2 = 1;
  var utils2 = requireUtils();
  var buildURL2 = requireBuildURL();
  var InterceptorManager = requireInterceptorManager();
  var dispatchRequest2 = requireDispatchRequest();
  var mergeConfig2 = requireMergeConfig();
  var buildFullPath2 = requireBuildFullPath();
  var validator2 = requireValidator();
  var validators = validator2.validators;
  function Axios2(instanceConfig) {
    this.defaults = instanceConfig;
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  Axios2.prototype.request = function request(configOrUrl, config) {
    if (typeof configOrUrl === "string") {
      config = config || {};
      config.url = configOrUrl;
    } else {
      config = configOrUrl || {};
    }
    config = mergeConfig2(this.defaults, config);
    if (config.method) {
      config.method = config.method.toLowerCase();
    } else if (this.defaults.method) {
      config.method = this.defaults.method.toLowerCase();
    } else {
      config.method = "get";
    }
    var transitional2 = config.transitional;
    if (transitional2 !== void 0) {
      validator2.assertOptions(transitional2, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
      }, false);
    }
    var paramsSerializer = config.paramsSerializer;
    utils2.isFunction(paramsSerializer) && (config.paramsSerializer = { serialize: paramsSerializer });
    var requestInterceptorChain = [];
    var synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
        return;
      }
      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
      requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
    });
    var responseInterceptorChain = [];
    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    });
    var promise;
    if (!synchronousRequestInterceptors) {
      var chain = [dispatchRequest2, void 0];
      Array.prototype.unshift.apply(chain, requestInterceptorChain);
      chain = chain.concat(responseInterceptorChain);
      promise = Promise.resolve(config);
      while (chain.length) {
        promise = promise.then(chain.shift(), chain.shift());
      }
      return promise;
    }
    var newConfig = config;
    while (requestInterceptorChain.length) {
      var onFulfilled = requestInterceptorChain.shift();
      var onRejected = requestInterceptorChain.shift();
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error) {
        onRejected(error);
        break;
      }
    }
    try {
      promise = dispatchRequest2(newConfig);
    } catch (error) {
      return Promise.reject(error);
    }
    while (responseInterceptorChain.length) {
      promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
    }
    return promise;
  };
  Axios2.prototype.getUri = function getUri(config) {
    config = mergeConfig2(this.defaults, config);
    var fullPath = buildFullPath2(config.baseURL, config.url);
    return buildURL2(fullPath, config.params, config.paramsSerializer);
  };
  utils2.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
    Axios2.prototype[method] = function(url, config) {
      return this.request(mergeConfig2(config || {}, {
        method,
        url,
        data: (config || {}).data
      }));
    };
  });
  utils2.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
    function generateHTTPMethod(isForm) {
      return function httpMethod(url, data2, config) {
        return this.request(mergeConfig2(config || {}, {
          method,
          headers: isForm ? {
            "Content-Type": "multipart/form-data"
          } : {},
          url,
          data: data2
        }));
      };
    }
    Axios2.prototype[method] = generateHTTPMethod();
    Axios2.prototype[method + "Form"] = generateHTTPMethod(true);
  });
  Axios_1 = Axios2;
  return Axios_1;
}
var CancelToken_1;
var hasRequiredCancelToken;
function requireCancelToken() {
  if (hasRequiredCancelToken) return CancelToken_1;
  hasRequiredCancelToken = 1;
  var CanceledError = requireCanceledError();
  function CancelToken(executor) {
    if (typeof executor !== "function") {
      throw new TypeError("executor must be a function.");
    }
    var resolvePromise;
    this.promise = new Promise(function promiseExecutor(resolve2) {
      resolvePromise = resolve2;
    });
    var token = this;
    this.promise.then(function(cancel) {
      if (!token._listeners) return;
      var i2 = token._listeners.length;
      while (i2-- > 0) {
        token._listeners[i2](cancel);
      }
      token._listeners = null;
    });
    this.promise.then = function(onfulfilled) {
      var _resolve;
      var promise = new Promise(function(resolve2) {
        token.subscribe(resolve2);
        _resolve = resolve2;
      }).then(onfulfilled);
      promise.cancel = function reject2() {
        token.unsubscribe(_resolve);
      };
      return promise;
    };
    executor(function cancel(message, config, request) {
      if (token.reason) {
        return;
      }
      token.reason = new CanceledError(message, config, request);
      resolvePromise(token.reason);
    });
  }
  CancelToken.prototype.throwIfRequested = function throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  };
  CancelToken.prototype.subscribe = function subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }
    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  };
  CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    var index2 = this._listeners.indexOf(listener);
    if (index2 !== -1) {
      this._listeners.splice(index2, 1);
    }
  };
  CancelToken.source = function source() {
    var cancel;
    var token = new CancelToken(function executor(c2) {
      cancel = c2;
    });
    return {
      token,
      cancel
    };
  };
  CancelToken_1 = CancelToken;
  return CancelToken_1;
}
var spread;
var hasRequiredSpread;
function requireSpread() {
  if (hasRequiredSpread) return spread;
  hasRequiredSpread = 1;
  spread = function spread2(callback) {
    return function wrap(arr) {
      return callback.apply(null, arr);
    };
  };
  return spread;
}
var isAxiosError;
var hasRequiredIsAxiosError;
function requireIsAxiosError() {
  if (hasRequiredIsAxiosError) return isAxiosError;
  hasRequiredIsAxiosError = 1;
  var utils2 = requireUtils();
  isAxiosError = function isAxiosError2(payload) {
    return utils2.isObject(payload) && payload.isAxiosError === true;
  };
  return isAxiosError;
}
var hasRequiredAxios$1;
function requireAxios$1() {
  if (hasRequiredAxios$1) return axios$1.exports;
  hasRequiredAxios$1 = 1;
  var utils2 = requireUtils();
  var bind2 = requireBind();
  var Axios2 = requireAxios$2();
  var mergeConfig2 = requireMergeConfig();
  var defaults = requireDefaults();
  var formDataToJSON = requireFormDataToJSON();
  function createInstance(defaultConfig) {
    var context = new Axios2(defaultConfig);
    var instance2 = bind2(Axios2.prototype.request, context);
    utils2.extend(instance2, Axios2.prototype, context);
    utils2.extend(instance2, context);
    instance2.create = function create2(instanceConfig) {
      return createInstance(mergeConfig2(defaultConfig, instanceConfig));
    };
    return instance2;
  }
  var axios2 = createInstance(defaults);
  axios2.Axios = Axios2;
  axios2.CanceledError = requireCanceledError();
  axios2.CancelToken = requireCancelToken();
  axios2.isCancel = requireIsCancel();
  axios2.VERSION = requireData$1().version;
  axios2.toFormData = requireToFormData();
  axios2.AxiosError = requireAxiosError();
  axios2.Cancel = axios2.CanceledError;
  axios2.all = function all(promises) {
    return Promise.all(promises);
  };
  axios2.spread = requireSpread();
  axios2.isAxiosError = requireIsAxiosError();
  axios2.formToJSON = function(thing) {
    return formDataToJSON(utils2.isHTMLForm(thing) ? new FormData(thing) : thing);
  };
  axios$1.exports = axios2;
  axios$1.exports.default = axios2;
  return axios$1.exports;
}
var axios;
var hasRequiredAxios;
function requireAxios() {
  if (hasRequiredAxios) return axios;
  hasRequiredAxios = 1;
  axios = requireAxios$1();
  return axios;
}
var axiosExports = requireAxios();
const Axios = /* @__PURE__ */ getDefaultExportFromCjs$1(axiosExports);
var __assign$3 = function() {
  __assign$3 = Object.assign || function(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
        t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$3.apply(this, arguments);
};
var __awaiter$a = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$a = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var GraphqlClient = (
  /** @class */
  function() {
    function GraphqlClient2(endpoint, options2) {
      this.endpoint = endpoint;
      this.options = options2;
      this.axios = Axios.create({
        withCredentials: true
      });
    }
    GraphqlClient2.prototype.setOptions = function(options2) {
      this.options = options2;
    };
    GraphqlClient2.prototype.request = function(options2) {
      var _a3, _b2;
      return __awaiter$a(this, void 0, void 0, function() {
        var query, token, variables, headers, data2, errors, responseData, error_1, statusCode, errorDetail, errmsg_1, errcode_1, data_1;
        var _this = this;
        return __generator$a(this, function(_c2) {
          switch (_c2.label) {
            case 0:
              query = options2.query, token = options2.token, variables = options2.variables;
              headers = {
                "content-type": "application/json"
              };
              headers[this.options.headers["app-id"]] = this.options.appId || "";
              headers[this.options.headers["tenant-id"]] = this.options.tenantId;
              headers[this.options.headers["userpool-id"]] = // @ts-ignore
              this.options.userPoolId || "";
              headers[this.options.headers["request-from"]] = this.options.requestFrom || "sdk";
              headers[this.options.headers["sdk-version"]] = "js:".concat(SDK_VERSION$1);
              headers[this.options.headers.lang] = this.options.lang || "";
              token && (headers.Authorization = "Bearer ".concat(token));
              data2 = null;
              errors = null;
              _c2.label = 1;
            case 1:
              _c2.trys.push([1, 3, , 4]);
              return [4, this.axios({
                url: this.endpoint,
                data: {
                  query,
                  variables
                },
                method: "post",
                headers: __assign$3({}, pickBy(headers, function(i2) {
                  return !!i2;
                })),
                timeout: this.options.timeout
              })];
            case 2:
              responseData = _c2.sent().data;
              data2 = responseData.data;
              errors = responseData.errors;
              return [3, 4];
            case 3:
              error_1 = _c2.sent();
              statusCode = error_1.code || ((_a3 = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _a3 === void 0 ? void 0 : _a3.status);
              errorDetail = error_1.message || ((_b2 = error_1 === null || error_1 === void 0 ? void 0 : error_1.response) === null || _b2 === void 0 ? void 0 : _b2.data);
              this.options.onError(statusCode || 500, error_1.message, errorDetail);
              throw {
                code: statusCode || 500,
                message: error_1.message,
                data: errorDetail
              };
            case 4:
              if ((errors === null || errors === void 0 ? void 0 : errors.length) > 0) {
                errmsg_1 = null;
                errcode_1 = null;
                data_1 = null;
                errors.map(function(err) {
                  var msg = err.message;
                  var code = msg.code, message = msg.message, _data = msg.data;
                  errcode_1 = code;
                  errmsg_1 = message;
                  data_1 = _data;
                  _this.options.onError(code, message, data_1);
                });
                throw { code: errcode_1, message: errmsg_1, data: data_1 };
              }
              return [2, data2];
          }
        });
      });
    };
    return GraphqlClient2;
  }()
);
var lib$2 = { exports: {} };
var atob$1;
var hasRequiredAtob;
function requireAtob() {
  if (hasRequiredAtob) return atob$1;
  hasRequiredAtob = 1;
  var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  function InvalidCharacterError(message) {
    this.message = message;
  }
  InvalidCharacterError.prototype = new Error();
  InvalidCharacterError.prototype.name = "InvalidCharacterError";
  function polyfill(input) {
    var str = String(input).replace(/=+$/, "");
    if (str.length % 4 == 1) {
      throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
    }
    for (
      var bc = 0, bs, buffer2, idx = 0, output = "";
      // get next character
      buffer2 = str.charAt(idx++);
      // character found in table? initialize bit storage and add its ascii value;
      ~buffer2 && (bs = bc % 4 ? bs * 64 + buffer2 : buffer2, // and if not first of each 4 characters,
      // convert the first 8 bits to one ascii character
      bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
    ) {
      buffer2 = chars2.indexOf(buffer2);
    }
    return output;
  }
  atob$1 = typeof window !== "undefined" && window.atob && window.atob.bind(window) || polyfill;
  return atob$1;
}
var base64_url_decode;
var hasRequiredBase64_url_decode;
function requireBase64_url_decode() {
  if (hasRequiredBase64_url_decode) return base64_url_decode;
  hasRequiredBase64_url_decode = 1;
  var atob2 = requireAtob();
  function b64DecodeUnicode(str) {
    return decodeURIComponent(atob2(str).replace(/(.)/g, function(m, p2) {
      var code = p2.charCodeAt(0).toString(16).toUpperCase();
      if (code.length < 2) {
        code = "0" + code;
      }
      return "%" + code;
    }));
  }
  base64_url_decode = function(str) {
    var output = str.replace(/-/g, "+").replace(/_/g, "/");
    switch (output.length % 4) {
      case 0:
        break;
      case 2:
        output += "==";
        break;
      case 3:
        output += "=";
        break;
      default:
        throw "Illegal base64url string!";
    }
    try {
      return b64DecodeUnicode(output);
    } catch (err) {
      return atob2(output);
    }
  };
  return base64_url_decode;
}
var hasRequiredLib;
function requireLib() {
  if (hasRequiredLib) return lib$2.exports;
  hasRequiredLib = 1;
  var base64_url_decode2 = requireBase64_url_decode();
  function InvalidTokenError(message) {
    this.message = message;
  }
  InvalidTokenError.prototype = new Error();
  InvalidTokenError.prototype.name = "InvalidTokenError";
  lib$2.exports = function(token, options2) {
    if (typeof token !== "string") {
      throw new InvalidTokenError("Invalid token specified");
    }
    options2 = options2 || {};
    var pos = options2.header === true ? 0 : 1;
    try {
      return JSON.parse(base64_url_decode2(token.split(".")[pos]));
    } catch (e4) {
      throw new InvalidTokenError("Invalid token specified: " + e4.message);
    }
  };
  lib$2.exports.InvalidTokenError = InvalidTokenError;
  return lib$2.exports;
}
var libExports = requireLib();
const jwtDecode = /* @__PURE__ */ getDefaultExportFromCjs$1(libExports);
var __extends = /* @__PURE__ */ function() {
  var extendStatics2 = function(d, b2) {
    extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b3) {
      d2.__proto__ = b3;
    } || function(d2, b3) {
      for (var p2 in b3) if (Object.prototype.hasOwnProperty.call(b3, p2)) d2[p2] = b3[p2];
    };
    return extendStatics2(d, b2);
  };
  return function(d, b2) {
    if (typeof b2 !== "function" && b2 !== null)
      throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null");
    extendStatics2(d, b2);
    function __() {
      this.constructor = d;
    }
    d.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __());
  };
}();
var __assign$2 = function() {
  __assign$2 = Object.assign || function(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
        t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$2.apply(this, arguments);
};
var __awaiter$9 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$9 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var HttpClient = (
  /** @class */
  function() {
    function HttpClient2(options2, tokenProvider) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.axios = Axios.create({
        withCredentials: true
      });
    }
    HttpClient2.prototype.setOptions = function(options2) {
      this.options = options2;
    };
    HttpClient2.prototype.request = function(config) {
      var _a3;
      return __awaiter$9(this, void 0, void 0, function() {
        var headers, token, data2, code, message, statusCode;
        return __generator$9(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              headers = {};
              headers[this.options.headers["app-id"]] = this.options.appId || "";
              headers[this.options.headers["tenant-id"]] = this.options.tenantId;
              headers[this.options.headers["userpool-id"]] = this.options.userPoolId || "";
              headers[this.options.headers["request-from"]] = this.options.requestFrom || "sdk";
              headers[this.options.headers["sdk-version"]] = "js:".concat(SDK_VERSION$1);
              headers[this.options.headers.lang] = this.options.lang || "";
              if (!!config.unSetToken) return [3, 3];
              if (!!(config && config.headers && config.headers.authorization)) return [3, 2];
              return [4, (_a3 = this.tokenProvider) === null || _a3 === void 0 ? void 0 : _a3.getToken()];
            case 1:
              token = _b2.sent();
              token && (headers.Authorization = "Bearer ".concat(token));
              return [3, 3];
            case 2:
              headers.authorization = config.headers.authorization;
              _b2.label = 3;
            case 3:
              config.headers = headers;
              config.timeout = this.options.timeout;
              return [4, this.axios.request(__assign$2(__assign$2({}, config), { headers: __assign$2({}, pickBy(config.headers, function(i2) {
                return !!i2;
              })) }))];
            case 4:
              data2 = _b2.sent().data;
              code = data2.code, message = data2.message, statusCode = data2.statusCode;
              if (config.notHandleRes) {
                return [2, data2];
              }
              if (code === 200 || statusCode === 200) {
                return [2, data2.data];
              } else {
                this.options.onError(code, message, data2.data);
                throw new Error(JSON.stringify({ code, message, data: data2.data }));
              }
          }
        });
      });
    };
    return HttpClient2;
  }()
);
(function(_super) {
  __extends(FastHttpClient, _super);
  function FastHttpClient(options2, tokenProvider) {
    return _super.call(this, options2, tokenProvider) || this;
  }
  FastHttpClient.prototype.request = function(config) {
    return __awaiter$9(this, void 0, void 0, function() {
      var headers, token, data2;
      return __generator$9(this, function(_a3) {
        switch (_a3.label) {
          case 0:
            headers = {};
            headers[this.options.headers["app-id"]] = this.options.appId || "";
            headers[this.options.headers["tenant-id"]] = this.options.tenantId;
            headers[this.options.headers["userpool-id"]] = this.options.userPoolId || "";
            headers[this.options.headers["request-from"]] = this.options.requestFrom || "sdk";
            headers[this.options.headers["sdk-version"]] = "js:".concat(SDK_VERSION$1);
            headers[this.options.headers.lang] = this.options.lang || "";
            if (!!(config && config.headers && config.headers.authorization)) return [3, 2];
            return [4, this.tokenProvider.getToken()];
          case 1:
            token = _a3.sent();
            token && (headers.Authorization = "Bearer ".concat(token));
            return [3, 3];
          case 2:
            headers.authorization = config.headers.authorization;
            _a3.label = 3;
          case 3:
            config.headers = headers;
            config.timeout = this.options.timeout;
            return [4, this.axios.request(__assign$2(__assign$2({}, config), { headers: __assign$2({}, pickBy(config.headers, function(i2) {
              return !!i2;
            })) }))];
          case 4:
            data2 = _a3.sent().data;
            return [2, data2];
        }
      });
    });
  };
  return FastHttpClient;
})(HttpClient);
var NaiveHttpClient = (
  /** @class */
  function(_super) {
    __extends(NaiveHttpClient2, _super);
    function NaiveHttpClient2(options2, tokenProvider) {
      return _super.call(this, options2, tokenProvider) || this;
    }
    NaiveHttpClient2.prototype.request = function(config) {
      return __awaiter$9(this, void 0, void 0, function() {
        var headers, data2;
        return __generator$9(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              headers = {};
              headers[this.options.headers["app-id"]] = this.options.appId || "";
              headers[this.options.headers["userpool-id"]] = headers[this.options.headers["tenant-id"]] = this.options.tenantId;
              this.options.userPoolId || "";
              headers[this.options.headers["request-from"]] = this.options.requestFrom || "sdk";
              headers[this.options.headers["sdk-version"]] = "js:".concat(SDK_VERSION$1);
              headers[this.options.headers.lang] = this.options.lang || "";
              config.headers = __assign$2(__assign$2({}, headers), config.headers);
              config.timeout = this.options.timeout;
              return [4, this.axios.request(__assign$2(__assign$2({}, config), { headers: __assign$2({}, pickBy(config.headers, function(i2) {
                return !!i2;
              })) }))];
            case 1:
              data2 = _a3.sent().data;
              return [2, data2];
          }
        });
      });
    };
    return NaiveHttpClient2;
  }(HttpClient)
);
var BaseAuthenticationClient = (
  /** @class */
  function() {
    function BaseAuthenticationClient2(options2) {
      this.options = options2;
    }
    Object.defineProperty(BaseAuthenticationClient2.prototype, "appHost", {
      get: function() {
        var _a3 = this.options, appHost = _a3.appHost, domain = _a3.domain, host = _a3.host;
        if (appHost) {
          return appHost.replace(/\/$/, "");
        } else if (domain) {
          var hostUrl = new URL(this.options.host);
          return "".concat(hostUrl.protocol, "//").concat(this.options.domain);
        } else {
          return host;
        }
      },
      enumerable: false,
      configurable: true
    });
    return BaseAuthenticationClient2;
  }()
);
var __awaiter$8 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$8 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var PublicKeyManager = (
  /** @class */
  function() {
    function PublicKeyManager2(options2, httpClient) {
      this.options = options2;
      this.baseClient = new BaseAuthenticationClient(this.options);
      this.httpClient = httpClient;
    }
    PublicKeyManager2.prototype.getPublicKey = function() {
      return __awaiter$8(this, void 0, void 0, function() {
        var api2, data2, publicKey2;
        return __generator$8(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (this.options.publicKey) {
                return [2, this.options.publicKey];
              }
              if (this.publicKey) {
                return [2, this.publicKey];
              }
              api2 = "".concat(this.baseClient.appHost, "/api/v2/.well-known");
              return [4, this.httpClient.request({
                method: "GET",
                url: api2
              })];
            case 1:
              data2 = _a3.sent();
              publicKey2 = data2.publicKey;
              this.publicKey = publicKey2;
              return [2, this.publicKey];
          }
        });
      });
    };
    return PublicKeyManager2;
  }()
);
var PasswordSecurityLevel;
(function(PasswordSecurityLevel2) {
  PasswordSecurityLevel2[PasswordSecurityLevel2["LOW"] = 1] = "LOW";
  PasswordSecurityLevel2[PasswordSecurityLevel2["MIDDLE"] = 2] = "MIDDLE";
  PasswordSecurityLevel2[PasswordSecurityLevel2["HIGH"] = 3] = "HIGH";
})(PasswordSecurityLevel || (PasswordSecurityLevel = {}));
var SocialConnectionProvider;
(function(SocialConnectionProvider2) {
  SocialConnectionProvider2["ALIPAY"] = "alipay";
  SocialConnectionProvider2["GOOGLE"] = "google";
  SocialConnectionProvider2["WECHATPC"] = "wechat:pc";
  SocialConnectionProvider2["WECHATMP"] = "wechat:webpage-authorization";
  SocialConnectionProvider2["WECHAT_MINIPROGRAM"] = "wechat:miniprogram:default";
  SocialConnectionProvider2["WECHAT_MINIPROGRAM_QRCODE"] = "wechat:miniprogram:qrconnect";
  SocialConnectionProvider2["WECHAT_MINIPROGRAM_APPLAUNCH"] = "wechat:miniprogram:app-launch";
  SocialConnectionProvider2["WECHATMOBILE"] = "wechat:mobile";
  SocialConnectionProvider2["GITHUB"] = "github";
  SocialConnectionProvider2["QQ"] = "qq";
  SocialConnectionProvider2["WECHATWORK_ADDRESS_BOOK"] = "wechatwork:addressbook";
  SocialConnectionProvider2["WECHATWORK_CORP_QRCONNECT"] = "wechatwork:corp:qrconnect";
  SocialConnectionProvider2["WECHATWORK_SERVICEPROVIDER_QRCONNECT"] = "wechatwork:service-provider:qrconnect";
  SocialConnectionProvider2["DINGTALK"] = "dingtalk";
  SocialConnectionProvider2["WEIBO"] = "weibo";
  SocialConnectionProvider2["APPLE"] = "apple";
  SocialConnectionProvider2["APPLE_WEB"] = "apple:web";
  SocialConnectionProvider2["LARK_PUBLIC"] = "lark-public";
  SocialConnectionProvider2["LARK_INTERNAL"] = "lark-internal";
  SocialConnectionProvider2["BAIDU"] = "baidu";
  SocialConnectionProvider2["LINKEDIN"] = "linkedin";
  SocialConnectionProvider2["SLACK"] = "slack";
  SocialConnectionProvider2["YIDUN"] = "yidun";
  SocialConnectionProvider2["QINGCLOUD"] = "qingcloud";
  SocialConnectionProvider2["FACEBOOK"] = "facebook";
})(SocialConnectionProvider || (SocialConnectionProvider = {}));
var Protocol$1;
(function(Protocol2) {
  Protocol2["OIDC"] = "oidc";
  Protocol2["OAUTH"] = "oauth";
  Protocol2["SAML"] = "saml";
  Protocol2["CAS"] = "cas";
  Protocol2["AZURE_AD"] = "azure-ad";
})(Protocol$1 || (Protocol$1 = {}));
var AppPasswordStrengthLimit;
(function(AppPasswordStrengthLimit2) {
  AppPasswordStrengthLimit2[AppPasswordStrengthLimit2["NoCheck"] = 0] = "NoCheck";
  AppPasswordStrengthLimit2[AppPasswordStrengthLimit2["Low"] = 1] = "Low";
  AppPasswordStrengthLimit2[AppPasswordStrengthLimit2["Middle"] = 2] = "Middle";
  AppPasswordStrengthLimit2[AppPasswordStrengthLimit2["High"] = 3] = "High";
})(AppPasswordStrengthLimit || (AppPasswordStrengthLimit = {}));
var RegisterMethods;
(function(RegisterMethods2) {
  RegisterMethods2["Email"] = "email";
  RegisterMethods2["Phone"] = "phone";
})(RegisterMethods || (RegisterMethods = {}));
var LoginMethods;
(function(LoginMethods2) {
  LoginMethods2["LDAP"] = "ldap";
  LoginMethods2["AppQr"] = "app-qrcode";
  LoginMethods2["Password"] = "password";
  LoginMethods2["PhoneCode"] = "phone-code";
  LoginMethods2["WxMinQr"] = "wechat-miniprogram-qrcode";
  LoginMethods2["AD"] = "ad";
})(LoginMethods || (LoginMethods = {}));
var OIDCConnectionMode;
(function(OIDCConnectionMode2) {
  OIDCConnectionMode2["FRONT_CHANNEL"] = "FRONT_CHANNEL";
  OIDCConnectionMode2["BACK_CHANNEL"] = "BACK_CHANNEL";
})(OIDCConnectionMode || (OIDCConnectionMode = {}));
var SceneType;
(function(SceneType2) {
  SceneType2["SCENE_TYPE_LOGIN"] = "login";
  SceneType2["SCENE_TYPE_REGISTER"] = "register";
  SceneType2["SCENE_TYPE_RESET"] = "reset";
  SceneType2["SCENE_TYPE_BIND"] = "bind";
  SceneType2["SCENE_TYPE_UNBIND"] = "unbind";
  SceneType2["SCENE_TYPE_MFA_BIND"] = "mfa-bind";
  SceneType2["SCENE_TYPE_MFA_VERIFY"] = "mfa-verify";
  SceneType2["SCENE_TYPE_MFA_UNBIND"] = "mfa-unbind";
  SceneType2["SCENE_TYPE_COMPLETE_PHONE"] = "complete-phone";
})(SceneType || (SceneType = {}));
var RelayMethodEnum;
(function(RelayMethodEnum2) {
  RelayMethodEnum2["WEB_MESSAGE"] = "web_message";
  RelayMethodEnum2["FORM_POST"] = "form_post";
  RelayMethodEnum2["QUERY"] = "query";
})(RelayMethodEnum || (RelayMethodEnum = {}));
var SigninByCredentialsConnection;
(function(SigninByCredentialsConnection2) {
  SigninByCredentialsConnection2["PASSWORD"] = "PASSWORD";
  SigninByCredentialsConnection2["PASSCODE"] = "PASSCODE";
  SigninByCredentialsConnection2["LDAP"] = "LDAP";
  SigninByCredentialsConnection2["AD"] = "AD";
})(SigninByCredentialsConnection || (SigninByCredentialsConnection = {}));
var PasswordEncryptType;
(function(PasswordEncryptType2) {
  PasswordEncryptType2["SM2"] = "sm2";
  PasswordEncryptType2["RSA"] = "rsa";
  PasswordEncryptType2["NONE"] = "none";
})(PasswordEncryptType || (PasswordEncryptType = {}));
var SignInResponseType;
(function(SignInResponseType2) {
  SignInResponseType2["IdTokenToken"] = "id_token token";
  SignInResponseType2["Code"] = "code";
})(SignInResponseType || (SignInResponseType = {}));
var tokenKey = "_authing_token";
var userKey = "_authing_user";
var AuthenticationTokenProvider = (
  /** @class */
  function() {
    function AuthenticationTokenProvider2(options2) {
      this.options = options2;
      this.token = null;
      this.user = null;
    }
    AuthenticationTokenProvider2.prototype.setToken = function(token) {
      if (typeof localStorage !== "undefined") {
        localStorage.setItem(tokenKey, token);
      } else {
        this.token = token;
      }
    };
    AuthenticationTokenProvider2.prototype.getToken = function() {
      if (typeof localStorage !== "undefined") {
        var token = localStorage.getItem(tokenKey);
        if (token === "null" || token === "undefined") {
          return null;
        }
        return token;
      }
      return this.token;
    };
    AuthenticationTokenProvider2.prototype.getUser = function() {
      return typeof localStorage !== "undefined" ? localStorage.getItem(userKey) ? JSON.parse(localStorage.getItem(userKey)) : null : this.user;
    };
    AuthenticationTokenProvider2.prototype.setUser = function(user2) {
      if (typeof localStorage !== "undefined") {
        localStorage.setItem(userKey, JSON.stringify(user2));
        localStorage.setItem(tokenKey, user2.token);
      } else {
        this.user = user2;
        this.token = user2.token;
      }
    };
    AuthenticationTokenProvider2.prototype.clearUser = function() {
      if (typeof localStorage !== "undefined") {
        localStorage.removeItem(userKey);
        localStorage.removeItem(tokenKey);
      } else {
        this.user = null;
        this.token = null;
      }
    };
    return AuthenticationTokenProvider2;
  }()
);
var sha256Exports = requireSha256();
const sha256 = /* @__PURE__ */ getDefaultExportFromCjs$1(sha256Exports);
var __awaiter$7 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$7 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var roundedImage = function(context2D, x2, y2, width, height, radius) {
  context2D.beginPath();
  context2D.moveTo(x2 + radius, y2);
  context2D.lineTo(x2 + width - radius, y2);
  context2D.quadraticCurveTo(x2 + width, y2, x2 + width, y2 + radius);
  context2D.lineTo(x2 + width, y2 + height - radius);
  context2D.quadraticCurveTo(x2 + width, y2 + height, x2 + width - radius, y2 + height);
  context2D.lineTo(x2 + radius, y2 + height);
  context2D.quadraticCurveTo(x2, y2 + height, x2, y2 + height - radius);
  context2D.lineTo(x2, y2 + radius);
  context2D.quadraticCurveTo(x2, y2, x2 + radius, y2);
  context2D.closePath();
};
var getOffset = function(size) {
  var containerHalfWidth = size.width / 2;
  var containerHalfHeight = size.height / 2;
  var ww = size.width / 2.4;
  var hh = size.height / 2.4;
  var logoHalfWidth = ww / 2;
  var logoHalfHeight = hh / 2;
  return {
    x: containerHalfWidth - logoHalfWidth,
    y: containerHalfHeight - logoHalfHeight,
    ww,
    hh
  };
};
var QrCodeAuthenticationClient = (
  /** @class */
  function() {
    function QrCodeAuthenticationClient2(options2, tokenProvider, httpClient, scene) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
      this.scene = scene;
      this.baseClient = new BaseAuthenticationClient(options2);
    }
    QrCodeAuthenticationClient2.prototype.startScanning = function(domId, options2) {
      return __awaiter$7(this, void 0, void 0, function() {
        function genRetry(qrcodeElm, tipText, retryId) {
          return __awaiter$7(this, void 0, void 0, function() {
            var tip, qrcodeImage, shadow, dom;
            return __generator$7(this, function(_a4) {
              switch (_a4.label) {
                case 0:
                  tip = genTip(tipText);
                  nodeWrapper = document.createElement("div");
                  nodeWrapper.id = "authing__qrcode-wrapper";
                  nodeWrapper.style.textAlign = "center";
                  nodeWrapper.style.position = "relative";
                  return [4, genImage("https://usercontents.authing.cn/0ab3a1bf19c0d7106673e494d532f91a.png")];
                case 1:
                  qrcodeImage = _a4.sent();
                  if (!needGenerate) {
                    qrcodeImage.style.marginTop = "12px";
                  } else {
                    qrcodeImage.style.marginTop = "16px";
                  }
                  qrcodeImage.onload = function() {
                    unloading();
                  };
                  shadow = genShadow(retry, function() {
                    if (onRetry) {
                      onRetry();
                    }
                    start();
                  }, "__authing_retry_btn");
                  nodeWrapper.appendChild(qrcodeImage);
                  nodeWrapper.appendChild(shadow);
                  nodeWrapper.appendChild(tip);
                  dom = document.querySelector("#authing__qrcode-wrapper");
                  if (dom)
                    dom.remove();
                  qrcodeElm.appendChild(nodeWrapper);
                  return [
                    2
                    /*return*/
                  ];
              }
            });
          });
        }
        var _a3, autoExchangeUserInfo, _b2, size, _c2, containerSize, _d2, interval, onStart, onResult, onScanned, onExpired, onSuccess, onCancel, onError, onCodeShow, onCodeLoaded, onCodeLoadFailed, onRetry, onMfa, onAuthFlow, _e2, tips, context, customData, extIdpConnId, withCustomData, lang, nowLang, _f2, title2, _h2, expired, _j2, succeed, _k2, retry, _l2, middleTitle, _m2, referText, node2, nodeWrapper, needGenerate, styleNode, style, loading, unloading, genTip, editTipText, genImage, genLogoInCenter, genShadowMiddleStatus, genReferTextNode, removeReferTextNode, genShadow, displayScannedUser, start;
        var _this = this;
        return __generator$7(this, function(_o) {
          options2 = options2 || {};
          _a3 = options2.autoExchangeUserInfo, autoExchangeUserInfo = _a3 === void 0 ? false : _a3, _b2 = options2.size, size = _b2 === void 0 ? {
            height: 240,
            width: 240
          } : _b2, _c2 = options2.containerSize, containerSize = _c2 === void 0 ? {
            height: 300,
            width: 300
          } : _c2, _d2 = options2.interval, interval = _d2 === void 0 ? 800 : _d2, onStart = options2.onStart, onResult = options2.onResult, onScanned = options2.onScanned, onExpired = options2.onExpired, onSuccess = options2.onSuccess, onCancel = options2.onCancel, onError = options2.onError, onCodeShow = options2.onCodeShow, onCodeLoaded = options2.onCodeLoaded, onCodeLoadFailed = options2.onCodeLoadFailed, onRetry = options2.onRetry, onMfa = options2.onMfa, onAuthFlow = options2.onAuthFlow, _e2 = options2.tips, tips = _e2 === void 0 ? {} : _e2, context = options2.context, customData = options2.customData, extIdpConnId = options2.extIdpConnId, withCustomData = options2.withCustomData;
          lang = this.options.lang;
          nowLang = lang === "zh-CN";
          _f2 = tips.title, title2 = _f2 === void 0 ? nowLang ? "请在移动端确认账号登录" : "Please be on the mobile" : _f2, tips.canceled, _h2 = tips.expired, expired = _h2 === void 0 ? nowLang ? "二维码已过期" : "QR code has expired" : _h2, _j2 = tips.succeed, succeed = _j2 === void 0 ? nowLang ? "扫码成功" : "Scan code successfully" : _j2, _k2 = tips.retry, retry = _k2 === void 0 ? nowLang ? "重试" : "Retry" : _k2, _l2 = tips.middleTitle, middleTitle = _l2 === void 0 ? nowLang ? "确认登录" : "Confirm login" : _l2, _m2 = tips.referText, referText = _m2 === void 0 ? nowLang ? "重新扫码" : "Scan the code" : _m2;
          node2 = document.getElementById(domId);
          needGenerate = false;
          if (!node2) {
            node2 = document.createElement("div");
            node2.id = domId;
            createCssClassStyleSheet("__authing-qrcode-node-mount", "z-index: 65535;position: fixed;background: #fff;width: ".concat(containerSize.width, "px;height: ").concat(containerSize.height, "px;left: 50%;margin-left: -").concat(containerSize.width / 2, "px;display: flex;justify-content: center;align-items: center;top: 50%;margin-top: -").concat(containerSize.height / 2, "px;border: 1px solid #ccc;"));
            node2.classList.add("__authing-qrcode-node-mount");
            document.getElementsByTagName("body")[0].appendChild(node2);
            needGenerate = true;
          } else {
            node2.style.position = "relative";
          }
          styleNode = document.createElement("style");
          style = "#authing__retry a:hover{outline:0px;text-decoration:none;}#authing__spinner{position:absolute;left:50%;margin-left:-6px;}.spinner{margin:100px auto;width:20px;height:20px;position:relative}.container1>div,.container2>div,.container3>div{width:6px;height:6px;background-color:#00a1ea;border-radius:100%;position:absolute;-webkit-animation:bouncedelay 1.2s infinite ease-in-out;animation:bouncedelay 1.2s infinite ease-in-out;-webkit-animation-fill-mode:both;animation-fill-mode:both}.spinner .spinner-container{position:absolute;width:100%;height:100%}.container2{-webkit-transform:rotateZ(45deg);transform:rotateZ(45deg)}.container3{-webkit-transform:rotateZ(90deg);transform:rotateZ(90deg)}.circle1{top:0;left:0}.circle2{top:0;right:0}.circle3{right:0;bottom:0}.circle4{left:0;bottom:0}.container2 .circle1{-webkit-animation-delay:-1.1s;animation-delay:-1.1s}.container3 .circle1{-webkit-animation-delay:-1.0s;animation-delay:-1.0s}.container1 .circle2{-webkit-animation-delay:-0.9s;animation-delay:-0.9s}.container2 .circle2{-webkit-animation-delay:-0.8s;animation-delay:-0.8s}.container3 .circle2{-webkit-animation-delay:-0.7s;animation-delay:-0.7s}.container1 .circle3{-webkit-animation-delay:-0.6s;animation-delay:-0.6s}.container2 .circle3{-webkit-animation-delay:-0.5s;animation-delay:-0.5s}.container3 .circle3{-webkit-animation-delay:-0.4s;animation-delay:-0.4s}.container1 .circle4{-webkit-animation-delay:-0.3s;animation-delay:-0.3s}.container2 .circle4{-webkit-animation-delay:-0.2s;animation-delay:-0.2s}.container3 .circle4{-webkit-animation-delay:-0.1s;animation-delay:-0.1s}@-webkit-keyframes bouncedelay{0%,80%,100%{-webkit-transform:scale(0.0)}40%{-webkit-transform:scale(1.0)}}@keyframes bouncedelay{0%,80%,100%{transform:scale(0.0);-webkit-transform:scale(0.0)}40%{transform:scale(1.0);-webkit-transform:scale(1.0)}}";
          styleNode.type = "text/css";
          if (styleNode.style) {
            styleNode.style.cssText = style;
          } else {
            styleNode.innerHTML = style;
          }
          document.getElementsByTagName("head")[0].appendChild(styleNode);
          loading = function() {
            node2.innerHTML = '<div id="authing__spinner" class="spinner"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div>';
          };
          unloading = function() {
            var child = document.getElementById("authing__spinner");
            if (child)
              node2.removeChild(child);
          };
          genTip = function(text) {
            var formattedText;
            try {
              formattedText = JSON.parse(text).message || text;
            } catch (e4) {
              formattedText = text;
            }
            var tip = document.createElement("span");
            tip.className = "authing__heading-subtitle";
            if (!needGenerate) {
              createCssClassStyleSheet("__authing__heading-subtitle-style", "display: block;font-weight: 400;font-size: 15px;color: #888;line-height: 20px;margin-top: 8px;");
              tip.classList.add("__authing__heading-subtitle-style");
            } else {
              createCssClassStyleSheet("__authing__heading-subtitle-style", "display: block;font-weight: 400;font-size: 12px;color: #888;");
              tip.classList.add("__authing__heading-subtitle-style");
            }
            tip.id = "authing__qrcode-tip-text";
            tip.innerHTML = formattedText;
            return tip;
          };
          editTipText = function(text) {
            var el = document.getElementById("authing__qrcode-tip-text");
            if (el) {
              el.innerText = text;
            }
          };
          genImage = function(src2) {
            return new Promise(function(resolve2) {
              var qrcodeImage = document.createElement("img");
              qrcodeImage.src = src2;
              qrcodeImage.width = size.width;
              qrcodeImage.height = size.height;
              qrcodeImage.setAttribute("crossOrigin", "Anonymous");
              qrcodeImage.onload = function() {
                resolve2(qrcodeImage);
              };
            });
          };
          genLogoInCenter = function(logo) {
            return new Promise(function(resolve2) {
              var qrcodeLogo = document.createElement("img");
              qrcodeLogo.src = logo;
              qrcodeLogo.setAttribute("crossOrigin", "Anonymous");
              qrcodeLogo.width = size.width / 2.4;
              qrcodeLogo.height = size.height / 2.4;
              qrcodeLogo.onload = function() {
                qrcodeLogo.style.display = "inline";
                resolve2(qrcodeLogo);
              };
              qrcodeLogo.onerror = function() {
                resolve2(qrcodeLogo);
              };
            });
          };
          genShadowMiddleStatus = function(text) {
            editTipText(middleTitle);
            var successWrapper = document.createElement("div");
            createCssClassStyleSheet("__authing-shadow-inner-style-position", "position:absolute;top:56%;left:50%;\n         width:64px;transform:translate(-50%,-50%);\n        background-position:center center;\n      align-items: center; /*垂直居中*/\n      justify-content: center; /*水平居中*/");
            successWrapper.classList.add("__authing-shadow-inner-style-position");
            var successImage = document.createElement("div");
            createCssClassStyleSheet("__authing-shadow-inner-image-style-position", "width:64px;height:64px;opacity:1;\n        background-position:center center;background-repeat:no-repeat;\n        background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTQiIGhlaWdodD0iNTQiIHZpZXdCb3g9IjAgMCA1NCA1NCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTI3IDUzLjY2NjdDMTIuMjcyIDUzLjY2NjcgMC4zMzMzNzQgNDEuNzI4IDAuMzMzMzc0IDI3QzAuMzMzMzc0IDEyLjI3MiAxMi4yNzIgMC4zMzMzMzIgMjcgMC4zMzMzMzJDNDEuNzI4IDAuMzMzMzMyIDUzLjY2NjcgMTIuMjcyIDUzLjY2NjcgMjdDNTMuNjY2NyA0MS43MjggNDEuNzI4IDUzLjY2NjcgMjcgNTMuNjY2N1pNMjQuMzQxNCAzNy42NjY3TDQzLjE5NDcgMTguODEwN0wzOS40MjQgMTUuMDRMMjQuMzQxNCAzMC4xMjUzTDE2Ljc5NzQgMjIuNTgxM0wxMy4wMjY3IDI2LjM1MkwyNC4zNDE0IDM3LjY2NjdaIiBmaWxsPSIjMUVCNzZEIi8+Cjwvc3ZnPgo=);\n        margin-bottom: 10px;\n      align-items: center; /*垂直居中*/\n      justify-content: center; /*水平居中*/");
            successImage.classList.add("__authing-shadow-inner-image-style-position");
            successImage.id = "authing_scan_success_image";
            var successTextNode = document.createElement("p");
            createCssClassStyleSheet("__authing-shadow-inner-text-style-position", "font-weight: 400;font-size: 14px;line-height: 20px;color: #282D3C;;align-items: center; /*垂直居中*/justify-content: center; /*水平居中*/");
            successTextNode.classList.add("__authing-shadow-inner-text-style-position");
            successTextNode.id = "authing_scan_success_text";
            successTextNode.innerText = text;
            successWrapper.appendChild(successImage);
            successWrapper.appendChild(successTextNode);
            return successWrapper;
          };
          genReferTextNode = function(text) {
            var referTextNode = document.createElement("p");
            createCssClassStyleSheet("__authing-shadow-inner-refer-text-style-position", "color: #215AE5;font-size: 14px;line-height:20px;font-weight: 400; text-align:center;cursor:pointer;padding-top:4px;");
            referTextNode.classList.add("__authing-shadow-inner-refer-text-style-position");
            referTextNode.id = "authing_scan_success_refer_text";
            referTextNode.innerText = text;
            referTextNode.onclick = function() {
              if (_this.timer) {
                clearInterval(_this.timer);
              }
              if (onRetry) {
                onRetry();
              }
              start();
            };
            return referTextNode;
          };
          removeReferTextNode = function() {
            var id = "authing_scan_success_refer_text";
            var dom = document.getElementById(id);
            if (dom) {
              dom.parentNode.removeChild(dom);
            }
          };
          genShadow = function(text, aOnClick, shadowAId) {
            var shadowId = "authing__retry";
            if (document.getElementById(shadowId)) {
              document.getElementById(shadowId).remove();
            }
            var shadow = document.createElement("div");
            shadow.id = shadowId;
            createCssClassStyleSheet("__authing-shadow-style", "text-align:center;width: ".concat(size.width, "px;height: ").concat(size.height, "px;position: absolute;left: 50%;top: 0px;margin-left: -").concat(size.width / 2, "px;background-color: rgba(0,0,0, 0.5);line-height:").concat(size.height, "px;color:#fff;font-weight:600;"));
            shadow.classList.add("__authing-shadow-style");
            var shadowA = document.createElement("a");
            shadowA.innerHTML = text;
            shadowA.style.color = "#fff";
            shadowA.style.borderBottom = "1px solid #fff";
            shadowA.style.cursor = "pointer";
            if (aOnClick) {
              shadowA.addEventListener("click", aOnClick);
            }
            shadowA.id = shadowAId;
            shadow.appendChild(shadowA);
            return shadow;
          };
          displayScannedUser = function(_2) {
            var shadowId = "authing__retry";
            if (document.getElementById(shadowId)) {
              document.getElementById(shadowId).remove();
            }
            var shadow = document.createElement("div");
            createCssClassStyleSheet("__authing-shadow-style-position", "text-align:center;width:".concat(size.width, "px;height: ").concat(size.height, "px;background:rgba(255,255,255,.97);position: absolute;left: 50%;top: 0px;margin-left: -").concat(size.width / 2, "px;line-height:").concat(size.height, "px;color:#fff;font-weight:600;display: flex;\n      align-items: center; /*垂直居中*/\n      justify-content: center; /*水平居中*/"));
            shadow.classList.add("__authing-shadow-style-position");
            shadow.id = shadowId;
            var successWrapper = genShadowMiddleStatus(succeed);
            var referTextNode = genReferTextNode(referText);
            nodeWrapper.appendChild(referTextNode);
            shadow.appendChild(successWrapper);
            return shadow;
          };
          start = function() {
            return __awaiter$7(_this, void 0, void 0, function() {
              var random, url, logo, data2, error_1, qrcodeImage, qrcodeLogo, canvas, context2D, _a4, x2, y2, ww, hh, base64, img, decoratedOnSuccess, decoratedOnScanned, decoratedOnCancel, decoratedOnExpired, decoratedOnError, tip, dom;
              var _this2 = this;
              return __generator$7(this, function(_b3) {
                switch (_b3.label) {
                  case 0:
                    loading();
                    random = null;
                    url = null;
                    logo = null;
                    _b3.label = 1;
                  case 1:
                    _b3.trys.push([1, 3, , 4]);
                    return [4, this.geneCode({
                      context,
                      customData,
                      extIdpConnId,
                      withCustomData
                    })];
                  case 2:
                    data2 = _b3.sent();
                    random = data2.random;
                    url = data2.url;
                    logo = data2.customLogo;
                    return [3, 4];
                  case 3:
                    error_1 = _b3.sent();
                    error_1 = error_1;
                    genRetry(node2, error_1.message);
                    if (onCodeLoadFailed) {
                      onCodeLoadFailed(error_1);
                    }
                    return [
                      2
                      /*return*/
                    ];
                  case 4:
                    if (onCodeLoaded) {
                      onCodeLoaded(random, url);
                    }
                    nodeWrapper = document.createElement("div");
                    nodeWrapper.id = "authing__qrcode-wrapper";
                    nodeWrapper.style.textAlign = "center";
                    nodeWrapper.style.position = "relative";
                    nodeWrapper.style.margin = "auto";
                    return [4, genImage(url)];
                  case 5:
                    qrcodeImage = _b3.sent();
                    if (!logo) return [3, 7];
                    return [4, genLogoInCenter(logo)];
                  case 6:
                    qrcodeLogo = _b3.sent();
                    _b3.label = 7;
                  case 7:
                    canvas = document.createElement("canvas");
                    canvas.width = size.width;
                    canvas.height = size.height;
                    context2D = canvas.getContext("2d");
                    url && context2D.drawImage(qrcodeImage, 0, 0, size.width, size.height);
                    _a4 = getOffset(size), x2 = _a4.x, y2 = _a4.y, ww = _a4.ww, hh = _a4.hh;
                    context2D.save();
                    roundedImage(context2D, x2, y2, ww, hh, ww / 2);
                    context2D.clip();
                    try {
                      qrcodeLogo && context2D.drawImage(qrcodeLogo, x2, y2, ww, hh);
                    } catch (_c3) {
                      console.log("Draw stop, check qrcodeLogo", qrcodeLogo);
                    }
                    context2D.restore();
                    try {
                      base64 = canvas.toDataURL();
                      img = document.createElement("img");
                      img.src = base64;
                      nodeWrapper.appendChild(img);
                    } catch (_d3) {
                      nodeWrapper.appendChild(canvas);
                    }
                    unloading();
                    if (onCodeShow) {
                      onCodeShow(random, url);
                    }
                    decoratedOnSuccess = function(userInfo, ticket) {
                      editTipText("");
                      removeReferTextNode();
                      var shadow = genShadow(succeed, null, "__authing_success_tip");
                      nodeWrapper.appendChild(shadow);
                      if (onSuccess) {
                        if (autoExchangeUserInfo) {
                          var token = userInfo.token;
                          if (!token) {
                            _this2.exchangeUserInfo(ticket).then(function(userInfo2) {
                              _this2.tokenProvider.setUser(userInfo2);
                              onSuccess(userInfo2, ticket);
                            });
                          } else {
                            onSuccess(userInfo, ticket);
                          }
                        } else {
                          onSuccess(userInfo, ticket);
                        }
                      }
                    };
                    decoratedOnScanned = function(userInfo) {
                      var shadow = displayScannedUser(userInfo.nickname);
                      nodeWrapper.appendChild(shadow);
                      if (onScanned) {
                        onScanned(userInfo);
                      }
                    };
                    decoratedOnCancel = function() {
                      if (start) {
                        start();
                      }
                      if (onCancel) {
                        onCancel();
                      }
                    };
                    decoratedOnExpired = function() {
                      var shadow = genShadow(expired, function() {
                        nodeWrapper.innerHTML = "";
                        start();
                      }, "__authing_success_tip");
                      nodeWrapper.appendChild(shadow);
                      if (onExpired) {
                        onExpired();
                      }
                    };
                    decoratedOnError = function(data3) {
                      var message = data3.message;
                      if (onError) {
                        onError(message);
                      }
                    };
                    this.startPolling(random, {
                      interval,
                      onStart,
                      onResult,
                      onScanned: decoratedOnScanned,
                      onExpired: decoratedOnExpired,
                      onSuccess: decoratedOnSuccess,
                      onCancel: decoratedOnCancel,
                      onError: decoratedOnError,
                      onMfa,
                      onAuthFlow
                    });
                    tip = genTip(title2);
                    nodeWrapper.appendChild(tip);
                    dom = document.querySelector("#authing__qrcode-wrapper");
                    if (dom)
                      dom.remove();
                    node2.appendChild(nodeWrapper);
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          };
          start();
          return [
            2
            /*return*/
          ];
        });
      });
    };
    QrCodeAuthenticationClient2.prototype.geneCode = function(options2) {
      return __awaiter$7(this, void 0, void 0, function() {
        var _a3, context, customData, extIdpConnId, withCustomData, api2, data2;
        return __generator$7(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              _a3 = options2 || {}, context = _a3.context, customData = _a3.customData, extIdpConnId = _a3.extIdpConnId, withCustomData = _a3.withCustomData;
              api2 = "".concat(this.baseClient.appHost, "/api/v2/qrcode/gene");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  autoMergeQrCode: false,
                  scene: this.scene,
                  context,
                  params: customData,
                  extIdpConnId,
                  withCustomData
                }
              })];
            case 1:
              data2 = _b2.sent();
              return [2, data2];
          }
        });
      });
    };
    QrCodeAuthenticationClient2.prototype.checkStatus = function(random) {
      return __awaiter$7(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$7(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/qrcode/check?random=").concat(random);
              return [4, this.httpClient.request({
                method: "GET",
                url: api2
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    QrCodeAuthenticationClient2.prototype.exchangeUserInfo = function(ticket) {
      return __awaiter$7(this, void 0, void 0, function() {
        var api2, userInfo;
        return __generator$7(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/qrcode/userinfo");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  ticket
                }
              })];
            case 1:
              userInfo = _a3.sent();
              return [2, userInfo];
          }
        });
      });
    };
    QrCodeAuthenticationClient2.prototype.startPolling = function(random, options2) {
      return __awaiter$7(this, void 0, void 0, function() {
        var _a3, interval, onStart, onResult, onScanned, onExpired, onSuccess, onCancel, onError, onMfa, onAuthFlow, calledOnScanned, callOnPoolingStart, timer;
        var _this = this;
        return __generator$7(this, function(_b2) {
          options2 = options2 || {};
          _a3 = options2.interval, interval = _a3 === void 0 ? 800 : _a3, onStart = options2.onStart, onResult = options2.onResult, onScanned = options2.onScanned, onExpired = options2.onExpired, onSuccess = options2.onSuccess, onCancel = options2.onCancel, onError = options2.onError, onMfa = options2.onMfa, onAuthFlow = options2.onAuthFlow;
          calledOnScanned = false;
          callOnPoolingStart = false;
          timer = this.timer = setInterval(function() {
            return __awaiter$7(_this, void 0, void 0, function() {
              var data2, status_1, ticket, userInfo, scannedResult, code, message, mfaData, scannedResult, scannedResult, errmsg, error_2;
              return __generator$7(this, function(_a4) {
                switch (_a4.label) {
                  case 0:
                    if (onStart && !callOnPoolingStart) {
                      onStart(timer);
                      callOnPoolingStart = true;
                    }
                    _a4.label = 1;
                  case 1:
                    _a4.trys.push([1, 3, , 4]);
                    return [4, this.checkStatus(random)];
                  case 2:
                    data2 = _a4.sent();
                    status_1 = data2.status, ticket = data2.ticket, userInfo = data2.userInfo;
                    if (onResult) {
                      onResult(data2);
                    }
                    if (status_1 === -1) {
                      clearInterval(timer);
                      if (onExpired) {
                        onExpired();
                      }
                    }
                    if (status_1 === 1) {
                      if (onScanned && !calledOnScanned) {
                        onScanned(userInfo);
                        calledOnScanned = true;
                      }
                    }
                    if (status_1 === 2) {
                      clearInterval(timer);
                      if (onSuccess) {
                        onSuccess(userInfo, ticket);
                      }
                    }
                    if (status_1 === 3) {
                      clearInterval(timer);
                      if (onCancel) {
                        onCancel();
                      }
                    }
                    if (status_1 === 4) {
                      clearInterval(timer);
                      if (onMfa) {
                        scannedResult = data2.scannedResult;
                        code = scannedResult.code, message = scannedResult.message, mfaData = scannedResult.data;
                        onMfa(code, message, mfaData);
                      }
                      if (onAuthFlow) {
                        scannedResult = data2.scannedResult;
                        onAuthFlow(scannedResult);
                      }
                    }
                    if (status_1 === 5) {
                      clearInterval(timer);
                      if (onError) {
                        scannedResult = data2.scannedResult;
                        errmsg = scannedResult.errmsg;
                        onError(errmsg);
                      }
                    }
                    return [3, 4];
                  case 3:
                    error_2 = _a4.sent();
                    if (onError) {
                      onError(error_2);
                    }
                    clearInterval(timer);
                    return [
                      2
                      /*return*/
                    ];
                  case 4:
                    return [
                      2
                      /*return*/
                    ];
                }
              });
            });
          }, interval);
          return [2, timer];
        });
      });
    };
    QrCodeAuthenticationClient2.prototype.stopPolling = function(timer) {
      return __awaiter$7(this, void 0, void 0, function() {
        return __generator$7(this, function(_a3) {
          clearInterval(timer);
          return [
            2
            /*return*/
          ];
        });
      });
    };
    return QrCodeAuthenticationClient2;
  }()
);
var __assign$1 = function() {
  __assign$1 = Object.assign || function(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
        t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign$1.apply(this, arguments);
};
var __awaiter$6 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$6 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var BrowserFingerprintClient = (
  /** @class */
  function() {
    function BrowserFingerprintClient2(options2, httpClient) {
      this.baseClient = new BaseAuthenticationClient(options2);
      this.options = options2;
      this.httpClient = httpClient;
    }
    BrowserFingerprintClient2.prototype.getBrowserFingers = function() {
      return __awaiter$6(this, void 0, void 0, function() {
        var localBrowserId, localDeviceFingers, localDeviceFingersObj, _a3, browserId, deviceFingers;
        return __generator$6(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              localBrowserId = localStorage.getItem("browserId");
              localDeviceFingers = localStorage.getItem("deviceFingers");
              localDeviceFingersObj = localDeviceFingers && JSON.parse(localDeviceFingers);
              if (!(!localBrowserId || !localDeviceFingers)) return [3, 2];
              return [4, createFingerprint()];
            case 1:
              _a3 = _b2.sent(), browserId = _a3.browserId, deviceFingers = _a3.deviceFingers;
              localBrowserId = browserId;
              localDeviceFingersObj = deviceFingers;
              _b2.label = 2;
            case 2:
              return [2, { browserId: localBrowserId, deviceFingers: handleFingerprint(localDeviceFingersObj) }];
          }
        });
      });
    };
    BrowserFingerprintClient2.prototype.getDeviceInfo = function() {
      return __awaiter$6(this, void 0, void 0, function() {
        var browserFingers;
        return __generator$6(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.getBrowserFingers()];
            case 1:
              browserFingers = _a3.sent();
              return [2, __assign$1({}, browserFingers)];
          }
        });
      });
    };
    BrowserFingerprintClient2.prototype.createDevice = function() {
      var _a3;
      return __awaiter$6(this, void 0, void 0, function() {
        var _b2, browserId, deviceFingers, browserFingers, BrowserInfo;
        return __generator$6(this, function(_c2) {
          switch (_c2.label) {
            case 0:
              _c2.trys.push([0, 4, , 5]);
              return [4, this.getBrowserFingers()];
            case 1:
              _b2 = _c2.sent(), browserId = _b2.browserId, deviceFingers = _b2.deviceFingers;
              browserFingers = __assign$1({ browserId }, deviceFingers);
              return [4, BrowserInfoFun()];
            case 2:
              BrowserInfo = _c2.sent();
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v3/create-device"),
                data: __assign$1(__assign$1({ deviceUniqueId: browserFingers.browserId, name: (_a3 = getBrowserInfo()) === null || _a3 === void 0 ? void 0 : _a3.toString() }, BrowserInfo), browserFingers)
              })];
            case 3:
              _c2.sent();
              return [2, true];
            case 4:
              _c2.sent();
              return [2, false];
            case 5:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    BrowserFingerprintClient2.prototype.myDevicesList = function() {
      return __awaiter$6(this, void 0, void 0, function() {
        var data2;
        return __generator$6(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v3/mydevices/list")
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    BrowserFingerprintClient2.prototype.myDevicesUnbind = function(deviceId) {
      return __awaiter$6(this, void 0, void 0, function() {
        return __generator$6(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              _a3.trys.push([0, 2, , 3]);
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v3/mydevices/unbind"),
                data: { deviceId }
              })];
            case 1:
              _a3.sent();
              return [2, true];
            case 2:
              _a3.sent();
              return [2, false];
            case 3:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    BrowserFingerprintClient2.prototype.myDevicesLogout = function(deviceId) {
      return __awaiter$6(this, void 0, void 0, function() {
        return __generator$6(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              _a3.trys.push([0, 2, , 3]);
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v3/mydevices/revoke-session"),
                data: { deviceId }
              })];
            case 1:
              _a3.sent();
              return [2, true];
            case 2:
              _a3.sent();
              return [2, false];
            case 3:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    return BrowserFingerprintClient2;
  }()
);
var __awaiter$5 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$5 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var MfaAuthenticationClient = (
  /** @class */
  function() {
    function MfaAuthenticationClient2(options2, tokenProvider, httpClient) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
      this.baseClient = new BaseAuthenticationClient(options2);
    }
    MfaAuthenticationClient2.prototype.getMfaAuthenticators = function(options2) {
      if (options2 === void 0) {
        options2 = { type: "totp", source: "SELF" };
      }
      return __awaiter$5(this, void 0, void 0, function() {
        var type2, mfaToken, source, api2, headers, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              type2 = options2.type, mfaToken = options2.mfaToken, source = options2.source;
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/authenticator");
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              return [4, this.httpClient.request({
                method: "GET",
                url: api2,
                params: {
                  type: type2,
                  source
                },
                headers
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.assosicateMfaAuthenticator = function(options2) {
      if (options2 === void 0) {
        options2 = { authenticatorType: "totp", source: "SELF" };
      }
      return __awaiter$5(this, void 0, void 0, function() {
        var authenticatorType, mfaToken, source, headers, api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              authenticatorType = options2.authenticatorType, mfaToken = options2.mfaToken, source = options2.source;
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/totp/associate");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  authenticator_type: authenticatorType,
                  source
                },
                headers
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.deleteMfaAuthenticator = function() {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/totp/associate");
              return [4, this.httpClient.request({
                method: "DELETE",
                url: api2
              })];
            case 1:
              _a3.sent();
              return [2, {
                code: 200,
                message: "TOTP MFA 解绑成功"
              }];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.confirmAssosicateMfaAuthenticator = function(options2) {
      if (options2 === void 0) {
        options2 = { authenticatorType: "totp", source: "SELF" };
      }
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, authenticatorType, totp, source, mfaToken, headers;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/totp/associate/confirm");
              authenticatorType = options2.authenticatorType, totp = options2.totp, source = options2.source, mfaToken = options2.mfaToken;
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  authenticator_type: authenticatorType,
                  totp,
                  source
                }
              })];
            case 1:
              _a3.sent();
              return [2, { code: 200, message: "TOTP MFA 绑定成功" }];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.verifyTotpMfa = function(options2) {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/totp/verify");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  totp: options2.totp
                },
                headers: {
                  authorization: "Bearer " + options2.mfaToken
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.verifyAppSmsMfa = function(options2) {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/applications/mfa/sms/verify");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  phone: options2.phone,
                  code: options2.code,
                  phoneCountryCode: options2.phoneCountryCode
                },
                headers: {
                  authorization: "Bearer " + options2.mfaToken
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.verifyAppEmailMfa = function(options2) {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/applications/mfa/email/verify");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  email: options2.email,
                  code: options2.code
                },
                headers: {
                  authorization: "Bearer " + options2.mfaToken
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.phoneOrEmailBindable = function(_a3) {
      var phone = _a3.phone, email = _a3.email, mfaToken = _a3.mfaToken;
      return __awaiter$5(this, void 0, void 0, function() {
        var api2;
        return __generator$5(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/applications/mfa/check");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  email,
                  phone
                },
                headers: {
                  authorization: "Bearer " + mfaToken
                }
              })];
            case 1:
              return [2, _b2.sent()];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.verifyTotpRecoveryCode = function(options2) {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/totp/recovery");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  recoveryCode: options2.recoveryCode
                },
                headers: {
                  authorization: "Bearer " + options2.mfaToken
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.associateFaceByUrl = function(options2) {
      return __awaiter$5(this, void 0, void 0, function() {
        var baseFace, compareFace, mfaToken, headers, api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              baseFace = options2.baseFace, compareFace = options2.compareFace, mfaToken = options2.mfaToken;
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/face/associate");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  photoA: baseFace,
                  photoB: compareFace,
                  isExternal: true
                },
                headers
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.associateFaceByLocalFile = function(mfaToken) {
      return __awaiter$5(this, void 0, void 0, function() {
        var headers, uploadedKey, key2, e_1, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              _a3.label = 1;
            case 1:
              _a3.trys.push([1, 3, , 4]);
              return [4, uploadFile({
                // 阿里云支持这些
                accept: ".jpeg,.jpg,.png,.bmp",
                url: "".concat(this.baseClient.appHost, "/api/v2/upload?folder=face-photo&private=true")
              })];
            case 2:
              key2 = _a3.sent().key;
              uploadedKey = key2;
              return [3, 4];
            case 3:
              e_1 = _a3.sent();
              this.options.onError(e_1.code, e_1.message);
              return [3, 4];
            case 4:
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v2/mfa/face/associate"),
                data: {
                  photoA: uploadedKey,
                  photoB: uploadedKey
                },
                headers
              })];
            case 5:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.associateFaceByBlob = function(opts) {
      return __awaiter$5(this, void 0, void 0, function() {
        var baseFace, compareFace, mfaToken, headers, photoA, photoB, uploadUrl, keyA, keyB, e_2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              baseFace = opts.baseFace, compareFace = opts.compareFace, mfaToken = opts.mfaToken;
              headers = {};
              if (mfaToken) {
                headers.authorization = "Bearer ".concat(mfaToken);
              }
              uploadUrl = "".concat(this.baseClient.appHost, "/api/v2/upload?folder=face-photo&private=true");
              _a3.label = 1;
            case 1:
              _a3.trys.push([1, 6, , 7]);
              return [4, xhrUpload(baseFace, uploadUrl)];
            case 2:
              keyA = _a3.sent().key;
              photoA = keyA;
              if (!compareFace) return [3, 4];
              return [4, xhrUpload(compareFace, uploadUrl)];
            case 3:
              keyB = _a3.sent().key;
              photoB = keyB;
              return [3, 5];
            case 4:
              photoB = keyA;
              _a3.label = 5;
            case 5:
              return [3, 7];
            case 6:
              e_2 = _a3.sent();
              this.options.onError(e_2.code, e_2.message);
              return [3, 7];
            case 7:
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v2/mfa/face/associate"),
                data: {
                  photoA,
                  photoB
                },
                headers
              })];
            case 8:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    MfaAuthenticationClient2.prototype.verifyFaceMfa = function(photo, mfaToken) {
      return __awaiter$5(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$5(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/mfa/face/verify");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  photo
                },
                headers: {
                  authorization: "Bearer ".concat(mfaToken)
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    return MfaAuthenticationClient2;
  }()
);
var __awaiter$4 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$4 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var SocialAuthenticationClient = (
  /** @class */
  function() {
    function SocialAuthenticationClient2(options2, tokenProvider, httpClient) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
      this.baseClient = new BaseAuthenticationClient(options2);
    }
    SocialAuthenticationClient2.prototype.authorize = function(provider, options2) {
      var _this = this;
      options2 = options2 || {};
      var position = options2.position, _a3 = options2.popup, popup = _a3 === void 0 ? true : _a3, onSuccess = options2.onSuccess, onError = options2.onError, authorization_params = options2.authorization_params, authorizationParams = options2.authorizationParams, context = options2.context, customData = options2.customData, _b2 = options2.withIdentities, withIdentities = _b2 === void 0 ? false : _b2, _c2 = options2.protocol, protocol = _c2 === void 0 ? "oidc" : _c2, uuid = options2.uuid, _d2 = options2.withCustomData, withCustomData = _d2 === void 0 ? false : _d2, targetUrl = options2.targetUrl, relayMethod = options2.relayMethod, guardVersion = options2.guardVersion;
      if (!uuid) {
        uuid = generateRandomString(20);
      }
      var query = {
        from_guard: "1",
        app_id: this.options.appId,
        authorization_params: JSON.stringify(authorization_params || authorizationParams),
        with_identities: withIdentities ? "1" : "0",
        with_custom_data: withCustomData ? "1" : "0",
        protocol,
        uuid,
        target_url: targetUrl,
        relay_method: relayMethod,
        guard_version: guardVersion
      };
      if (context) {
        query.context = JSON.stringify(context);
      }
      if (this.options.tenantId) {
        query.tenant_id = this.options.tenantId;
      }
      if (customData) {
        query.custom_data = JSON.stringify(customData);
      }
      var url = "".concat(this.baseClient.appHost, "/connections/social/").concat(provider, "?").concat(serialize(query));
      var onMessage = function(e4) {
        var _a4 = e4.data, code = _a4.code, message = _a4.message, resData = _a4.data, event = _a4.event;
        event = event || {};
        var source = event.source, eventType = event.eventType;
        if (source !== "authing" || eventType !== "socialLogin") {
          return;
        }
        try {
          var parsedMsg = JSON.parse(message);
          code = parsedMsg.code;
        } catch (e5) {
        }
        if (code === 200) {
          _this.tokenProvider.setUser(resData);
          onSuccess && onSuccess(resData);
        } else {
          onError && onError(code, message, resData);
        }
        window.removeEventListener("message", onMessage);
      };
      window.addEventListener("message", onMessage);
      if (isMobileBrowser()) {
        url = "".concat(url, "&redirected=1&from_hosted_guard=1&redirect_url=").concat(this.baseClient.appHost, "/interaction/oidc/").concat(uuid, "/login");
        window.location.href = url;
      } else if (popup) {
        popupCenter(url, position);
      } else {
        window.open(url);
      }
      return Promise.resolve();
    };
    SocialAuthenticationClient2.prototype.generateLinkExtIdpUrl = function(params) {
      return __awaiter$4(this, void 0, void 0, function() {
        var extIdpConnIdentifier, idToken, data2;
        return __generator$4(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              extIdpConnIdentifier = params.extIdpConnIdentifier, idToken = params.idToken;
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v3/generate-link-extidp-url"),
                params: {
                  ext_idp_conn_identifier: extIdpConnIdentifier,
                  id_token: idToken,
                  app_id: this.options.appId
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    SocialAuthenticationClient2.prototype.unlinkExtIdp = function(params) {
      return __awaiter$4(this, void 0, void 0, function() {
        var extIdpId, data2;
        return __generator$4(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              extIdpId = params.extIdpId;
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v3/unlink-extidp"),
                data: {
                  extIdpId
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    SocialAuthenticationClient2.prototype.getIdentities = function() {
      return __awaiter$4(this, void 0, void 0, function() {
        var data2;
        return __generator$4(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v3/get-identities")
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    return SocialAuthenticationClient2;
  }()
);
var __awaiter$3 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$3 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var EnterpriseAuthenticationClient = (
  /** @class */
  function() {
    function EnterpriseAuthenticationClient2(options2, tokenProvider, httpClient) {
      this.options = options2;
      this.baseClient = new BaseAuthenticationClient(options2);
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
    }
    EnterpriseAuthenticationClient2.prototype.initProviderContext = function(appId) {
      return __awaiter$3(this, void 0, void 0, function() {
        var appConfig;
        return __generator$3(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v2/applications/").concat(appId, "/public-config")
              })];
            case 1:
              appConfig = _a3.sent();
              return [2, appConfig];
          }
        });
      });
    };
    EnterpriseAuthenticationClient2.prototype.getProviderConfigAndError = function(protocol, appConfig, identifier) {
      var _a3, _b2;
      var providerConfig = (_b2 = (_a3 = appConfig.identityProviders) === null || _a3 === void 0 ? void 0 : _a3.find(function(item) {
        return item.protocol === protocol && item.identifier === identifier;
      })) === null || _b2 === void 0 ? void 0 : _b2.config;
      if (!providerConfig) {
        throw new Error("身份源配置不存在");
      }
      return providerConfig;
    };
    EnterpriseAuthenticationClient2.prototype.getLoginUrl = function(protocol, appConfig, identifier, state) {
      var config = this.getProviderConfigAndError(protocol, appConfig, identifier);
      switch (protocol) {
        case Protocol$1.OIDC:
          config = config;
          var query = serialize({
            state,
            client_id: config.clientId,
            redirect_uri: config.redirectUri,
            scope: config.scopes,
            response_type: config.responseType,
            nonce: generateUidKey(32)
          });
          return "".concat(config.authorizationEdpoint, "?").concat(query);
        case Protocol$1.SAML:
          config = config;
          return config.samlRequest;
        case Protocol$1.CAS:
          config = config;
          return config.casConnectionLoginUrl;
        case Protocol$1.OAUTH:
          config = config;
          return config.authUrl;
        case Protocol$1.AZURE_AD:
          config = config;
          return config.authorizationUrl;
        default:
          return "";
      }
    };
    EnterpriseAuthenticationClient2.prototype.authorize = function(protocol, identifier, options2) {
      var _this = this;
      options2 = options2 || {};
      var position = options2.position, _a3 = options2.popup, popup = _a3 === void 0 ? true : _a3, onSuccess = options2.onSuccess, onError = options2.onError;
      var appId = this.options.appId;
      var state = generateUidKey(32);
      var windowRef;
      if (isWechatBrowser()) {
        windowRef = window;
      } else if (popup) {
        windowRef = popupCenter("", position);
      } else {
        windowRef = window.open("");
      }
      this.initProviderContext(appId).then(function(appConfig) {
        var promise = protocol === Protocol$1.OIDC ? _this.httpClient.request({
          method: "POST",
          url: "".concat(_this.baseClient.appHost, "/api/v2/connections/oidc/start-interaction"),
          data: {
            state,
            protocol,
            userPoolId: appConfig.userPoolId,
            appId,
            referer: window.location.href,
            connection: { providerIentifier: identifier }
          }
        }) : Promise.resolve();
        promise.then(function() {
          var url = _this.getLoginUrl(protocol, appConfig, identifier, state);
          var onMessage = function(e4) {
            var _a4 = e4.data, code = _a4.code, message = _a4.message, userInfo = _a4.data, event = _a4.event;
            event = event || {};
            var source = event.source, eventType = event.eventType;
            if (source !== "authing" || eventType !== "enterpriseLogin") {
              return;
            }
            try {
              var parsedMsg = JSON.parse(message);
              message = parsedMsg.message;
              code = parsedMsg.code;
            } catch (e5) {
            }
            if (code === 200) {
              _this.tokenProvider.setUser(userInfo);
              onSuccess && onSuccess(userInfo);
            } else {
              onError && onError(code, message);
            }
            window.removeEventListener("message", onMessage);
          };
          window.addEventListener("message", onMessage);
          windowRef.location.assign(url);
        });
      });
      return Promise.resolve();
    };
    return EnterpriseAuthenticationClient2;
  }()
);
var __awaiter$2 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$2 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var PrincipalAuthenticationClient = (
  /** @class */
  function() {
    function PrincipalAuthenticationClient2(options2, tokenProvider, httpClient) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
      this.baseClient = new BaseAuthenticationClient(options2);
    }
    PrincipalAuthenticationClient2.prototype.detail = function() {
      return __awaiter$2(this, void 0, void 0, function() {
        var api2, data2;
        return __generator$2(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/users/principal_authentication");
              return [4, this.httpClient.request({
                method: "GET",
                url: api2
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    PrincipalAuthenticationClient2.prototype.authenticate = function(info) {
      return __awaiter$2(this, void 0, void 0, function() {
        var api2, params;
        return __generator$2(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/users/principal_authentication");
              if (info.type === "P") {
                params = {
                  type: "P",
                  name: info.name,
                  idCard: info.idCard,
                  ext: info.bankCard
                };
              } else {
                params = {
                  type: "E",
                  name: info.enterpriseName,
                  idCard: info.enterpriseCode,
                  ext: info.legalPersonName
                };
              }
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: params
              })];
            case 1:
              _a3.sent();
              return [2, true];
          }
        });
      });
    };
    return PrincipalAuthenticationClient2;
  }()
);
var __awaiter$1 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator$1 = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var EventAuthenticationClient = (
  /** @class */
  function() {
    function EventAuthenticationClient2(options2, tokenProvider, httpClient) {
      this.options = options2;
      this.tokenProvider = tokenProvider;
      this.httpClient = httpClient;
      this.wsMap = {};
      this.eventBus = {};
      this.baseClient = new BaseAuthenticationClient(options2);
    }
    EventAuthenticationClient2.prototype.reconnect = function(eventName) {
      var _this = this;
      return new Promise(function(resolve2, reject2) {
        if (_this.options.retryTimes && _this.wsMap[eventName].timeConnect < _this.options.retryTimes) {
          if (!_this.wsMap[eventName].lockConnect) {
            _this.wsMap[eventName].lockConnect = true;
            _this.wsMap[eventName].timeConnect++;
            setTimeout(function() {
              _this.wsMap[eventName].lockConnect = false;
              _this.initWebSocket(eventName, true).then(function() {
                resolve2(true);
              }).catch(function(e4) {
                reject2(e4);
              });
            }, 2e3);
          }
        } else {
          reject2("socket 服务器连接超时");
        }
      });
    };
    EventAuthenticationClient2.prototype.initWebSocket = function(eventName, retry) {
      var _this = this;
      return new Promise(function(resolve2, reject2) {
        return __awaiter$1(_this, void 0, void 0, function() {
          var token;
          var _this2 = this;
          return __generator$1(this, function(_a3) {
            switch (_a3.label) {
              case 0:
                if (!(!this.wsMap[eventName] || retry)) return [3, 2];
                return [4, this.tokenProvider.getToken()];
              case 1:
                token = _a3.sent();
                this.wsMap[eventName] = {
                  socket: new WebSocket("".concat(this.options.socketUri, "/events/v1/authentication/sub?code=").concat(eventName, "&token=").concat(token)),
                  timeConnect: retry ? this.wsMap[eventName].timeConnect : 0,
                  lockConnect: false
                };
                this.wsMap[eventName].socket.onopen = function() {
                  resolve2(true);
                };
                this.wsMap[eventName].socket.addEventListener("message", function(event) {
                  try {
                    if (_this2.eventBus[eventName]) {
                      _this2.eventBus[eventName].forEach(function(callback) {
                        callback[0](event.data.toString("utf8"));
                      });
                    } else {
                      console.warn("未订阅的事件：", eventName);
                    }
                  } catch (error) {
                    return reject2("数据格式化错误，检查传输数据格式！！！ ".concat(error));
                  }
                });
                this.wsMap[eventName].socket.addEventListener("error", function(e4) {
                  return __awaiter$1(_this2, void 0, void 0, function() {
                    return __generator$1(this, function(_a4) {
                      switch (_a4.label) {
                        case 0:
                          _a4.trys.push([0, 2, , 3]);
                          return [4, this.reconnect(eventName)];
                        case 1:
                          _a4.sent();
                          resolve2(true);
                          return [3, 3];
                        case 2:
                          _a4.sent();
                          return [2, reject2("socket 连接异常：".concat(JSON.stringify(e4)))];
                        case 3:
                          return [
                            2
                            /*return*/
                          ];
                      }
                    });
                  });
                });
                this.wsMap[eventName].socket.onclose = function() {
                  return __awaiter$1(_this2, void 0, void 0, function() {
                    return __generator$1(this, function(_a4) {
                      switch (_a4.label) {
                        case 0:
                          _a4.trys.push([0, 2, , 3]);
                          return [4, this.reconnect(eventName)];
                        case 1:
                          _a4.sent();
                          resolve2(true);
                          return [3, 3];
                        case 2:
                          _a4.sent();
                          return [2, reject2("socket 服务器连接超时")];
                        case 3:
                          return [
                            2
                            /*return*/
                          ];
                      }
                    });
                  });
                };
                return [3, 3];
              case 2:
                resolve2(true);
                _a3.label = 3;
              case 3:
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      });
    };
    EventAuthenticationClient2.prototype.sub = function(eventName, callback, errCallback) {
      var _this = this;
      if (typeof eventName !== "string") {
        throw new Error("订阅事件名称为 string 类型！！！");
      }
      if (typeof callback !== "function") {
        throw new Error("订阅事件回调函数需要为 function 类型！！！");
      }
      if (!this.options.socketUri) {
        throw new Error("订阅事件需要添加 socketUri 连接地址！！！");
      }
      this.initWebSocket(eventName).catch(function(e4) {
        _this.eventBus[eventName].forEach(function(item) {
          var _a3;
          (_a3 = item[1]) === null || _a3 === void 0 ? void 0 : _a3.call(item, e4);
        });
      });
      if (this.eventBus[eventName]) {
        this.eventBus[eventName].push([callback, errCallback]);
      } else {
        this.eventBus[eventName] = [[callback, errCallback]];
      }
    };
    EventAuthenticationClient2.prototype.pub = function(eventName, data2) {
      return __awaiter$1(this, void 0, void 0, function() {
        return __generator$1(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (typeof eventName !== "string") {
                throw new Error("事件名称为 string 类型！！！");
              }
              if (typeof data2 !== "string") {
                throw new Error("发布数据为 string 类型！！！");
              }
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v3/pub-userEvent"),
                data: {
                  eventType: eventName,
                  source: "authing-js-sdk: ".concat(SDK_VERSION$1),
                  eventData: data2
                }
              })];
            case 1:
              return [2, _a3.sent()];
          }
        });
      });
    };
    return EventAuthenticationClient2;
  }()
);
var __assign = function() {
  __assign = Object.assign || function(t2) {
    for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
      s2 = arguments[i2];
      for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2))
        t2[p2] = s2[p2];
    }
    return t2;
  };
  return __assign.apply(this, arguments);
};
var __awaiter = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, reject2) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e4) {
        reject2(e4);
      }
    }
    function step(result) {
      result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __generator = function(thisArg, body) {
  var _2 = { label: 0, sent: function() {
    if (t2[0] & 1) throw t2[1];
    return t2[1];
  }, trys: [], ops: [] }, f2, y2, t2, g;
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n2) {
    return function(v2) {
      return step([n2, v2]);
    };
  }
  function step(op) {
    if (f2) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_2 = 0)), _2) try {
      if (f2 = 1, y2 && (t2 = op[0] & 2 ? y2["return"] : op[0] ? y2["throw"] || ((t2 = y2["return"]) && t2.call(y2), 0) : y2.next) && !(t2 = t2.call(y2, op[1])).done) return t2;
      if (y2 = 0, t2) op = [op[0] & 2, t2.value];
      switch (op[0]) {
        case 0:
        case 1:
          t2 = op;
          break;
        case 4:
          _2.label++;
          return { value: op[1], done: false };
        case 5:
          _2.label++;
          y2 = op[1];
          op = [0];
          continue;
        case 7:
          op = _2.ops.pop();
          _2.trys.pop();
          continue;
        default:
          if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _2 = 0;
            continue;
          }
          if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) {
            _2.label = op[1];
            break;
          }
          if (op[0] === 6 && _2.label < t2[1]) {
            _2.label = t2[1];
            t2 = op;
            break;
          }
          if (t2 && _2.label < t2[2]) {
            _2.label = t2[2];
            _2.ops.push(op);
            break;
          }
          if (t2[2]) _2.ops.pop();
          _2.trys.pop();
          continue;
      }
      op = body.call(thisArg, _2);
    } catch (e4) {
      op = [6, e4];
      y2 = 0;
    } finally {
      f2 = t2 = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
};
var DEFAULT_OPTIONS = {
  appId: void 0,
  tenantId: void 0,
  appHost: void 0,
  protocol: "oidc",
  tokenEndPointAuthMethod: "client_secret_post",
  introspectionEndPointAuthMethod: "client_secret_post",
  revocationEndPointAuthMethod: "client_secret_post",
  timeout: 3e4,
  onError: function(code, message, data2) {
    throw { code, message, data: data2 };
  },
  requestFrom: "sdk",
  encryptFunction: encrypt,
  host: "https://core.authing.cn",
  headers: {
    "userpool-id": "x-authing-userpool-id",
    "app-id": "x-authing-app-id",
    "request-from": "x-authing-request-from",
    "sdk-version": "x-authing-sdk-version",
    "tenant-id": "x-authing-app-tenant-id",
    lang: "x-authing-lang"
  },
  lang: "zh-CN",
  socketUri: "wss://openevent.authing.cn",
  retryTimes: 5
};
var AuthenticationClient = (
  /** @class */
  function() {
    function AuthenticationClient2(options2) {
      Object.keys(options2).forEach(function(i2) {
        return !options2[i2] && delete options2[i2];
      });
      this.options = Object.assign({}, DEFAULT_OPTIONS, options2);
      this.baseClient = new BaseAuthenticationClient(this.options);
      var graphqlEndpoint = "".concat(this.baseClient.appHost, "/graphql/v2");
      this.graphqlClient = new (this.options.graphqlClient || GraphqlClient)(graphqlEndpoint, this.options);
      this.tokenProvider = new (this.options.tokenProvider || AuthenticationTokenProvider)(this.options);
      this.httpClient = new (this.options.httpClient || HttpClient)(this.options, this.tokenProvider);
      this.naiveHttpClient = new NaiveHttpClient(this.options, this.tokenProvider);
      this.publicKeyManager = new PublicKeyManager(this.options, this.httpClient);
      this.browserFingerprint = new BrowserFingerprintClient(this.options, this.httpClient);
      this.wxqrcode = new QrCodeAuthenticationClient(this.options, this.tokenProvider, this.httpClient, "WXAPP_AUTH");
      this.qrcode = new QrCodeAuthenticationClient(this.options, this.tokenProvider, this.httpClient, "APP_AUTH");
      this.wechatmpqrcode = new QrCodeAuthenticationClient(this.options, this.tokenProvider, this.httpClient, "WECHATMP_AUTH");
      this.mfa = new MfaAuthenticationClient(this.options, this.tokenProvider, this.httpClient);
      this.social = new SocialAuthenticationClient(this.options, this.tokenProvider, this.httpClient);
      this.enterprise = new EnterpriseAuthenticationClient(this.options, this.tokenProvider, this.httpClient);
      this.principal = new PrincipalAuthenticationClient(this.options, this.tokenProvider, this.httpClient);
      if (this.options.token) {
        this.setToken(this.options.token);
      }
      this.event = new EventAuthenticationClient(this.options, this.tokenProvider, this.httpClient);
    }
    AuthenticationClient2.prototype.checkLoggedIn = function() {
      var _a3;
      var user2 = this.tokenProvider.getUser();
      if (user2) {
        return user2.id;
      }
      var token = this.tokenProvider.getToken();
      if (!token) {
        throw new Error("请先登录！");
      }
      var decoded = jwtDecode(token);
      var userId = decoded.sub || ((_a3 = decoded.data) === null || _a3 === void 0 ? void 0 : _a3.id);
      if (!userId) {
        throw new Error("不合法的 accessToken");
      }
      return userId;
    };
    AuthenticationClient2.prototype.setCurrentUser = function(user2) {
      this.tokenProvider.setUser(user2);
    };
    AuthenticationClient2.prototype.setToken = function(token) {
      this.tokenProvider.setToken(token);
    };
    AuthenticationClient2.prototype.setRequestFrom = function(requestFrom) {
      this.options.requestFrom = requestFrom;
      this.graphqlClient.setOptions(this.options);
      this.httpClient.setOptions(this.options);
    };
    AuthenticationClient2.prototype.registerByEmail = function(email, password, profile, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, forceLogin, _b2, generateToken, clientIp, params, context, customData, phoneToken, _c2, _d2, _e2, extraParams, extraContext, user2;
        return __generator(this, function(_f2) {
          switch (_f2.label) {
            case 0:
              options2 = options2 || {};
              profile = profile || {};
              _a3 = options2.forceLogin, forceLogin = _a3 === void 0 ? false : _a3, _b2 = options2.generateToken, generateToken = _b2 === void 0 ? false : _b2, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData, phoneToken = options2.phoneToken;
              _d2 = (_c2 = this.options).encryptFunction;
              _e2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _d2.apply(_c2, _e2.concat([_f2.sent(), this.options.encryption]))];
            case 2:
              password = _f2.sent();
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, registerByEmail(this.graphqlClient, this.tokenProvider, {
                input: {
                  email,
                  password,
                  profile,
                  forceLogin,
                  generateToken,
                  clientIp,
                  params: extraParams,
                  context: extraContext,
                  phoneToken
                }
              })];
            case 3:
              user2 = _f2.sent().registerByEmail;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.registerByEmailCode = function(email, code, profile, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, params, data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/register/email-code");
              params = __assign({ email, code, profile }, options2);
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: params
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.registerByUsername = function(username, password, profile, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, forceLogin, _b2, generateToken, clientIp, params, context, customData, phoneToken, emailToken, _c2, _d2, _e2, extraParams, extraContext, user2;
        return __generator(this, function(_f2) {
          switch (_f2.label) {
            case 0:
              options2 = options2 || {};
              profile = profile || {};
              _a3 = options2.forceLogin, forceLogin = _a3 === void 0 ? false : _a3, _b2 = options2.generateToken, generateToken = _b2 === void 0 ? false : _b2, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData, phoneToken = options2.phoneToken, emailToken = options2.emailToken;
              _d2 = (_c2 = this.options).encryptFunction;
              _e2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _d2.apply(_c2, _e2.concat([_f2.sent(), this.options.encryption]))];
            case 2:
              password = _f2.sent();
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, registerByUsername(this.graphqlClient, this.tokenProvider, {
                input: {
                  username,
                  password,
                  profile,
                  forceLogin,
                  generateToken,
                  clientIp,
                  params: extraParams,
                  context: extraContext,
                  phoneToken,
                  emailToken
                }
              })];
            case 3:
              user2 = _f2.sent().registerByUsername;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.registerByPhoneCode = function(phone, code, password, profile, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, forceLogin, _b2, generateToken, clientIp, params, context, customData, phoneCountryCode, emailToken, _c2, _d2, _e2, extraParams, extraContext, user2;
        return __generator(this, function(_f2) {
          switch (_f2.label) {
            case 0:
              options2 = options2 || {};
              profile = profile || {};
              _a3 = options2.forceLogin, forceLogin = _a3 === void 0 ? false : _a3, _b2 = options2.generateToken, generateToken = _b2 === void 0 ? false : _b2, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData, phoneCountryCode = options2.phoneCountryCode, emailToken = options2.emailToken;
              if (!password) return [3, 3];
              _d2 = (_c2 = this.options).encryptFunction;
              _e2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _d2.apply(_c2, _e2.concat([_f2.sent(), this.options.encryption]))];
            case 2:
              password = _f2.sent();
              _f2.label = 3;
            case 3:
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, registerByPhoneCode(this.graphqlClient, this.tokenProvider, {
                input: {
                  phone,
                  code,
                  phoneCountryCode,
                  password,
                  profile,
                  forceLogin,
                  generateToken,
                  clientIp,
                  params: extraParams,
                  context: extraContext,
                  emailToken
                }
              })];
            case 4:
              user2 = _f2.sent().registerByPhoneCode;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.checkPasswordStrength = function(password) {
      return __awaiter(this, void 0, void 0, function() {
        var result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, checkPasswordStrength(this.graphqlClient, this.tokenProvider, { password })];
            case 1:
              result = _a3.sent().checkPasswordStrength;
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype.sendSmsCode = function(phone, phoneCountryCode, scene) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, params, data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/api/v2/sms/send");
              params = { phone };
              if (phoneCountryCode) {
                params.phoneCountryCode = phoneCountryCode;
              }
              if (scene) {
                params.scene = scene;
              }
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: params
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByEmail = function(email, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, autoRegister, captchaCode, clientIp, params, context, customData, _b2, _c2, _d2, extraParams, extraContext, user2;
        return __generator(this, function(_e2) {
          switch (_e2.label) {
            case 0:
              options2 = options2 || {};
              _a3 = options2.autoRegister, autoRegister = _a3 === void 0 ? false : _a3, captchaCode = options2.captchaCode, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData;
              _c2 = (_b2 = this.options).encryptFunction;
              _d2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _c2.apply(_b2, _d2.concat([_e2.sent(), this.options.encryption]))];
            case 2:
              password = _e2.sent();
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, loginByEmail(this.graphqlClient, this.tokenProvider, {
                input: {
                  email,
                  password,
                  autoRegister,
                  captchaCode,
                  clientIp,
                  params: extraParams,
                  context: extraContext
                }
              })];
            case 3:
              user2 = _e2.sent().loginByEmail;
              if (user2.customData) {
                user2.customData = convertUdvToKeyValuePair(user2.customData);
              }
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByUsername = function(username, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, autoRegister, captchaCode, clientIp, params, context, customData, _b2, _c2, _d2, extraParams, extraContext, user2;
        return __generator(this, function(_e2) {
          switch (_e2.label) {
            case 0:
              options2 = options2 || {};
              _a3 = options2.autoRegister, autoRegister = _a3 === void 0 ? false : _a3, captchaCode = options2.captchaCode, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData;
              _c2 = (_b2 = this.options).encryptFunction;
              _d2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _c2.apply(_b2, _d2.concat([_e2.sent(), this.options.encryption]))];
            case 2:
              password = _e2.sent();
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, loginByUsername(this.graphqlClient, this.tokenProvider, {
                input: {
                  username,
                  password,
                  autoRegister,
                  captchaCode,
                  clientIp,
                  params: extraParams,
                  context: extraContext
                }
              })];
            case 3:
              user2 = _e2.sent().loginByUsername;
              if (user2.customData) {
                user2.customData = convertUdvToKeyValuePair(user2.customData);
              }
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByPhoneCode = function(phone, code, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var clientIp, params, context, customData, phoneCountryCode, extraParams, extraContext, user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              options2 = options2 || {};
              clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData, phoneCountryCode = options2.phoneCountryCode;
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, loginByPhoneCode(this.graphqlClient, this.tokenProvider, {
                input: {
                  phone,
                  code,
                  phoneCountryCode,
                  clientIp,
                  params: extraParams,
                  context: extraContext
                }
              })];
            case 1:
              user2 = _a3.sent().loginByPhoneCode;
              if (user2.customData) {
                user2.customData = convertUdvToKeyValuePair(user2.customData);
              }
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByEmailCode = function(email, code, options2) {
      var _a3;
      return __awaiter(this, void 0, void 0, function() {
        var clientIp, params, context, customData, phoneCountryCode, extraParams, extraContext, url, user2;
        return __generator(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              options2 = options2 || {};
              clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData, phoneCountryCode = options2.phoneCountryCode;
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              url = "".concat((_a3 = this.options.appHost) !== null && _a3 !== void 0 ? _a3 : "", "/api/v2/login/email-code");
              return [4, this.httpClient.request({
                method: "POST",
                url,
                data: {
                  email,
                  code,
                  phoneCountryCode,
                  clientIp,
                  params: extraParams,
                  context: extraContext
                },
                unSetToken: true
              })];
            case 1:
              user2 = _b2.sent();
              if (user2.customData) {
                user2.customData = convertUdvToKeyValuePair(user2.customData);
              }
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByPhonePassword = function(phone, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var captchaCode, _a3, autoRegister, clientIp, params, context, customData, _b2, _c2, _d2, extraParams, extraContext, user2;
        return __generator(this, function(_e2) {
          switch (_e2.label) {
            case 0:
              options2 = options2 || {};
              captchaCode = options2.captchaCode, _a3 = options2.autoRegister, autoRegister = _a3 === void 0 ? false : _a3, clientIp = options2.clientIp, params = options2.params, context = options2.context, customData = options2.customData;
              _c2 = (_b2 = this.options).encryptFunction;
              _d2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _c2.apply(_b2, _d2.concat([_e2.sent(), this.options.encryption]))];
            case 2:
              password = _e2.sent();
              extraParams = null;
              if (customData) {
                extraParams = JSON.stringify(convertObjectToKeyValueList(customData));
              } else if (params) {
                extraParams = JSON.stringify(params);
              }
              extraContext = null;
              if (context) {
                extraContext = JSON.stringify(context);
              }
              return [4, loginByPhonePassword(this.graphqlClient, this.tokenProvider, {
                input: {
                  phone,
                  password,
                  captchaCode,
                  autoRegister,
                  clientIp,
                  params: extraParams,
                  context: extraContext
                }
              })];
            case 3:
              user2 = _e2.sent().loginByPhonePassword;
              if (user2.customData) {
                user2.customData = convertUdvToKeyValuePair(user2.customData);
              }
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginBySubAccount = function(account, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var captchaCode, clientIp, _a3, _b2, _c2, user2;
        return __generator(this, function(_d2) {
          switch (_d2.label) {
            case 0:
              options2 = options2 || {};
              captchaCode = options2.captchaCode, clientIp = options2.clientIp;
              _b2 = (_a3 = this.options).encryptFunction;
              _c2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _b2.apply(_a3, _c2.concat([_d2.sent(), this.options.encryption]))];
            case 2:
              password = _d2.sent();
              return [4, loginBySubAccount(this.graphqlClient, this.tokenProvider, {
                account,
                password,
                captchaCode,
                clientIp
              })];
            case 3:
              user2 = _d2.sent().loginBySubAccount;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.checkLoginStatus = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var res;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, checkLoginStatus(this.graphqlClient, this.tokenProvider, {
                token
              })];
            case 1:
              res = _a3.sent();
              return [2, res.checkLoginStatus];
          }
        });
      });
    };
    AuthenticationClient2.prototype.sendEmail = function(email, scene) {
      return __awaiter(this, void 0, void 0, function() {
        var data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, sendEmail(this.graphqlClient, this.tokenProvider, { email, scene })];
            case 1:
              data2 = _a3.sent().sendEmail;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.resetPasswordByPhoneCode = function(phone, code, newPassword, phoneCountryCode) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, _b2, _c2, data2;
        return __generator(this, function(_d2) {
          switch (_d2.label) {
            case 0:
              _b2 = (_a3 = this.options).encryptFunction;
              _c2 = [newPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _b2.apply(_a3, _c2.concat([_d2.sent(), this.options.encryption]))];
            case 2:
              newPassword = _d2.sent();
              return [4, resetPassword(this.graphqlClient, this.tokenProvider, {
                phone,
                code,
                newPassword,
                phoneCountryCode
              })];
            case 3:
              data2 = _d2.sent().resetPassword;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.resetPasswordByEmailCode = function(email, code, newPassword) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, _b2, _c2, data2;
        return __generator(this, function(_d2) {
          switch (_d2.label) {
            case 0:
              _b2 = (_a3 = this.options).encryptFunction;
              _c2 = [newPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _b2.apply(_a3, _c2.concat([_d2.sent(), this.options.encryption]))];
            case 2:
              newPassword = _d2.sent();
              return [4, resetPassword(this.graphqlClient, this.tokenProvider, {
                email,
                code,
                newPassword
              })];
            case 3:
              data2 = _d2.sent().resetPassword;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.resetPasswordByFirstLoginToken = function(params) {
      return __awaiter(this, void 0, void 0, function() {
        var token, password, _a3, _b2, _c2, data2;
        return __generator(this, function(_d2) {
          switch (_d2.label) {
            case 0:
              token = params.token, password = params.password;
              _b2 = (_a3 = this.options).encryptFunction;
              _c2 = [password];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _b2.apply(_a3, _c2.concat([_d2.sent(), this.options.encryption]))];
            case 2:
              password = _d2.sent();
              return [4, resetPasswordByFirstLoginToken(this.graphqlClient, this.tokenProvider, {
                token,
                password
              })];
            case 3:
              data2 = _d2.sent().resetPasswordByFirstLoginToken;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.resetPasswordByForceResetToken = function(params) {
      return __awaiter(this, void 0, void 0, function() {
        var token, newPassword, oldPassword, _a3, _b2, _c2, _d2, _e2, _f2, data2;
        return __generator(this, function(_g2) {
          switch (_g2.label) {
            case 0:
              token = params.token, newPassword = params.newPassword, oldPassword = params.oldPassword;
              _b2 = (_a3 = this.options).encryptFunction;
              _c2 = [newPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _b2.apply(_a3, _c2.concat([_g2.sent(), this.options.encryption]))];
            case 2:
              newPassword = _g2.sent();
              _e2 = (_d2 = this.options).encryptFunction;
              _f2 = [oldPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 3:
              return [4, _e2.apply(_d2, _f2.concat([_g2.sent(), this.options.encryption]))];
            case 4:
              oldPassword = _g2.sent();
              return [4, resetPasswordByForceResetToken(this.graphqlClient, this.tokenProvider, {
                token,
                oldPassword,
                newPassword
              })];
            case 5:
              data2 = _g2.sent().resetPasswordByForceResetToken;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.updateProfile = function(updates, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var userId, _a3, emailToken, phoneToken, updated;
        return __generator(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              userId = this.checkLoggedIn();
              _a3 = options2 || {}, emailToken = _a3.emailToken, phoneToken = _a3.phoneToken;
              if (updates && updates.password) {
                delete updates.password;
              }
              return [4, updateUser(this.graphqlClient, this.tokenProvider, {
                id: userId,
                input: updates,
                emailToken,
                phoneToken
              })];
            case 1:
              updated = _b2.sent().updateUser;
              this.setCurrentUser(updated);
              return [2, updated];
          }
        });
      });
    };
    AuthenticationClient2.prototype.updatePassword = function(newPassword, oldPassword) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, user2;
        return __generator(this, function(_j2) {
          switch (_j2.label) {
            case 0:
              _a3 = newPassword;
              if (!_a3) return [3, 3];
              _c2 = (_b2 = this.options).encryptFunction;
              _d2 = [newPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 1:
              return [4, _c2.apply(_b2, _d2.concat([_j2.sent(), this.options.encryption]))];
            case 2:
              _a3 = _j2.sent();
              _j2.label = 3;
            case 3:
              newPassword = _a3;
              _e2 = oldPassword;
              if (!_e2) return [3, 6];
              _g2 = (_f2 = this.options).encryptFunction;
              _h2 = [oldPassword];
              return [4, this.publicKeyManager.getPublicKey()];
            case 4:
              return [4, _g2.apply(_f2, _h2.concat([_j2.sent(), this.options.encryption]))];
            case 5:
              _e2 = _j2.sent();
              _j2.label = 6;
            case 6:
              oldPassword = _e2;
              return [4, updatePassword(this.graphqlClient, this.tokenProvider, {
                newPassword,
                oldPassword
              })];
            case 7:
              user2 = _j2.sent().updatePassword;
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.updatePhone = function(phone, phoneCode, oldPhone, oldPhoneCode, phoneCountryCode, oldPhoneCountryCode) {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, updatePhone(this.graphqlClient, this.tokenProvider, {
                phone,
                phoneCode,
                oldPhone,
                oldPhoneCode,
                phoneCountryCode,
                oldPhoneCountryCode
              })];
            case 1:
              user2 = _a3.sent().updatePhone;
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.updateEmail = function(email, emailCode, oldEmail, oldEmailCode) {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, updateEmail(this.graphqlClient, this.tokenProvider, {
                email,
                emailCode,
                oldEmail,
                oldEmailCode
              })];
            case 1:
              user2 = _a3.sent().updateEmail;
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.refreshToken = function() {
      return __awaiter(this, void 0, void 0, function() {
        var data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, refreshToken(this.graphqlClient, this.tokenProvider, {})];
            case 1:
              data2 = _a3.sent().refreshToken;
              this.setToken(data2.token);
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.linkAccount = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v2/users/link"),
                data: {
                  primaryUserToken: options2.primaryUserToken,
                  secondaryUserToken: options2.secondaryUserToken
                }
              })];
            case 1:
              _a3.sent();
              return [2, { code: 200, message: "绑定成功" }];
          }
        });
      });
    };
    AuthenticationClient2.prototype.unLinkAccount = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "POST",
                url: "".concat(this.baseClient.appHost, "/api/v2/users/unlink"),
                data: {
                  primaryUserToken: options2.primaryUserToken,
                  provider: options2.provider
                }
              })];
            case 1:
              _a3.sent();
              return [2, { code: 200, message: "解绑成功" }];
          }
        });
      });
    };
    AuthenticationClient2.prototype.bindPhone = function(phone, phoneCode, phoneCountryCode) {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, bindPhone(this.graphqlClient, this.tokenProvider, {
                phone,
                phoneCode,
                phoneCountryCode
              })];
            case 1:
              user2 = _a3.sent().bindPhone;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.unbindPhone = function() {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, unbindPhone(this.graphqlClient, this.tokenProvider, {})];
            case 1:
              user2 = _a3.sent().unbindPhone;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.bindEmail = function(email, emailCode) {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, bindEmail(this.graphqlClient, this.tokenProvider, {
                email,
                emailCode
              })];
            case 1:
              user2 = _a3.sent().bindEmail;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.unbindEmail = function() {
      return __awaiter(this, void 0, void 0, function() {
        var user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, unbindEmail(this.graphqlClient, this.tokenProvider, {})];
            case 1:
              user2 = _a3.sent().unbindEmail;
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getCurrentUser = function() {
      return __awaiter(this, void 0, void 0, function() {
        var data2;
        return __generator(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              _b2.trys.push([0, 2, , 3]);
              return [4, user(this.graphqlClient, this.tokenProvider, {})];
            case 1:
              data2 = _b2.sent().user;
              if (data2.customData) {
                data2.customData = convertUdvToKeyValuePair(data2.customData);
              }
              this.setCurrentUser(data2);
              return [2, data2];
            case 2:
              _b2.sent();
              return [2, null];
            case 3:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.logout = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v2/logout?app_id=").concat(this.options.appId),
                withCredentials: true
              })];
            case 1:
              _a3.sent();
              this.tokenProvider.clearUser();
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.logoutCurrent = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/logout?appId=").concat(this.options.appId, "&deviceId=current"),
                withCredentials: true
              })];
            case 1:
              _a3.sent();
              this.tokenProvider.clearUser();
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.listUdv = function() {
      return __awaiter(this, void 0, void 0, function() {
        var userId, list;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              return [4, udv(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId
              })];
            case 1:
              list = _a3.sent().udv;
              return [2, convertUdv(list)];
          }
        });
      });
    };
    AuthenticationClient2.prototype.setUdv = function(key2, value) {
      return __awaiter(this, void 0, void 0, function() {
        var userId, list;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              value = JSON.stringify(value);
              return [4, setUdv(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId,
                key: key2,
                value
              })];
            case 1:
              list = _a3.sent().setUdv;
              return [2, convertUdv(list)];
          }
        });
      });
    };
    AuthenticationClient2.prototype.removeUdv = function(key2) {
      return __awaiter(this, void 0, void 0, function() {
        var userId, list;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              return [4, removeUdv(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId,
                key: key2
              })];
            case 1:
              list = _a3.sent().removeUdv;
              return [2, convertUdv(list)];
          }
        });
      });
    };
    AuthenticationClient2.prototype.listOrgs = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v2/users/me/orgs")
              })];
            case 1:
              return [2, _a3.sent()];
          }
        });
      });
    };
    AuthenticationClient2.prototype.listDepartments = function() {
      return __awaiter(this, void 0, void 0, function() {
        var userId, departments;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              return [4, getUserDepartments(this.graphqlClient, this.tokenProvider, {
                id: userId
              })];
            case 1:
              departments = _a3.sent().user.departments;
              return [2, departments];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByLdap = function(username, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var clientIp, withCustomData, api2, user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              options2 = options2 || {};
              clientIp = options2.clientIp, withCustomData = options2.withCustomData;
              api2 = "".concat(this.baseClient.appHost, "/api/v2/ldap/verify-user");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  username,
                  password,
                  clientIp,
                  withCustomData
                }
              })];
            case 1:
              user2 = _a3.sent();
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.loginByAd = function(username, password, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var clientIp, withCustomData, firstLevelDomain, websocketHost, api2, user2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              options2 = options2 || {};
              clientIp = options2.clientIp, withCustomData = options2.withCustomData;
              firstLevelDomain = new URL(this.baseClient.appHost).hostname.split(".").slice(1).join(".");
              websocketHost = this.options.websocketHost || "https://ws.".concat(firstLevelDomain);
              api2 = "".concat(websocketHost, "/api/v2/ad/verify-user");
              return [4, this.httpClient.request({
                method: "POST",
                url: api2,
                data: {
                  username,
                  password,
                  clientIp,
                  withCustomData
                }
              })];
            case 1:
              user2 = _a3.sent();
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.uploadPhoto = function(accept, cb) {
      accept = accept || "image/*";
      var authing = this;
      uploadFile({
        accept,
        url: "".concat(this.baseClient.appHost, "/api/v2/upload?folder=avatar")
      }).then(function(_a3) {
        var url = _a3.url;
        return cb(url);
      }).catch(function(_a3) {
        var code = _a3.code, message = _a3.message;
        return authing.options.onError(code, message);
      });
    };
    AuthenticationClient2.prototype.updateAvatar = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.uploadAvatar(options2)];
            case 1:
              return [2, _a3.sent()];
          }
        });
      });
    };
    AuthenticationClient2.prototype.uploadAvatar = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        var accept, task, src2, user2;
        var _this = this;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              accept = (options2 || {}).accept;
              this.checkLoggedIn();
              task = new Promise(function(resolve2) {
                _this.uploadPhoto(accept, function(src3) {
                  resolve2(src3);
                });
              });
              return [4, task];
            case 1:
              src2 = _a3.sent();
              return [4, this.updateProfile({ photo: src2 })];
            case 2:
              user2 = _a3.sent();
              this.setCurrentUser(user2);
              return [2, user2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getUdfValue = function() {
      return __awaiter(this, void 0, void 0, function() {
        var userId, list;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              return [4, udv(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId
              })];
            case 1:
              list = _a3.sent().udv;
              return [2, convertUdvToKeyValuePair(list)];
          }
        });
      });
    };
    AuthenticationClient2.prototype.setUdfValue = function(data2) {
      return __awaiter(this, void 0, void 0, function() {
        var userId, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (Object.keys(data2).length === 0) {
                throw new Error("empty udf value list");
              }
              userId = this.checkLoggedIn();
              return [4, setUdvBatch(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId,
                udvList: Object.keys(data2).map(function(key2) {
                  return {
                    key: key2,
                    value: JSON.stringify(data2[key2])
                  };
                })
              })];
            case 1:
              result = _a3.sent().setUdvBatch;
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype.removeUdfValue = function(key2) {
      return __awaiter(this, void 0, void 0, function() {
        var userId;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              userId = this.checkLoggedIn();
              return [4, removeUdv(this.graphqlClient, this.tokenProvider, {
                targetType: UdfTargetType.User,
                targetId: userId,
                key: key2
              })];
            case 1:
              _a3.sent();
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getSecurityLevel = function() {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.httpClient.request({
                method: "GET",
                url: "".concat(this.baseClient.appHost, "/api/v2/users/me/security-level")
              })];
            case 1:
              return [2, _a3.sent()];
          }
        });
      });
    };
    AuthenticationClient2.prototype.listAuthorizedResources = function(namespace, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var userId, resourceType, user2, _a3, list, totalCount;
        return __generator(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              userId = this.checkLoggedIn();
              resourceType = (options2 || {}).resourceType;
              return [4, listUserAuthorizedResources(this.graphqlClient, this.tokenProvider, {
                id: userId,
                namespace,
                resourceType
              })];
            case 1:
              user2 = _b2.sent().user;
              if (!user2) {
                throw new Error("用户不存在");
              }
              _a3 = user2.authorizedResources, list = _a3.list, totalCount = _a3.totalCount;
              list = formatAuthorizedResources(list);
              return [2, {
                list,
                totalCount
              }];
          }
        });
      });
    };
    AuthenticationClient2.prototype.isUserExists = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        var username, email, phone, externalId, data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              username = options2.username, email = options2.email, phone = options2.phone, externalId = options2.externalId;
              return [4, isUserExists(this.graphqlClient, this.tokenProvider, {
                username,
                email,
                phone,
                externalId
              })];
            case 1:
              data2 = _a3.sent().isUserExists;
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.computedPasswordSecurityLevel = function(password) {
      if (typeof password !== "string") {
        throw "password must be a `string`";
      }
      var highLevel = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{12,}$/g);
      var middleLevel = new RegExp(/^(?=.*[a-zA-Z])(?=.*\d)[^]{8,}$/g);
      if (password.match(highLevel) !== null) {
        return PasswordSecurityLevel.HIGH;
      }
      if (password.match(middleLevel) !== null) {
        return PasswordSecurityLevel.MIDDLE;
      }
      return PasswordSecurityLevel.LOW;
    };
    AuthenticationClient2.prototype._generateTokenRequest = function(params) {
      var ret = {};
      Object.keys(params).map(function(key2) {
        if (typeof params[key2] !== "undefined") {
          ret[key2] = params[key2];
        }
      });
      var p2 = new URLSearchParams(ret);
      return p2.toString();
    };
    AuthenticationClient2.prototype._generateBasicAuthToken = function(appId, secret) {
      var id = appId || this.options.appId;
      var s2 = secret || this.options.secret;
      var token = "Basic " + Buffer.from(id + ":" + s2).toString("base64");
      return token;
    };
    AuthenticationClient2.prototype._getAccessTokenByCodeWithClientSecretPost = function(code, codeVerifier) {
      return __awaiter(this, void 0, void 0, function() {
        var qstr, api2, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                client_secret: this.options.secret,
                grant_type: "authorization_code",
                code,
                redirect_uri: this.options.redirectUri,
                code_verifier: codeVerifier
              });
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._getAccessTokenByCodeWithClientSecretBasic = function(code, codeVerifier) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              qstr = this._generateTokenRequest({
                grant_type: "authorization_code",
                code,
                redirect_uri: this.options.redirectUri,
                code_verifier: codeVerifier
              });
              return [4, this.naiveHttpClient.request({
                data: qstr,
                method: "POST",
                url: api2,
                headers: {
                  Authorization: this._generateBasicAuthToken()
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._getAccessTokenByCodeWithNone = function(code, codeVerifier) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                grant_type: "authorization_code",
                code,
                redirect_uri: this.options.redirectUri,
                code_verifier: codeVerifier
              });
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getAccessTokenByIdToken = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        var redirectUri, idToken, _a3, scope, protocolApiMap, api2, tokenSet;
        return __generator(this, function(_b2) {
          switch (_b2.label) {
            case 0:
              redirectUri = options2.redirectUri, idToken = options2.idToken, _a3 = options2.scope, scope = _a3 === void 0 ? "" : _a3;
              protocolApiMap = {
                oidc: "/oidc/token",
                oauth: "/oauth/token"
              };
              api2 = this.baseClient.appHost + protocolApiMap[this.options.protocol] || "";
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: this._generateTokenRequest({
                  client_id: this.options.appId,
                  grant_type: "http://authing.cn/oidc/grant_type/authing_token",
                  redirect_uri: redirectUri,
                  token: idToken,
                  scope
                }),
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _b2.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getAccessTokenByCode = function(code, options2) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!["oauth", "oidc"].includes(this.options.protocol)) {
                throw new Error("初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc，请检查参数");
              }
              if (!this.options.secret && this.options.tokenEndPointAuthMethod !== "none") {
                throw new Error("请在初始化 AuthenticationClient 时传入 appId 和 secret 参数");
              }
              if (!(this.options.tokenEndPointAuthMethod === "client_secret_post")) return [3, 2];
              return [4, this._getAccessTokenByCodeWithClientSecretPost(code, options2 === null || options2 === void 0 ? void 0 : options2.codeVerifier)];
            case 1:
              return [2, _a3.sent()];
            case 2:
              if (!(this.options.tokenEndPointAuthMethod === "client_secret_basic")) return [3, 4];
              return [4, this._getAccessTokenByCodeWithClientSecretBasic(code, options2 === null || options2 === void 0 ? void 0 : options2.codeVerifier)];
            case 3:
              return [2, _a3.sent()];
            case 4:
              if (!(this.options.tokenEndPointAuthMethod === "none")) return [3, 6];
              return [4, this._getAccessTokenByCodeWithNone(code, options2 === null || options2 === void 0 ? void 0 : options2.codeVerifier)];
            case 5:
              return [2, _a3.sent()];
            case 6:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.generateCodeChallenge = function() {
      return generateRandomString(43);
    };
    AuthenticationClient2.prototype.getCodeChallengeDigest = function(options2) {
      if (!options2) {
        throw new Error("请提供 options 参数，options.codeChallenge 为一个长度大于等于 43 的字符串，options.method 可选值为 S256、plain");
      }
      if (!options2.codeChallenge) {
        throw new Error("请提供 options.codeChallenge，值为一个长度大于等于 43 的字符串");
      }
      var _a3 = options2.method, method = _a3 === void 0 ? "S256" : _a3;
      if (method === "S256") {
        return sha256(options2.codeChallenge).toString(CryptoJS.enc.Base64).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
      }
      if (method === "plain") {
        return options2.codeChallenge;
      }
      throw new Error("不支持的 options.method，可选值为 S256、plain");
    };
    AuthenticationClient2.prototype.getAccessTokenByClientCredentials = function(scope, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var i2, s2, qstr, api2, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!scope) {
                throw new Error("请传入 scope 参数，请看文档：https://docs.authing.cn/v2/guides/authorization/m2m-authz.html");
              }
              if (!options2) {
                throw new Error(
                  "请在调用本方法时传入 { accessKey: string, accessSecret: string }，请看文档：https://docs.authing.cn/v2/guides/authorization/m2m-authz.html"
                  // '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数或者在调用本方法时传入 { accessKey: string, accessSecret: string }，请看文档：https://docs.authing.cn/v2/guides/authorization/m2m-authz.html'
                );
              }
              i2 = (options2 === null || options2 === void 0 ? void 0 : options2.accessKey) || this.options.appId;
              s2 = (options2 === null || options2 === void 0 ? void 0 : options2.accessSecret) || this.options.secret;
              qstr = this._generateTokenRequest({
                client_id: i2,
                client_secret: s2,
                grant_type: "client_credentials",
                scope
              });
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getUserInfoByAccessToken = function(accessToken, options2) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, userInfo, userInfo, userInfo, userInfo, userInfo, userInfo;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (options2) {
                if (options2.method && !["POST", "GET"].includes(options2.method)) {
                  throw new Error("options.method 参数的可选值为 POST、GET，请检查输入");
                }
                if (options2.tokenPlace && !["query", "header", "body"].includes(options2.tokenPlace)) {
                  throw new Error("options.tokenPlace 参数的可选值为 query、header、body，请检查输入");
                }
                if (options2.method === "GET" && options2.tokenPlace === "body") {
                  throw new Error("options.method 参数为 GET 时，options.tokenPlace 参数不能为 body");
                }
                options2.method = options2.method || "GET";
                options2.tokenPlace = options2.tokenPlace || "query";
              }
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/me");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/me");
              }
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.method) === "POST")) return [3, 7];
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.tokenPlace) === "header")) return [3, 2];
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                headers: {
                  Authorization: "Bearer " + accessToken
                }
              })];
            case 1:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 2:
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.tokenPlace) === "query")) return [3, 4];
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                params: {
                  access_token: accessToken
                }
              })];
            case 3:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 4:
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.tokenPlace) === "body")) return [3, 6];
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: serialize({
                  access_token: accessToken
                })
              })];
            case 5:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 6:
              return [3, 14];
            case 7:
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.method) === "GET")) return [3, 12];
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.tokenPlace) === "header")) return [3, 9];
              return [4, this.naiveHttpClient.request({
                method: "GET",
                url: api2,
                headers: {
                  Authorization: "Bearer " + accessToken
                }
              })];
            case 8:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 9:
              if (!((options2 === null || options2 === void 0 ? void 0 : options2.tokenPlace) === "query")) return [3, 11];
              return [4, this.naiveHttpClient.request({
                method: "GET",
                url: api2,
                params: {
                  access_token: accessToken
                }
              })];
            case 10:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 11:
              return [3, 14];
            case 12:
              return [4, this.naiveHttpClient.request({
                method: "GET",
                url: api2,
                params: {
                  access_token: accessToken
                }
              })];
            case 13:
              userInfo = _a3.sent();
              return [2, userInfo];
            case 14:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.buildAuthorizeUrl = function(options2) {
      if (!this.baseClient.appHost) {
        throw new Error("请在初始化 AuthenticationClient 时传入应用域名 appHost 参数，形如：https://app1.authing.cn");
      }
      if (this.options.protocol === "oidc") {
        return this._buildOidcAuthorizeUrl(options2);
      }
      if (this.options.protocol === "oauth") {
        return this._buildOauthAuthorizeUrl(options2);
      }
      if (this.options.protocol === "saml") {
        return this._buildSamlAuthorizeUrl();
      }
      if (this.options.protocol === "cas") {
        return this._buildCasAuthorizeUrl(options2);
      }
      throw new Error("不支持的协议类型，请在初始化 AuthenticationClient 时传入 protocol 参数，可选值为 oidc、oauth、saml、cas");
    };
    AuthenticationClient2.prototype._buildOidcAuthorizeUrl = function(options2) {
      var map = {
        appId: "client_id",
        scope: "scope",
        state: "state",
        nonce: "nonce",
        responseMode: "response_mode",
        responseType: "response_type",
        redirectUri: "redirect_uri",
        codeChallenge: "code_challenge",
        codeChallengeMethod: "code_challenge_method",
        tenantId: "tenant_id"
      };
      var res = {
        nonce: Math.random().toString().slice(2),
        state: Math.random().toString().slice(2),
        scope: "openid profile email phone address",
        client_id: this.options.appId,
        redirect_uri: this.options.redirectUri,
        response_type: "code"
      };
      Object.keys(map).forEach(function(k2) {
        if (options2 && options2[k2]) {
          if (k2 === "scope" && options2.scope.includes("offline_access")) {
            res.prompt = "consent";
          }
          res[map[k2]] = options2[k2];
        }
      });
      var params = new URLSearchParams(res);
      var authorizeUrl = this.baseClient.appHost + "/oidc/auth?" + params.toString();
      return authorizeUrl;
    };
    AuthenticationClient2.prototype._buildOauthAuthorizeUrl = function(options2) {
      var map = {
        appId: "client_id",
        scope: "scope",
        state: "state",
        responseType: "response_type",
        redirectUri: "redirect_uri"
      };
      var res = {
        state: Math.random().toString().slice(2),
        scope: "user",
        client_id: this.options.appId,
        redirect_uri: this.options.redirectUri,
        response_type: "code"
      };
      Object.keys(map).forEach(function(k2) {
        if (options2 && options2[k2]) {
          res[map[k2]] = options2[k2];
        }
      });
      var params = new URLSearchParams(res);
      var authorizeUrl = this.baseClient.appHost + "/oauth/auth?" + params.toString();
      return authorizeUrl;
    };
    AuthenticationClient2.prototype._buildSamlAuthorizeUrl = function() {
      return this.baseClient.appHost + "/api/v2/saml-idp/" + this.options.appId;
    };
    AuthenticationClient2.prototype._buildCasAuthorizeUrl = function(options2) {
      if (options2 === null || options2 === void 0 ? void 0 : options2.service) {
        return "".concat(this.baseClient.appHost, "/cas-idp/").concat(this.options.appId, "?service=").concat(options2 === null || options2 === void 0 ? void 0 : options2.service);
      }
      return "".concat(this.baseClient.appHost, "/cas-idp/").concat(this.options.appId);
    };
    AuthenticationClient2.prototype._buildCasLogoutUrl = function(options2) {
      if (options2 === null || options2 === void 0 ? void 0 : options2.redirectUri) {
        return this.baseClient.appHost + "/cas-idp/logout?url=" + options2.redirectUri;
      }
      return "".concat(this.baseClient.appHost, "/cas-idp/logout");
    };
    AuthenticationClient2.prototype._buildOidcLogoutUrl = function(options2) {
      if (options2 && !(options2.idToken && options2.redirectUri)) {
        throw new Error("必须同时传入 idToken 和 redirectUri 参数，或者同时都不传入");
      }
      if (options2 === null || options2 === void 0 ? void 0 : options2.redirectUri) {
        return "".concat(this.baseClient.appHost, "/oidc/session/end?id_token_hint=").concat(options2.idToken, "&post_logout_redirect_uri=").concat(options2.redirectUri);
      }
      return "".concat(this.baseClient.appHost, "/oidc/session/end");
    };
    AuthenticationClient2.prototype._buildEasyLogoutUrl = function(options2) {
      if (options2 === null || options2 === void 0 ? void 0 : options2.redirectUri) {
        return "".concat(this.baseClient.appHost, "/login/profile/logout?redirect_uri=").concat(options2.redirectUri);
      }
      return "".concat(this.baseClient.appHost, "/login/profile/logout");
    };
    AuthenticationClient2.prototype.buildLogoutUrl = function(options2) {
      if (this.options.protocol === "cas") {
        return this._buildCasLogoutUrl(options2);
      }
      if (this.options.protocol === "oidc" && (options2 === null || options2 === void 0 ? void 0 : options2.expert)) {
        return this._buildOidcLogoutUrl(options2);
      }
      return this._buildEasyLogoutUrl(options2);
    };
    AuthenticationClient2.prototype._getNewAccessTokenByRefreshTokenWithClientSecretPost = function(refreshToken2) {
      return __awaiter(this, void 0, void 0, function() {
        var qstr, api2, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                client_secret: this.options.secret,
                grant_type: "refresh_token",
                refresh_token: refreshToken2
              });
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._getNewAccessTokenByRefreshTokenWithClientSecretBasic = function(refreshToken2) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              qstr = this._generateTokenRequest({
                grant_type: "refresh_token",
                refresh_token: refreshToken2
              });
              return [4, this.naiveHttpClient.request({
                data: qstr,
                method: "POST",
                url: api2,
                headers: {
                  Authorization: this._generateBasicAuthToken()
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._getNewAccessTokenByRefreshTokenWithNone = function(refreshToken2) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token");
              }
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                grant_type: "refresh_token",
                refresh_token: refreshToken2
              });
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype.getNewAccessTokenByRefreshToken = function(refreshToken2) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!["oauth", "oidc"].includes(this.options.protocol)) {
                throw new Error("初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc，请检查参数");
              }
              if (!this.options.secret && this.options.tokenEndPointAuthMethod !== "none") {
                throw new Error("请在初始化 AuthenticationClient 时传入 appId 和 secret 参数");
              }
              if (!(this.options.tokenEndPointAuthMethod === "client_secret_post")) return [3, 2];
              return [4, this._getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken2)];
            case 1:
              return [2, _a3.sent()];
            case 2:
              if (!(this.options.tokenEndPointAuthMethod === "client_secret_basic")) return [3, 4];
              return [4, this._getNewAccessTokenByRefreshTokenWithClientSecretBasic(refreshToken2)];
            case 3:
              return [2, _a3.sent()];
            case 4:
              if (!(this.options.tokenEndPointAuthMethod === "none")) return [3, 6];
              return [4, this._getNewAccessTokenByRefreshTokenWithNone(refreshToken2)];
            case 5:
              return [2, _a3.sent()];
            case 6:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype._revokeTokenWithClientSecretPost = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var qstr, api2, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                client_secret: this.options.secret,
                token
              });
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/revocation");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token/revocation");
              }
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._revokeTokenWithClientSecretBasic = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/revocation");
              } else if (this.options.protocol === "oauth") {
                throw new Error("OAuth 2.0 暂不支持用 client_secret_basic 模式身份验证撤回 Token");
              }
              qstr = this._generateTokenRequest({
                token
              });
              return [4, this.naiveHttpClient.request({
                data: qstr,
                method: "POST",
                url: api2,
                headers: {
                  Authorization: this._generateBasicAuthToken()
                }
              })];
            case 1:
              result = _a3.sent();
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype._revokeTokenWithNone = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/revocation");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token/revocation");
              }
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                token
              });
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr
              })];
            case 1:
              result = _a3.sent();
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype.revokeToken = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!["oauth", "oidc"].includes(this.options.protocol)) {
                throw new Error("初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc，请检查参数");
              }
              if (!this.options.secret && this.options.revocationEndPointAuthMethod !== "none") {
                throw new Error("请在初始化 AuthenticationClient 时传入 appId 和 secret 参数");
              }
              if (!(this.options.revocationEndPointAuthMethod === "client_secret_post")) return [3, 2];
              return [4, this._revokeTokenWithClientSecretPost(token)];
            case 1:
              _a3.sent();
              return [2, true];
            case 2:
              if (!(this.options.revocationEndPointAuthMethod === "client_secret_basic")) return [3, 4];
              return [4, this._revokeTokenWithClientSecretBasic(token)];
            case 3:
              _a3.sent();
              return [2, true];
            case 4:
              if (!(this.options.revocationEndPointAuthMethod === "none")) return [3, 6];
              return [4, this._revokeTokenWithNone(token)];
            case 5:
              _a3.sent();
              return [2, true];
            case 6:
              throw new Error("初始化 AuthenticationClient 时传入的 revocationEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none，请检查参数");
          }
        });
      });
    };
    AuthenticationClient2.prototype._introspectTokenWithClientSecretPost = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var qstr, api2, tokenSet;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                client_secret: this.options.secret,
                token
              });
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/introspection");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token/introspection");
              }
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded"
                }
              })];
            case 1:
              tokenSet = _a3.sent();
              return [2, tokenSet];
          }
        });
      });
    };
    AuthenticationClient2.prototype._introspectTokenWithClientSecretBasic = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/introspection");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token/introspection");
              }
              qstr = this._generateTokenRequest({
                token
              });
              return [4, this.naiveHttpClient.request({
                data: qstr,
                method: "POST",
                url: api2,
                headers: {
                  Authorization: this._generateBasicAuthToken()
                }
              })];
            case 1:
              result = _a3.sent();
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype._introspectTokenWithNone = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, qstr, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "";
              if (this.options.protocol === "oidc") {
                api2 = "".concat(this.baseClient.appHost, "/oidc/token/introspection");
              } else if (this.options.protocol === "oauth") {
                api2 = "".concat(this.baseClient.appHost, "/oauth/token/introspection");
              }
              qstr = this._generateTokenRequest({
                client_id: this.options.appId,
                token
              });
              return [4, this.naiveHttpClient.request({
                method: "POST",
                url: api2,
                data: qstr
              })];
            case 1:
              result = _a3.sent();
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype.introspectToken = function(token) {
      return __awaiter(this, void 0, void 0, function() {
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!["oauth", "oidc"].includes(this.options.protocol)) {
                throw new Error("初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc，请检查参数");
              }
              if (!this.options.secret && this.options.introspectionEndPointAuthMethod !== "none") {
                throw new Error("请在初始化 AuthenticationClient 时传入 appId 和 secret 参数");
              }
              if (!(this.options.introspectionEndPointAuthMethod === "client_secret_post")) return [3, 2];
              return [4, this._introspectTokenWithClientSecretPost(token)];
            case 1:
              return [2, _a3.sent()];
            case 2:
              if (!(this.options.introspectionEndPointAuthMethod === "client_secret_basic")) return [3, 4];
              return [4, this._introspectTokenWithClientSecretBasic(token)];
            case 3:
              return [2, _a3.sent()];
            case 4:
              if (!(this.options.introspectionEndPointAuthMethod === "none")) return [3, 6];
              return [4, this._introspectTokenWithNone(token)];
            case 5:
              return [2, _a3.sent()];
            case 6:
              throw new Error("初始化 AuthenticationClient 时传入的 introspectionEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none，请检查参数");
          }
        });
      });
    };
    AuthenticationClient2.prototype.validateTicketV1 = function(ticket, service) {
      return __awaiter(this, void 0, void 0, function() {
        var api2, result, valid;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              api2 = "".concat(this.baseClient.appHost, "/cas-idp/").concat(this.options.appId, "/validate");
              return [4, this.naiveHttpClient.request({
                method: "GET",
                url: api2,
                params: {
                  service,
                  ticket
                }
              })];
            case 1:
              result = _a3.sent();
              valid = result.split("\n")[0];
              return [2, __assign({ valid: valid === "yes" }, valid !== "yes" && { message: "ticket 不合法" })];
          }
        });
      });
    };
    AuthenticationClient2.prototype.validateTicketV2 = function(ticket, service, format2) {
      if (format2 === void 0) {
        format2 = "JSON";
      }
      return __awaiter(this, void 0, void 0, function() {
        var api2, result;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!ticket) {
                throw new Error("请传入 ticket 一次性票据");
              }
              if (!service) {
                throw new Error("请传入 service 服务地址");
              }
              if (format2 !== "XML" && format2 !== "JSON") {
                throw new Error("format 参数可选值为 XML、JSON，请检查输入");
              }
              api2 = "".concat(this.baseClient.appHost, "/cas-idp/").concat(this.options.appId, "/serviceValidate");
              return [4, this.naiveHttpClient.request({
                method: "GET",
                url: api2,
                params: {
                  service,
                  ticket,
                  format: format2
                }
              })];
            case 1:
              result = _a3.sent();
              return [2, result];
          }
        });
      });
    };
    AuthenticationClient2.prototype.hasRole = function(roleCode, namespace) {
      return __awaiter(this, void 0, void 0, function() {
        var user2, roleList, hasRole;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, getUserRoles(this.graphqlClient, this.tokenProvider, {
                id: this.checkLoggedIn(),
                namespace
              })];
            case 1:
              user2 = _a3.sent().user;
              if (!user2) {
                return [2, false];
              }
              roleList = user2.roles;
              if (roleList.totalCount < 1) {
                return [2, false];
              }
              hasRole = false;
              roleList.list.forEach(function(item) {
                if (item.code === roleCode) {
                  hasRole = true;
                }
              });
              return [2, hasRole];
          }
        });
      });
    };
    AuthenticationClient2.prototype.listApplications = function(params) {
      return __awaiter(this, void 0, void 0, function() {
        var _a3, _b2, page, _c2, limit, data2;
        return __generator(this, function(_d2) {
          switch (_d2.label) {
            case 0:
              _a3 = params || {}, _b2 = _a3.page, page = _b2 === void 0 ? 1 : _b2, _c2 = _a3.limit, limit = _c2 === void 0 ? 10 : _c2;
              return [4, this.httpClient.request({
                url: "".concat(this.baseClient.appHost, "/api/v2/users/me/applications/allowed?page=").concat(page, "&limit=").concat(limit),
                method: "GET"
              })];
            case 1:
              data2 = _d2.sent();
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.validateToken = function(options2) {
      return __awaiter(this, void 0, void 0, function() {
        var data2, data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              if (!options2) {
                throw new Error("请在传入的参数对象中包含 accessToken 或 idToken 字段");
              }
              if (options2.accessToken && options2.idToken) {
                throw new Error("accessToken 和 idToken 只能传入一个，不能同时传入");
              }
              if (!options2.idToken) return [3, 2];
              return [4, this.naiveHttpClient.request({
                url: "".concat(this.baseClient.appHost, "/api/v2/oidc/validate_token"),
                method: "GET",
                params: {
                  id_token: options2.idToken
                }
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
            case 2:
              if (!options2.accessToken) return [3, 4];
              return [4, this.naiveHttpClient.request({
                url: "".concat(this.baseClient.appHost, "/api/v2/oidc/validate_token"),
                method: "GET",
                params: {
                  access_token: options2.accessToken
                }
              })];
            case 3:
              data2 = _a3.sent();
              return [2, data2];
            case 4:
              return [
                2
                /*return*/
              ];
          }
        });
      });
    };
    AuthenticationClient2.prototype.trackSession = function() {
      return __awaiter(this, void 0, void 0, function() {
        var data2;
        return __generator(this, function(_a3) {
          switch (_a3.label) {
            case 0:
              return [4, this.naiveHttpClient.request({
                url: "".concat(this.baseClient.appHost, "/cas/session"),
                method: "GET"
              })];
            case 1:
              data2 = _a3.sent();
              return [2, data2];
          }
        });
      });
    };
    AuthenticationClient2.prototype.setLang = function(lang) {
      this.options.lang = lang;
    };
    AuthenticationClient2.prototype.signinByCredentials = function(params) {
      var _a3, _b2;
      return __awaiter(this, void 0, void 0, function() {
        var res, state;
        return __generator(this, function(_c2) {
          switch (_c2.label) {
            case 0:
              if (((_a3 = params.options) === null || _a3 === void 0 ? void 0 : _a3.responseType) === SignInResponseType.Code) {
                params.options.redirectUri = params.options.redirectUri || this.options.redirectUri;
              }
              return [4, this.naiveHttpClient.request({
                url: "".concat(this.baseClient.appHost, "/api/v3/signin"),
                data: params,
                method: "POST",
                notHandleRes: true
              })];
            case 1:
              res = _c2.sent();
              state = params.options.state || Math.random().toString(36).slice(-8);
              if (res.statusCode === 200) {
                if ((_b2 = params.options) === null || _b2 === void 0 ? void 0 : _b2.autoRedirect) {
                  console.log("".concat(params.options.redirectUri, "?code=").concat(res.data.code, "&state=").concat(state));
                  window.location.href = "".concat(params.options.redirectUri, "?code=").concat(res.data.code, "&state=").concat(params.options.state || Math.random().toString(36).slice(-8));
                }
                return [2, __assign(__assign({}, res.data), { state })];
              }
              throw new Error(JSON.stringify(res));
          }
        });
      });
    };
    return AuthenticationClient2;
  }()
);
var cryptoBrowserifyExports = /* @__PURE__ */ requireCryptoBrowserify();
const publicKey = Buffer.from("LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1NRnd3RFFZSktvWklodmNOQVFFQkJRQURTd0F3U0FKQkFLZG5XelRubVFOR3Fyb0ZTVjlITEtYNGhNZGp5NTY5SjZSYUdMTVRQUXhKUWowZHoyY2VRTEJhbEF0aUg0K21BY0kvakFKKzJhZ2IrK1Z4ZjROS1RBc0NBd0VBQVE9PS0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ==", "base64").toString("utf-8");
function decrypt(encryptedText) {
  try {
    const encryptedBuffer = Buffer.from(encryptedText, "base64");
    const decryptedBuffer = cryptoBrowserifyExports.publicDecrypt(
      {
        key: publicKey,
        padding: cryptoBrowserifyExports.constants.RSA_PKCS1_PADDING
      },
      encryptedBuffer
    );
    const removePadding = (data2) => {
      const bytes = Array.from(data2);
      let startIndex = 0;
      while (startIndex < bytes.length && bytes[startIndex] === 0) {
        startIndex++;
      }
      if (startIndex < bytes.length && bytes[startIndex] === 1) {
        startIndex++;
      }
      while (startIndex < bytes.length && bytes[startIndex] === 255) {
        startIndex++;
      }
      if (startIndex < bytes.length && bytes[startIndex] === 0) {
        startIndex++;
      }
      return Buffer.from(bytes.slice(startIndex)).toString("utf8");
    };
    return removePadding(decryptedBuffer);
  } catch (error) {
    throw new Error(`解密失败: ${error.message}`);
  }
}
function validatePhoneNumber(phone) {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
}
function formatPhoneNumber(phone) {
  return phone.replace(/\s+/g, "").replace(/[^\d]/g, "");
}
class PhoneValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "PhoneValidationError";
  }
}
function ox12jdiowqdqoi() {
  return decrypt("NgF3cAwslW3JrCfF7xsyUy++H0dqMvdJMNjjVwiVZFOb08Kq8v6oeklzFzri9O7rl1cOcWgaWRhX+SLtNw1NVw==").toString();
}
class DefaultLoginProvider {
  constructor(authingAppId = ox12jdiowqdqoi()) {
    __publicField2(this, "authing");
    this.authingAppId = authingAppId;
    this.authing = new AuthenticationClient({
      appId: authingAppId
    });
  }
  async intervalCheck(token) {
    return { loginValid: true, nextCheckTime: 3600 * 1e3 };
  }
  async validateToken(token) {
    const result = await this.authing.validateToken({ idToken: token });
    if (!result.data) {
      throw new Error("Invalid token");
    }
    return {
      username: result.data.username || "",
      email: result.data.email || ""
    };
  }
  async register(params) {
    if ("passwordPayload" in params) {
      if ("username" in params.passwordPayload) {
        await this.authing.registerByUsername(params.passwordPayload.username, params.passwordPayload.password);
      } else if ("email" in params.passwordPayload) {
        await this.authing.registerByEmail(params.passwordPayload.email, params.passwordPayload.password);
      } else if ("phone" in params.passwordPayload) {
        throw new Error("Phone registration by password is not supported");
      }
    } else if ("passcodePayload" in params) {
      if ("phone" in params.passcodePayload) {
        const formattedPhone = formatPhoneNumber(params.passcodePayload.phone);
        if (!validatePhoneNumber(formattedPhone)) {
          throw new PhoneValidationError("Invalid phone number format");
        }
        if (!params.passcodePayload.code || params.passcodePayload.code.trim().length === 0) {
          throw new Error("Verification code is required");
        }
        try {
          await this.authing.registerByPhoneCode(formattedPhone, params.passcodePayload.code.trim());
        } catch (error) {
          throw new Error(`Phone registration failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
      } else if ("email" in params.passcodePayload) {
        if (!params.passcodePayload.code || params.passcodePayload.code.trim().length === 0) {
          throw new Error("Verification code is required");
        }
        try {
          await this.authing.registerByEmailCode(params.passcodePayload.email, params.passcodePayload.code.trim());
        } catch (error) {
          throw new Error(`Email registration failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
      }
    } else {
      throw new Error("Either passwordPayload or passcodePayload must be provided");
    }
  }
  async login(params) {
    if ("passwordPayload" in params) {
      if ("identifier" in params.passwordPayload) {
        const identifier = params.passwordPayload.identifier;
        const password = params.passwordPayload.password;
        let lastError;
        if (/^\+?\d+$/.test(identifier)) {
          try {
            const user2 = await this.authing.loginByPhonePassword(identifier, password);
            return {
              ...user2,
              ...{ authingAppId: this.authingAppId },
              token: user2.token || ""
            };
          } catch (error) {
            lastError = error;
            try {
              const user2 = await this.authing.loginByUsername(identifier, password);
              return {
                ...user2,
                ...{ authingAppId: this.authingAppId },
                token: user2.token || ""
              };
            } catch (fallbackError) {
              throw lastError;
            }
          }
        } else if (identifier.includes("@")) {
          try {
            const user2 = await this.authing.loginByEmail(identifier, password);
            return {
              ...user2,
              ...{ authingAppId: this.authingAppId },
              token: user2.token || ""
            };
          } catch (error) {
            lastError = error;
            try {
              const user2 = await this.authing.loginByUsername(identifier, password);
              return {
                ...user2,
                ...{ authingAppId: this.authingAppId },
                token: user2.token || ""
              };
            } catch (fallbackError) {
              throw lastError;
            }
          }
        } else {
          const user2 = await this.authing.loginByUsername(identifier, password);
          return {
            ...user2,
            ...{ authingAppId: this.authingAppId },
            token: user2.token || ""
          };
        }
      } else if ("username" in params.passwordPayload) {
        const user2 = await this.authing.loginByUsername(params.passwordPayload.username, params.passwordPayload.password);
        return {
          ...user2,
          ...{ authingAppId: this.authingAppId },
          token: user2.token || ""
        };
      } else if ("email" in params.passwordPayload) {
        const user2 = await this.authing.loginByEmail(params.passwordPayload.email, params.passwordPayload.password);
        return {
          ...user2,
          ...{ authingAppId: this.authingAppId },
          token: user2.token || ""
        };
      } else if ("phone" in params.passwordPayload) {
        const user2 = await this.authing.loginByUsername(params.passwordPayload.phone, params.passwordPayload.password);
        return {
          ...user2,
          ...{ authingAppId: this.authingAppId },
          token: user2.token || ""
        };
      } else {
        throw new Error("Invalid passwordPayload format");
      }
    } else if (params.passcodePayload) {
      if ("phone" in params.passcodePayload) {
        const formattedPhone = formatPhoneNumber(params.passcodePayload.phone);
        if (!validatePhoneNumber(formattedPhone)) {
          throw new PhoneValidationError("Invalid phone number format");
        }
        if (!params.passcodePayload.code || params.passcodePayload.code.trim().length === 0) {
          throw new Error("Verification code is required");
        }
        try {
          const user2 = await this.authing.loginByPhoneCode(formattedPhone, params.passcodePayload.code.trim());
          return {
            ...user2,
            ...{ authingAppId: this.authingAppId },
            token: user2.token || ""
          };
        } catch (error) {
          throw new Error(`Phone login failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
      } else if ("email" in params.passcodePayload) {
        if (!params.passcodePayload.code || params.passcodePayload.code.trim().length === 0) {
          throw new Error("Verification code is required");
        }
        try {
          const user2 = await this.authing.loginByEmailCode(params.passcodePayload.email, params.passcodePayload.code.trim());
          return {
            ...user2,
            ...{ authingAppId: this.authingAppId },
            token: user2.token || ""
          };
        } catch (error) {
          throw new Error(`Email login failed: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
      } else {
        throw new Error("Invalid passcodePayload format");
      }
    } else {
      throw new Error("Either passwordPayload or passcodePayload must be provided");
    }
  }
  isQRCodeSupported() {
    return true;
  }
  async *loginByQRCode() {
    const { url, random } = await this.authing.wxqrcode.geneCode();
    yield { qrcodeURL: url, status: "ready" };
    const events2 = [];
    let finished = false;
    this.authing.wxqrcode.startPolling(random, {
      onScanned: (userInfo) => {
        events2.push({ status: "scanned" });
      },
      onResult: (data2) => {
        if (data2 && typeof data2 === "object" && "ticket" in data2 && data2.ticket) {
          this.authing.wxqrcode.exchangeUserInfo(data2.ticket).then((userInfo) => {
            events2.push({
              status: "success",
              userInfo: { ...userInfo, token: userInfo.token || "" }
            });
            finished = true;
          }).catch(() => {
            events2.push({ status: "error" });
            finished = true;
          });
        }
      },
      onCancel: () => {
        events2.push({ status: "cancel" });
        finished = true;
      },
      onExpired: () => {
        events2.push({ status: "expired" });
        finished = true;
      },
      onError: (error) => {
        events2.push({ status: "error" });
        finished = true;
      }
    });
    while (!finished || events2.length > 0) {
      if (events2.length > 0) {
        const event = events2.shift();
        yield { qrcodeURL: url, status: event.status, userInfo: event.userInfo };
        if (event.status === "success" || event.status === "cancel" || event.status === "expired" || event.status === "error") {
          break;
        }
      }
      await new Promise((resolve2) => setTimeout(resolve2, 100));
    }
  }
  isPhoneLoginSupported() {
    return true;
  }
  async sendPassCode(params) {
    if (params.phone) {
      const formattedPhone = formatPhoneNumber(params.phone);
      if (!validatePhoneNumber(formattedPhone)) {
        throw new PhoneValidationError("Invalid phone number format");
      }
      try {
        await this.authing.sendSmsCode(formattedPhone);
      } catch (error) {
        throw new Error(`Failed to send SMS code: ${error instanceof Error ? error.message : "Unknown error"}`);
      }
    } else if (params.email) {
      throw new Error("Email code sending is not supported");
    } else {
      throw new Error("Either phone or email must be provided");
    }
  }
  async getUserProfile(token) {
    const response = await fetch("https://api.authing.cn/api/v3/get-profile", {
      method: "GET",
      headers: {
        "Authorization": `Bearer ${token}`,
        "x-authing-app-id": this.authingAppId
      }
    });
    const result = await response.json();
    if (!result.data) {
      throw new Error("Invalid token");
    }
    return {
      username: result.data.username || "",
      email: result.data.email || "",
      ...result.data
    };
  }
}
const createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set();
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const api2 = { setState, getState, getInitialState, subscribe };
  const initialState = state = createState(setState, getState, api2);
  return api2;
};
const createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;
var react = { exports: {} };
var react_development = { exports: {} };
react_development.exports;
var hasRequiredReact_development;
function requireReact_development() {
  if (hasRequiredReact_development) return react_development.exports;
  hasRequiredReact_development = 1;
  (function(module2, exports) {
    /**
     * @license React
     * react.development.js
     *
     * Copyright (c) Facebook, Inc. and its affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    {
      (function() {
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
        }
        var ReactVersion = "18.3.1";
        var REACT_ELEMENT_TYPE = Symbol.for("react.element");
        var REACT_PORTAL_TYPE = Symbol.for("react.portal");
        var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
        var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
        var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
        var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
        var REACT_CONTEXT_TYPE = Symbol.for("react.context");
        var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
        var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
        var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
        var REACT_MEMO_TYPE = Symbol.for("react.memo");
        var REACT_LAZY_TYPE = Symbol.for("react.lazy");
        var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
        var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
        var FAUX_ITERATOR_SYMBOL = "@@iterator";
        function getIteratorFn(maybeIterable) {
          if (maybeIterable === null || typeof maybeIterable !== "object") {
            return null;
          }
          var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
          if (typeof maybeIterator === "function") {
            return maybeIterator;
          }
          return null;
        }
        var ReactCurrentDispatcher = {
          /**
           * @internal
           * @type {ReactComponent}
           */
          current: null
        };
        var ReactCurrentBatchConfig = {
          transition: null
        };
        var ReactCurrentActQueue = {
          current: null,
          // Used to reproduce behavior of `batchedUpdates` in legacy mode.
          isBatchingLegacy: false,
          didScheduleLegacyUpdate: false
        };
        var ReactCurrentOwner = {
          /**
           * @internal
           * @type {ReactComponent}
           */
          current: null
        };
        var ReactDebugCurrentFrame = {};
        var currentExtraStackFrame = null;
        function setExtraStackFrame(stack) {
          {
            currentExtraStackFrame = stack;
          }
        }
        {
          ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
            {
              currentExtraStackFrame = stack;
            }
          };
          ReactDebugCurrentFrame.getCurrentStack = null;
          ReactDebugCurrentFrame.getStackAddendum = function() {
            var stack = "";
            if (currentExtraStackFrame) {
              stack += currentExtraStackFrame;
            }
            var impl = ReactDebugCurrentFrame.getCurrentStack;
            if (impl) {
              stack += impl() || "";
            }
            return stack;
          };
        }
        var enableScopeAPI = false;
        var enableCacheElement = false;
        var enableTransitionTracing = false;
        var enableLegacyHidden = false;
        var enableDebugTracing = false;
        var ReactSharedInternals = {
          ReactCurrentDispatcher,
          ReactCurrentBatchConfig,
          ReactCurrentOwner
        };
        {
          ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
          ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue;
        }
        function warn(format2) {
          {
            {
              for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
                args[_key - 1] = arguments[_key];
              }
              printWarning("warn", format2, args);
            }
          }
        }
        function error(format2) {
          {
            {
              for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
                args[_key2 - 1] = arguments[_key2];
              }
              printWarning("error", format2, args);
            }
          }
        }
        function printWarning(level, format2, args) {
          {
            var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
            var stack = ReactDebugCurrentFrame2.getStackAddendum();
            if (stack !== "") {
              format2 += "%s";
              args = args.concat([stack]);
            }
            var argsWithFormat = args.map(function(item) {
              return String(item);
            });
            argsWithFormat.unshift("Warning: " + format2);
            Function.prototype.apply.call(console[level], console, argsWithFormat);
          }
        }
        var didWarnStateUpdateForUnmountedComponent = {};
        function warnNoop(publicInstance, callerName) {
          {
            var _constructor = publicInstance.constructor;
            var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass";
            var warningKey = componentName + "." + callerName;
            if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
              return;
            }
            error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName);
            didWarnStateUpdateForUnmountedComponent[warningKey] = true;
          }
        }
        var ReactNoopUpdateQueue = {
          /**
           * Checks whether or not this composite component is mounted.
           * @param {ReactClass} publicInstance The instance we want to test.
           * @return {boolean} True if mounted, false otherwise.
           * @protected
           * @final
           */
          isMounted: function(publicInstance) {
            return false;
          },
          /**
           * Forces an update. This should only be invoked when it is known with
           * certainty that we are **not** in a DOM transaction.
           *
           * You may want to call this when you know that some deeper aspect of the
           * component's state has changed but `setState` was not called.
           *
           * This will not invoke `shouldComponentUpdate`, but it will invoke
           * `componentWillUpdate` and `componentDidUpdate`.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {?function} callback Called after component is updated.
           * @param {?string} callerName name of the calling function in the public API.
           * @internal
           */
          enqueueForceUpdate: function(publicInstance, callback, callerName) {
            warnNoop(publicInstance, "forceUpdate");
          },
          /**
           * Replaces all of the state. Always use this or `setState` to mutate state.
           * You should treat `this.state` as immutable.
           *
           * There is no guarantee that `this.state` will be immediately updated, so
           * accessing `this.state` after calling this method may return the old value.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {object} completeState Next state.
           * @param {?function} callback Called after component is updated.
           * @param {?string} callerName name of the calling function in the public API.
           * @internal
           */
          enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
            warnNoop(publicInstance, "replaceState");
          },
          /**
           * Sets a subset of the state. This only exists because _pendingState is
           * internal. This provides a merging strategy that is not available to deep
           * properties which is confusing. TODO: Expose pendingState or don't use it
           * during the merge.
           *
           * @param {ReactClass} publicInstance The instance that should rerender.
           * @param {object} partialState Next partial state to be merged with state.
           * @param {?function} callback Called after component is updated.
           * @param {?string} Name of the calling function in the public API.
           * @internal
           */
          enqueueSetState: function(publicInstance, partialState, callback, callerName) {
            warnNoop(publicInstance, "setState");
          }
        };
        var assign = Object.assign;
        var emptyObject = {};
        {
          Object.freeze(emptyObject);
        }
        function Component(props, context, updater) {
          this.props = props;
          this.context = context;
          this.refs = emptyObject;
          this.updater = updater || ReactNoopUpdateQueue;
        }
        Component.prototype.isReactComponent = {};
        Component.prototype.setState = function(partialState, callback) {
          if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) {
            throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
          }
          this.updater.enqueueSetState(this, partialState, callback, "setState");
        };
        Component.prototype.forceUpdate = function(callback) {
          this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
        };
        {
          var deprecatedAPIs = {
            isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],
            replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]
          };
          var defineDeprecationWarning = function(methodName, info) {
            Object.defineProperty(Component.prototype, methodName, {
              get: function() {
                warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
                return void 0;
              }
            });
          };
          for (var fnName in deprecatedAPIs) {
            if (deprecatedAPIs.hasOwnProperty(fnName)) {
              defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
            }
          }
        }
        function ComponentDummy() {
        }
        ComponentDummy.prototype = Component.prototype;
        function PureComponent(props, context, updater) {
          this.props = props;
          this.context = context;
          this.refs = emptyObject;
          this.updater = updater || ReactNoopUpdateQueue;
        }
        var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
        pureComponentPrototype.constructor = PureComponent;
        assign(pureComponentPrototype, Component.prototype);
        pureComponentPrototype.isPureReactComponent = true;
        function createRef() {
          var refObject = {
            current: null
          };
          {
            Object.seal(refObject);
          }
          return refObject;
        }
        var isArrayImpl = Array.isArray;
        function isArray2(a2) {
          return isArrayImpl(a2);
        }
        function typeName(value) {
          {
            var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
            var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
            return type2;
          }
        }
        function willCoercionThrow(value) {
          {
            try {
              testStringCoercion(value);
              return false;
            } catch (e4) {
              return true;
            }
          }
        }
        function testStringCoercion(value) {
          return "" + value;
        }
        function checkKeyStringCoercion(value) {
          {
            if (willCoercionThrow(value)) {
              error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
              return testStringCoercion(value);
            }
          }
        }
        function getWrappedName(outerType, innerType, wrapperName) {
          var displayName = outerType.displayName;
          if (displayName) {
            return displayName;
          }
          var functionName = innerType.displayName || innerType.name || "";
          return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
        }
        function getContextName(type2) {
          return type2.displayName || "Context";
        }
        function getComponentNameFromType(type2) {
          if (type2 == null) {
            return null;
          }
          {
            if (typeof type2.tag === "number") {
              error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
            }
          }
          if (typeof type2 === "function") {
            return type2.displayName || type2.name || null;
          }
          if (typeof type2 === "string") {
            return type2;
          }
          switch (type2) {
            case REACT_FRAGMENT_TYPE:
              return "Fragment";
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_PROFILER_TYPE:
              return "Profiler";
            case REACT_STRICT_MODE_TYPE:
              return "StrictMode";
            case REACT_SUSPENSE_TYPE:
              return "Suspense";
            case REACT_SUSPENSE_LIST_TYPE:
              return "SuspenseList";
          }
          if (typeof type2 === "object") {
            switch (type2.$$typeof) {
              case REACT_CONTEXT_TYPE:
                var context = type2;
                return getContextName(context) + ".Consumer";
              case REACT_PROVIDER_TYPE:
                var provider = type2;
                return getContextName(provider._context) + ".Provider";
              case REACT_FORWARD_REF_TYPE:
                return getWrappedName(type2, type2.render, "ForwardRef");
              case REACT_MEMO_TYPE:
                var outerName = type2.displayName || null;
                if (outerName !== null) {
                  return outerName;
                }
                return getComponentNameFromType(type2.type) || "Memo";
              case REACT_LAZY_TYPE: {
                var lazyComponent = type2;
                var payload = lazyComponent._payload;
                var init2 = lazyComponent._init;
                try {
                  return getComponentNameFromType(init2(payload));
                } catch (x2) {
                  return null;
                }
              }
            }
          }
          return null;
        }
        var hasOwnProperty = Object.prototype.hasOwnProperty;
        var RESERVED_PROPS = {
          key: true,
          ref: true,
          __self: true,
          __source: true
        };
        var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
        {
          didWarnAboutStringRefs = {};
        }
        function hasValidRef(config) {
          {
            if (hasOwnProperty.call(config, "ref")) {
              var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.ref !== void 0;
        }
        function hasValidKey(config) {
          {
            if (hasOwnProperty.call(config, "key")) {
              var getter = Object.getOwnPropertyDescriptor(config, "key").get;
              if (getter && getter.isReactWarning) {
                return false;
              }
            }
          }
          return config.key !== void 0;
        }
        function defineKeyPropWarningGetter(props, displayName) {
          var warnAboutAccessingKey = function() {
            {
              if (!specialPropKeyWarningShown) {
                specialPropKeyWarningShown = true;
                error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            }
          };
          warnAboutAccessingKey.isReactWarning = true;
          Object.defineProperty(props, "key", {
            get: warnAboutAccessingKey,
            configurable: true
          });
        }
        function defineRefPropWarningGetter(props, displayName) {
          var warnAboutAccessingRef = function() {
            {
              if (!specialPropRefWarningShown) {
                specialPropRefWarningShown = true;
                error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
              }
            }
          };
          warnAboutAccessingRef.isReactWarning = true;
          Object.defineProperty(props, "ref", {
            get: warnAboutAccessingRef,
            configurable: true
          });
        }
        function warnIfStringRefCannotBeAutoConverted(config) {
          {
            if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
              var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
              if (!didWarnAboutStringRefs[componentName]) {
                error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref);
                didWarnAboutStringRefs[componentName] = true;
              }
            }
          }
        }
        var ReactElement = function(type2, key2, ref2, self2, source, owner, props) {
          var element = {
            // This tag allows us to uniquely identify this as a React Element
            $$typeof: REACT_ELEMENT_TYPE,
            // Built-in properties that belong on the element
            type: type2,
            key: key2,
            ref: ref2,
            props,
            // Record the component responsible for creating this element.
            _owner: owner
          };
          {
            element._store = {};
            Object.defineProperty(element._store, "validated", {
              configurable: false,
              enumerable: false,
              writable: true,
              value: false
            });
            Object.defineProperty(element, "_self", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: self2
            });
            Object.defineProperty(element, "_source", {
              configurable: false,
              enumerable: false,
              writable: false,
              value: source
            });
            if (Object.freeze) {
              Object.freeze(element.props);
              Object.freeze(element);
            }
          }
          return element;
        };
        function createElement(type2, config, children) {
          var propName;
          var props = {};
          var key2 = null;
          var ref2 = null;
          var self2 = null;
          var source = null;
          if (config != null) {
            if (hasValidRef(config)) {
              ref2 = config.ref;
              {
                warnIfStringRefCannotBeAutoConverted(config);
              }
            }
            if (hasValidKey(config)) {
              {
                checkKeyStringCoercion(config.key);
              }
              key2 = "" + config.key;
            }
            self2 = config.__self === void 0 ? null : config.__self;
            source = config.__source === void 0 ? null : config.__source;
            for (propName in config) {
              if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
                props[propName] = config[propName];
              }
            }
          }
          var childrenLength = arguments.length - 2;
          if (childrenLength === 1) {
            props.children = children;
          } else if (childrenLength > 1) {
            var childArray = Array(childrenLength);
            for (var i2 = 0; i2 < childrenLength; i2++) {
              childArray[i2] = arguments[i2 + 2];
            }
            {
              if (Object.freeze) {
                Object.freeze(childArray);
              }
            }
            props.children = childArray;
          }
          if (type2 && type2.defaultProps) {
            var defaultProps = type2.defaultProps;
            for (propName in defaultProps) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps[propName];
              }
            }
          }
          {
            if (key2 || ref2) {
              var displayName = typeof type2 === "function" ? type2.displayName || type2.name || "Unknown" : type2;
              if (key2) {
                defineKeyPropWarningGetter(props, displayName);
              }
              if (ref2) {
                defineRefPropWarningGetter(props, displayName);
              }
            }
          }
          return ReactElement(type2, key2, ref2, self2, source, ReactCurrentOwner.current, props);
        }
        function cloneAndReplaceKey(oldElement, newKey) {
          var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
          return newElement;
        }
        function cloneElement(element, config, children) {
          if (element === null || element === void 0) {
            throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
          }
          var propName;
          var props = assign({}, element.props);
          var key2 = element.key;
          var ref2 = element.ref;
          var self2 = element._self;
          var source = element._source;
          var owner = element._owner;
          if (config != null) {
            if (hasValidRef(config)) {
              ref2 = config.ref;
              owner = ReactCurrentOwner.current;
            }
            if (hasValidKey(config)) {
              {
                checkKeyStringCoercion(config.key);
              }
              key2 = "" + config.key;
            }
            var defaultProps;
            if (element.type && element.type.defaultProps) {
              defaultProps = element.type.defaultProps;
            }
            for (propName in config) {
              if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
                if (config[propName] === void 0 && defaultProps !== void 0) {
                  props[propName] = defaultProps[propName];
                } else {
                  props[propName] = config[propName];
                }
              }
            }
          }
          var childrenLength = arguments.length - 2;
          if (childrenLength === 1) {
            props.children = children;
          } else if (childrenLength > 1) {
            var childArray = Array(childrenLength);
            for (var i2 = 0; i2 < childrenLength; i2++) {
              childArray[i2] = arguments[i2 + 2];
            }
            props.children = childArray;
          }
          return ReactElement(element.type, key2, ref2, self2, source, owner, props);
        }
        function isValidElement(object) {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
        var SEPARATOR = ".";
        var SUBSEPARATOR = ":";
        function escape2(key2) {
          var escapeRegex = /[=:]/g;
          var escaperLookup = {
            "=": "=0",
            ":": "=2"
          };
          var escapedString = key2.replace(escapeRegex, function(match) {
            return escaperLookup[match];
          });
          return "$" + escapedString;
        }
        var didWarnAboutMaps = false;
        var userProvidedKeyEscapeRegex = /\/+/g;
        function escapeUserProvidedKey(text) {
          return text.replace(userProvidedKeyEscapeRegex, "$&/");
        }
        function getElementKey(element, index2) {
          if (typeof element === "object" && element !== null && element.key != null) {
            {
              checkKeyStringCoercion(element.key);
            }
            return escape2("" + element.key);
          }
          return index2.toString(36);
        }
        function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
          var type2 = typeof children;
          if (type2 === "undefined" || type2 === "boolean") {
            children = null;
          }
          var invokeCallback = false;
          if (children === null) {
            invokeCallback = true;
          } else {
            switch (type2) {
              case "string":
              case "number":
                invokeCallback = true;
                break;
              case "object":
                switch (children.$$typeof) {
                  case REACT_ELEMENT_TYPE:
                  case REACT_PORTAL_TYPE:
                    invokeCallback = true;
                }
            }
          }
          if (invokeCallback) {
            var _child = children;
            var mappedChild = callback(_child);
            var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar;
            if (isArray2(mappedChild)) {
              var escapedChildKey = "";
              if (childKey != null) {
                escapedChildKey = escapeUserProvidedKey(childKey) + "/";
              }
              mapIntoArray(mappedChild, array, escapedChildKey, "", function(c2) {
                return c2;
              });
            } else if (mappedChild != null) {
              if (isValidElement(mappedChild)) {
                {
                  if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) {
                    checkKeyStringCoercion(mappedChild.key);
                  }
                }
                mappedChild = cloneAndReplaceKey(
                  mappedChild,
                  // Keep both the (mapped) and old keys if they differ, just as
                  // traverseAllChildren used to do for objects as children
                  escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
                  (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? (
                    // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
                    // eslint-disable-next-line react-internal/safe-string-coercion
                    escapeUserProvidedKey("" + mappedChild.key) + "/"
                  ) : "") + childKey
                );
              }
              array.push(mappedChild);
            }
            return 1;
          }
          var child;
          var nextName;
          var subtreeCount = 0;
          var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR;
          if (isArray2(children)) {
            for (var i2 = 0; i2 < children.length; i2++) {
              child = children[i2];
              nextName = nextNamePrefix + getElementKey(child, i2);
              subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
            }
          } else {
            var iteratorFn = getIteratorFn(children);
            if (typeof iteratorFn === "function") {
              var iterableChildren = children;
              {
                if (iteratorFn === iterableChildren.entries) {
                  if (!didWarnAboutMaps) {
                    warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
                  }
                  didWarnAboutMaps = true;
                }
              }
              var iterator = iteratorFn.call(iterableChildren);
              var step;
              var ii = 0;
              while (!(step = iterator.next()).done) {
                child = step.value;
                nextName = nextNamePrefix + getElementKey(child, ii++);
                subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
              }
            } else if (type2 === "object") {
              var childrenString = String(children);
              throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead.");
            }
          }
          return subtreeCount;
        }
        function mapChildren(children, func, context) {
          if (children == null) {
            return children;
          }
          var result = [];
          var count = 0;
          mapIntoArray(children, result, "", "", function(child) {
            return func.call(context, child, count++);
          });
          return result;
        }
        function countChildren(children) {
          var n2 = 0;
          mapChildren(children, function() {
            n2++;
          });
          return n2;
        }
        function forEachChildren(children, forEachFunc, forEachContext) {
          mapChildren(children, function() {
            forEachFunc.apply(this, arguments);
          }, forEachContext);
        }
        function toArray(children) {
          return mapChildren(children, function(child) {
            return child;
          }) || [];
        }
        function onlyChild(children) {
          if (!isValidElement(children)) {
            throw new Error("React.Children.only expected to receive a single React element child.");
          }
          return children;
        }
        function createContext(defaultValue) {
          var context = {
            $$typeof: REACT_CONTEXT_TYPE,
            // As a workaround to support multiple concurrent renderers, we categorize
            // some renderers as primary and others as secondary. We only expect
            // there to be two concurrent renderers at most: React Native (primary) and
            // Fabric (secondary); React DOM (primary) and React ART (secondary).
            // Secondary renderers store their context values on separate fields.
            _currentValue: defaultValue,
            _currentValue2: defaultValue,
            // Used to track how many concurrent renderers this context currently
            // supports within in a single renderer. Such as parallel server rendering.
            _threadCount: 0,
            // These are circular
            Provider: null,
            Consumer: null,
            // Add these to use same hidden class in VM as ServerContext
            _defaultValue: null,
            _globalName: null
          };
          context.Provider = {
            $$typeof: REACT_PROVIDER_TYPE,
            _context: context
          };
          var hasWarnedAboutUsingNestedContextConsumers = false;
          var hasWarnedAboutUsingConsumerProvider = false;
          var hasWarnedAboutDisplayNameOnConsumer = false;
          {
            var Consumer = {
              $$typeof: REACT_CONTEXT_TYPE,
              _context: context
            };
            Object.defineProperties(Consumer, {
              Provider: {
                get: function() {
                  if (!hasWarnedAboutUsingConsumerProvider) {
                    hasWarnedAboutUsingConsumerProvider = true;
                    error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?");
                  }
                  return context.Provider;
                },
                set: function(_Provider) {
                  context.Provider = _Provider;
                }
              },
              _currentValue: {
                get: function() {
                  return context._currentValue;
                },
                set: function(_currentValue) {
                  context._currentValue = _currentValue;
                }
              },
              _currentValue2: {
                get: function() {
                  return context._currentValue2;
                },
                set: function(_currentValue2) {
                  context._currentValue2 = _currentValue2;
                }
              },
              _threadCount: {
                get: function() {
                  return context._threadCount;
                },
                set: function(_threadCount) {
                  context._threadCount = _threadCount;
                }
              },
              Consumer: {
                get: function() {
                  if (!hasWarnedAboutUsingNestedContextConsumers) {
                    hasWarnedAboutUsingNestedContextConsumers = true;
                    error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
                  }
                  return context.Consumer;
                }
              },
              displayName: {
                get: function() {
                  return context.displayName;
                },
                set: function(displayName) {
                  if (!hasWarnedAboutDisplayNameOnConsumer) {
                    warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName);
                    hasWarnedAboutDisplayNameOnConsumer = true;
                  }
                }
              }
            });
            context.Consumer = Consumer;
          }
          {
            context._currentRenderer = null;
            context._currentRenderer2 = null;
          }
          return context;
        }
        var Uninitialized = -1;
        var Pending = 0;
        var Resolved = 1;
        var Rejected = 2;
        function lazyInitializer(payload) {
          if (payload._status === Uninitialized) {
            var ctor = payload._result;
            var thenable = ctor();
            thenable.then(function(moduleObject2) {
              if (payload._status === Pending || payload._status === Uninitialized) {
                var resolved = payload;
                resolved._status = Resolved;
                resolved._result = moduleObject2;
              }
            }, function(error2) {
              if (payload._status === Pending || payload._status === Uninitialized) {
                var rejected = payload;
                rejected._status = Rejected;
                rejected._result = error2;
              }
            });
            if (payload._status === Uninitialized) {
              var pending = payload;
              pending._status = Pending;
              pending._result = thenable;
            }
          }
          if (payload._status === Resolved) {
            var moduleObject = payload._result;
            {
              if (moduleObject === void 0) {
                error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject);
              }
            }
            {
              if (!("default" in moduleObject)) {
                error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
              }
            }
            return moduleObject.default;
          } else {
            throw payload._result;
          }
        }
        function lazy(ctor) {
          var payload = {
            // We use these fields to store the result.
            _status: Uninitialized,
            _result: ctor
          };
          var lazyType2 = {
            $$typeof: REACT_LAZY_TYPE,
            _payload: payload,
            _init: lazyInitializer
          };
          {
            var defaultProps;
            var propTypes;
            Object.defineProperties(lazyType2, {
              defaultProps: {
                configurable: true,
                get: function() {
                  return defaultProps;
                },
                set: function(newDefaultProps) {
                  error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
                  defaultProps = newDefaultProps;
                  Object.defineProperty(lazyType2, "defaultProps", {
                    enumerable: true
                  });
                }
              },
              propTypes: {
                configurable: true,
                get: function() {
                  return propTypes;
                },
                set: function(newPropTypes) {
                  error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it.");
                  propTypes = newPropTypes;
                  Object.defineProperty(lazyType2, "propTypes", {
                    enumerable: true
                  });
                }
              }
            });
          }
          return lazyType2;
        }
        function forwardRef(render) {
          {
            if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
              error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).");
            } else if (typeof render !== "function") {
              error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render);
            } else {
              if (render.length !== 0 && render.length !== 2) {
                error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
              }
            }
            if (render != null) {
              if (render.defaultProps != null || render.propTypes != null) {
                error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");
              }
            }
          }
          var elementType = {
            $$typeof: REACT_FORWARD_REF_TYPE,
            render
          };
          {
            var ownName;
            Object.defineProperty(elementType, "displayName", {
              enumerable: false,
              configurable: true,
              get: function() {
                return ownName;
              },
              set: function(name) {
                ownName = name;
                if (!render.name && !render.displayName) {
                  render.displayName = name;
                }
              }
            });
          }
          return elementType;
        }
        var REACT_MODULE_REFERENCE;
        {
          REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
        }
        function isValidElementType(type2) {
          if (typeof type2 === "string" || typeof type2 === "function") {
            return true;
          }
          if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
            return true;
          }
          if (typeof type2 === "object" && type2 !== null) {
            if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
            // types supported by any Flight configuration anywhere since
            // we don't know which Flight build this will end up being used
            // with.
            type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) {
              return true;
            }
          }
          return false;
        }
        function memo(type2, compare) {
          {
            if (!isValidElementType(type2)) {
              error("memo: The first argument must be a component. Instead received: %s", type2 === null ? "null" : typeof type2);
            }
          }
          var elementType = {
            $$typeof: REACT_MEMO_TYPE,
            type: type2,
            compare: compare === void 0 ? null : compare
          };
          {
            var ownName;
            Object.defineProperty(elementType, "displayName", {
              enumerable: false,
              configurable: true,
              get: function() {
                return ownName;
              },
              set: function(name) {
                ownName = name;
                if (!type2.name && !type2.displayName) {
                  type2.displayName = name;
                }
              }
            });
          }
          return elementType;
        }
        function resolveDispatcher() {
          var dispatcher = ReactCurrentDispatcher.current;
          {
            if (dispatcher === null) {
              error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
            }
          }
          return dispatcher;
        }
        function useContext(Context) {
          var dispatcher = resolveDispatcher();
          {
            if (Context._context !== void 0) {
              var realContext = Context._context;
              if (realContext.Consumer === Context) {
                error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?");
              } else if (realContext.Provider === Context) {
                error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?");
              }
            }
          }
          return dispatcher.useContext(Context);
        }
        function useState(initialState) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useState(initialState);
        }
        function useReducer(reducer, initialArg, init2) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useReducer(reducer, initialArg, init2);
        }
        function useRef(initialValue) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useRef(initialValue);
        }
        function useEffect(create2, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useEffect(create2, deps);
        }
        function useInsertionEffect(create2, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useInsertionEffect(create2, deps);
        }
        function useLayoutEffect(create2, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useLayoutEffect(create2, deps);
        }
        function useCallback(callback, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useCallback(callback, deps);
        }
        function useMemo(create2, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useMemo(create2, deps);
        }
        function useImperativeHandle(ref2, create2, deps) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useImperativeHandle(ref2, create2, deps);
        }
        function useDebugValue(value, formatterFn) {
          {
            var dispatcher = resolveDispatcher();
            return dispatcher.useDebugValue(value, formatterFn);
          }
        }
        function useTransition() {
          var dispatcher = resolveDispatcher();
          return dispatcher.useTransition();
        }
        function useDeferredValue(value) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useDeferredValue(value);
        }
        function useId() {
          var dispatcher = resolveDispatcher();
          return dispatcher.useId();
        }
        function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
          var dispatcher = resolveDispatcher();
          return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
        }
        var disabledDepth = 0;
        var prevLog;
        var prevInfo;
        var prevWarn;
        var prevError;
        var prevGroup;
        var prevGroupCollapsed;
        var prevGroupEnd;
        function disabledLog() {
        }
        disabledLog.__reactDisabledLog = true;
        function disableLogs() {
          {
            if (disabledDepth === 0) {
              prevLog = console.log;
              prevInfo = console.info;
              prevWarn = console.warn;
              prevError = console.error;
              prevGroup = console.group;
              prevGroupCollapsed = console.groupCollapsed;
              prevGroupEnd = console.groupEnd;
              var props = {
                configurable: true,
                enumerable: true,
                value: disabledLog,
                writable: true
              };
              Object.defineProperties(console, {
                info: props,
                log: props,
                warn: props,
                error: props,
                group: props,
                groupCollapsed: props,
                groupEnd: props
              });
            }
            disabledDepth++;
          }
        }
        function reenableLogs() {
          {
            disabledDepth--;
            if (disabledDepth === 0) {
              var props = {
                configurable: true,
                enumerable: true,
                writable: true
              };
              Object.defineProperties(console, {
                log: assign({}, props, {
                  value: prevLog
                }),
                info: assign({}, props, {
                  value: prevInfo
                }),
                warn: assign({}, props, {
                  value: prevWarn
                }),
                error: assign({}, props, {
                  value: prevError
                }),
                group: assign({}, props, {
                  value: prevGroup
                }),
                groupCollapsed: assign({}, props, {
                  value: prevGroupCollapsed
                }),
                groupEnd: assign({}, props, {
                  value: prevGroupEnd
                })
              });
            }
            if (disabledDepth < 0) {
              error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
            }
          }
        }
        var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
        var prefix;
        function describeBuiltInComponentFrame(name, source, ownerFn) {
          {
            if (prefix === void 0) {
              try {
                throw Error();
              } catch (x2) {
                var match = x2.stack.trim().match(/\n( *(at )?)/);
                prefix = match && match[1] || "";
              }
            }
            return "\n" + prefix + name;
          }
        }
        var reentry = false;
        var componentFrameCache;
        {
          var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
          componentFrameCache = new PossiblyWeakMap();
        }
        function describeNativeComponentFrame(fn, construct) {
          if (!fn || reentry) {
            return "";
          }
          {
            var frame = componentFrameCache.get(fn);
            if (frame !== void 0) {
              return frame;
            }
          }
          var control;
          reentry = true;
          var previousPrepareStackTrace = Error.prepareStackTrace;
          Error.prepareStackTrace = void 0;
          var previousDispatcher;
          {
            previousDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = null;
            disableLogs();
          }
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if (typeof Reflect === "object" && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x2) {
                  control = x2;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x2) {
                control = x2;
              }
              fn();
            }
          } catch (sample) {
            if (sample && control && typeof sample.stack === "string") {
              var sampleLines = sample.stack.split("\n");
              var controlLines = control.stack.split("\n");
              var s2 = sampleLines.length - 1;
              var c2 = controlLines.length - 1;
              while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) {
                c2--;
              }
              for (; s2 >= 1 && c2 >= 0; s2--, c2--) {
                if (sampleLines[s2] !== controlLines[c2]) {
                  if (s2 !== 1 || c2 !== 1) {
                    do {
                      s2--;
                      c2--;
                      if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) {
                        var _frame = "\n" + sampleLines[s2].replace(" at new ", " at ");
                        if (fn.displayName && _frame.includes("<anonymous>")) {
                          _frame = _frame.replace("<anonymous>", fn.displayName);
                        }
                        {
                          if (typeof fn === "function") {
                            componentFrameCache.set(fn, _frame);
                          }
                        }
                        return _frame;
                      }
                    } while (s2 >= 1 && c2 >= 0);
                  }
                  break;
                }
              }
            }
          } finally {
            reentry = false;
            {
              ReactCurrentDispatcher$1.current = previousDispatcher;
              reenableLogs();
            }
            Error.prepareStackTrace = previousPrepareStackTrace;
          }
          var name = fn ? fn.displayName || fn.name : "";
          var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
          {
            if (typeof fn === "function") {
              componentFrameCache.set(fn, syntheticFrame);
            }
          }
          return syntheticFrame;
        }
        function describeFunctionComponentFrame(fn, source, ownerFn) {
          {
            return describeNativeComponentFrame(fn, false);
          }
        }
        function shouldConstruct(Component2) {
          var prototype = Component2.prototype;
          return !!(prototype && prototype.isReactComponent);
        }
        function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) {
          if (type2 == null) {
            return "";
          }
          if (typeof type2 === "function") {
            {
              return describeNativeComponentFrame(type2, shouldConstruct(type2));
            }
          }
          if (typeof type2 === "string") {
            return describeBuiltInComponentFrame(type2);
          }
          switch (type2) {
            case REACT_SUSPENSE_TYPE:
              return describeBuiltInComponentFrame("Suspense");
            case REACT_SUSPENSE_LIST_TYPE:
              return describeBuiltInComponentFrame("SuspenseList");
          }
          if (typeof type2 === "object") {
            switch (type2.$$typeof) {
              case REACT_FORWARD_REF_TYPE:
                return describeFunctionComponentFrame(type2.render);
              case REACT_MEMO_TYPE:
                return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn);
              case REACT_LAZY_TYPE: {
                var lazyComponent = type2;
                var payload = lazyComponent._payload;
                var init2 = lazyComponent._init;
                try {
                  return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn);
                } catch (x2) {
                }
              }
            }
          }
          return "";
        }
        var loggedTypeFailures = {};
        var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
        function setCurrentlyValidatingElement(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
            } else {
              ReactDebugCurrentFrame$1.setExtraStackFrame(null);
            }
          }
        }
        function checkPropTypes(typeSpecs, values, location, componentName, element) {
          {
            var has = Function.call.bind(hasOwnProperty);
            for (var typeSpecName in typeSpecs) {
              if (has(typeSpecs, typeSpecName)) {
                var error$1 = void 0;
                try {
                  if (typeof typeSpecs[typeSpecName] !== "function") {
                    var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                    err.name = "Invariant Violation";
                    throw err;
                  }
                  error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
                } catch (ex) {
                  error$1 = ex;
                }
                if (error$1 && !(error$1 instanceof Error)) {
                  setCurrentlyValidatingElement(element);
                  error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
                  setCurrentlyValidatingElement(null);
                }
                if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                  loggedTypeFailures[error$1.message] = true;
                  setCurrentlyValidatingElement(element);
                  error("Failed %s type: %s", location, error$1.message);
                  setCurrentlyValidatingElement(null);
                }
              }
            }
          }
        }
        function setCurrentlyValidatingElement$1(element) {
          {
            if (element) {
              var owner = element._owner;
              var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
              setExtraStackFrame(stack);
            } else {
              setExtraStackFrame(null);
            }
          }
        }
        var propTypesMisspellWarningShown;
        {
          propTypesMisspellWarningShown = false;
        }
        function getDeclarationErrorAddendum() {
          if (ReactCurrentOwner.current) {
            var name = getComponentNameFromType(ReactCurrentOwner.current.type);
            if (name) {
              return "\n\nCheck the render method of `" + name + "`.";
            }
          }
          return "";
        }
        function getSourceInfoErrorAddendum(source) {
          if (source !== void 0) {
            var fileName = source.fileName.replace(/^.*[\\\/]/, "");
            var lineNumber = source.lineNumber;
            return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
          }
          return "";
        }
        function getSourceInfoErrorAddendumForProps(elementProps) {
          if (elementProps !== null && elementProps !== void 0) {
            return getSourceInfoErrorAddendum(elementProps.__source);
          }
          return "";
        }
        var ownerHasKeyUseWarning = {};
        function getCurrentComponentErrorInfo(parentType) {
          var info = getDeclarationErrorAddendum();
          if (!info) {
            var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
            if (parentName) {
              info = "\n\nCheck the top-level render call using <" + parentName + ">.";
            }
          }
          return info;
        }
        function validateExplicitKey(element, parentType) {
          if (!element._store || element._store.validated || element.key != null) {
            return;
          }
          element._store.validated = true;
          var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
          if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
            return;
          }
          ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
          var childOwner = "";
          if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
            childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
          }
          {
            setCurrentlyValidatingElement$1(element);
            error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
            setCurrentlyValidatingElement$1(null);
          }
        }
        function validateChildKeys(node2, parentType) {
          if (typeof node2 !== "object") {
            return;
          }
          if (isArray2(node2)) {
            for (var i2 = 0; i2 < node2.length; i2++) {
              var child = node2[i2];
              if (isValidElement(child)) {
                validateExplicitKey(child, parentType);
              }
            }
          } else if (isValidElement(node2)) {
            if (node2._store) {
              node2._store.validated = true;
            }
          } else if (node2) {
            var iteratorFn = getIteratorFn(node2);
            if (typeof iteratorFn === "function") {
              if (iteratorFn !== node2.entries) {
                var iterator = iteratorFn.call(node2);
                var step;
                while (!(step = iterator.next()).done) {
                  if (isValidElement(step.value)) {
                    validateExplicitKey(step.value, parentType);
                  }
                }
              }
            }
          }
        }
        function validatePropTypes(element) {
          {
            var type2 = element.type;
            if (type2 === null || type2 === void 0 || typeof type2 === "string") {
              return;
            }
            var propTypes;
            if (typeof type2 === "function") {
              propTypes = type2.propTypes;
            } else if (typeof type2 === "object" && (type2.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
            // Inner props are checked in the reconciler.
            type2.$$typeof === REACT_MEMO_TYPE)) {
              propTypes = type2.propTypes;
            } else {
              return;
            }
            if (propTypes) {
              var name = getComponentNameFromType(type2);
              checkPropTypes(propTypes, element.props, "prop", name, element);
            } else if (type2.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
              propTypesMisspellWarningShown = true;
              var _name = getComponentNameFromType(type2);
              error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
            }
            if (typeof type2.getDefaultProps === "function" && !type2.getDefaultProps.isReactClassApproved) {
              error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
            }
          }
        }
        function validateFragmentProps(fragment) {
          {
            var keys = Object.keys(fragment.props);
            for (var i2 = 0; i2 < keys.length; i2++) {
              var key2 = keys[i2];
              if (key2 !== "children" && key2 !== "key") {
                setCurrentlyValidatingElement$1(fragment);
                error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key2);
                setCurrentlyValidatingElement$1(null);
                break;
              }
            }
            if (fragment.ref !== null) {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid attribute `ref` supplied to `React.Fragment`.");
              setCurrentlyValidatingElement$1(null);
            }
          }
        }
        function createElementWithValidation(type2, props, children) {
          var validType = isValidElementType(type2);
          if (!validType) {
            var info = "";
            if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) {
              info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            }
            var sourceInfo = getSourceInfoErrorAddendumForProps(props);
            if (sourceInfo) {
              info += sourceInfo;
            } else {
              info += getDeclarationErrorAddendum();
            }
            var typeString;
            if (type2 === null) {
              typeString = "null";
            } else if (isArray2(type2)) {
              typeString = "array";
            } else if (type2 !== void 0 && type2.$$typeof === REACT_ELEMENT_TYPE) {
              typeString = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />";
              info = " Did you accidentally export a JSX literal instead of a component?";
            } else {
              typeString = typeof type2;
            }
            {
              error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
            }
          }
          var element = createElement.apply(this, arguments);
          if (element == null) {
            return element;
          }
          if (validType) {
            for (var i2 = 2; i2 < arguments.length; i2++) {
              validateChildKeys(arguments[i2], type2);
            }
          }
          if (type2 === REACT_FRAGMENT_TYPE) {
            validateFragmentProps(element);
          } else {
            validatePropTypes(element);
          }
          return element;
        }
        var didWarnAboutDeprecatedCreateFactory = false;
        function createFactoryWithValidation(type2) {
          var validatedFactory = createElementWithValidation.bind(null, type2);
          validatedFactory.type = type2;
          {
            if (!didWarnAboutDeprecatedCreateFactory) {
              didWarnAboutDeprecatedCreateFactory = true;
              warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.");
            }
            Object.defineProperty(validatedFactory, "type", {
              enumerable: false,
              get: function() {
                warn("Factory.type is deprecated. Access the class directly before passing it to createFactory.");
                Object.defineProperty(this, "type", {
                  value: type2
                });
                return type2;
              }
            });
          }
          return validatedFactory;
        }
        function cloneElementWithValidation(element, props, children) {
          var newElement = cloneElement.apply(this, arguments);
          for (var i2 = 2; i2 < arguments.length; i2++) {
            validateChildKeys(arguments[i2], newElement.type);
          }
          validatePropTypes(newElement);
          return newElement;
        }
        function startTransition(scope, options2) {
          var prevTransition = ReactCurrentBatchConfig.transition;
          ReactCurrentBatchConfig.transition = {};
          var currentTransition = ReactCurrentBatchConfig.transition;
          {
            ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set();
          }
          try {
            scope();
          } finally {
            ReactCurrentBatchConfig.transition = prevTransition;
            {
              if (prevTransition === null && currentTransition._updatedFibers) {
                var updatedFibersCount = currentTransition._updatedFibers.size;
                if (updatedFibersCount > 10) {
                  warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.");
                }
                currentTransition._updatedFibers.clear();
              }
            }
          }
        }
        var didWarnAboutMessageChannel = false;
        var enqueueTaskImpl = null;
        function enqueueTask(task) {
          if (enqueueTaskImpl === null) {
            try {
              var requireString = ("require" + Math.random()).slice(0, 7);
              var nodeRequire = module2 && module2[requireString];
              enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate;
            } catch (_err) {
              enqueueTaskImpl = function(callback) {
                {
                  if (didWarnAboutMessageChannel === false) {
                    didWarnAboutMessageChannel = true;
                    if (typeof MessageChannel === "undefined") {
                      error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning.");
                    }
                  }
                }
                var channel = new MessageChannel();
                channel.port1.onmessage = callback;
                channel.port2.postMessage(void 0);
              };
            }
          }
          return enqueueTaskImpl(task);
        }
        var actScopeDepth = 0;
        var didWarnNoAwaitAct = false;
        function act(callback) {
          {
            var prevActScopeDepth = actScopeDepth;
            actScopeDepth++;
            if (ReactCurrentActQueue.current === null) {
              ReactCurrentActQueue.current = [];
            }
            var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy;
            var result;
            try {
              ReactCurrentActQueue.isBatchingLegacy = true;
              result = callback();
              if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) {
                var queue = ReactCurrentActQueue.current;
                if (queue !== null) {
                  ReactCurrentActQueue.didScheduleLegacyUpdate = false;
                  flushActQueue(queue);
                }
              }
            } catch (error2) {
              popActScope(prevActScopeDepth);
              throw error2;
            } finally {
              ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
            }
            if (result !== null && typeof result === "object" && typeof result.then === "function") {
              var thenableResult = result;
              var wasAwaited = false;
              var thenable = {
                then: function(resolve2, reject2) {
                  wasAwaited = true;
                  thenableResult.then(function(returnValue2) {
                    popActScope(prevActScopeDepth);
                    if (actScopeDepth === 0) {
                      recursivelyFlushAsyncActWork(returnValue2, resolve2, reject2);
                    } else {
                      resolve2(returnValue2);
                    }
                  }, function(error2) {
                    popActScope(prevActScopeDepth);
                    reject2(error2);
                  });
                }
              };
              {
                if (!didWarnNoAwaitAct && typeof Promise !== "undefined") {
                  Promise.resolve().then(function() {
                  }).then(function() {
                    if (!wasAwaited) {
                      didWarnNoAwaitAct = true;
                      error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);");
                    }
                  });
                }
              }
              return thenable;
            } else {
              var returnValue = result;
              popActScope(prevActScopeDepth);
              if (actScopeDepth === 0) {
                var _queue = ReactCurrentActQueue.current;
                if (_queue !== null) {
                  flushActQueue(_queue);
                  ReactCurrentActQueue.current = null;
                }
                var _thenable = {
                  then: function(resolve2, reject2) {
                    if (ReactCurrentActQueue.current === null) {
                      ReactCurrentActQueue.current = [];
                      recursivelyFlushAsyncActWork(returnValue, resolve2, reject2);
                    } else {
                      resolve2(returnValue);
                    }
                  }
                };
                return _thenable;
              } else {
                var _thenable2 = {
                  then: function(resolve2, reject2) {
                    resolve2(returnValue);
                  }
                };
                return _thenable2;
              }
            }
          }
        }
        function popActScope(prevActScopeDepth) {
          {
            if (prevActScopeDepth !== actScopeDepth - 1) {
              error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
            }
            actScopeDepth = prevActScopeDepth;
          }
        }
        function recursivelyFlushAsyncActWork(returnValue, resolve2, reject2) {
          {
            var queue = ReactCurrentActQueue.current;
            if (queue !== null) {
              try {
                flushActQueue(queue);
                enqueueTask(function() {
                  if (queue.length === 0) {
                    ReactCurrentActQueue.current = null;
                    resolve2(returnValue);
                  } else {
                    recursivelyFlushAsyncActWork(returnValue, resolve2, reject2);
                  }
                });
              } catch (error2) {
                reject2(error2);
              }
            } else {
              resolve2(returnValue);
            }
          }
        }
        var isFlushing = false;
        function flushActQueue(queue) {
          {
            if (!isFlushing) {
              isFlushing = true;
              var i2 = 0;
              try {
                for (; i2 < queue.length; i2++) {
                  var callback = queue[i2];
                  do {
                    callback = callback(true);
                  } while (callback !== null);
                }
                queue.length = 0;
              } catch (error2) {
                queue = queue.slice(i2 + 1);
                throw error2;
              } finally {
                isFlushing = false;
              }
            }
          }
        }
        var createElement$1 = createElementWithValidation;
        var cloneElement$1 = cloneElementWithValidation;
        var createFactory = createFactoryWithValidation;
        var Children = {
          map: mapChildren,
          forEach: forEachChildren,
          count: countChildren,
          toArray,
          only: onlyChild
        };
        exports.Children = Children;
        exports.Component = Component;
        exports.Fragment = REACT_FRAGMENT_TYPE;
        exports.Profiler = REACT_PROFILER_TYPE;
        exports.PureComponent = PureComponent;
        exports.StrictMode = REACT_STRICT_MODE_TYPE;
        exports.Suspense = REACT_SUSPENSE_TYPE;
        exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;
        exports.act = act;
        exports.cloneElement = cloneElement$1;
        exports.createContext = createContext;
        exports.createElement = createElement$1;
        exports.createFactory = createFactory;
        exports.createRef = createRef;
        exports.forwardRef = forwardRef;
        exports.isValidElement = isValidElement;
        exports.lazy = lazy;
        exports.memo = memo;
        exports.startTransition = startTransition;
        exports.unstable_act = act;
        exports.useCallback = useCallback;
        exports.useContext = useContext;
        exports.useDebugValue = useDebugValue;
        exports.useDeferredValue = useDeferredValue;
        exports.useEffect = useEffect;
        exports.useId = useId;
        exports.useImperativeHandle = useImperativeHandle;
        exports.useInsertionEffect = useInsertionEffect;
        exports.useLayoutEffect = useLayoutEffect;
        exports.useMemo = useMemo;
        exports.useReducer = useReducer;
        exports.useRef = useRef;
        exports.useState = useState;
        exports.useSyncExternalStore = useSyncExternalStore;
        exports.useTransition = useTransition;
        exports.version = ReactVersion;
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
        }
      })();
    }
  })(react_development, react_development.exports);
  return react_development.exports;
}
var hasRequiredReact;
function requireReact() {
  if (hasRequiredReact) return react.exports;
  hasRequiredReact = 1;
  {
    react.exports = requireReact_development();
  }
  return react.exports;
}
var reactExports = requireReact();
const React = /* @__PURE__ */ getDefaultExportFromCjs$1(reactExports);
const identity = (arg) => arg;
function useStore(api2, selector = identity) {
  const slice = React.useSyncExternalStore(
    api2.subscribe,
    React.useCallback(() => selector(api2.getState()), [api2, selector]),
    React.useCallback(() => selector(api2.getInitialState()), [api2, selector])
  );
  React.useDebugValue(slice);
  return slice;
}
const createImpl = (createState) => {
  const api2 = createStore(createState);
  const useBoundStore = (selector) => useStore(api2, selector);
  Object.assign(useBoundStore, api2);
  return useBoundStore;
};
const create = (createState) => createState ? createImpl(createState) : createImpl;
const APP_NAME = "四喜AI";
const PSUXPInternalStore = createStore((set, get2) => ({
  headerTitle: APP_NAME,
  manifestVersion: "",
  loginProvider: new DefaultLoginProvider(),
  headerTailElems: [],
  footerElems: [],
  comfyWebviewNeedRefresh: true,
  contentWebviewLastFocusTime: 0,
  uxpPanelLastMouseOverTime: 0,
  tasks: /* @__PURE__ */ new Map()
}));
(async () => {
  const localFileSystem = uxp.storage.localFileSystem;
  const pluginFolder = await localFileSystem.getPluginFolder();
  const manifest = await pluginFolder.getEntry("manifest.json");
  const manifestContent = await manifest.read();
  const manifestJson = JSON.parse(manifestContent);
  PSUXPInternalStore.setState({
    manifestVersion: manifestJson.version
  });
})().catch(console.error);
const taskHelpers = {
  addTask: (task) => {
    PSUXPInternalStore.setState((state) => {
      const newTasks = new Map(state.tasks);
      newTasks.set(task.taskId, task);
      return { tasks: newTasks };
    });
  },
  updateTask: (taskId, updates) => {
    PSUXPInternalStore.setState((state) => {
      const newTasks = new Map(state.tasks);
      const existingTask = newTasks.get(taskId);
      if (existingTask) {
        newTasks.set(taskId, { ...existingTask, ...updates });
      }
      return { tasks: newTasks };
    });
  },
  removeTask: (taskId) => {
    const currentState = PSUXPInternalStore.getState();
    if (currentState.tasks.has(taskId)) {
      PSUXPInternalStore.setState((state) => {
        const newTasks = new Map(state.tasks);
        newTasks.delete(taskId);
        return { tasks: newTasks };
      });
      return true;
    }
    return false;
  },
  getTask: (taskId) => {
    const currentState = PSUXPInternalStore.getState();
    return currentState.tasks.get(taskId);
  }
};
class SDPPPLoginProvider extends DefaultLoginProvider {
  constructor(authingAppId) {
    super(authingAppId);
    __publicField2(this, "errorCount", 0);
  }
  isQRCodeSupported() {
    return false;
  }
  async login(params) {
    const user2 = await super.login(params);
    const userInfo = await this.getUserProfile(user2.token);
    localStorage.setItem("sdppp-authing-lastLogin", new Date(userInfo.lastLogin).getTime().toString());
    return user2;
  }
  async intervalCheck(token) {
    try {
      const userInfo = await this.getUserProfile(token);
      const remoteLastLogin = new Date(userInfo.lastLogin).getTime().toString();
      const localLastLogin = localStorage.getItem("sdppp-authing-lastLogin");
      this.errorCount = 0;
      return { loginValid: remoteLastLogin === localLastLogin, nextCheckTime: 1e4 };
    } catch (e4) {
      this.errorCount++;
      if (this.errorCount > 3) {
        return { loginValid: false, nextCheckTime: 1e4 };
      }
      return { loginValid: true, nextCheckTime: 1e3 };
    }
  }
}
class GraphDefinitionClass {
  constructor(definition) {
    __publicField2(this, "definition");
    this.definition = definition;
    const validation = this.validate();
    if (!validation.valid) {
      throw new Error(`Invalid graph definition: ${validation.errors.join(", ")}`);
    }
  }
  /**
   * Validate the graph definition
   */
  validate() {
    const errors = [];
    if (!this.definition.nodes || Object.keys(this.definition.nodes).length === 0) {
      errors.push("Graph must have at least one node");
    }
    for (const [from2, to2] of this.definition.edges) {
      if (!this.definition.nodes[from2]) {
        errors.push(`Edge references unknown source node: ${from2}`);
      }
      if (!this.definition.nodes[to2]) {
        errors.push(`Edge references unknown target node: ${to2}`);
      }
    }
    const cycleCheck = this.detectCycles();
    if (!cycleCheck.valid) {
      errors.push(...cycleCheck.errors);
    }
    return {
      valid: errors.length === 0,
      errors
    };
  }
  /**
   * Build directed adjacency list from edges (for cycle detection)
   */
  buildDirectedAdjacencyList() {
    const adjacencyList = /* @__PURE__ */ new Map();
    for (const nodeId of Object.keys(this.definition.nodes)) {
      adjacencyList.set(nodeId, []);
    }
    for (const [from2, to2] of this.definition.edges) {
      const neighbors = adjacencyList.get(from2) || [];
      neighbors.push(to2);
      adjacencyList.set(from2, neighbors);
    }
    return adjacencyList;
  }
  /**
   * Detect cycles in the graph using DFS
   */
  detectCycles() {
    const errors = [];
    const visited = /* @__PURE__ */ new Set();
    const recursionStack = /* @__PURE__ */ new Set();
    const adjacencyList = this.buildDirectedAdjacencyList();
    const dfs = (node2, path) => {
      if (recursionStack.has(node2)) {
        const cycleStart = path.indexOf(node2);
        const cycle = path.slice(cycleStart).concat(node2);
        errors.push(`Cycle detected: ${cycle.join(" -> ")}`);
        return true;
      }
      if (visited.has(node2)) {
        return false;
      }
      visited.add(node2);
      recursionStack.add(node2);
      const neighbors = adjacencyList.get(node2) || [];
      for (const neighbor of neighbors) {
        if (dfs(neighbor, [...path, node2])) {
          return true;
        }
      }
      recursionStack.delete(node2);
      return false;
    };
    for (const nodeId of Object.keys(this.definition.nodes)) {
      if (!visited.has(nodeId)) {
        dfs(nodeId, []);
      }
    }
    return {
      valid: errors.length === 0,
      errors
    };
  }
  /**
   * Build adjacency list from edges (bidirectional)
   */
  buildAdjacencyList() {
    const adjacencyList = /* @__PURE__ */ new Map();
    for (const nodeId of Object.keys(this.definition.nodes)) {
      adjacencyList.set(nodeId, []);
    }
    for (const [from2, to2] of this.definition.edges) {
      const fromNeighbors = adjacencyList.get(from2) || [];
      fromNeighbors.push(to2);
      adjacencyList.set(from2, fromNeighbors);
      const toNeighbors = adjacencyList.get(to2) || [];
      toNeighbors.push(from2);
      adjacencyList.set(to2, toNeighbors);
    }
    return adjacencyList;
  }
  /**
   * Get all neighbors of a node
   */
  getNeighbors(nodeId) {
    const adjacencyList = this.buildAdjacencyList();
    return adjacencyList.get(nodeId) || [];
  }
  /**
   * Get node definition
   */
  getNode(nodeId) {
    return this.definition.nodes[nodeId];
  }
  /**
   * Get all node IDs
   */
  getNodeIds() {
    return Object.keys(this.definition.nodes);
  }
  /**
   * Check if edge exists between two nodes (bidirectional)
   */
  hasEdge(from2, to2) {
    return this.definition.edges.some(
      ([f2, t2]) => f2 === from2 && t2 === to2 || f2 === to2 && t2 === from2
    );
  }
  /**
   * Find path between two nodes using BFS
   * Returns shortest path as array of node IDs, or null if no path exists
   */
  findPath(from2, to2) {
    if (from2 === to2) {
      return [from2];
    }
    const adjacencyList = this.buildAdjacencyList();
    const queue = [{ nodeId: from2, path: [from2] }];
    const visited = /* @__PURE__ */ new Set();
    while (queue.length > 0) {
      const { nodeId, path } = queue.shift();
      if (visited.has(nodeId)) {
        continue;
      }
      visited.add(nodeId);
      if (nodeId === to2) {
        return path;
      }
      const neighbors = adjacencyList.get(nodeId) || [];
      for (const neighbor of neighbors) {
        if (!visited.has(neighbor)) {
          queue.push({ nodeId: neighbor, path: [...path, neighbor] });
        }
      }
    }
    return null;
  }
  /**
   * Check if there's a path between two nodes (direct or indirect)
   */
  hasPath(from2, to2) {
    return this.findPath(from2, to2) !== null;
  }
  /**
   * Get the raw definition
   */
  getDefinition() {
    return { ...this.definition };
  }
}
var util$3;
(function(util2) {
  util2.assertEqual = (_2) => {
  };
  function assertIs(_arg) {
  }
  util2.assertIs = assertIs;
  function assertNever(_x) {
    throw new Error();
  }
  util2.assertNever = assertNever;
  util2.arrayToEnum = (items2) => {
    const obj = {};
    for (const item of items2) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number");
    const filtered = {};
    for (const k2 of validKeys) {
      filtered[k2] = obj[k2];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e4) {
      return obj[e4];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
    const keys = [];
    for (const key2 in object) {
      if (Object.prototype.hasOwnProperty.call(object, key2)) {
        keys.push(key2);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues(array, separator = " | ") {
    return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues;
  util2.jsonStringifyReplacer = (_2, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util$3 || (util$3 = {}));
var objectUtil$1;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil$1 || (objectUtil$1 = {}));
const ZodParsedType$1 = util$3.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
const getParsedType$1 = (data2) => {
  const t2 = typeof data2;
  switch (t2) {
    case "undefined":
      return ZodParsedType$1.undefined;
    case "string":
      return ZodParsedType$1.string;
    case "number":
      return Number.isNaN(data2) ? ZodParsedType$1.nan : ZodParsedType$1.number;
    case "boolean":
      return ZodParsedType$1.boolean;
    case "function":
      return ZodParsedType$1.function;
    case "bigint":
      return ZodParsedType$1.bigint;
    case "symbol":
      return ZodParsedType$1.symbol;
    case "object":
      if (Array.isArray(data2)) {
        return ZodParsedType$1.array;
      }
      if (data2 === null) {
        return ZodParsedType$1.null;
      }
      if (data2.then && typeof data2.then === "function" && data2.catch && typeof data2.catch === "function") {
        return ZodParsedType$1.promise;
      }
      if (typeof Map !== "undefined" && data2 instanceof Map) {
        return ZodParsedType$1.map;
      }
      if (typeof Set !== "undefined" && data2 instanceof Set) {
        return ZodParsedType$1.set;
      }
      if (typeof Date !== "undefined" && data2 instanceof Date) {
        return ZodParsedType$1.date;
      }
      return ZodParsedType$1.object;
    default:
      return ZodParsedType$1.unknown;
  }
};
const ZodIssueCode$1 = util$3.arrayToEnum([
  "invalid_type",
  "invalid_literal",
  "custom",
  "invalid_union",
  "invalid_union_discriminator",
  "invalid_enum_value",
  "unrecognized_keys",
  "invalid_arguments",
  "invalid_return_type",
  "invalid_date",
  "invalid_string",
  "too_small",
  "too_big",
  "invalid_intersection_types",
  "not_multiple_of",
  "not_finite"
]);
let ZodError$1 = class ZodError2 extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue) {
      return issue.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error) => {
      for (const issue of error.issues) {
        if (issue.code === "invalid_union") {
          issue.unionErrors.map(processError);
        } else if (issue.code === "invalid_return_type") {
          processError(issue.returnTypeError);
        } else if (issue.code === "invalid_arguments") {
          processError(issue.argumentsError);
        } else if (issue.path.length === 0) {
          fieldErrors._errors.push(mapper(issue));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue.path.length) {
            const el = issue.path[i2];
            const terminal = i2 === issue.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof ZodError2)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util$3.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue) => issue.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError$1.create = (issues) => {
  const error = new ZodError$1(issues);
  return error;
};
const errorMap$1 = (issue, _ctx) => {
  let message;
  switch (issue.code) {
    case ZodIssueCode$1.invalid_type:
      if (issue.received === ZodParsedType$1.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue.expected}, received ${issue.received}`;
      }
      break;
    case ZodIssueCode$1.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util$3.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode$1.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util$3.joinValues(issue.keys, ", ")}`;
      break;
    case ZodIssueCode$1.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode$1.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util$3.joinValues(issue.options)}`;
      break;
    case ZodIssueCode$1.invalid_enum_value:
      message = `Invalid enum value. Expected ${util$3.joinValues(issue.options)}, received '${issue.received}'`;
      break;
    case ZodIssueCode$1.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode$1.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode$1.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode$1.invalid_string:
      if (typeof issue.validation === "object") {
        if ("includes" in issue.validation) {
          message = `Invalid input: must include "${issue.validation.includes}"`;
          if (typeof issue.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
          }
        } else if ("startsWith" in issue.validation) {
          message = `Invalid input: must start with "${issue.validation.startsWith}"`;
        } else if ("endsWith" in issue.validation) {
          message = `Invalid input: must end with "${issue.validation.endsWith}"`;
        } else {
          util$3.assertNever(issue.validation);
        }
      } else if (issue.validation !== "regex") {
        message = `Invalid ${issue.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode$1.too_small:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "bigint")
        message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode$1.too_big:
      if (issue.type === "array")
        message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
      else if (issue.type === "string")
        message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
      else if (issue.type === "number")
        message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "bigint")
        message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
      else if (issue.type === "date")
        message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode$1.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode$1.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode$1.not_multiple_of:
      message = `Number must be a multiple of ${issue.multipleOf}`;
      break;
    case ZodIssueCode$1.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util$3.assertNever(issue);
  }
  return { message };
};
let overrideErrorMap$1 = errorMap$1;
function getErrorMap$1() {
  return overrideErrorMap$1;
}
const makeIssue$1 = (params) => {
  const { data: data2, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m) => !!m).slice().reverse();
  for (const map of maps) {
    errorMessage = map(fullIssue, { data: data2, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
function addIssueToContext$1(ctx, issueData) {
  const overrideMap = getErrorMap$1();
  const issue = makeIssue$1({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === errorMap$1 ? void 0 : errorMap$1
      // then global default map
    ].filter((x2) => !!x2)
  });
  ctx.common.issues.push(issue);
}
let ParseStatus$1 = class ParseStatus2 {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s2 of results) {
      if (s2.status === "aborted")
        return INVALID$1;
      if (s2.status === "dirty")
        status.dirty();
      arrayValue.push(s2.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key2 = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key: key2,
        value
      });
    }
    return ParseStatus2.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key: key2, value } = pair;
      if (key2.status === "aborted")
        return INVALID$1;
      if (value.status === "aborted")
        return INVALID$1;
      if (key2.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key2.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key2.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
};
const INVALID$1 = Object.freeze({
  status: "aborted"
});
const DIRTY$1 = (value) => ({ status: "dirty", value });
const OK$1 = (value) => ({ status: "valid", value });
const isAborted$1 = (x2) => x2.status === "aborted";
const isDirty$1 = (x2) => x2.status === "dirty";
const isValid$1 = (x2) => x2.status === "valid";
const isAsync$1 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise;
var errorUtil$1;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
})(errorUtil$1 || (errorUtil$1 = {}));
let ParseInputLazyPath$1 = class ParseInputLazyPath2 {
  constructor(parent, value, path, key2) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key2;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
const handleResult$1 = (ctx, result) => {
  if (isValid$1(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error = new ZodError$1(ctx.common.issues);
        this._error = error;
        return this._error;
      }
    };
  }
};
function processCreateParams$1(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description: description2 } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description: description2 };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description: description2 };
}
let ZodType$1 = class ZodType2 {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType$1(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType$1(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus$1(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType$1(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync$1(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data2, params) {
    const result = this.safeParse(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data2, params) {
    const ctx = {
      common: {
        issues: [],
        async: (params == null ? void 0 : params.async) ?? false,
        contextualErrorMap: params == null ? void 0 : params.errorMap
      },
      path: (params == null ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType$1(data2)
    };
    const result = this._parseSync({ data: data2, path: ctx.path, parent: ctx });
    return handleResult$1(ctx, result);
  }
  "~validate"(data2) {
    var _a3, _b2;
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType$1(data2)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data: data2, path: [], parent: ctx });
        return isValid$1(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if ((_b2 = (_a3 = err == null ? void 0 : err.message) == null ? void 0 : _a3.toLowerCase()) == null ? void 0 : _b2.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data: data2, path: [], parent: ctx }).then((result) => isValid$1(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data2, params) {
    const result = await this.safeParseAsync(data2, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data2, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params == null ? void 0 : params.errorMap,
        async: true
      },
      path: (params == null ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data: data2,
      parsedType: getParsedType$1(data2)
    };
    const maybeAsyncResult = this._parse({ data: data2, path: ctx.path, parent: ctx });
    const result = await (isAsync$1(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult$1(ctx, result);
  }
  refine(check, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode$1.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data2) => {
          if (!data2) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects$1({
      schema: this,
      typeName: ZodFirstPartyTypeKind$1.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    this.parse = this.parse.bind(this);
    this.safeParse = this.safeParse.bind(this);
    this.parseAsync = this.parseAsync.bind(this);
    this.safeParseAsync = this.safeParseAsync.bind(this);
    this.spa = this.spa.bind(this);
    this.refine = this.refine.bind(this);
    this.refinement = this.refinement.bind(this);
    this.superRefine = this.superRefine.bind(this);
    this.optional = this.optional.bind(this);
    this.nullable = this.nullable.bind(this);
    this.nullish = this.nullish.bind(this);
    this.array = this.array.bind(this);
    this.promise = this.promise.bind(this);
    this.or = this.or.bind(this);
    this.and = this.and.bind(this);
    this.transform = this.transform.bind(this);
    this.brand = this.brand.bind(this);
    this.default = this.default.bind(this);
    this.catch = this.catch.bind(this);
    this.describe = this.describe.bind(this);
    this.pipe = this.pipe.bind(this);
    this.readonly = this.readonly.bind(this);
    this.isNullable = this.isNullable.bind(this);
    this.isOptional = this.isOptional.bind(this);
    this["~standard"] = {
      version: 1,
      vendor: "zod",
      validate: (data2) => this["~validate"](data2)
    };
  }
  optional() {
    return ZodOptional$1.create(this, this._def);
  }
  nullable() {
    return ZodNullable$1.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray$1.create(this);
  }
  promise() {
    return ZodPromise$1.create(this, this._def);
  }
  or(option) {
    return ZodUnion$1.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection$1.create(this, incoming, this._def);
  }
  transform(transform) {
    return new ZodEffects$1({
      ...processCreateParams$1(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind$1.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault$1({
      ...processCreateParams$1(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind$1.ZodDefault
    });
  }
  brand() {
    return new ZodBranded$1({
      typeName: ZodFirstPartyTypeKind$1.ZodBranded,
      type: this,
      ...processCreateParams$1(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch$1({
      ...processCreateParams$1(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind$1.ZodCatch
    });
  }
  describe(description2) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description: description2
    });
  }
  pipe(target) {
    return ZodPipeline$1.create(this, target);
  }
  readonly() {
    return ZodReadonly$1.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
const cuidRegex$1 = /^c[^\s-]{8,}$/i;
const cuid2Regex$1 = /^[0-9a-z]+$/;
const ulidRegex$1 = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex$1 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex$1 = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex$1 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex$1 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
let emojiRegex$1;
const ipv4Regex$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex$1 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex$1 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource$1 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
const dateRegex$1 = new RegExp(`^${dateRegexSource$1}$`);
function timeRegexSource$1(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex$1(args) {
  return new RegExp(`^${timeRegexSource$1(args)}$`);
}
function datetimeRegex$1(args) {
  let regex = `${dateRegexSource$1}T${timeRegexSource$1(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP$1(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex$1.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex$1.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
let ZodString$1 = class ZodString2 extends ZodType$1 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx2, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.string,
        received: ctx2.parsedType
      });
      return INVALID$1;
    }
    const status = new ParseStatus$1();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.length < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_small,
            minimum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.length > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_big,
            maximum: check.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "length") {
        const tooBig = input.data.length > check.value;
        const tooSmall = input.data.length < check.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext$1(ctx, {
              code: ZodIssueCode$1.too_big,
              maximum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          } else if (tooSmall) {
            addIssueToContext$1(ctx, {
              code: ZodIssueCode$1.too_small,
              minimum: check.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check.message
            });
          }
          status.dirty();
        }
      } else if (check.kind === "email") {
        if (!emailRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "email",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "emoji") {
        if (!emojiRegex$1) {
          emojiRegex$1 = new RegExp(_emojiRegex$1, "u");
        }
        if (!emojiRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "emoji",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "uuid") {
        if (!uuidRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "uuid",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "nanoid") {
        if (!nanoidRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "nanoid",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid") {
        if (!cuidRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "cuid",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cuid2") {
        if (!cuid2Regex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "cuid2",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ulid") {
        if (!ulidRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "ulid",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "url") {
        try {
          new URL(input.data);
        } catch {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "url",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "regex") {
        check.regex.lastIndex = 0;
        const testResult = check.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "regex",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "trim") {
        input.data = input.data.trim();
      } else if (check.kind === "includes") {
        if (!input.data.includes(check.value, check.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: { includes: check.value, position: check.position },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check.kind === "startsWith") {
        if (!input.data.startsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: { startsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "endsWith") {
        if (!input.data.endsWith(check.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: { endsWith: check.value },
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "datetime") {
        const regex = datetimeRegex$1(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: "datetime",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "date") {
        const regex = dateRegex$1;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: "date",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "time") {
        const regex = timeRegex$1(check);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_string,
            validation: "time",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "duration") {
        if (!durationRegex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "duration",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "ip") {
        if (!isValidIP$1(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "ip",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "jwt") {
        if (!isValidJWT(input.data, check.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "jwt",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "cidr") {
        if (!isValidCidr(input.data, check.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "cidr",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64") {
        if (!base64Regex$1.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "base64",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            validation: "base64url",
            code: ZodIssueCode$1.invalid_string,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data2) => regex.test(data2), {
      validation,
      code: ZodIssueCode$1.invalid_string,
      ...errorUtil$1.errToObj(message)
    });
  }
  _addCheck(check) {
    return new ZodString2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil$1.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil$1.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil$1.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil$1.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil$1.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil$1.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil$1.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil$1.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil$1.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil$1.errToObj(message)
    });
  }
  jwt(options2) {
    return this._addCheck({ kind: "jwt", ...errorUtil$1.errToObj(options2) });
  }
  ip(options2) {
    return this._addCheck({ kind: "ip", ...errorUtil$1.errToObj(options2) });
  }
  cidr(options2) {
    return this._addCheck({ kind: "cidr", ...errorUtil$1.errToObj(options2) });
  }
  datetime(options2) {
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options2
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options2 == null ? void 0 : options2.precision) === "undefined" ? null : options2 == null ? void 0 : options2.precision,
      offset: (options2 == null ? void 0 : options2.offset) ?? false,
      local: (options2 == null ? void 0 : options2.local) ?? false,
      ...errorUtil$1.errToObj(options2 == null ? void 0 : options2.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options2) {
    if (typeof options2 === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options2
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options2 == null ? void 0 : options2.precision) === "undefined" ? null : options2 == null ? void 0 : options2.precision,
      ...errorUtil$1.errToObj(options2 == null ? void 0 : options2.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil$1.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil$1.errToObj(message)
    });
  }
  includes(value, options2) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options2 == null ? void 0 : options2.position,
      ...errorUtil$1.errToObj(options2 == null ? void 0 : options2.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil$1.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil$1.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil$1.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil$1.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil$1.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil$1.errToObj(message));
  }
  trim() {
    return new ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxLength() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
};
ZodString$1.create = (params) => {
  return new ZodString$1({
    checks: [],
    typeName: ZodFirstPartyTypeKind$1.ZodString,
    coerce: (params == null ? void 0 : params.coerce) ?? false,
    ...processCreateParams$1(params)
  });
};
function floatSafeRemainder$1(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
let ZodNumber$1 = class ZodNumber2 extends ZodType$1 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx2, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.number,
        received: ctx2.parsedType
      });
      return INVALID$1;
    }
    let ctx = void 0;
    const status = new ParseStatus$1();
    for (const check of this._def.checks) {
      if (check.kind === "int") {
        if (!util$3.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.invalid_type,
            expected: "integer",
            received: "float",
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_small,
            minimum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_big,
            maximum: check.value,
            type: "number",
            inclusive: check.inclusive,
            exact: false,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (floatSafeRemainder$1(input.data, check.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.not_finite,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil$1.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil$1.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil$1.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil$1.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodNumber2({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil$1.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodNumber2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil$1.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil$1.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil$1.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil$1.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil$1.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil$1.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil$1.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil$1.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil$1.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util$3.isInteger(ch.value));
  }
  get isFinite() {
    let max2 = null;
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      } else if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return Number.isFinite(min2) && Number.isFinite(max2);
  }
};
ZodNumber$1.create = (params) => {
  return new ZodNumber$1({
    checks: [],
    typeName: ZodFirstPartyTypeKind$1.ZodNumber,
    coerce: (params == null ? void 0 : params.coerce) || false,
    ...processCreateParams$1(params)
  });
};
let ZodBigInt$1 = class ZodBigInt2 extends ZodType$1 {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus$1();
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_small,
            type: "bigint",
            minimum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_big,
            type: "bigint",
            maximum: check.value,
            inclusive: check.inclusive,
            message: check.message
          });
          status.dirty();
        }
      } else if (check.kind === "multipleOf") {
        if (input.data % check.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.not_multiple_of,
            multipleOf: check.value,
            message: check.message
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext$1(ctx, {
      code: ZodIssueCode$1.invalid_type,
      expected: ZodParsedType$1.bigint,
      received: ctx.parsedType
    });
    return INVALID$1;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil$1.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil$1.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil$1.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil$1.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new ZodBigInt2({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil$1.toString(message)
        }
      ]
    });
  }
  _addCheck(check) {
    return new ZodBigInt2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil$1.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil$1.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil$1.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil$1.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil$1.toString(message)
    });
  }
  get minValue() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2;
  }
  get maxValue() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2;
  }
};
ZodBigInt$1.create = (params) => {
  return new ZodBigInt$1({
    checks: [],
    typeName: ZodFirstPartyTypeKind$1.ZodBigInt,
    coerce: (params == null ? void 0 : params.coerce) ?? false,
    ...processCreateParams$1(params)
  });
};
let ZodBoolean$1 = class ZodBoolean2 extends ZodType$1 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.boolean,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
};
ZodBoolean$1.create = (params) => {
  return new ZodBoolean$1({
    typeName: ZodFirstPartyTypeKind$1.ZodBoolean,
    coerce: (params == null ? void 0 : params.coerce) || false,
    ...processCreateParams$1(params)
  });
};
let ZodDate$1 = class ZodDate2 extends ZodType$1 {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx2, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.date,
        received: ctx2.parsedType
      });
      return INVALID$1;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx2, {
        code: ZodIssueCode$1.invalid_date
      });
      return INVALID$1;
    }
    const status = new ParseStatus$1();
    let ctx = void 0;
    for (const check of this._def.checks) {
      if (check.kind === "min") {
        if (input.data.getTime() < check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_small,
            message: check.message,
            inclusive: true,
            exact: false,
            minimum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check.kind === "max") {
        if (input.data.getTime() > check.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.too_big,
            message: check.message,
            inclusive: true,
            exact: false,
            maximum: check.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util$3.assertNever(check);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check) {
    return new ZodDate2({
      ...this._def,
      checks: [...this._def.checks, check]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil$1.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil$1.toString(message)
    });
  }
  get minDate() {
    let min2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min2 === null || ch.value > min2)
          min2 = ch.value;
      }
    }
    return min2 != null ? new Date(min2) : null;
  }
  get maxDate() {
    let max2 = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max2 === null || ch.value < max2)
          max2 = ch.value;
      }
    }
    return max2 != null ? new Date(max2) : null;
  }
};
ZodDate$1.create = (params) => {
  return new ZodDate$1({
    checks: [],
    coerce: (params == null ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind$1.ZodDate,
    ...processCreateParams$1(params)
  });
};
let ZodSymbol$1 = class ZodSymbol2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.symbol,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
};
ZodSymbol$1.create = (params) => {
  return new ZodSymbol$1({
    typeName: ZodFirstPartyTypeKind$1.ZodSymbol,
    ...processCreateParams$1(params)
  });
};
let ZodUndefined$1 = class ZodUndefined2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.undefined,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
};
ZodUndefined$1.create = (params) => {
  return new ZodUndefined$1({
    typeName: ZodFirstPartyTypeKind$1.ZodUndefined,
    ...processCreateParams$1(params)
  });
};
let ZodNull$1 = class ZodNull2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.null,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
};
ZodNull$1.create = (params) => {
  return new ZodNull$1({
    typeName: ZodFirstPartyTypeKind$1.ZodNull,
    ...processCreateParams$1(params)
  });
};
let ZodAny$1 = class ZodAny2 extends ZodType$1 {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK$1(input.data);
  }
};
ZodAny$1.create = (params) => {
  return new ZodAny$1({
    typeName: ZodFirstPartyTypeKind$1.ZodAny,
    ...processCreateParams$1(params)
  });
};
let ZodUnknown$1 = class ZodUnknown2 extends ZodType$1 {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK$1(input.data);
  }
};
ZodUnknown$1.create = (params) => {
  return new ZodUnknown$1({
    typeName: ZodFirstPartyTypeKind$1.ZodUnknown,
    ...processCreateParams$1(params)
  });
};
let ZodNever$1 = class ZodNever2 extends ZodType$1 {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext$1(ctx, {
      code: ZodIssueCode$1.invalid_type,
      expected: ZodParsedType$1.never,
      received: ctx.parsedType
    });
    return INVALID$1;
  }
};
ZodNever$1.create = (params) => {
  return new ZodNever$1({
    typeName: ZodFirstPartyTypeKind$1.ZodNever,
    ...processCreateParams$1(params)
  });
};
let ZodVoid$1 = class ZodVoid2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.void,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
};
ZodVoid$1.create = (params) => {
  return new ZodVoid$1({
    typeName: ZodFirstPartyTypeKind$1.ZodVoid,
    ...processCreateParams$1(params)
  });
};
let ZodArray$1 = class ZodArray2 extends ZodType$1 {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType$1.array) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.array,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext$1(ctx, {
          code: tooBig ? ZodIssueCode$1.too_big : ZodIssueCode$1.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext$1(ctx, {
          code: ZodIssueCode$1.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext$1(ctx, {
          code: ZodIssueCode$1.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i2) => {
        return def.type._parseAsync(new ParseInputLazyPath$1(ctx, item, ctx.path, i2));
      })).then((result2) => {
        return ParseStatus$1.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i2) => {
      return def.type._parseSync(new ParseInputLazyPath$1(ctx, item, ctx.path, i2));
    });
    return ParseStatus$1.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new ZodArray2({
      ...this._def,
      minLength: { value: minLength, message: errorUtil$1.toString(message) }
    });
  }
  max(maxLength, message) {
    return new ZodArray2({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil$1.toString(message) }
    });
  }
  length(len, message) {
    return new ZodArray2({
      ...this._def,
      exactLength: { value: len, message: errorUtil$1.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray$1.create = (schema, params) => {
  return new ZodArray$1({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind$1.ZodArray,
    ...processCreateParams$1(params)
  });
};
function deepPartialify$1(schema) {
  if (schema instanceof ZodObject$1) {
    const newShape = {};
    for (const key2 in schema.shape) {
      const fieldSchema = schema.shape[key2];
      newShape[key2] = ZodOptional$1.create(deepPartialify$1(fieldSchema));
    }
    return new ZodObject$1({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray$1) {
    return new ZodArray$1({
      ...schema._def,
      type: deepPartialify$1(schema.element)
    });
  } else if (schema instanceof ZodOptional$1) {
    return ZodOptional$1.create(deepPartialify$1(schema.unwrap()));
  } else if (schema instanceof ZodNullable$1) {
    return ZodNullable$1.create(deepPartialify$1(schema.unwrap()));
  } else if (schema instanceof ZodTuple$1) {
    return ZodTuple$1.create(schema.items.map((item) => deepPartialify$1(item)));
  } else {
    return schema;
  }
}
let ZodObject$1 = class ZodObject2 extends ZodType$1 {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util$3.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx2, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.object,
        received: ctx2.parsedType
      });
      return INVALID$1;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever$1 && this._def.unknownKeys === "strip")) {
      for (const key2 in ctx.data) {
        if (!shapeKeys.includes(key2)) {
          extraKeys.push(key2);
        }
      }
    }
    const pairs = [];
    for (const key2 of shapeKeys) {
      const keyValidator = shape[key2];
      const value = ctx.data[key2];
      pairs.push({
        key: { status: "valid", value: key2 },
        value: keyValidator._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, key2)),
        alwaysSet: key2 in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever$1) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key2 of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key2 },
            value: { status: "valid", value: ctx.data[key2] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext$1(ctx, {
            code: ZodIssueCode$1.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") ;
      else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key2 of extraKeys) {
        const value = ctx.data[key2];
        pairs.push({
          key: { status: "valid", value: key2 },
          value: catchall._parse(
            new ParseInputLazyPath$1(ctx, value, ctx.path, key2)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key2 in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key2 = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key: key2,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus$1.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus$1.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil$1.errToObj;
    return new ZodObject2({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue, ctx) => {
          var _a3, _b2;
          const defaultError = ((_b2 = (_a3 = this._def).errorMap) == null ? void 0 : _b2.call(_a3, issue, ctx).message) ?? ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: errorUtil$1.errToObj(message).message ?? defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new ZodObject2({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject2({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new ZodObject2({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new ZodObject2({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind$1.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key2, schema) {
    return this.augment({ [key2]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index2) {
    return new ZodObject2({
      ...this._def,
      catchall: index2
    });
  }
  pick(mask) {
    const shape = {};
    for (const key2 of util$3.objectKeys(mask)) {
      if (mask[key2] && this.shape[key2]) {
        shape[key2] = this.shape[key2];
      }
    }
    return new ZodObject2({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key2 of util$3.objectKeys(this.shape)) {
      if (!mask[key2]) {
        shape[key2] = this.shape[key2];
      }
    }
    return new ZodObject2({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify$1(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key2 of util$3.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key2];
      if (mask && !mask[key2]) {
        newShape[key2] = fieldSchema;
      } else {
        newShape[key2] = fieldSchema.optional();
      }
    }
    return new ZodObject2({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key2 of util$3.objectKeys(this.shape)) {
      if (mask && !mask[key2]) {
        newShape[key2] = this.shape[key2];
      } else {
        const fieldSchema = this.shape[key2];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional$1) {
          newField = newField._def.innerType;
        }
        newShape[key2] = newField;
      }
    }
    return new ZodObject2({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum$1(util$3.objectKeys(this.shape));
  }
};
ZodObject$1.create = (shape, params) => {
  return new ZodObject$1({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever$1.create(),
    typeName: ZodFirstPartyTypeKind$1.ZodObject,
    ...processCreateParams$1(params)
  });
};
ZodObject$1.strictCreate = (shape, params) => {
  return new ZodObject$1({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever$1.create(),
    typeName: ZodFirstPartyTypeKind$1.ZodObject,
    ...processCreateParams$1(params)
  });
};
ZodObject$1.lazycreate = (shape, params) => {
  return new ZodObject$1({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever$1.create(),
    typeName: ZodFirstPartyTypeKind$1.ZodObject,
    ...processCreateParams$1(params)
  });
};
let ZodUnion$1 = class ZodUnion2 extends ZodType$1 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options2 = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError$1(result.ctx.common.issues));
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_union,
        unionErrors
      });
      return INVALID$1;
    }
    if (ctx.common.async) {
      return Promise.all(options2.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options2) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError$1(issues2));
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_union,
        unionErrors
      });
      return INVALID$1;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion$1.create = (types, params) => {
  return new ZodUnion$1({
    options: types,
    typeName: ZodFirstPartyTypeKind$1.ZodUnion,
    ...processCreateParams$1(params)
  });
};
const getDiscriminator$1 = (type2) => {
  if (type2 instanceof ZodLazy$1) {
    return getDiscriminator$1(type2.schema);
  } else if (type2 instanceof ZodEffects$1) {
    return getDiscriminator$1(type2.innerType());
  } else if (type2 instanceof ZodLiteral$1) {
    return [type2.value];
  } else if (type2 instanceof ZodEnum$1) {
    return type2.options;
  } else if (type2 instanceof ZodNativeEnum$1) {
    return util$3.objectValues(type2.enum);
  } else if (type2 instanceof ZodDefault$1) {
    return getDiscriminator$1(type2._def.innerType);
  } else if (type2 instanceof ZodUndefined$1) {
    return [void 0];
  } else if (type2 instanceof ZodNull$1) {
    return [null];
  } else if (type2 instanceof ZodOptional$1) {
    return [void 0, ...getDiscriminator$1(type2.unwrap())];
  } else if (type2 instanceof ZodNullable$1) {
    return [null, ...getDiscriminator$1(type2.unwrap())];
  } else if (type2 instanceof ZodBranded$1) {
    return getDiscriminator$1(type2.unwrap());
  } else if (type2 instanceof ZodReadonly$1) {
    return getDiscriminator$1(type2.unwrap());
  } else if (type2 instanceof ZodCatch$1) {
    return getDiscriminator$1(type2._def.innerType);
  } else {
    return [];
  }
};
let ZodDiscriminatedUnion$1 = class ZodDiscriminatedUnion2 extends ZodType$1 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.object) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.object,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID$1;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options2, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type2 of options2) {
      const discriminatorValues = getDiscriminator$1(type2.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type2);
      }
    }
    return new ZodDiscriminatedUnion2({
      typeName: ZodFirstPartyTypeKind$1.ZodDiscriminatedUnion,
      discriminator,
      options: options2,
      optionsMap,
      ...processCreateParams$1(params)
    });
  }
};
function mergeValues$1(a2, b2) {
  const aType = getParsedType$1(a2);
  const bType = getParsedType$1(b2);
  if (a2 === b2) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType$1.object && bType === ZodParsedType$1.object) {
    const bKeys = util$3.objectKeys(b2);
    const sharedKeys = util$3.objectKeys(a2).filter((key2) => bKeys.indexOf(key2) !== -1);
    const newObj = { ...a2, ...b2 };
    for (const key2 of sharedKeys) {
      const sharedValue = mergeValues$1(a2[key2], b2[key2]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key2] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType$1.array && bType === ZodParsedType$1.array) {
    if (a2.length !== b2.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a2.length; index2++) {
      const itemA = a2[index2];
      const itemB = b2[index2];
      const sharedValue = mergeValues$1(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType$1.date && bType === ZodParsedType$1.date && +a2 === +b2) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}
let ZodIntersection$1 = class ZodIntersection2 extends ZodType$1 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted$1(parsedLeft) || isAborted$1(parsedRight)) {
        return INVALID$1;
      }
      const merged = mergeValues$1(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext$1(ctx, {
          code: ZodIssueCode$1.invalid_intersection_types
        });
        return INVALID$1;
      }
      if (isDirty$1(parsedLeft) || isDirty$1(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection$1.create = (left, right, params) => {
  return new ZodIntersection$1({
    left,
    right,
    typeName: ZodFirstPartyTypeKind$1.ZodIntersection,
    ...processCreateParams$1(params)
  });
};
let ZodTuple$1 = class ZodTuple2 extends ZodType$1 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.array) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.array,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID$1;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items2 = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, itemIndex));
    }).filter((x2) => !!x2);
    if (ctx.common.async) {
      return Promise.all(items2).then((results) => {
        return ParseStatus$1.mergeArray(status, results);
      });
    } else {
      return ParseStatus$1.mergeArray(status, items2);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new ZodTuple2({
      ...this._def,
      rest
    });
  }
};
ZodTuple$1.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple$1({
    items: schemas,
    typeName: ZodFirstPartyTypeKind$1.ZodTuple,
    rest: null,
    ...processCreateParams$1(params)
  });
};
let ZodRecord$1 = class ZodRecord2 extends ZodType$1 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.object) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.object,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key2 in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath$1(ctx, key2, ctx.path, key2)),
        value: valueType._parse(new ParseInputLazyPath$1(ctx, ctx.data[key2], ctx.path, key2)),
        alwaysSet: key2 in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus$1.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus$1.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType$1) {
      return new ZodRecord2({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind$1.ZodRecord,
        ...processCreateParams$1(third)
      });
    }
    return new ZodRecord2({
      keyType: ZodString$1.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind$1.ZodRecord,
      ...processCreateParams$1(second)
    });
  }
};
let ZodMap$1 = class ZodMap2 extends ZodType$1 {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.map) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.map,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key2, value], index2) => {
      return {
        key: keyType._parse(new ParseInputLazyPath$1(ctx, key2, ctx.path, [index2, "key"])),
        value: valueType._parse(new ParseInputLazyPath$1(ctx, value, ctx.path, [index2, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key2 = await pair.key;
          const value = await pair.value;
          if (key2.status === "aborted" || value.status === "aborted") {
            return INVALID$1;
          }
          if (key2.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key2.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key2 = pair.key;
        const value = pair.value;
        if (key2.status === "aborted" || value.status === "aborted") {
          return INVALID$1;
        }
        if (key2.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key2.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap$1.create = (keyType, valueType, params) => {
  return new ZodMap$1({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind$1.ZodMap,
    ...processCreateParams$1(params)
  });
};
let ZodSet$1 = class ZodSet2 extends ZodType$1 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.set) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.set,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext$1(ctx, {
          code: ZodIssueCode$1.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext$1(ctx, {
          code: ZodIssueCode$1.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID$1;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath$1(ctx, item, ctx.path, i2)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new ZodSet2({
      ...this._def,
      minSize: { value: minSize, message: errorUtil$1.toString(message) }
    });
  }
  max(maxSize, message) {
    return new ZodSet2({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil$1.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet$1.create = (valueType, params) => {
  return new ZodSet$1({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind$1.ZodSet,
    ...processCreateParams$1(params)
  });
};
let ZodLazy$1 = class ZodLazy2 extends ZodType$1 {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy$1.create = (getter, params) => {
  return new ZodLazy$1({
    getter,
    typeName: ZodFirstPartyTypeKind$1.ZodLazy,
    ...processCreateParams$1(params)
  });
};
let ZodLiteral$1 = class ZodLiteral2 extends ZodType$1 {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        received: ctx.data,
        code: ZodIssueCode$1.invalid_literal,
        expected: this._def.value
      });
      return INVALID$1;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral$1.create = (value, params) => {
  return new ZodLiteral$1({
    value,
    typeName: ZodFirstPartyTypeKind$1.ZodLiteral,
    ...processCreateParams$1(params)
  });
};
function createZodEnum$1(values, params) {
  return new ZodEnum$1({
    values,
    typeName: ZodFirstPartyTypeKind$1.ZodEnum,
    ...processCreateParams$1(params)
  });
}
let ZodEnum$1 = class ZodEnum2 extends ZodType$1 {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext$1(ctx, {
        expected: util$3.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode$1.invalid_type
      });
      return INVALID$1;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext$1(ctx, {
        received: ctx.data,
        code: ZodIssueCode$1.invalid_enum_value,
        options: expectedValues
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return ZodEnum2.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return ZodEnum2.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum$1.create = createZodEnum$1;
let ZodNativeEnum$1 = class ZodNativeEnum2 extends ZodType$1 {
  _parse(input) {
    const nativeEnumValues = util$3.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType$1.string && ctx.parsedType !== ZodParsedType$1.number) {
      const expectedValues = util$3.objectValues(nativeEnumValues);
      addIssueToContext$1(ctx, {
        expected: util$3.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode$1.invalid_type
      });
      return INVALID$1;
    }
    if (!this._cache) {
      this._cache = new Set(util$3.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util$3.objectValues(nativeEnumValues);
      addIssueToContext$1(ctx, {
        received: ctx.data,
        code: ZodIssueCode$1.invalid_enum_value,
        options: expectedValues
      });
      return INVALID$1;
    }
    return OK$1(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum$1.create = (values, params) => {
  return new ZodNativeEnum$1({
    values,
    typeName: ZodFirstPartyTypeKind$1.ZodNativeEnum,
    ...processCreateParams$1(params)
  });
};
let ZodPromise$1 = class ZodPromise2 extends ZodType$1 {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType$1.promise && ctx.common.async === false) {
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.promise,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    const promisified = ctx.parsedType === ZodParsedType$1.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK$1(promisified.then((data2) => {
      return this._def.type.parseAsync(data2, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise$1.create = (schema, params) => {
  return new ZodPromise$1({
    type: schema,
    typeName: ZodFirstPartyTypeKind$1.ZodPromise,
    ...processCreateParams$1(params)
  });
};
let ZodEffects$1 = class ZodEffects2 extends ZodType$1 {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind$1.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext$1(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID$1;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID$1;
          if (result.status === "dirty")
            return DIRTY$1(result.value);
          if (status.value === "dirty")
            return DIRTY$1(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID$1;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID$1;
        if (result.status === "dirty")
          return DIRTY$1(result.value);
        if (status.value === "dirty")
          return DIRTY$1(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID$1;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID$1;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base2 = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid$1(base2))
          return INVALID$1;
        const result = effect.transform(base2.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
          if (!isValid$1(base2))
            return INVALID$1;
          return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util$3.assertNever(effect);
  }
};
ZodEffects$1.create = (schema, effect, params) => {
  return new ZodEffects$1({
    schema,
    typeName: ZodFirstPartyTypeKind$1.ZodEffects,
    effect,
    ...processCreateParams$1(params)
  });
};
ZodEffects$1.createWithPreprocess = (preprocess, schema, params) => {
  return new ZodEffects$1({
    schema,
    effect: { type: "preprocess", transform: preprocess },
    typeName: ZodFirstPartyTypeKind$1.ZodEffects,
    ...processCreateParams$1(params)
  });
};
let ZodOptional$1 = class ZodOptional2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType$1.undefined) {
      return OK$1(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional$1.create = (type2, params) => {
  return new ZodOptional$1({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind$1.ZodOptional,
    ...processCreateParams$1(params)
  });
};
let ZodNullable$1 = class ZodNullable2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType$1.null) {
      return OK$1(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable$1.create = (type2, params) => {
  return new ZodNullable$1({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind$1.ZodNullable,
    ...processCreateParams$1(params)
  });
};
let ZodDefault$1 = class ZodDefault2 extends ZodType$1 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data2 = ctx.data;
    if (ctx.parsedType === ZodParsedType$1.undefined) {
      data2 = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault$1.create = (type2, params) => {
  return new ZodDefault$1({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind$1.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams$1(params)
  });
};
let ZodCatch$1 = class ZodCatch2 extends ZodType$1 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync$1(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError$1(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError$1(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch$1.create = (type2, params) => {
  return new ZodCatch$1({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind$1.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams$1(params)
  });
};
let ZodNaN$1 = class ZodNaN2 extends ZodType$1 {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType$1.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext$1(ctx, {
        code: ZodIssueCode$1.invalid_type,
        expected: ZodParsedType$1.nan,
        received: ctx.parsedType
      });
      return INVALID$1;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN$1.create = (params) => {
  return new ZodNaN$1({
    typeName: ZodFirstPartyTypeKind$1.ZodNaN,
    ...processCreateParams$1(params)
  });
};
let ZodBranded$1 = class ZodBranded2 extends ZodType$1 {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data2 = ctx.data;
    return this._def.type._parse({
      data: data2,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
let ZodPipeline$1 = class ZodPipeline2 extends ZodType$1 {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID$1;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY$1(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID$1;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a2, b2) {
    return new ZodPipeline2({
      in: a2,
      out: b2,
      typeName: ZodFirstPartyTypeKind$1.ZodPipeline
    });
  }
};
let ZodReadonly$1 = class ZodReadonly2 extends ZodType$1 {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data2) => {
      if (isValid$1(data2)) {
        data2.value = Object.freeze(data2.value);
      }
      return data2;
    };
    return isAsync$1(result) ? result.then((data2) => freeze(data2)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly$1.create = (type2, params) => {
  return new ZodReadonly$1({
    innerType: type2,
    typeName: ZodFirstPartyTypeKind$1.ZodReadonly,
    ...processCreateParams$1(params)
  });
};
function cleanParams(params, data2) {
  const p2 = typeof params === "function" ? params(data2) : typeof params === "string" ? { message: params } : params;
  const p22 = typeof p2 === "string" ? { message: p2 } : p2;
  return p22;
}
function custom$2(check, _params = {}, fatal) {
  if (check)
    return ZodAny$1.create().superRefine((data2, ctx) => {
      const r2 = check(data2);
      if (r2 instanceof Promise) {
        return r2.then((r3) => {
          if (!r3) {
            const params = cleanParams(_params, data2);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r2) {
        const params = cleanParams(_params, data2);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny$1.create();
}
var ZodFirstPartyTypeKind$1;
(function(ZodFirstPartyTypeKind2) {
  ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind$1 || (ZodFirstPartyTypeKind$1 = {}));
const instanceOfType$1 = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom$2((data2) => data2 instanceof cls, params);
const stringType$1 = ZodString$1.create;
const numberType$1 = ZodNumber$1.create;
const booleanType$1 = ZodBoolean$1.create;
const anyType$1 = ZodAny$1.create;
const unknownType$1 = ZodUnknown$1.create;
ZodNever$1.create;
const voidType$1 = ZodVoid$1.create;
const arrayType$1 = ZodArray$1.create;
const objectType$1 = ZodObject$1.create;
const unionType$1 = ZodUnion$1.create;
const discriminatedUnionType$1 = ZodDiscriminatedUnion$1.create;
ZodIntersection$1.create;
ZodTuple$1.create;
const recordType$1 = ZodRecord$1.create;
const literalType$1 = ZodLiteral$1.create;
const enumType$1 = ZodEnum$1.create;
ZodPromise$1.create;
const optionalType$1 = ZodOptional$1.create;
ZodNullable$1.create;
class NodeProxyImpl {
  constructor(graphInstance, nodeId) {
    __publicField2(this, "graphInstance");
    __publicField2(this, "nodeId");
    this.graphInstance = graphInstance;
    this.nodeId = nodeId;
  }
  /**
   * Get the store for this node
   */
  get store() {
    const nodeStore = this.graphInstance.getNodeStore(this.nodeId);
    if (!nodeStore) {
      throw new Error(`No store found for node ${this.nodeId}`);
    }
    return nodeStore;
  }
  /**
   * Get typed actions for this node
   */
  get actions() {
    const nodeDef = this.graphInstance.getDefinition().getNode(this.nodeId);
    if (!nodeDef) {
      throw new Error(`Node definition not found for ${this.nodeId}`);
    }
    const actionProxy = new Proxy({}, {
      get: (target, actionName) => {
        if (typeof actionName !== "string") {
          return void 0;
        }
        const actionDef = nodeDef.actions[actionName];
        const isInternalAction = actionName.startsWith("__internal_");
        if (!actionDef && !isInternalAction) {
          throw new Error(`Action ${actionName} not found for node ${this.nodeId}`);
        }
        return async (data2, signal) => {
          const connectionInfo = this.getConnectionInfo();
          if (!connectionInfo) {
            throw new Error(`No connection available for node ${this.nodeId}`);
          }
          const { transport, path } = connectionInfo;
          const sourceNodeId = this.graphInstance.getCurrentNodeId();
          if (!(actionDef == null ? void 0 : actionDef.stream)) {
            const responseSchema = anyType$1();
            let result;
            if (path.length === 2) {
              result = await transport.request({
                method: "sdppp/directRequest",
                params: {
                  action: actionName,
                  data: data2,
                  sourceNodeId
                }
              }, responseSchema);
            } else {
              try {
                result = await transport.request({
                  method: "sdppp/directRequest",
                  params: {
                    action: "__proxy_forward",
                    data: {
                      targetNodeId: this.nodeId,
                      targetAction: actionName,
                      targetData: data2,
                      forwardPath: path.slice(1)
                      // Remove current node from path
                    },
                    sourceNodeId
                  }
                }, responseSchema);
              } catch (error) {
                console.error(`Error in direct request ${actionName}:`, error);
                console.error({
                  targetNodeId: this.nodeId,
                  targetAction: actionName,
                  targetData: data2,
                  forwardPath: path.slice(1)
                  // Remove current node from path
                });
                throw error;
              }
            }
            return result;
          }
          let streamIteratorPromise;
          if (path.length === 2) {
            streamIteratorPromise = transport.streamRequest({
              action: actionName,
              data: data2,
              sourceNodeId
            }, actionDef.responseSchema, signal);
          } else {
            streamIteratorPromise = transport.streamRequest({
              action: "__proxy_forward",
              data: {
                targetNodeId: this.nodeId,
                targetAction: actionName,
                targetData: data2,
                forwardPath: path.slice(1)
                // Remove current node from path
              },
              sourceNodeId
            }, actionDef.responseSchema, signal);
          }
          return streamIteratorPromise;
        };
      }
    });
    return actionProxy;
  }
  /**
   * Get the transport connection for this node proxy
   */
  getConnectionInfo() {
    return this.graphInstance.getTransportToNode(this.nodeId);
  }
}
class GraphStoreSynchronizer {
  // BroadcastManager type
  constructor(graphInstance) {
    __publicField2(this, "graphInstance");
    // GraphInstance type
    __publicField2(this, "actionManager");
    // ActionManager type
    __publicField2(this, "broadcastManager");
    this.graphInstance = graphInstance;
    this.actionManager = graphInstance.actionManager;
    this.broadcastManager = graphInstance.broadcastManager;
  }
  initializeConsumer({
    store,
    storeName,
    onStateUpdate,
    requestInitialState
  }) {
    this.broadcastManager.registerHandler(`store:update:${storeName}`, (payload) => {
      try {
        if (payload.sourceNodeId !== this.graphInstance.getCurrentNodeId()) {
          onStateUpdate(payload.stateUpdate);
        } else {
        }
      } catch (error) {
        console.error(`[GraphStoreSynchronizer] Error processing store update for ${storeName}:`, error);
      }
    });
  }
  initializeProducer({
    store,
    storeName,
    sendStateUpdate,
    onInitialStateRequested
  }) {
    const currentNodeId = this.graphInstance.getCurrentNodeId();
    const broadcastStateUpdate = async (state, isInitialState = false) => {
      const transportReady = this.isTransportReady();
      if (transportReady) {
        try {
          await this.broadcastManager.broadcast(`store:update:${storeName}`, {
            storeName,
            sourceNodeId: currentNodeId,
            stateUpdate: state,
            isInitialState
          });
        } catch (error) {
          console.error(`[GraphStoreSynchronizer] Error broadcasting state update for ${storeName}:`, error);
        }
      }
    };
    const unsubscribe = store.subscribe((state) => {
      broadcastStateUpdate(state, false);
    });
    onInitialStateRequested(() => {
      broadcastStateUpdate(store.getState(), true);
    });
    const actionName = `__internal_requestInitialState_${storeName}`;
    this.actionManager.implementInternalAction(actionName, async () => {
      const currentState = store.getState();
      await broadcastStateUpdate(currentState, true);
      return { success: true };
    });
    this.broadcastManager.registerHandler(`__connection_established`, async (payload) => {
      try {
        if (payload.toNode === currentNodeId || payload.fromNode === currentNodeId) {
          await broadcastStateUpdate(store.getState(), true);
        }
      } catch (error) {
      }
    });
    return () => {
      var _a3;
      unsubscribe();
      (_a3 = this.actionManager.actionHandlers) == null ? void 0 : _a3.delete(actionName);
    };
  }
  isTransportReady() {
    var _a3;
    try {
      const connectionManager = this.graphInstance.connectionManager;
      const hasConnectedNodes = connectionManager && connectionManager.getConnectionCount() > 0;
      const hasMountedEndpoint = ((_a3 = this.broadcastManager.mountedEndpoints) == null ? void 0 : _a3.size) > 0;
      return hasConnectedNodes || hasMountedEndpoint;
    } catch {
      return !!this.broadcastManager;
    }
  }
  /**
   * Manually broadcast the current state of a store
   */
  async broadcastCurrentState(store, storeName) {
    const currentNodeId = this.graphInstance.getCurrentNodeId();
    const transportReady = this.isTransportReady();
    if (transportReady) {
      try {
        await this.broadcastManager.broadcast(`store:update:${storeName}`, {
          storeName,
          sourceNodeId: currentNodeId,
          stateUpdate: store.getState(),
          isInitialState: true
        });
      } catch (error) {
      }
    }
  }
}
function bindStoreConsumerSideGraph({
  graphInstance,
  store,
  name
}) {
  const synchronizer = new GraphStoreSynchronizer(graphInstance);
  const onStateUpdate = (newState) => {
    const currentState = store.getState();
    const updatedState = { ...currentState, ...newState };
    store.setState(updatedState);
  };
  const requestInitialState = async () => {
    const actionName = `__internal_requestInitialState_${name}`;
    try {
      const nodeProxy = graphInstance.getNode(name);
      if (nodeProxy && nodeProxy.actions && nodeProxy.actions[actionName]) {
        await nodeProxy.actions[actionName]();
      }
    } catch (error) {
      console.warn(`Failed to request initial state for ${name}:`, error);
    }
  };
  synchronizer.initializeConsumer({
    store,
    storeName: name,
    onStateUpdate,
    requestInitialState
  });
}
function bindStoreProducerSideGraph({
  graphInstance,
  store,
  name
}) {
  const synchronizer = new GraphStoreSynchronizer(graphInstance);
  const sendStateUpdate = async (state) => {
  };
  const onInitialStateRequested = (callback) => {
  };
  return synchronizer.initializeProducer({
    store,
    storeName: name,
    sendStateUpdate,
    onInitialStateRequested
  });
}
class BroadcastManager {
  constructor(currentNodeId) {
    __publicField2(this, "broadcastHandlers", /* @__PURE__ */ new Map());
    __publicField2(this, "transports", /* @__PURE__ */ new Map());
    __publicField2(this, "mountedTransports", /* @__PURE__ */ new Set());
    __publicField2(this, "currentNodeId");
    this.currentNodeId = currentNodeId;
  }
  /**
   * Create a global dispatcher that handles all message types
   */
  createGlobalDispatcherForType(broadcastType) {
    return (payload) => {
      if (payload && payload.__origin === this.currentNodeId) {
        return;
      }
      const handlers = this.broadcastHandlers.get(broadcastType);
      if (handlers) {
        const { __origin: _origin, forwarded: _fwd, ...clean } = payload || {};
        for (const handler of handlers) {
          try {
            handler(clean);
          } catch (error) {
            console.error(`Error in broadcast handler for ${broadcastType}:`, error);
          }
        }
      }
      if (!payload.forwarded) {
        this.forwardBroadcast(broadcastType, payload);
      }
    };
  }
  /**
   * Forward a broadcast message to all other transports
   * This enables indirect synchronization through intermediate nodes
   */
  async forwardBroadcast(broadcastType, payload) {
    try {
      const forwardedPayload = { ...payload, forwarded: true };
      const allTransports = [
        ...Array.from(this.transports.values()),
        ...Array.from(this.mountedTransports)
      ];
      const forwardPromises = allTransports.map((transport) => {
        return transport.notification({
          method: "sdppp/broadcast",
          params: { messageType: broadcastType, message: forwardedPayload }
        }).catch((error) => {
          console.error(`[BroadcastManager] Error forwarding ${broadcastType}:`, error);
        });
      });
      await Promise.all(forwardPromises);
    } catch (error) {
      console.error("[BroadcastManager] Error forwarding broadcast:", error);
    }
  }
  /**
   * Register a broadcast message handler
   */
  registerHandler(broadcastType, handler) {
    if (!this.broadcastHandlers.has(broadcastType)) {
      this.broadcastHandlers.set(broadcastType, /* @__PURE__ */ new Set());
    }
    this.broadcastHandlers.get(broadcastType).add(handler);
  }
  /**
   * Setup broadcast handlers for a new transport
   */
  setupTransportHandlers(transport) {
    this.setupGeneralBroadcastHandler(transport);
  }
  /**
   * Setup a general broadcast handler that handles all broadcast types
   */
  setupGeneralBroadcastHandler(transport) {
    const broadcastSchema = objectType$1({
      method: literalType$1("sdppp/broadcast"),
      params: objectType$1({
        messageType: stringType$1(),
        message: anyType$1()
      })
    });
    transport.setNotificationHandler(broadcastSchema, async (notification) => {
      const broadcastType = notification.params.messageType;
      const dispatcher = this.createGlobalDispatcherForType(broadcastType);
      dispatcher(notification.params.message);
    });
  }
  /**
   * Add a transport to the broadcast manager
   */
  addMiddleware(nodeId, transport) {
    this.transports.set(nodeId, transport);
    this.setupTransportHandlers(transport);
  }
  /**
   * Remove a transport from the broadcast manager
   */
  removeMiddleware(nodeId) {
    this.transports.delete(nodeId);
  }
  /**
   * Broadcast a named message to all connected nodes (excluding self)
   */
  async broadcast(broadcastName, payload) {
    const allTransports = [
      ...Array.from(this.transports.values()),
      ...Array.from(this.mountedTransports)
    ];
    const broadcastPromises = allTransports.map((transport) => {
      return transport.notification({
        method: "sdppp/broadcast",
        params: { messageType: broadcastName, message: payload }
      });
    });
    await Promise.all(broadcastPromises);
  }
  /**
   * Mount broadcast handlers to a transport
   */
  mountTo(transport) {
    this.mountedTransports.add(transport);
    this.setupTransportHandlers(transport);
  }
  /**
   * Get all registered handler types
   */
  getHandlerTypes() {
    return Array.from(this.broadcastHandlers.keys());
  }
  /**
   * Clear all handlers and transports
   */
  clear() {
    this.broadcastHandlers.clear();
    this.transports.clear();
    this.mountedTransports.clear();
  }
}
class ActionManager {
  constructor(definition, currentNodeId, getTransport) {
    __publicField2(this, "actionHandlers", /* @__PURE__ */ new Map());
    __publicField2(this, "definition");
    __publicField2(this, "currentNodeId");
    __publicField2(this, "getTransport");
    this.definition = definition;
    this.currentNodeId = currentNodeId;
    this.getTransport = getTransport;
  }
  /**
   * Implement an action handler
   */
  implementAction(actionName, handler) {
    const nodeDef = this.definition.getNode(this.currentNodeId);
    if (!nodeDef) {
      throw new Error(`Node definition not found for ${this.currentNodeId}`);
    }
    const actionDef = nodeDef.actions[actionName];
    if (!actionDef) {
      throw new Error(`Action ${String(actionName)} not found for node ${this.currentNodeId}`);
    }
    this.validateHandlerType(actionName, handler, actionDef);
    this.actionHandlers.set(actionName, handler);
  }
  /**
   * Validate that the handler matches the expected type based on stream property
   */
  validateHandlerType(actionName, handler, actionDef) {
    actionDef.stream === true;
  }
  /**
   * Implement an internal action handler without validation against graph definition
   * This is used for system-level actions like store synchronization
   */
  implementInternalAction(actionName, handler) {
    this.actionHandlers.set(actionName, handler);
  }
  /**
   * Mount action handlers to middleware and streamRequestor
   */
  mountTo(transport) {
    for (const [actionName, handler] of this.actionHandlers) {
      const nodeDef = this.definition.getNode(this.currentNodeId);
      const actionDef = nodeDef == null ? void 0 : nodeDef.actions[actionName];
      const isInternalAction = actionName.startsWith("__internal_");
      const isStreaming = isInternalAction ? false : (actionDef == null ? void 0 : actionDef.stream) === true;
      if (isStreaming) {
        const actionSchema = objectType$1({
          action: literalType$1(actionName)
        });
        transport.registerStreamRequestorHandler(actionSchema, async function* (params, extra, signal) {
          const actualParams = params.data || params;
          const result = handler(actualParams, extra, signal);
          if (result && typeof result === "object" && Symbol.asyncIterator in result) {
            for await (const item of result) {
              yield item === void 0 ? {} : item;
            }
          } else {
            const awaitedResult = await result;
            yield awaitedResult === void 0 ? {} : awaitedResult;
          }
        });
      }
    }
    this.registerProxyForwardHandler(transport);
    this.registerDirectRequestHandlerGeneric(transport);
  }
  /**
   * Register the proxy forward handler for indirect action calls
   */
  registerProxyForwardHandler(transport) {
    const proxyForwardSchema = objectType$1({
      action: literalType$1("__proxy_forward")
    });
    const self2 = this;
    transport.registerStreamRequestorHandler(proxyForwardSchema, async function* (params, extra, signal) {
      const requestData = params.data || params;
      const { targetNodeId, targetAction, targetData, forwardPath } = requestData;
      if (!forwardPath || forwardPath.length === 0) {
        throw new Error("Invalid forward path for proxy action");
      }
      const nextNodeId = forwardPath[0];
      const remainingPath = forwardPath.slice(1);
      if (remainingPath.length === 0 && nextNodeId === self2.currentNodeId) {
        const handler = self2.actionHandlers.get(targetAction);
        if (!handler) {
          throw new Error(`Action ${targetAction} not found on node ${self2.currentNodeId}`);
        }
        const result = handler(targetData, extra, signal);
        if (result && typeof result === "object" && Symbol.asyncIterator in result) {
          for await (const item of result) {
            yield item === void 0 ? {} : item;
          }
        } else {
          const awaitedResult = await result;
          yield awaitedResult === void 0 ? {} : awaitedResult;
        }
        return;
      }
      if (nextNodeId === self2.currentNodeId && remainingPath.length > 0) {
        const nextHopNodeId = remainingPath[0];
        const nextHopTransport = self2.getTransport(nextHopNodeId);
        if (nextHopTransport) {
          const forwardedAction = await nextHopTransport.streamRequest({
            action: "__proxy_forward",
            data: {
              targetNodeId,
              targetAction,
              targetData,
              forwardPath: remainingPath
            }
          }, objectType$1({}), signal);
          for await (const item of forwardedAction) {
            yield item === void 0 ? {} : item;
          }
          return;
        }
        throw new Error(`Cannot forward to node ${nextHopNodeId} - no connection available`);
      }
      throw new Error(`Invalid proxy forwarding: current node ${self2.currentNodeId} not in path ${forwardPath}`);
    });
  }
  /**
   * Get all registered action names
   */
  getRegisteredActions() {
    return Array.from(this.actionHandlers.keys());
  }
  /**
   * Check if an action is registered
   */
  hasAction(actionName) {
    return this.actionHandlers.has(actionName);
  }
  /**
   * Get action handler by name (for internal use by GraphInstance)
   */
  getHandler(actionName) {
    return this.actionHandlers.get(actionName);
  }
  /**
   * Clear all action handlers
   */
  clear() {
    this.actionHandlers.clear();
  }
  /**
   * Register direct request handler for a specific action (non-streaming)
   */
  registerDirectRequestHandler(endpoint, actionName, handler) {
  }
  /**
   * Register generic direct request handler for all non-streaming actions
   */
  registerDirectRequestHandlerGeneric(transport) {
    const directRequestSchema = objectType$1({
      method: literalType$1("sdppp/directRequest"),
      params: objectType$1({
        action: stringType$1(),
        data: anyType$1().optional()
      })
    });
    const self2 = this;
    transport.setRequestHandler(directRequestSchema, async (request, extra) => {
      const { action, data: data2 } = request.params;
      if (action === "__proxy_forward") {
        return await self2.handleDirectProxyForward(data2, extra);
      }
      const actionHandler = self2.actionHandlers.get(action);
      if (!actionHandler) {
        throw new Error(`Action ${action} not found on node ${self2.currentNodeId}`);
      }
      const result = actionHandler(data2, extra);
      const awaitedResult = await result;
      return awaitedResult === void 0 ? {} : awaitedResult;
    });
  }
  /**
   * Handle direct proxy forward for non-streaming actions
   */
  async handleDirectProxyForward(requestData, extra) {
    const { targetNodeId, targetAction, targetData, forwardPath } = requestData;
    if (!forwardPath || forwardPath.length === 0) {
      throw new Error("Invalid forward path for proxy action");
    }
    const nextNodeId = forwardPath[0];
    const remainingPath = forwardPath.slice(1);
    if (remainingPath.length === 0 && nextNodeId === this.currentNodeId) {
      const handler = this.actionHandlers.get(targetAction);
      if (!handler) {
        throw new Error(`Action ${targetAction} not found on node ${this.currentNodeId}`);
      }
      const result = handler(targetData, extra);
      const awaitedResult = await result;
      return awaitedResult === void 0 ? {} : awaitedResult;
    }
    if (nextNodeId === this.currentNodeId && remainingPath.length > 0) {
      const nextHopNodeId = remainingPath[0];
      const nextHopTransport = this.getTransport(nextHopNodeId);
      if (nextHopTransport) {
        return await nextHopTransport.request({
          method: "sdppp/directRequest",
          params: {
            action: "__proxy_forward",
            data: {
              targetNodeId,
              targetAction,
              targetData,
              forwardPath: remainingPath
            }
          }
        }, anyType$1());
      }
      throw new Error(`Cannot forward to node ${nextHopNodeId} - no connection available`);
    }
    throw new Error(`Invalid proxy forwarding: current node ${this.currentNodeId} not in path ${forwardPath}`);
  }
}
class ConnectionManager {
  constructor(definition, currentNodeId) {
    __publicField2(this, "definition");
    __publicField2(this, "currentNodeId");
    __publicField2(this, "connectedNodes", /* @__PURE__ */ new Set());
    this.definition = definition;
    this.currentNodeId = currentNodeId;
  }
  /**
   * Mark a node as connected
   */
  markConnected(nodeId) {
    this.connectedNodes.add(nodeId);
  }
  /**
   * Mark a node as disconnected
   */
  markDisconnected(nodeId) {
    this.connectedNodes.delete(nodeId);
  }
  /**
   * Check if a node is connected
   */
  isConnected(nodeId) {
    return this.connectedNodes.has(nodeId);
  }
  /**
   * Find path between two nodes using BFS
   */
  findPath(fromNodeId, toNodeId) {
    if (fromNodeId === toNodeId) {
      return [fromNodeId];
    }
    const visited = /* @__PURE__ */ new Set();
    const queue = [{ nodeId: fromNodeId, path: [fromNodeId] }];
    while (queue.length > 0) {
      const { nodeId, path } = queue.shift();
      if (visited.has(nodeId)) {
        continue;
      }
      visited.add(nodeId);
      const neighbors = this.definition.getNeighbors(nodeId);
      for (const neighbor of neighbors) {
        if (neighbor === toNodeId) {
          return [...path, neighbor];
        }
        if (!visited.has(neighbor)) {
          queue.push({ nodeId: neighbor, path: [...path, neighbor] });
        }
      }
    }
    return void 0;
  }
  /**
   * Get all connected node IDs
   */
  getConnectedNodeIds() {
    return Array.from(this.connectedNodes);
  }
  /**
   * Get the number of connections
   */
  getConnectionCount() {
    return this.connectedNodes.size;
  }
  /**
   * Get all nodes reachable from the current node
   * Uses BFS to find all nodes that can be reached through direct or indirect connections
   */
  getAllReachableNodes() {
    const reachable = /* @__PURE__ */ new Set();
    const visited = /* @__PURE__ */ new Set();
    const queue = [this.currentNodeId];
    visited.add(this.currentNodeId);
    while (queue.length > 0) {
      const currentNode = queue.shift();
      const neighbors = this.definition.getNeighbors(currentNode);
      for (const neighbor of neighbors) {
        if (!visited.has(neighbor)) {
          visited.add(neighbor);
          if (this.connectedNodes.has(neighbor) || this.canReachThroughConnectedNodes(neighbor, visited)) {
            reachable.add(neighbor);
            queue.push(neighbor);
          }
        }
      }
    }
    return Array.from(reachable);
  }
  /**
   * Check if a node can be reached through connected nodes
   */
  canReachThroughConnectedNodes(targetNode, visited) {
    const path = this.findPath(this.currentNodeId, targetNode);
    if (!path || path.length <= 1) {
      return false;
    }
    for (let i2 = 1; i2 < path.length - 1; i2++) {
      if (!this.connectedNodes.has(path[i2])) {
        return false;
      }
    }
    return true;
  }
  /**
   * Clear all connections
   */
  clear() {
    this.connectedNodes.clear();
  }
}
class GraphInstanceImpl {
  constructor(definition, nodeId) {
    __publicField2(this, "definition");
    __publicField2(this, "currentNodeId");
    __publicField2(this, "nodeStores", /* @__PURE__ */ new Map());
    __publicField2(this, "nodeProxies", /* @__PURE__ */ new Map());
    __publicField2(this, "broadcastManager");
    __publicField2(this, "actionManager");
    __publicField2(this, "connectionManager");
    // 统一使用MCPSDPPPSessionAdaptor，同时具备middleware和streaming能力
    __publicField2(this, "nodeTransports", /* @__PURE__ */ new Map());
    this.definition = definition;
    this.currentNodeId = nodeId;
    this.initializeNodeStores();
    this.broadcastManager = new BroadcastManager(nodeId);
    this.actionManager = new ActionManager(
      definition,
      nodeId,
      (nodeId2) => this.getTransportInternal(nodeId2)
    );
    this.connectionManager = new ConnectionManager(
      definition,
      nodeId
    );
    this.setupGraphStoreSync();
  }
  /**
   * Initialize Zustand stores for all nodes based on their schemas
   */
  initializeNodeStores() {
    for (const nodeId of this.definition.getNodeIds()) {
      const nodeDef = this.definition.getNode(nodeId);
      if (nodeDef && nodeDef.store) {
        const defaultValues = this.getDefaultValuesFromSchema(nodeDef.store);
        const store = createStore(() => defaultValues);
        this.nodeStores.set(nodeId, store);
      }
    }
  }
  /**
   * Extract default values from Zod schema
   */
  getDefaultValuesFromSchema(schema) {
    if (!schema) {
      return {};
    }
    try {
      return schema.parse({});
    } catch (error) {
      return this.manuallyExtractDefaults(schema);
    }
  }
  /**
   * Manually extract defaults as fallback
   */
  manuallyExtractDefaults(schema) {
    if (!schema || !schema.def) {
      return {};
    }
    if (schema.def.type === "default") {
      const defaultValue = schema.def.defaultValue;
      return typeof defaultValue === "function" ? defaultValue() : defaultValue;
    }
    if (schema.def.type === "object") {
      const result = {};
      let shape;
      try {
        shape = schema.def.shape;
      } catch (error) {
        return {};
      }
      if (shape) {
        for (const [key2, fieldSchema] of Object.entries(shape)) {
          const defaultValue = this.getDefaultValueFromField(fieldSchema);
          if (defaultValue !== void 0) {
            result[key2] = defaultValue;
          }
        }
      }
      return result;
    }
    return {};
  }
  /**
   * Get default value from individual field schema
   */
  getDefaultValueFromField(schema) {
    if (!schema) {
      return void 0;
    }
    try {
      return schema.parse(void 0);
    } catch {
      return this.manuallyExtractDefaults(schema);
    }
  }
  /**
   * Connect to a node using MCPMiddleware
   */
  async connect(nodeId, transport) {
    if (!this.definition.hasEdge(this.currentNodeId, nodeId)) {
      throw new Error(`No edge defined from ${this.currentNodeId} to ${nodeId}`);
    }
    if (this.nodeTransports.has(nodeId)) {
      throw new Error(`Already connected to node ${nodeId}`);
    }
    try {
      this.nodeTransports.set(nodeId, transport);
      this.connectionManager.markConnected(nodeId);
      this.setupNodeBindings(nodeId, transport);
      await this.syncStoresToNewConnection(nodeId);
      await this.requestInitialStateForNode(nodeId);
    } catch (error) {
      this.cleanupConnection(nodeId);
      throw error;
    }
  }
  /**
   * Disconnect from a node
   */
  disconnect(nodeId) {
    this.cleanupConnection(nodeId);
  }
  /**
   * Sync stores to a newly connected node
   */
  async syncStoresToNewConnection(nodeId) {
    await new Promise((resolve2) => setTimeout(resolve2, 100));
    for (const [storeNodeId, store] of this.nodeStores) {
      if (storeNodeId === this.currentNodeId) {
        try {
          await this.broadcastManager.broadcast(`store:update:${storeNodeId}`, {
            storeName: storeNodeId,
            sourceNodeId: this.currentNodeId,
            stateUpdate: store.getState(),
            isInitialState: true
          });
        } catch (error) {
        }
      }
    }
    try {
      await this.broadcastManager.broadcast(`__connection_established`, {
        fromNode: this.currentNodeId,
        toNode: nodeId
      });
    } catch (error) {
    }
  }
  /**
   * Request initial state for all nodes reachable after establishing a new connection
   */
  async requestInitialStateForNode(nodeId) {
    try {
      const reachableNodes = this.connectionManager.getAllReachableNodes();
      for (const reachableNodeId of reachableNodes) {
        try {
          const actionName = `__internal_requestInitialState_${reachableNodeId}`;
          const nodeProxy = this.getNode(reachableNodeId);
          if (nodeProxy && nodeProxy.actions && nodeProxy.actions[actionName]) {
            const call = nodeProxy.actions[actionName]({});
            await Promise.race([
              call,
              new Promise((resolve2) => setTimeout(resolve2, 300))
            ]);
          }
        } catch (error) {
          console.log(`Failed to request initial state for ${reachableNodeId}:`, error);
        }
      }
    } catch (error) {
      console.log(`Failed to request initial states after connecting to ${nodeId}:`, error);
    }
  }
  /**
   * Cleanup connection resources
   */
  cleanupConnection(nodeId) {
    const transport = this.nodeTransports.get(nodeId);
    this.nodeTransports.delete(nodeId);
    this.connectionManager.markDisconnected(nodeId);
    this.broadcastManager.removeMiddleware(nodeId);
    if (transport) {
      transport.cleanup();
    }
  }
  /**
   * Setup current node connection bindings (merged from mountTo functionality)
   */
  setupNodeBindings(nodeId, transport) {
    const currentStore = this.nodeStores.get(this.currentNodeId);
    if (!currentStore) {
      throw new Error(`Store not found for ${this.currentNodeId}`);
    }
    this.actionManager.mountTo(transport);
    this.broadcastManager.addMiddleware(nodeId, transport);
  }
  /**
   * Setup graph-based store synchronization for all stores
   * This enables indirect synchronization through broadcast mechanism
   */
  setupGraphStoreSync() {
    for (const [nodeId, store] of this.nodeStores) {
      if (nodeId === this.currentNodeId) {
        bindStoreProducerSideGraph({
          graphInstance: this,
          store,
          name: nodeId
        });
      } else {
        bindStoreConsumerSideGraph({
          graphInstance: this,
          store,
          name: nodeId
        });
      }
    }
  }
  /**
   * Get the node proxy
   */
  getNode(nodeId) {
    if (!this.nodeProxies.has(nodeId)) {
      const proxy = new NodeProxyImpl(this, nodeId);
      this.nodeProxies.set(nodeId, proxy);
    }
    return this.nodeProxies.get(nodeId);
  }
  /**
   * Get the middleware for a specific node (internal use only)
   */
  getTransportInternal(nodeId) {
    return this.nodeTransports.get(nodeId);
  }
  /**
   * Get middleware and streamRequestor for a node (direct or indirect)
   */
  getTransportToNode(nodeId) {
    const directTransport = this.nodeTransports.get(nodeId);
    if (directTransport) {
      return {
        transport: directTransport,
        path: [this.currentNodeId, nodeId]
      };
    }
    const path = this.findPathInternal(this.currentNodeId, nodeId);
    if (path && path.length > 1) {
      const firstHop = path[1];
      const transport = this.nodeTransports.get(firstHop);
      if (transport) {
        return { transport, path };
      }
    }
    return void 0;
  }
  /**
   * Get node store
   */
  getNodeStore(nodeId) {
    return this.nodeStores.get(nodeId);
  }
  /**
   * Get the store for the current node
   */
  get store() {
    const currentStore = this.nodeStores.get(this.currentNodeId);
    if (!currentStore) {
      throw new Error(`Store not found for current node ${this.currentNodeId}`);
    }
    return currentStore;
  }
  /**
   * Get typed actions for the current node
   */
  get actions() {
    const currentNodeDef = this.definition.getNode(this.currentNodeId);
    if (!currentNodeDef) {
      throw new Error(`Node definition not found for current node ${this.currentNodeId}`);
    }
    const actionProxy = new Proxy({}, {
      get: (_target, actionName) => {
        if (typeof actionName !== "string") {
          return void 0;
        }
        const actionDef = currentNodeDef.actions[actionName];
        if (!actionDef) {
          throw new Error(`Action ${actionName} not found for current node ${this.currentNodeId}`);
        }
        return (data2, signal) => {
          const handler = this.actionManager.getHandler(actionName);
          if (!handler) {
            throw new Error(`Action handler ${actionName} not implemented for node ${this.currentNodeId}`);
          }
          const extra = {
            nodeId: this.currentNodeId
            // Can add other context information
          };
          if (actionDef.stream === true) {
            const result = handler(data2, extra, signal);
            if (result && typeof result === "object" && Symbol.asyncIterator in result) {
              return async function* () {
                for await (const item of result) {
                  yield item === void 0 ? {} : item;
                }
              }();
            } else {
              return async function* () {
                const awaitedResult = await result;
                yield awaitedResult === void 0 ? {} : awaitedResult;
              }();
            }
          } else {
            return (async () => {
              const result = handler(data2, extra, signal);
              if (result && typeof result === "object" && Symbol.asyncIterator in result) {
                const iterator = result[Symbol.asyncIterator]();
                const firstResult = await iterator.next();
                return firstResult.value === void 0 ? {} : firstResult.value;
              } else {
                const awaitedResult = await result;
                return awaitedResult === void 0 ? {} : awaitedResult;
              }
            })();
          }
        };
      }
    });
    return actionProxy;
  }
  /**
   * Get the graph definition
   */
  getDefinition() {
    return this.definition;
  }
  /**
   * Get the current node ID
   */
  getCurrentNodeId() {
    return this.currentNodeId;
  }
  /**
   * Get connection to a node (direct or indirect) - internal use
   */
  getConnectionToNodeInternal(nodeId) {
    return this.getTransportToNode(nodeId);
  }
  /**
   * Mount store listeners and action handlers to MCP instance
   */
  /**
   * Implement action for current node with type safety
   */
  implementAction(actionName, handler) {
    this.actionManager.implementAction(actionName, handler);
  }
  /**
   * Cleanup resources
   */
  destroy() {
    const nodeIds = Array.from(this.nodeTransports.keys());
    for (const nodeId of nodeIds) {
      this.cleanupConnection(nodeId);
    }
    this.broadcastManager.clear();
    this.actionManager.clear();
    this.connectionManager.clear();
  }
  /**
   * Find path between two nodes using BFS - internal use
   */
  findPathInternal(fromNodeId, toNodeId) {
    return this.connectionManager.findPath(fromNodeId, toNodeId);
  }
  /**
   * Find path between two nodes using BFS - public interface
   */
  findPath(fromNodeId, toNodeId) {
    return this.findPathInternal(fromNodeId, toNodeId);
  }
  /**
   * Broadcast a named message to all connected nodes (excluding self)
   */
  async broadcast(broadcastName, payload) {
    const outgoing = {
      ...payload,
      __origin: this.currentNodeId
    };
    return this.broadcastManager.broadcast(broadcastName, outgoing);
  }
  /**
   * Register a handler for received broadcast messages
   */
  broadcastReceived(broadcastName, handler) {
    this.broadcastManager.registerHandler(broadcastName, handler);
  }
}
function defineGraph(definition) {
  const graphDef = new GraphDefinitionClass(definition);
  return {
    /**
     * Join as a specific node in the graph
     * @param nodeId The node ID to join as
     * @param monitorOptions Optional connection monitoring options
     * @returns GraphInstance for this node
     */
    joinAs(nodeId) {
      if (!graphDef.getNode(nodeId)) {
        throw new Error(`Node ${String(nodeId)} not found in graph definition`);
      }
      return new GraphInstanceImpl(graphDef, nodeId);
    },
    /**
     * Get the graph definition
     */
    getDefinition() {
      return definition;
    },
    /**
     * Get all node IDs
     */
    getNodeIds() {
      return graphDef.getNodeIds();
    },
    /**
     * Get neighbors of a node
     */
    getNeighbors(nodeId) {
      return graphDef.getNeighbors(nodeId);
    },
    /**
     * Check if an edge exists
     */
    hasEdge(from2, to2) {
      return graphDef.hasEdge(from2, to2);
    },
    /**
     * Check if there's a path between two nodes (direct or indirect)
     */
    hasPath(from2, to2) {
      return graphDef.hasPath(from2, to2);
    },
    /**
     * Find path between two nodes using BFS
     */
    findPath(from2, to2) {
      return graphDef.findPath(from2, to2);
    }
  };
}
const MiddlewareErrors = {
  INTERCEPTOR_ERROR: "interceptor_error"
};
class MiddlewareError extends Error {
  constructor(type2, method, message, originalError) {
    super(message);
    __publicField2(this, "type");
    __publicField2(this, "method");
    __publicField2(this, "originalError");
    this.name = "MiddlewareError";
    this.type = type2;
    this.method = method;
    this.originalError = originalError;
  }
}
class MCPMiddleware {
  constructor(protocol, options2 = {}) {
    __publicField2(this, "protocol");
    __publicField2(this, "realTransport", null);
    __publicField2(this, "options");
    // 传入消息处理器
    __publicField2(this, "requestHandlers", /* @__PURE__ */ new Map());
    __publicField2(this, "notificationHandlers", /* @__PURE__ */ new Map());
    // 传出消息拦截器
    __publicField2(this, "outgoingRequestInterceptors", /* @__PURE__ */ new Map());
    __publicField2(this, "outgoingNotificationInterceptors", /* @__PURE__ */ new Map());
    // Transport接口需要的事件处理器
    __publicField2(this, "messageHandlers", []);
    __publicField2(this, "closeHandlers", []);
    __publicField2(this, "errorHandlers", []);
    // 统计信息
    __publicField2(this, "stats", {
      requestsHandled: 0,
      notificationsHandled: 0,
      requestsIntercepted: 0,
      notificationsIntercepted: 0,
      errors: 0
    });
    this.protocol = protocol;
    this.options = {
      debug: false,
      interceptorTimeout: 5e3,
      continueOnInterceptorError: true,
      ...options2
    };
  }
  /**
   * 连接到真实transport，并将自己作为transport传给protocol
   */
  async connect(transport) {
    this.realTransport = transport;
    transport.onmessage = (message) => {
      this.handleIncomingMessage(message);
    };
    transport.onclose = () => {
      this.closeHandlers.forEach((handler) => handler());
    };
    transport.onerror = (error) => {
      this.errorHandlers.forEach((handler) => handler(error));
    };
    await this.protocol.connect(this);
  }
  /**
   * 处理从真实transport来的消息
   */
  async handleIncomingMessage(message) {
    this.log("debug", "Incoming message:", message);
    try {
      if (this.isRequest(message)) {
        const handled = await this.handleIncomingRequest(message);
        if (handled) {
          return;
        }
      }
      if (this.isNotification(message)) {
        const handled = await this.handleIncomingNotification(message);
        if (handled) {
          return;
        }
      }
      this.messageHandlers.forEach((handler) => handler(message));
    } catch (error) {
      this.stats.errors++;
      this.log("error", "Error handling incoming message:", error);
      this.messageHandlers.forEach((handler) => handler(message));
    }
  }
  /**
   * 处理传入的请求
   */
  async handleIncomingRequest(request) {
    const handler = this.requestHandlers.get(request.method);
    if (!handler) {
      return false;
    }
    try {
      this.stats.requestsHandled++;
      const response = await handler(request, {});
      if (this.realTransport && "id" in request) {
        await this.realTransport.send({
          jsonrpc: "2.0",
          id: request.id,
          result: response
        });
      }
      return true;
    } catch (error) {
      this.stats.errors++;
      if (this.realTransport && "id" in request) {
        await this.realTransport.send({
          jsonrpc: "2.0",
          id: request.id,
          error: {
            code: -32603,
            message: `Request handler failed: ${JSON.stringify(request.params)} ${error.message}`
          }
        });
      }
      return true;
    }
  }
  /**
   * 处理传入的通知
   */
  async handleIncomingNotification(notification) {
    const handler = this.notificationHandlers.get(notification.method);
    if (!handler) {
      return false;
    }
    try {
      this.stats.notificationsHandled++;
      await handler(notification);
      return true;
    } catch (error) {
      this.stats.errors++;
      this.log("error", `Notification handler failed for ${notification.method}:`, error);
      return true;
    }
  }
  /**
   * Transport接口实现：发送消息
   */
  async send(message) {
    this.log("debug", "Outgoing message:", message);
    try {
      if (this.isRequest(message)) {
        const interceptResult = await this.executeOutgoingRequestInterceptor(message);
        if (!interceptResult.success) {
          if (this.options.continueOnInterceptorError) {
            this.log("warn", `Request interceptor failed for ${message.method}:`, interceptResult.error);
          } else {
            throw interceptResult.error;
          }
        } else if (interceptResult.result === null) {
          return;
        } else if (interceptResult.result) {
          message = { ...interceptResult.result, jsonrpc: "2.0" };
          this.stats.requestsIntercepted++;
        }
      }
      if (this.isNotification(message)) {
        const interceptResult = await this.executeOutgoingNotificationInterceptor(message);
        if (!interceptResult.success) {
          if (this.options.continueOnInterceptorError) {
            this.log("warn", `Notification interceptor failed for ${message.method}:`, interceptResult.error);
          } else {
            throw interceptResult.error;
          }
        } else if (interceptResult.result === null) {
          return;
        } else if (interceptResult.result) {
          message = { ...interceptResult.result, jsonrpc: "2.0" };
          this.stats.notificationsIntercepted++;
        }
      }
      if (this.realTransport) {
        await this.realTransport.send(message);
      }
    } catch (error) {
      this.stats.errors++;
      throw error;
    }
  }
  /**
   * Transport接口实现：开始传输
   */
  async start() {
    if (this.realTransport) {
      await this.realTransport.start();
    }
  }
  /**
   * Transport接口实现：关闭连接
   */
  async close() {
    if (this.realTransport) {
      await this.realTransport.close();
    }
  }
  /**
   * Transport接口实现：消息监听器
   */
  set onmessage(handler) {
    this.messageHandlers = [handler];
  }
  /**
   * Transport接口实现：关闭监听器
   */
  set onclose(handler) {
    this.closeHandlers = [handler];
  }
  /**
   * Transport接口实现：错误监听器
   */
  set onerror(handler) {
    this.errorHandlers = [handler];
  }
  /**
   * 执行传出请求拦截器
   */
  async executeOutgoingRequestInterceptor(request) {
    const interceptor = this.outgoingRequestInterceptors.get(request.method);
    if (!interceptor) {
      return { success: true, result: request };
    }
    try {
      const result = await this.withTimeout(
        interceptor(request),
        this.options.interceptorTimeout
      );
      return { success: true, result };
    } catch (error) {
      this.stats.errors++;
      return {
        success: false,
        error: new MiddlewareError(
          MiddlewareErrors.INTERCEPTOR_ERROR,
          request.method,
          `Outgoing request interceptor failed: ${error.message}`,
          error
        )
      };
    }
  }
  /**
   * 执行传出通知拦截器
   */
  async executeOutgoingNotificationInterceptor(notification) {
    const interceptor = this.outgoingNotificationInterceptors.get(notification.method);
    if (!interceptor) {
      return { success: true, result: notification };
    }
    try {
      const result = await this.withTimeout(
        interceptor(notification),
        this.options.interceptorTimeout
      );
      return { success: true, result };
    } catch (error) {
      this.stats.errors++;
      return {
        success: false,
        error: new MiddlewareError(
          MiddlewareErrors.INTERCEPTOR_ERROR,
          notification.method,
          `Outgoing notification interceptor failed: ${error.message}`,
          error
        )
      };
    }
  }
  /**
   * 发送请求 (通过Protocol)
   */
  async request(request, responseSchema) {
    return await this.protocol.request(request, responseSchema, {
      timeout: 36e5
    });
  }
  /**
   * 发送通知 (通过Protocol)
   */
  async notification(notification) {
    return await this.protocol.notification(notification);
  }
  /**
   * 注册请求处理器
   */
  setRequestHandler(requestSchema, handler) {
    const method = requestSchema.shape.method.value;
    this.requestHandlers.set(method, handler);
  }
  /**
   * 注册通知处理器
   */
  setNotificationHandler(notificationSchema, handler) {
    const method = notificationSchema.shape.method.value;
    this.notificationHandlers.set(method, handler);
  }
  /**
   * 注册传出请求拦截器
   */
  setOutgoingRequestInterceptor(requestSchema, interceptor) {
    const method = requestSchema.shape.method.value;
    this.outgoingRequestInterceptors.set(method, interceptor);
  }
  /**
   * 注册传出通知拦截器
   */
  setOutgoingNotificationInterceptor(notificationSchema, interceptor) {
    const method = notificationSchema.shape.method.value;
    this.outgoingNotificationInterceptors.set(method, interceptor);
  }
  /**
   * 移除请求处理器
   */
  unsetRequestHandler(method) {
    this.requestHandlers.delete(method);
  }
  /**
   * 移除通知处理器
   */
  unsetNotificationHandler(method) {
    this.notificationHandlers.delete(method);
  }
  /**
   * 移除传出请求拦截器
   */
  unsetOutgoingRequestInterceptor(method) {
    this.outgoingRequestInterceptors.delete(method);
  }
  /**
   * 移除传出通知拦截器
   */
  unsetOutgoingNotificationInterceptor(method) {
    this.outgoingNotificationInterceptors.delete(method);
  }
  /**
   * 检查是否有请求处理器
   */
  hasRequestHandler(method) {
    return this.requestHandlers.has(method);
  }
  /**
   * 检查是否有通知处理器
   */
  hasNotificationHandler(method) {
    return this.notificationHandlers.has(method);
  }
  /**
   * 检查是否有传出请求拦截器
   */
  hasOutgoingRequestInterceptor(method) {
    return this.outgoingRequestInterceptors.has(method);
  }
  /**
   * 检查是否有传出通知拦截器
   */
  hasOutgoingNotificationInterceptor(method) {
    return this.outgoingNotificationInterceptors.has(method);
  }
  /**
   * 获取统计信息
   */
  getStats() {
    return { ...this.stats };
  }
  /**
   * 重置统计信息
   */
  resetStats() {
    this.stats = {
      requestsHandled: 0,
      notificationsHandled: 0,
      requestsIntercepted: 0,
      notificationsIntercepted: 0,
      errors: 0
    };
  }
  /**
   * 获取底层Protocol实例
   */
  getProtocol() {
    return this.protocol;
  }
  /**
   * 清理所有处理器和拦截器
   */
  cleanup() {
    this.requestHandlers.clear();
    this.notificationHandlers.clear();
    this.outgoingRequestInterceptors.clear();
    this.outgoingNotificationInterceptors.clear();
  }
  /**
   * 检查消息是否为请求
   */
  isRequest(message) {
    return message.jsonrpc === "2.0" && "method" in message && "id" in message;
  }
  /**
   * 检查消息是否为通知
   */
  isNotification(message) {
    return message.jsonrpc === "2.0" && "method" in message && !("id" in message);
  }
  /**
   * 带超时的Promise执行
   */
  async withTimeout(promise, timeoutMs) {
    const timeoutPromise = new Promise((_2, reject2) => {
      setTimeout(() => reject2(new Error("Timeout")), timeoutMs);
    });
    return await Promise.race([promise, timeoutPromise]);
  }
  /**
   * 日志记录
   */
  log(level, message, ...args) {
    if (!this.options.debug && level === "debug") {
      return;
    }
    const prefix = `[MCPMiddleware]`;
    switch (level) {
      case "debug":
        console.debug(prefix, message, ...args);
        break;
      case "info":
        console.info(prefix, message, ...args);
        break;
      case "warn":
        console.warn(prefix, message, ...args);
        break;
      case "error":
        console.error(prefix, message, ...args);
        break;
    }
  }
}
objectType$1({
  method: literalType$1("sdppp/streamResponse"),
  params: objectType$1({
    requestId: stringType$1(),
    data: anyType$1(),
    error: stringType$1().nullable(),
    finished: booleanType$1()
  })
});
objectType$1({
  method: literalType$1("sdppp/streamRequest"),
  params: objectType$1({
    action: stringType$1(),
    data: anyType$1()
  })
});
objectType$1({
  method: literalType$1("sdppp/abort"),
  params: objectType$1({
    requestId: stringType$1()
  })
});
const streamResponseSchema = objectType$1({
  method: literalType$1("sdppp/streamResponse"),
  params: objectType$1({
    requestId: stringType$1(),
    data: anyType$1(),
    error: stringType$1().nullable(),
    finished: booleanType$1()
  })
});
const streamRequestSchema = objectType$1({
  method: literalType$1("sdppp/streamRequest"),
  params: objectType$1({
    action: stringType$1(),
    data: anyType$1()
  })
});
const abortRequestSchema = objectType$1({
  method: literalType$1("sdppp/abort"),
  params: objectType$1({
    requestId: stringType$1()
  })
});
class NotificationQueue {
  constructor() {
    __publicField2(this, "queues", /* @__PURE__ */ new Map());
    __publicField2(this, "waiters", /* @__PURE__ */ new Map());
  }
  push(notification) {
    const { requestId } = notification.params;
    const queue = this.queues.get(requestId) || [];
    const waiters = this.waiters.get(requestId) || [];
    if (waiters.length > 0) {
      const waiter = waiters.shift();
      waiter(notification.params);
    } else {
      queue.push(notification.params);
      this.queues.set(requestId, queue);
    }
  }
  async pop(requestId) {
    const queue = this.queues.get(requestId) || [];
    if (queue.length > 0) {
      return queue.shift();
    }
    return new Promise((resolve2) => {
      const waiters = this.waiters.get(requestId) || [];
      waiters.push(resolve2);
      this.waiters.set(requestId, waiters);
    });
  }
  cleanup(requestId) {
    this.queues.delete(requestId);
    this.waiters.delete(requestId);
  }
}
class MCPSDPPPSessionAdaptor extends MCPMiddleware {
  constructor(protocol, options2 = {}) {
    super(protocol, options2);
    // streamRequestor handler 注册表
    __publicField2(this, "streamRequestorHandlers", /* @__PURE__ */ new Map());
    // requestId 生成器
    __publicField2(this, "requestIdSeq", 1);
    // 正在执行的请求的 AbortController
    __publicField2(this, "runningRequests", /* @__PURE__ */ new Map());
    // 通知队列
    __publicField2(this, "notificationQueue", new NotificationQueue());
    this.setupStreamProtocolHandlers();
  }
  /**
   * 设置流协议处理器
   */
  setupStreamProtocolHandlers() {
    this.setupStreamResponseHandler();
    this.setupAbortHandler();
    this.setupStreamRequestHandler();
  }
  /**
   * 设置流响应通知处理器
   */
  setupStreamResponseHandler() {
    this.setNotificationHandler(
      streamResponseSchema,
      async (notification) => {
        this.notificationQueue.push(notification);
      }
    );
  }
  /**
   * 设置中止请求处理器
   */
  setupAbortHandler() {
    this.setRequestHandler(abortRequestSchema, async (request, extra) => {
      const { requestId } = request.params;
      const abortController = this.runningRequests.get(requestId);
      if (abortController) {
        abortController.abort();
        this.runningRequests.delete(requestId);
      }
      return { success: true };
    });
  }
  /**
   * 设置流请求处理器
   */
  setupStreamRequestHandler() {
    this.setRequestHandler(streamRequestSchema, async (request, extra) => {
      const requestId = `req_${this.requestIdSeq++}`;
      const handler = this.streamRequestorHandlers.get(request.params.action);
      if (!handler) {
        throw new Error("No handler for streamRequestor: " + request.params.action);
      }
      const abortController = new AbortController();
      this.runningRequests.set(requestId, abortController);
      this.executeHandlerAsync(requestId, handler, request.params, extra, abortController);
      return { requestId };
    });
  }
  /**
   * 异步执行streamRequestor处理器
   */
  async executeHandlerAsync(requestId, handler, params, extra, abortController) {
    try {
      const iterable = handler(params, extra, abortController.signal);
      for await (const data2 of iterable) {
        if (abortController.signal.aborted) {
          break;
        }
        await this.notification({
          method: "sdppp/streamResponse",
          params: {
            requestId,
            data: data2,
            error: null,
            finished: false
          }
        });
      }
      if (!abortController.signal.aborted) {
        await this.notification({
          method: "sdppp/streamResponse",
          params: {
            requestId,
            data: null,
            error: null,
            finished: true
          }
        });
      }
    } catch (error) {
      if (!abortController.signal.aborted) {
        await this.notification({
          method: "sdppp/streamResponse",
          params: {
            requestId,
            data: null,
            error: error.message,
            finished: true
          }
        });
      }
    } finally {
      this.runningRequests.delete(requestId);
    }
  }
  /**
   * 注册 streamRequestor handler
   */
  registerStreamRequestorHandler(paramsSchema, handler) {
    this.streamRequestorHandlers.set(paramsSchema.shape.action.value, handler);
  }
  /**
   * 发起 streamRequestor 请求，返回异步迭代器
   */
  async streamRequest(params, responseSchema, signal) {
    this.validateStreamRequestorRequest(signal);
    const requestId = await this.sendStreamRequestorRequest(params);
    const responseQueue = this.initializeResponseQueue(requestId);
    const streamState = this.createStreamState();
    return this.createAsyncIterator(responseQueue, streamState, requestId, signal);
  }
  /**
   * 验证streamRequestor请求
   */
  validateStreamRequestorRequest(signal) {
    if (signal && signal.aborted) {
      throw new Error("AbortSignal is already aborted");
    }
  }
  /**
   * 发送streamRequestor请求
   */
  async sendStreamRequestorRequest(params) {
    const response = await this.request({
      method: "sdppp/streamRequest",
      params: {
        action: params.action,
        data: params.data
      }
    }, objectType$1({ requestId: stringType$1() }));
    return response.requestId;
  }
  /**
   * 初始化响应队列
   */
  initializeResponseQueue(requestId) {
    return this.notificationQueue;
  }
  /**
   * 创建流状态
   */
  createStreamState() {
    return { finished: false, error: null };
  }
  /**
   * 创建异步迭代器
   */
  createAsyncIterator(queue, streamState, requestId, signal) {
    const self2 = this;
    return {
      async *[Symbol.asyncIterator]() {
        try {
          while (!streamState.finished && !streamState.error) {
            if (signal && signal.aborted) {
              await self2.request({
                method: "sdppp/abort",
                params: { requestId }
              }, objectType$1({ success: booleanType$1() }));
              throw new Error("Aborted");
            }
            const response = await queue.pop(requestId);
            if (response.error) {
              streamState.error = response.error;
              throw new Error(response.error);
            }
            if (response.finished) {
              streamState.finished = true;
              break;
            }
            if (response.data !== null) {
              yield response.data;
            }
          }
        } finally {
          queue.cleanup(requestId);
        }
      }
    };
  }
  /**
   * 获取正在运行的请求数量
   */
  getRunningRequestsCount() {
    return this.runningRequests.size;
  }
  /**
   * 中止指定请求
   */
  async abortRequest(requestId) {
    const abortController = this.runningRequests.get(requestId);
    if (abortController) {
      abortController.abort();
      this.runningRequests.delete(requestId);
      return true;
    }
    return false;
  }
  /**
   * 中止所有正在运行的请求
   */
  abortAllRequests() {
    for (const [requestId, abortController] of this.runningRequests) {
      abortController.abort();
    }
    this.runningRequests.clear();
  }
  /**
   * 清理资源 - 重写父类方法以包含流处理清理
   */
  cleanup() {
    super.cleanup();
    this.abortAllRequests();
    this.streamRequestorHandlers.clear();
  }
}
objectType$1({
  id: stringType$1(),
  method: stringType$1(),
  params: anyType$1().optional(),
  traceId: stringType$1().optional()
});
objectType$1({
  id: stringType$1(),
  result: anyType$1().optional(),
  error: objectType$1({ code: numberType$1(), message: stringType$1(), data: anyType$1().optional() }).optional()
});
objectType$1({
  method: stringType$1(),
  params: anyType$1().optional()
});
objectType$1({
  method: literalType$1("sdppp/streamRequest"),
  params: objectType$1({ action: stringType$1(), data: anyType$1() })
});
objectType$1({
  method: literalType$1("sdppp/streamResponse"),
  params: objectType$1({
    requestId: stringType$1(),
    data: anyType$1().optional(),
    error: stringType$1().nullable().optional(),
    finished: booleanType$1().default(false)
  })
});
objectType$1({
  method: literalType$1("sdppp/abort"),
  params: objectType$1({ requestId: stringType$1() })
});
objectType$1({
  method: literalType$1("sdppp/broadcast"),
  params: objectType$1({ messageType: stringType$1(), message: anyType$1() })
});
const BoundaryRectSchema = objectType$1({
  leftDistance: numberType$1(),
  topDistance: numberType$1(),
  rightDistance: numberType$1(),
  bottomDistance: numberType$1(),
  width: numberType$1(),
  height: numberType$1()
});
const WidgetableBaseWidgetSchemaPart = {
  name: stringType$1(),
  uiWeight: numberType$1()
};
const WidgetableImagesWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("images"),
  options: objectType$1({
    required: booleanType$1(),
    maxCount: numberType$1().optional(),
    maskMode: booleanType$1().optional()
  })
});
const WidgetableMasksWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("masks"),
  options: objectType$1({
    required: booleanType$1()
  })
});
const WidgetableStringWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("string"),
  options: objectType$1({
    required: booleanType$1()
  })
});
const WidgetableToggleWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("boolean"),
  options: objectType$1({
    required: booleanType$1()
  })
});
const WidgetableNumberWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("number"),
  options: objectType$1({
    required: booleanType$1(),
    min: numberType$1().optional(),
    max: numberType$1().optional(),
    step: numberType$1().optional(),
    random: booleanType$1().optional(),
    slider: booleanType$1().optional()
  })
});
const WidgetableComboWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("combo"),
  options: objectType$1({
    required: booleanType$1(),
    values: arrayType$1(stringType$1()),
    labels: arrayType$1(stringType$1()).optional()
  })
});
const WidgetableSegmentWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("segment"),
  options: objectType$1({
    required: booleanType$1(),
    values: arrayType$1(stringType$1())
  })
});
const WidgetableVideoWidgetSchema = objectType$1({
  ...WidgetableBaseWidgetSchemaPart,
  outputType: literalType$1("video"),
  options: objectType$1({
    required: booleanType$1()
  })
});
const WidgetableWidgetSchema = discriminatedUnionType$1("outputType", [
  WidgetableImagesWidgetSchema,
  WidgetableMasksWidgetSchema,
  WidgetableStringWidgetSchema,
  WidgetableToggleWidgetSchema,
  WidgetableNumberWidgetSchema,
  WidgetableComboWidgetSchema,
  WidgetableSegmentWidgetSchema,
  WidgetableVideoWidgetSchema
]);
const WidgetableNodeSchema = objectType$1({
  id: stringType$1(),
  title: stringType$1(),
  widgets: arrayType$1(WidgetableWidgetSchema),
  uiWeightSum: numberType$1()
});
const WidgetableStructureSchema = objectType$1({
  widgetableID: stringType$1(),
  widgetablePath: stringType$1(),
  nodes: recordType$1(stringType$1(), WidgetableNodeSchema),
  nodeIndexes: arrayType$1(stringType$1()),
  note: stringType$1().optional(),
  options: recordType$1(stringType$1(), anyType$1())
});
const ComfyStoreSchema = objectType$1({
  widgetableStructure: WidgetableStructureSchema.default({
    widgetableID: "",
    widgetablePath: "",
    nodes: {},
    note: "",
    options: {},
    nodeIndexes: []
  }),
  widgetableValues: recordType$1(stringType$1(), arrayType$1(anyType$1())).default({}),
  widgetableErrors: recordType$1(stringType$1(), stringType$1()).default({}),
  queueSize: numberType$1().default(0),
  lastError: stringType$1().default(""),
  progress: numberType$1().default(0),
  executingNodeTitle: stringType$1().default(""),
  executingNodeID: stringType$1().default(""),
  graphProgress: numberType$1().default(0),
  comfyUserToken: stringType$1().default(""),
  comfyOrgLoggedIn: booleanType$1().default(false),
  comfyOrgAPIKey: stringType$1().default(""),
  comfyWSState: enumType$1(["connected", "reconnecting"]).default("connected"),
  lastRunTime: numberType$1().default(0)
});
const SDKStoreSchema = objectType$1({
  bannerData: anyType$1().optional(),
  refreshable: booleanType$1().default(false),
  backwardable: booleanType$1().default(false),
  loginable: booleanType$1().default(false),
  runnable: booleanType$1().default(false),
  workBoundaries: recordType$1(numberType$1(), BoundaryRectSchema).default({}),
  // Map of active document ID -> max width/height limit for image operations
  workBoundaryMaxSizes: recordType$1(numberType$1(), numberType$1()).default({})
});
const UXPStoreSchema = objectType$1({
  // Photoshop state
  uname: stringType$1().default(""),
  activeDocumentID: numberType$1().default(0),
  layers: arrayType$1(objectType$1({
    id: numberType$1(),
    name: stringType$1(),
    identify: stringType$1()
  })).default([]),
  actions: arrayType$1(stringType$1()).default([]),
  theme: stringType$1().default("kPanelBrightnessMediumGray"),
  sdpppX: recordType$1(stringType$1(), anyType$1()).default({}),
  locale: enumType$1(["zh-CN", "en-US"]).default("en-US"),
  // ComfyUI webview connection state
  comfyWebviewConnectStatus: enumType$1(["connecting", "connected", "disconnected"]).default("disconnected"),
  comfyWebviewLoadError: stringType$1().default(""),
  comfyWebviewLoading: booleanType$1().default(false),
  comfyWebviewVersion: stringType$1().default(""),
  comfyHTTPCode: numberType$1().default(200),
  comfyURL: stringType$1().default(""),
  // SDK webview state
  sdkWebviewFocusing: booleanType$1().default(false),
  sdkWebviewConnectStatus: enumType$1(["connecting", "connected", "disconnected"]).default("disconnected"),
  // SDPPP authentication state
  isLogin: booleanType$1().default(false),
  isGuest: booleanType$1().default(false),
  requestingLogin: booleanType$1().default(false),
  loginMessage: stringType$1().default(""),
  token: stringType$1().default(""),
  userInfo: recordType$1(stringType$1(), anyType$1()).default({}),
  // Task execution tracking
  taskLastRun: numberType$1().default(0),
  // Photoshop canvas state tracking
  canvasStateID: numberType$1().optional(),
  // Photoshop selection state tracking (changes when selection area/doc/layer changes)
  selectionStateID: stringType$1().optional(),
  // Current selection boundary represented as a BoundaryRect, or null if no selection
  selectionBoundary: BoundaryRectSchema.nullable().optional()
  // canvasThumbnail / curlayerThumbnail were unused by the frontend; keep schema slots commented out for now
  // canvasThumbnail: z.string().default(''),
  // curlayerThumbnail: z.string().default(''),
});
const comfyUtilActions = {
  setNodeTitle: {
    requestSchema: objectType$1({
      node_id: stringType$1(),
      title: stringType$1()
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  // System management
  reboot: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({
      success: booleanType$1(),
      error: stringType$1().optional()
    })
  },
  setComfyOrgAPIKey: {
    requestSchema: objectType$1({
      api_key: stringType$1()
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  logout: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  uploadComfyImageFromUXP: {
    requestSchema: objectType$1({
      fileName: stringType$1(),
      overwrite: booleanType$1().optional(),
      mimeType: stringType$1().optional(),
      dataBase64: stringType$1()
    }),
    responseSchema: objectType$1({
      name: stringType$1()
    })
  },
  sdpppHandshake: {
    requestSchema: objectType$1({
      hostVersion: stringType$1().optional()
    }),
    responseSchema: objectType$1({
      comfyVersion: stringType$1(),
      hostVersion: stringType$1().optional()
    })
  }
};
const WorkflowListSchema = objectType$1({
  workflows: arrayType$1(stringType$1()),
  error: stringType$1().optional()
});
const RunResultSchema = objectType$1({
  success: booleanType$1(),
  nodeErrors: recordType$1(stringType$1()).optional(),
  prompt_ids: arrayType$1(stringType$1()).optional(),
  images: arrayType$1(objectType$1({
    url: stringType$1(),
    thumbnail: stringType$1()
  })).optional()
});
const comfyWorkflowActions = {
  // Node manipulation
  setWidgetValue: {
    requestSchema: objectType$1({
      values: arrayType$1(objectType$1({
        nodeID: stringType$1(),
        widgetIndex: numberType$1(),
        value: recordType$1(stringType$1(), anyType$1()).or(stringType$1()).or(numberType$1()).or(booleanType$1()).or(arrayType$1(anyType$1()))
      }))
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  // Workflow management
  openWorkflow: {
    requestSchema: objectType$1({
      workflow_path: stringType$1(),
      reset: booleanType$1().default(false)
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  openWorkflowJSON: {
    requestSchema: objectType$1({
      workflow_content: recordType$1(anyType$1()),
      workflow_path: stringType$1()
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  listWorkflows: {
    requestSchema: objectType$1({
      listMode: stringType$1().optional(),
      sdpppID: stringType$1().optional(),
      sdpppToken: stringType$1().optional()
    }),
    responseSchema: WorkflowListSchema
  },
  saveWorkflow: {
    requestSchema: objectType$1({
      workflow_path: stringType$1(),
      from_sid: stringType$1().optional()
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  // Workflow execution
  run: {
    requestSchema: objectType$1({
      size: numberType$1()
    }),
    responseSchema: RunResultSchema,
    stream: true
  },
  stopAll: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  }
  // interrupt: {
  //     requestSchema: z.object({}),
  //     responseSchema: z.object({
  //         success: z.boolean(),
  //     })
  // },
  // clearQueue: {
  //     requestSchema: z.object({}),
  //     responseSchema: z.object({
  //         success: z.boolean(),
  //     })
  // }
};
const sdkActions = {
  backward: {
    requestSchema: voidType$1(),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  refresh: {
    requestSchema: voidType$1(),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  run: {
    requestSchema: voidType$1(),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  }
};
const UXPAuthRegisterRequestSchema = objectType$1({
  passwordPayload: objectType$1({
    username: stringType$1(),
    password: stringType$1()
  }).or(objectType$1({
    email: stringType$1(),
    password: stringType$1()
  })).or(objectType$1({
    phone: stringType$1(),
    password: stringType$1()
  })).or(objectType$1({
    identifier: stringType$1(),
    password: stringType$1()
  }))
}).or(objectType$1({
  passcodePayload: objectType$1({
    phone: stringType$1(),
    code: stringType$1()
  }).or(objectType$1({
    email: stringType$1(),
    code: stringType$1()
  }))
}));
const UXPAuthLoginRequestSchema = objectType$1({
  passwordPayload: objectType$1({
    username: stringType$1(),
    password: stringType$1()
  }).or(objectType$1({
    email: stringType$1(),
    password: stringType$1()
  })).or(objectType$1({
    phone: stringType$1(),
    password: stringType$1()
  })).or(objectType$1({
    identifier: stringType$1(),
    password: stringType$1()
  }))
}).or(objectType$1({
  passcodePayload: objectType$1({
    phone: stringType$1(),
    code: stringType$1()
  }).or(objectType$1({
    email: stringType$1(),
    code: stringType$1()
  }))
}));
const uxpAuthActions = {
  // SDPPP authentication actions
  register: {
    requestSchema: UXPAuthRegisterRequestSchema,
    responseSchema: objectType$1({})
  },
  login: {
    requestSchema: UXPAuthLoginRequestSchema,
    responseSchema: objectType$1({})
  },
  sendPassCode: {
    requestSchema: objectType$1({
      phone: stringType$1().optional(),
      email: stringType$1().optional()
    }),
    responseSchema: objectType$1({})
  },
  logout: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({})
  },
  guestLogin: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({})
  }
};
objectType$1({
  resource: stringType$1().optional(),
  thumbnail: stringType$1().optional(),
  width: numberType$1().optional(),
  height: numberType$1().optional(),
  mimeType: stringType$1().optional(),
  source: stringType$1().optional(),
  error: stringType$1().optional()
});
objectType$1({
  boundary: enumType$1(["canvas", "curlayer", "selection"]),
  content: enumType$1(["canvas", "curlayer", "selection"]).or(stringType$1()),
  imageSize: numberType$1(),
  imageQuality: numberType$1(),
  cropBySelection: enumType$1(["no", "positive", "negative"]),
  layer_identify: stringType$1().nullable().optional()
});
objectType$1({
  content: enumType$1(["canvas", "curlayer", "selection"]),
  reverse: booleanType$1(),
  imageSize: numberType$1(),
  layer_identify: stringType$1().nullable().optional()
});
objectType$1({
  selection: enumType$1(["newdoc_canvas", "newlayer_canvas", "newlayer_curlayer", "newlayer_selection", "curlayer_canvas", "curlayer_curlayer", "curlayer_selection", "newdoc_canvas"]),
  url: stringType$1(),
  source: stringType$1(),
  cropBySelection: enumType$1(["no", "positive", "negative"])
});
const uxpImagingActions = {
  // Removed legacy content-webview operations (doGetImage/doGetMask/doSendImage)
  // Removed legacy request* actions (requestImageGet/requestMaskGet/requestImageSend)
  downloadImage: {
    requestSchema: objectType$1({
      url: stringType$1()
    }),
    responseSchema: objectType$1({
      thumbnail: stringType$1().optional(),
      resource: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      error: stringType$1().optional()
    })
  },
  getThumbnail: {
    requestSchema: objectType$1({
      resource: stringType$1(),
      maxSize: numberType$1().optional()
    }),
    responseSchema: objectType$1({
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      error: stringType$1().optional()
    })
  }
  // deleteDownloadedImage: {
  //     requestSchema: z.object({
  //         resources: z.array(z.string()),
  //     }),
  //     responseSchema: z.object({
  //         error: z.string().optional(),
  //     })
  // },
  // requestAndDoSaveImage: {
  //     requestSchema: z.object({
  //         resources: z.array(z.string()),
  //     }),
  //     responseSchema: z.object({
  //         error: z.string().optional(),
  //     })
  // }
};
const uxpPhotoshopActions = {
  manageGuides: {
    requestSchema: objectType$1({
      action: enumType$1(["create", "clear"]),
      rect: BoundaryRectSchema.optional()
    }),
    responseSchema: objectType$1({
      success: booleanType$1()
    })
  },
  getBoundary: {
    requestSchema: objectType$1({
      type: enumType$1(["curlayer", "selection"])
    }),
    responseSchema: BoundaryRectSchema
  },
  getImage: {
    requestSchema: objectType$1({
      boundary: unionType$1([
        enumType$1(["canvas", "curlayer", "selection"]),
        BoundaryRectSchema
      ]),
      content: unionType$1([enumType$1(["canvas", "curlayer"]), stringType$1()]),
      imageSize: numberType$1(),
      imageQuality: numberType$1(),
      cropBySelection: enumType$1(["no", "positive", "negative"]),
      SkipNonNormalLayer: booleanType$1(),
      layer_identify: stringType$1().nullable().optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mimeType: stringType$1().optional(),
      source: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  getMask: {
    requestSchema: objectType$1({
      boundary: unionType$1([
        enumType$1(["canvas", "curlayer", "selection"]),
        BoundaryRectSchema
      ]),
      content: enumType$1(["canvas", "curlayer", "selection"]),
      reverse: booleanType$1(),
      imageSize: numberType$1(),
      layer_identify: stringType$1().nullable().optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mimeType: stringType$1().optional(),
      source: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  getCurrentLayerIdentify: {
    requestSchema: objectType$1({}),
    responseSchema: objectType$1({
      layer_identify: stringType$1().nullable()
    })
  },
  importImage: {
    requestSchema: objectType$1({
      resource: stringType$1(),
      boundary: unionType$1([
        enumType$1(["canvas", "curlayer", "selection"]),
        BoundaryRectSchema
      ]).optional(),
      type: enumType$1(["canvas", "curlayer", "newdoc", "smartobject"]),
      // Optional source image size to avoid opening files in UXP
      sourceWidth: numberType$1().optional(),
      sourceHeight: numberType$1().optional(),
      applyMask: booleanType$1().optional()
    }),
    responseSchema: objectType$1({
      success: booleanType$1(),
      layers: arrayType$1(objectType$1({
        identify: stringType$1()
      })).optional(),
      message: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  applyMaskToImage: {
    requestSchema: objectType$1({
      imageResource: stringType$1(),
      maskResource: stringType$1(),
      invertMask: booleanType$1().optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1(),
      thumbnail: stringType$1().optional(),
      width: numberType$1(),
      height: numberType$1(),
      mimeType: stringType$1()
    })
  },
  showBoundarySelectionDialog: {
    requestSchema: objectType$1({
      additionalData: recordType$1(anyType$1()).optional()
    }),
    responseSchema: objectType$1({
      boundary: enumType$1(["canvas", "curlayer", "selection"]).optional(),
      cancelled: booleanType$1().optional()
    })
  },
  selectImageSource: {
    requestSchema: objectType$1({
      additionalData: recordType$1(anyType$1()).optional()
    }),
    responseSchema: objectType$1({
      action: enumType$1(["getImage", "pickLocalFile"]).optional(),
      params: anyType$1().optional(),
      cancelled: booleanType$1().optional()
    })
  },
  selectContentSource: {
    requestSchema: objectType$1({
      additionalData: recordType$1(anyType$1()).optional()
    }).optional(),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      fileName: stringType$1().optional(),
      mimeType: stringType$1().optional(),
      size: numberType$1().optional(),
      layerIdentify: stringType$1().optional(),
      cancelled: booleanType$1().optional()
    })
  }
};
const BaseTaskSchema = objectType$1({
  taskId: stringType$1(),
  taskName: stringType$1(),
  status: enumType$1(["running", "completed", "failed", "cancelled"]),
  currentStep: numberType$1().optional(),
  totalSteps: numberType$1().optional(),
  stepDescription: stringType$1().optional(),
  progressPercentage: numberType$1().min(0).max(100).optional(),
  startTime: stringType$1(),
  endTime: stringType$1().optional(),
  error: stringType$1().optional(),
  errorCode: stringType$1().optional(),
  result: anyType$1().optional(),
  metadata: recordType$1(anyType$1()).optional()
});
const TaskResponseSchema = objectType$1({
  success: booleanType$1(),
  error: stringType$1().optional()
});
const uxpTaskManagementActions = {
  // Add a new task
  taskAdd: {
    requestSchema: BaseTaskSchema,
    responseSchema: TaskResponseSchema
  },
  // Update a task (id required, other fields optional)
  taskUpdate: {
    requestSchema: BaseTaskSchema.partial().required({ taskId: true }),
    responseSchema: TaskResponseSchema
  },
  // Remove a task
  taskRemove: {
    requestSchema: BaseTaskSchema.pick({ taskId: true }),
    responseSchema: TaskResponseSchema
  }
};
const uxpUtilActions = {
  // UXP-related actions
  log: {
    requestSchema: objectType$1({
      level: enumType$1(["log", "info", "warn", "error"]),
      messages: arrayType$1(stringType$1())
    }),
    responseSchema: objectType$1({})
  },
  // UXP-related actions
  openExternalLink: {
    requestSchema: objectType$1({
      url: stringType$1()
    }),
    responseSchema: objectType$1({
      error: stringType$1().optional()
    })
  },
  getStorage: {
    requestSchema: objectType$1({
      key: stringType$1()
    }),
    responseSchema: objectType$1({
      value: stringType$1(),
      error: stringType$1().optional()
    })
  },
  setStorage: {
    requestSchema: objectType$1({
      key: stringType$1(),
      value: stringType$1()
    }),
    responseSchema: objectType$1({
      error: stringType$1().optional()
    })
  },
  removeStorage: {
    requestSchema: objectType$1({
      key: stringType$1()
    }),
    responseSchema: objectType$1({
      error: stringType$1().optional()
    })
  },
  // Keyboard action forwarding
  keyboardAction: {
    requestSchema: objectType$1({
      keycode: stringType$1()
    }),
    responseSchema: objectType$1({})
  },
  // Photoshop utility actions
  setComfyWebviewURL: {
    requestSchema: objectType$1({
      url: stringType$1()
    }),
    responseSchema: objectType$1({})
  },
  // 将 ImageHolder 的图片以 base64 返回
  getImageBase64: {
    requestSchema: objectType$1({
      token: stringType$1()
    }),
    responseSchema: objectType$1({
      base64: stringType$1().optional(),
      mimeType: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  uploadComfyImage: {
    requestSchema: objectType$1({
      uploadInput: objectType$1({
        type: unionType$1([literalType$1("buffer"), literalType$1("token"), literalType$1("resource")]),
        resource: anyType$1(),
        fileName: stringType$1(),
        mimeType: stringType$1().optional(),
        resourceId: stringType$1().optional()
      }),
      overwrite: booleanType$1().optional().default(true)
    }),
    responseSchema: objectType$1({
      name: stringType$1()
    })
  },
  pickLocalFile: {
    requestSchema: objectType$1({
      acceptExtensions: arrayType$1(stringType$1()).optional(),
      kind: enumType$1(["image", "file"]).optional()
    }).optional(),
    responseSchema: objectType$1({
      cancelled: booleanType$1().optional(),
      resource: stringType$1().optional(),
      fileName: stringType$1().optional(),
      mimeType: stringType$1().optional(),
      size: numberType$1().optional(),
      error: stringType$1().optional()
    })
  },
  // Proxied fetch action
  proxiedFetch: {
    requestSchema: objectType$1({
      url: stringType$1(),
      method: stringType$1().optional(),
      headers: recordType$1(stringType$1()).optional(),
      body: anyType$1().optional(),
      bodyType: enumType$1(["json", "formData", "text"]).optional()
    }),
    responseSchema: objectType$1({
      success: booleanType$1(),
      status: numberType$1().optional(),
      statusText: stringType$1().optional(),
      headers: recordType$1(stringType$1()).optional(),
      data: anyType$1().optional(),
      error: stringType$1().optional()
    })
  },
  // OpenAI image editing action
  openaiImageEdit: {
    requestSchema: objectType$1({
      apiKey: stringType$1(),
      baseURL: stringType$1(),
      imageToken: stringType$1(),
      prompt: stringType$1(),
      model: stringType$1()
    }),
    responseSchema: objectType$1({
      success: booleanType$1(),
      imageUrl: stringType$1().optional(),
      apiTime: numberType$1().optional(),
      error: stringType$1().optional()
    })
  },
  // Gemini image generation action
  geminiImageGenerate: {
    requestSchema: objectType$1({
      apiKey: stringType$1(),
      baseURL: stringType$1().optional(),
      // Support multiple images; keep single for backward compatibility
      imageInputs: arrayType$1(stringType$1()).optional(),
      imageInput: stringType$1().optional(),
      imageInputType: enumType$1(["token", "base64"]),
      prompt: stringType$1()
    }),
    responseSchema: objectType$1({
      success: booleanType$1(),
      imageUrl: stringType$1().optional(),
      apiTime: numberType$1().optional(),
      error: stringType$1().optional()
    })
  }
};
const BufferInputSchema = unionType$1([
  stringType$1(),
  instanceOfType$1(Uint8Array),
  instanceOfType$1(ArrayBuffer),
  instanceOfType$1(DataView)
]);
const FileResourceBufferDescriptorSchema = objectType$1({
  buffer: BufferInputSchema,
  name: stringType$1().nullable().optional(),
  mime: stringType$1().nullable().optional(),
  width: numberType$1().nullable().optional(),
  height: numberType$1().nullable().optional(),
  thumbnail: stringType$1().nullable().optional(),
  meta: recordType$1(unknownType$1()).optional()
});
const uxpResourcingActions = {
  "fileResource.createFromExternal": {
    requestSchema: objectType$1({
      url: stringType$1(),
      fileName: stringType$1().optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      mimeType: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.createFromLocal": {
    requestSchema: objectType$1({
      types: arrayType$1(objectType$1({
        description: stringType$1().optional(),
        extensions: arrayType$1(stringType$1()).optional()
      })).optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.createFromBuffer": {
    requestSchema: objectType$1({
      files: arrayType$1(FileResourceBufferDescriptorSchema).min(1)
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.createByContent": {
    requestSchema: objectType$1({
      contentUri: stringType$1(),
      boundaryUri: stringType$1().optional(),
      options: recordType$1(unknownType$1()).optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.createByMask": {
    requestSchema: objectType$1({
      maskUri: stringType$1(),
      boundaryUri: stringType$1().optional(),
      options: recordType$1(unknownType$1()).optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.combineByCBM": {
    requestSchema: objectType$1({
      contentUri: stringType$1(),
      boundaryUri: stringType$1(),
      maskUri: stringType$1().nullable().optional(),
      options: recordType$1(unknownType$1()).optional(),
      thumbnail: booleanType$1().optional()
    }),
    responseSchema: objectType$1({
      resource: stringType$1().optional(),
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      mime: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.delete": {
    requestSchema: objectType$1({
      resources: arrayType$1(stringType$1())
    }),
    responseSchema: objectType$1({
      error: stringType$1().optional()
    })
  },
  "fileResource.thumbnail": {
    requestSchema: objectType$1({
      resource: stringType$1(),
      maxSize: numberType$1().optional()
    }),
    responseSchema: objectType$1({
      thumbnail: stringType$1().optional(),
      width: numberType$1().optional(),
      height: numberType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "fileResource.saveAs": {
    requestSchema: objectType$1({
      resources: arrayType$1(stringType$1())
    }),
    responseSchema: objectType$1({
      error: stringType$1().optional()
    })
  },
  "boundary.normalize": {
    requestSchema: objectType$1({
      boundary: stringType$1()
    }),
    responseSchema: objectType$1({
      boundary: stringType$1().optional(),
      error: stringType$1().optional()
    })
  },
  "layer.resolve": {
    requestSchema: objectType$1({
      uri: stringType$1(),
      type: enumType$1(["content", "mask"])
    }),
    responseSchema: objectType$1({
      uri: stringType$1().optional(),
      error: stringType$1().optional()
    })
  }
};
const BoundaryRectUtils = {
  /**
   * Calculate width from a BoundaryRect
   */
  getWidth: (rect) => {
    return rect.width;
  },
  /**
   * Calculate height from a BoundaryRect
   */
  getHeight: (rect) => {
    return rect.height;
  },
  /**
   * Create a BoundaryRect from legacy Rect format (left, top, right, bottom)
   * where right and bottom are absolute coordinates
   */
  fromLegacyRect: (rect) => {
    return {
      leftDistance: rect.left,
      topDistance: rect.top,
      rightDistance: rect.right,
      bottomDistance: rect.bottom,
      width: rect.right - rect.left,
      height: rect.bottom - rect.top
    };
  },
  /**
   * Create a BoundaryRect from position and size
   */
  fromPositionAndSize: (x2, y2, width, height, docWidth, docHeight) => {
    return {
      leftDistance: x2,
      topDistance: y2,
      rightDistance: docWidth - (x2 + width),
      bottomDistance: docHeight - (y2 + height),
      width,
      height
    };
  },
  /**
   * Convert BoundaryRect to legacy format for compatibility
   */
  toLegacyRect: (rect, docWidth, docHeight) => {
    const left = rect.leftDistance;
    const top = rect.topDistance;
    const right = Math.max(left, docWidth - rect.rightDistance);
    const bottom = Math.max(top, docHeight - rect.bottomDistance);
    return { left, top, right, bottom };
  },
  /**
   * Convert BoundaryRect to SDPPPBounds format
   */
  toSDPPPBounds: (rect, docWidth, docHeight) => {
    const left = rect.leftDistance;
    const top = rect.topDistance;
    const right = Math.max(left, docWidth - rect.rightDistance);
    const bottom = Math.max(top, docHeight - rect.bottomDistance);
    return { left, top, right, bottom, width: rect.width, height: rect.height };
  },
  /**
   * Convert BoundaryRect to SDPPPBounds without explicit document dimensions.
   * The document size is inferred from the distances and width/height.
   */
  toSDPPPBoundsAuto: (rect) => {
    const docWidth = rect.leftDistance + rect.width + rect.rightDistance;
    const docHeight = rect.topDistance + rect.height + rect.bottomDistance;
    return BoundaryRectUtils.toSDPPPBounds(rect, docWidth, docHeight);
  },
  /**
   * Get the inferred document width/height from a BoundaryRect.
   */
  getDocumentSize: (rect) => {
    return {
      width: rect.leftDistance + rect.width + rect.rightDistance,
      height: rect.topDistance + rect.height + rect.bottomDistance
    };
  },
  /**
   * Validate that a BoundaryRect has valid dimensions
   */
  isValid: (rect) => {
    return rect.width > 0 && rect.height > 0 && rect.leftDistance >= 0 && rect.topDistance >= 0 && rect.rightDistance >= 0 && rect.bottomDistance >= 0;
  },
  /**
   * Clamp a BoundaryRect to fit within document bounds
   */
  clampToDocument: (rect, docWidth, docHeight) => {
    const actualRight = docWidth - rect.rightDistance;
    const actualBottom = docHeight - rect.bottomDistance;
    const clampedLeft = Math.max(0, Math.min(rect.leftDistance, docWidth));
    const clampedTop = Math.max(0, Math.min(rect.topDistance, docHeight));
    const clampedRight = Math.max(clampedLeft, Math.min(actualRight, docWidth));
    const clampedBottom = Math.max(clampedTop, Math.min(actualBottom, docHeight));
    const finalRight = Math.min(clampedRight, docWidth);
    const finalBottom = Math.min(clampedBottom, docHeight);
    const clampedWidth = finalRight - clampedLeft;
    const clampedHeight = finalBottom - clampedTop;
    return {
      leftDistance: clampedLeft,
      topDistance: clampedTop,
      rightDistance: Math.max(0, docWidth - finalRight),
      bottomDistance: Math.max(0, docHeight - finalBottom),
      width: clampedWidth,
      height: clampedHeight
    };
  },
  /**
   * Convert Photoshop Bounds object to BoundaryRect
   * Photoshop Bounds has { left, top, right, bottom } where right/bottom are absolute coordinates
   */
  fromPhotoshopBounds: (bounds, docWidth, docHeight) => {
    return {
      leftDistance: bounds.left,
      topDistance: bounds.top,
      rightDistance: docWidth - bounds.right,
      bottomDistance: docHeight - bounds.bottom,
      width: bounds.right - bounds.left,
      height: bounds.bottom - bounds.top
    };
  },
  /**
   * Convert SDPPP Bounds format to BoundaryRect
   */
  fromSDPPPBounds: (bounds) => {
    return {
      leftDistance: bounds.left,
      topDistance: bounds.top,
      rightDistance: bounds.right,
      bottomDistance: bounds.bottom,
      width: bounds.width,
      height: bounds.height
    };
  }
};
const meshDef = defineGraph({
  nodes: {
    // SDK node - represents the content webview/SDK layer
    sdk: {
      store: SDKStoreSchema,
      actions: {
        ...sdkActions
      }
    },
    // UXP node - represents the Photoshop UXP plugin
    uxp: {
      store: UXPStoreSchema,
      actions: {
        // Disabled: deleteDownloadedImage / requestAndDoSaveImage (see uxp-imaging-defs.ts)
        ...uxpImagingActions,
        ...uxpResourcingActions,
        ...uxpUtilActions,
        ...uxpAuthActions,
        ...uxpTaskManagementActions,
        ...uxpPhotoshopActions
      }
    },
    // Comfy node - represents ComfyUI instances
    comfy: {
      store: ComfyStoreSchema,
      actions: {
        ...comfyWorkflowActions,
        ...comfyUtilActions
      }
    }
  },
  edges: [
    ["sdk", "uxp"],
    // SDK connects to UXP
    ["comfy", "uxp"]
    // Comfy connects to UXP
  ]
});
class PostMessageClientTransport {
  constructor(options2) {
    this.messageQueue = [];
    this.lastPingTime = 0;
    this.connectionState = "disconnected";
    this.posterIdentifier = options2.posterIdentifier;
    this.messagePoster = options2.messagePoster;
    this.addMessageEventListener = options2.addMessageEventListener;
    this.removeMessageEventListener = options2.removeMessageEventListener;
    const intervalInput = options2.heartbeatInterval ?? options2.heartbeatTimeout;
    const timeoutInput = options2.heartbeatTimeout ?? options2.heartbeatInterval;
    const interval = this.normalizeDuration(intervalInput);
    const timeout = this.normalizeDuration(timeoutInput);
    if (interval && timeout) {
      this.heartbeatInterval = interval;
      this.heartbeatTimeout = timeout;
    }
    this.debugDisableHeartbeatResponse = options2.debugDisableHeartbeatResponse ?? false;
    this.listenMessageCallback = this.listenMessageCallback.bind(this);
    this.externalListenMessageCallback = this.addMessageEventListener(this.listenMessageCallback);
  }
  normalizeDuration(value) {
    if (typeof value !== "number") return void 0;
    if (!Number.isFinite(value) || value <= 0) return void 0;
    return value;
  }
  isHeartbeatEnabled() {
    return typeof this.heartbeatInterval === "number" && typeof this.heartbeatTimeout === "number";
  }
  listenMessageCallback(message) {
    if (message.posterIdentifier !== this.posterIdentifier) return;
    if (message.channel === "sdppp-heartbeat") {
      if (message.type === "ping" && !this.debugDisableHeartbeatResponse) {
        this.messagePoster({
          channel: "sdppp-heartbeat",
          posterIdentifier: this.posterIdentifier,
          type: "pong",
          timestamp: message.timestamp
        });
      } else if (message.type === "pong" && message.timestamp === this.lastPingTime) {
        if (this.connectionState === "reconnecting") {
          this.handleReconnectSuccess();
        } else if (this.heartbeatCheckTimer) {
          clearTimeout(this.heartbeatCheckTimer);
          this.heartbeatCheckTimer = void 0;
        }
      }
      return;
    }
    if (message.channel !== "sdppp") return;
    if (this.onmessage && "payload" in message) {
      this.onmessage(message.payload);
    } else if ("payload" in message) {
      this.messageQueue.push(message.payload);
    }
  }
  async start() {
    while (this.messageQueue.length > 0) {
      const queuedMessage = this.messageQueue.shift();
      if (queuedMessage && this.onmessage) {
        this.onmessage(queuedMessage);
      }
    }
    this.setConnectionState("connected");
    if (this.isHeartbeatEnabled()) {
      this.startHeartbeat();
    }
  }
  startHeartbeat() {
    if (!this.isHeartbeatEnabled()) {
      return;
    }
    const interval = this.heartbeatInterval;
    const timeout = this.heartbeatTimeout;
    console.log("startHeartbeat", interval, timeout);
    this.clearHeartbeatTimers();
    this.heartbeatTimer = setInterval(() => {
      const now = Date.now();
      this.lastPingTime = now;
      this.messagePoster({
        channel: "sdppp-heartbeat",
        posterIdentifier: this.posterIdentifier,
        type: "ping",
        timestamp: now
      });
      this.heartbeatCheckTimer = setTimeout(() => {
        this.handleHeartbeatTimeout();
      }, timeout);
    }, interval);
  }
  async send(message, options2) {
    this.messagePoster({
      channel: "sdppp",
      posterIdentifier: this.posterIdentifier,
      payload: message
    });
  }
  async close() {
    this.setConnectionState("disconnected");
    this.clearHeartbeatTimers();
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = void 0;
    }
    this.removeMessageEventListener(this.externalListenMessageCallback);
  }
  setConnectionState(state) {
    this.connectionState = state;
    if (this.onconnectionstatechange) {
      this.onconnectionstatechange(state);
    }
  }
  handleHeartbeatTimeout() {
    if (!this.isHeartbeatEnabled()) {
      return;
    }
    if (this.connectionState === "connected") {
      this.setConnectionState("reconnecting");
      this.clearHeartbeatTimers();
      this.startReconnectAttempts();
    }
  }
  clearHeartbeatTimers() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = void 0;
    }
    if (this.heartbeatCheckTimer) {
      clearTimeout(this.heartbeatCheckTimer);
      this.heartbeatCheckTimer = void 0;
    }
  }
  startReconnectAttempts() {
    if (!this.isHeartbeatEnabled()) {
      return;
    }
    const attemptReconnect = () => {
      if (this.connectionState !== "reconnecting") {
        return;
      }
      const now = Date.now();
      this.lastPingTime = now;
      this.messagePoster({
        channel: "sdppp-heartbeat",
        posterIdentifier: this.posterIdentifier,
        type: "ping",
        timestamp: now
      });
      this.reconnectTimer = setTimeout(() => {
        attemptReconnect();
      }, 1e3);
    };
    attemptReconnect();
  }
  handleReconnectSuccess() {
    if (this.connectionState === "reconnecting") {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = void 0;
      }
      this.setConnectionState("connected");
      if (this.isHeartbeatEnabled()) {
        this.startHeartbeat();
      }
    }
  }
}
const LATEST_PROTOCOL_VERSION = "2025-06-18";
const SUPPORTED_PROTOCOL_VERSIONS = [
  LATEST_PROTOCOL_VERSION,
  "2025-03-26",
  "2024-11-05",
  "2024-10-07"
];
const JSONRPC_VERSION = "2.0";
const ProgressTokenSchema = unionType$1([stringType$1(), numberType$1().int()]);
const CursorSchema = stringType$1();
const RequestMetaSchema = objectType$1({
  /**
   * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
   */
  progressToken: optionalType$1(ProgressTokenSchema)
}).passthrough();
const BaseRequestParamsSchema = objectType$1({
  _meta: optionalType$1(RequestMetaSchema)
}).passthrough();
const RequestSchema = objectType$1({
  method: stringType$1(),
  params: optionalType$1(BaseRequestParamsSchema)
});
const BaseNotificationParamsSchema = objectType$1({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const NotificationSchema = objectType$1({
  method: stringType$1(),
  params: optionalType$1(BaseNotificationParamsSchema)
});
const ResultSchema = objectType$1({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const RequestIdSchema = unionType$1([stringType$1(), numberType$1().int()]);
const JSONRPCRequestSchema = objectType$1({
  jsonrpc: literalType$1(JSONRPC_VERSION),
  id: RequestIdSchema
}).merge(RequestSchema).strict();
const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
const JSONRPCNotificationSchema = objectType$1({
  jsonrpc: literalType$1(JSONRPC_VERSION)
}).merge(NotificationSchema).strict();
const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
const JSONRPCResponseSchema = objectType$1({
  jsonrpc: literalType$1(JSONRPC_VERSION),
  id: RequestIdSchema,
  result: ResultSchema
}).strict();
const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
  ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
  ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
  ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
  ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
  ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
})(ErrorCode || (ErrorCode = {}));
const JSONRPCErrorSchema = objectType$1({
  jsonrpc: literalType$1(JSONRPC_VERSION),
  id: RequestIdSchema,
  error: objectType$1({
    /**
     * The error type that occurred.
     */
    code: numberType$1().int(),
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: stringType$1(),
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data: optionalType$1(unknownType$1())
  })
}).strict();
const isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
unionType$1([
  JSONRPCRequestSchema,
  JSONRPCNotificationSchema,
  JSONRPCResponseSchema,
  JSONRPCErrorSchema
]);
const EmptyResultSchema = ResultSchema.strict();
const CancelledNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/cancelled"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The ID of the request to cancel.
     *
     * This MUST correspond to the ID of a request previously issued in the same direction.
     */
    requestId: RequestIdSchema,
    /**
     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
     */
    reason: stringType$1().optional()
  })
});
const BaseMetadataSchema = objectType$1({
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
  name: stringType$1(),
  /**
  * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
  * even by those unfamiliar with domain-specific terminology.
  *
  * If not provided, the name should be used for display (except for Tool,
  * where `annotations.title` should be given precedence over using `name`,
  * if present).
  */
  title: optionalType$1(stringType$1())
}).passthrough();
const ImplementationSchema = BaseMetadataSchema.extend({
  version: stringType$1()
});
const ClientCapabilitiesSchema = objectType$1({
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the client supports sampling from an LLM.
   */
  sampling: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the client supports eliciting user input.
   */
  elicitation: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the client supports listing roots.
   */
  roots: optionalType$1(objectType$1({
    /**
     * Whether the client supports issuing notifications for changes to the roots list.
     */
    listChanged: optionalType$1(booleanType$1())
  }).passthrough())
}).passthrough();
const InitializeRequestSchema = RequestSchema.extend({
  method: literalType$1("initialize"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
     */
    protocolVersion: stringType$1(),
    capabilities: ClientCapabilitiesSchema,
    clientInfo: ImplementationSchema
  })
});
const ServerCapabilitiesSchema = objectType$1({
  /**
   * Experimental, non-standard capabilities that the server supports.
   */
  experimental: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the server supports sending log messages to the client.
   */
  logging: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the server supports sending completions to the client.
   */
  completions: optionalType$1(objectType$1({}).passthrough()),
  /**
   * Present if the server offers any prompt templates.
   */
  prompts: optionalType$1(objectType$1({
    /**
     * Whether this server supports issuing notifications for changes to the prompt list.
     */
    listChanged: optionalType$1(booleanType$1())
  }).passthrough()),
  /**
   * Present if the server offers any resources to read.
   */
  resources: optionalType$1(objectType$1({
    /**
     * Whether this server supports clients subscribing to resource updates.
     */
    subscribe: optionalType$1(booleanType$1()),
    /**
     * Whether this server supports issuing notifications for changes to the resource list.
     */
    listChanged: optionalType$1(booleanType$1())
  }).passthrough()),
  /**
   * Present if the server offers any tools to call.
   */
  tools: optionalType$1(objectType$1({
    /**
     * Whether this server supports issuing notifications for changes to the tool list.
     */
    listChanged: optionalType$1(booleanType$1())
  }).passthrough())
}).passthrough();
const InitializeResultSchema = ResultSchema.extend({
  /**
   * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
   */
  protocolVersion: stringType$1(),
  capabilities: ServerCapabilitiesSchema,
  serverInfo: ImplementationSchema,
  /**
   * Instructions describing how to use the server and its features.
   *
   * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
   */
  instructions: optionalType$1(stringType$1())
});
const InitializedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/initialized")
});
const PingRequestSchema = RequestSchema.extend({
  method: literalType$1("ping")
});
const ProgressSchema = objectType$1({
  /**
   * The progress thus far. This should increase every time progress is made, even if the total is unknown.
   */
  progress: numberType$1(),
  /**
   * Total number of items to process (or total progress required), if known.
   */
  total: optionalType$1(numberType$1()),
  /**
   * An optional message describing the current progress.
   */
  message: optionalType$1(stringType$1())
}).passthrough();
const ProgressNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/progress"),
  params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
    /**
     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
     */
    progressToken: ProgressTokenSchema
  })
});
const PaginatedRequestSchema = RequestSchema.extend({
  params: BaseRequestParamsSchema.extend({
    /**
     * An opaque token representing the current pagination position.
     * If provided, the server should return results starting after this cursor.
     */
    cursor: optionalType$1(CursorSchema)
  }).optional()
});
const PaginatedResultSchema = ResultSchema.extend({
  /**
   * An opaque token representing the pagination position after the last returned result.
   * If present, there may be more results available.
   */
  nextCursor: optionalType$1(CursorSchema)
});
const ResourceContentsSchema = objectType$1({
  /**
   * The URI of this resource.
   */
  uri: stringType$1(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optionalType$1(stringType$1()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const TextResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
   */
  text: stringType$1()
});
const BlobResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: stringType$1().base64()
});
const ResourceSchema = BaseMetadataSchema.extend({
  /**
   * The URI of this resource.
   */
  uri: stringType$1(),
  /**
   * A description of what this resource represents.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optionalType$1(stringType$1()),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optionalType$1(stringType$1()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
});
const ResourceTemplateSchema = BaseMetadataSchema.extend({
  /**
   * A URI template (according to RFC 6570) that can be used to construct resource URIs.
   */
  uriTemplate: stringType$1(),
  /**
   * A description of what this template is for.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optionalType$1(stringType$1()),
  /**
   * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
   */
  mimeType: optionalType$1(stringType$1()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
});
const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
  method: literalType$1("resources/list")
});
const ListResourcesResultSchema = PaginatedResultSchema.extend({
  resources: arrayType$1(ResourceSchema)
});
const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
  method: literalType$1("resources/templates/list")
});
const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
  resourceTemplates: arrayType$1(ResourceTemplateSchema)
});
const ReadResourceRequestSchema = RequestSchema.extend({
  method: literalType$1("resources/read"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
     */
    uri: stringType$1()
  })
});
const ReadResourceResultSchema = ResultSchema.extend({
  contents: arrayType$1(unionType$1([TextResourceContentsSchema, BlobResourceContentsSchema]))
});
const ResourceListChangedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/resources/list_changed")
});
const SubscribeRequestSchema = RequestSchema.extend({
  method: literalType$1("resources/subscribe"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
     */
    uri: stringType$1()
  })
});
const UnsubscribeRequestSchema = RequestSchema.extend({
  method: literalType$1("resources/unsubscribe"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to unsubscribe from.
     */
    uri: stringType$1()
  })
});
const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/resources/updated"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
     */
    uri: stringType$1()
  })
});
const PromptArgumentSchema = objectType$1({
  /**
   * The name of the argument.
   */
  name: stringType$1(),
  /**
   * A human-readable description of the argument.
   */
  description: optionalType$1(stringType$1()),
  /**
   * Whether this argument must be provided.
   */
  required: optionalType$1(booleanType$1())
}).passthrough();
const PromptSchema = BaseMetadataSchema.extend({
  /**
   * An optional description of what this prompt provides
   */
  description: optionalType$1(stringType$1()),
  /**
   * A list of arguments to use for templating the prompt.
   */
  arguments: optionalType$1(arrayType$1(PromptArgumentSchema)),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
});
const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
  method: literalType$1("prompts/list")
});
const ListPromptsResultSchema = PaginatedResultSchema.extend({
  prompts: arrayType$1(PromptSchema)
});
const GetPromptRequestSchema = RequestSchema.extend({
  method: literalType$1("prompts/get"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The name of the prompt or prompt template.
     */
    name: stringType$1(),
    /**
     * Arguments to use for templating the prompt.
     */
    arguments: optionalType$1(recordType$1(stringType$1()))
  })
});
const TextContentSchema = objectType$1({
  type: literalType$1("text"),
  /**
   * The text content of the message.
   */
  text: stringType$1(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const ImageContentSchema = objectType$1({
  type: literalType$1("image"),
  /**
   * The base64-encoded image data.
   */
  data: stringType$1().base64(),
  /**
   * The MIME type of the image. Different providers may support different image types.
   */
  mimeType: stringType$1(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const AudioContentSchema = objectType$1({
  type: literalType$1("audio"),
  /**
   * The base64-encoded audio data.
   */
  data: stringType$1().base64(),
  /**
   * The MIME type of the audio. Different providers may support different audio types.
   */
  mimeType: stringType$1(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const EmbeddedResourceSchema = objectType$1({
  type: literalType$1("resource"),
  resource: unionType$1([TextResourceContentsSchema, BlobResourceContentsSchema]),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const ResourceLinkSchema = ResourceSchema.extend({
  type: literalType$1("resource_link")
});
const ContentBlockSchema = unionType$1([
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ResourceLinkSchema,
  EmbeddedResourceSchema
]);
const PromptMessageSchema = objectType$1({
  role: enumType$1(["user", "assistant"]),
  content: ContentBlockSchema
}).passthrough();
const GetPromptResultSchema = ResultSchema.extend({
  /**
   * An optional description for the prompt.
   */
  description: optionalType$1(stringType$1()),
  messages: arrayType$1(PromptMessageSchema)
});
const PromptListChangedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/prompts/list_changed")
});
const ToolAnnotationsSchema = objectType$1({
  /**
   * A human-readable title for the tool.
   */
  title: optionalType$1(stringType$1()),
  /**
   * If true, the tool does not modify its environment.
   *
   * Default: false
   */
  readOnlyHint: optionalType$1(booleanType$1()),
  /**
   * If true, the tool may perform destructive updates to its environment.
   * If false, the tool performs only additive updates.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: true
   */
  destructiveHint: optionalType$1(booleanType$1()),
  /**
   * If true, calling the tool repeatedly with the same arguments
   * will have no additional effect on the its environment.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: false
   */
  idempotentHint: optionalType$1(booleanType$1()),
  /**
   * If true, this tool may interact with an "open world" of external
   * entities. If false, the tool's domain of interaction is closed.
   * For example, the world of a web search tool is open, whereas that
   * of a memory tool is not.
   *
   * Default: true
   */
  openWorldHint: optionalType$1(booleanType$1())
}).passthrough();
const ToolSchema = BaseMetadataSchema.extend({
  /**
   * A human-readable description of the tool.
   */
  description: optionalType$1(stringType$1()),
  /**
   * A JSON Schema object defining the expected parameters for the tool.
   */
  inputSchema: objectType$1({
    type: literalType$1("object"),
    properties: optionalType$1(objectType$1({}).passthrough()),
    required: optionalType$1(arrayType$1(stringType$1()))
  }).passthrough(),
  /**
   * An optional JSON Schema object defining the structure of the tool's output returned in
   * the structuredContent field of a CallToolResult.
   */
  outputSchema: optionalType$1(objectType$1({
    type: literalType$1("object"),
    properties: optionalType$1(objectType$1({}).passthrough()),
    required: optionalType$1(arrayType$1(stringType$1()))
  }).passthrough()),
  /**
   * Optional additional tool information.
   */
  annotations: optionalType$1(ToolAnnotationsSchema),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
});
const ListToolsRequestSchema = PaginatedRequestSchema.extend({
  method: literalType$1("tools/list")
});
const ListToolsResultSchema = PaginatedResultSchema.extend({
  tools: arrayType$1(ToolSchema)
});
const CallToolResultSchema = ResultSchema.extend({
  /**
   * A list of content objects that represent the result of the tool call.
   *
   * If the Tool does not define an outputSchema, this field MUST be present in the result.
   * For backwards compatibility, this field is always present, but it may be empty.
   */
  content: arrayType$1(ContentBlockSchema).default([]),
  /**
   * An object containing structured tool output.
   *
   * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
   */
  structuredContent: objectType$1({}).passthrough().optional(),
  /**
   * Whether the tool call ended in an error.
   *
   * If not set, this is assumed to be false (the call was successful).
   *
   * Any errors that originate from the tool SHOULD be reported inside the result
   * object, with `isError` set to true, _not_ as an MCP protocol-level error
   * response. Otherwise, the LLM would not be able to see that an error occurred
   * and self-correct.
   *
   * However, any errors in _finding_ the tool, an error indicating that the
   * server does not support tool calls, or any other exceptional conditions,
   * should be reported as an MCP error response.
   */
  isError: optionalType$1(booleanType$1())
});
CallToolResultSchema.or(ResultSchema.extend({
  toolResult: unknownType$1()
}));
const CallToolRequestSchema = RequestSchema.extend({
  method: literalType$1("tools/call"),
  params: BaseRequestParamsSchema.extend({
    name: stringType$1(),
    arguments: optionalType$1(recordType$1(unknownType$1()))
  })
});
const ToolListChangedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/tools/list_changed")
});
const LoggingLevelSchema = enumType$1([
  "debug",
  "info",
  "notice",
  "warning",
  "error",
  "critical",
  "alert",
  "emergency"
]);
const SetLevelRequestSchema = RequestSchema.extend({
  method: literalType$1("logging/setLevel"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
     */
    level: LoggingLevelSchema
  })
});
const LoggingMessageNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/message"),
  params: BaseNotificationParamsSchema.extend({
    /**
     * The severity of this log message.
     */
    level: LoggingLevelSchema,
    /**
     * An optional name of the logger issuing this message.
     */
    logger: optionalType$1(stringType$1()),
    /**
     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
     */
    data: unknownType$1()
  })
});
const ModelHintSchema = objectType$1({
  /**
   * A hint for a model name.
   */
  name: stringType$1().optional()
}).passthrough();
const ModelPreferencesSchema = objectType$1({
  /**
   * Optional hints to use for model selection.
   */
  hints: optionalType$1(arrayType$1(ModelHintSchema)),
  /**
   * How much to prioritize cost when selecting a model.
   */
  costPriority: optionalType$1(numberType$1().min(0).max(1)),
  /**
   * How much to prioritize sampling speed (latency) when selecting a model.
   */
  speedPriority: optionalType$1(numberType$1().min(0).max(1)),
  /**
   * How much to prioritize intelligence and capabilities when selecting a model.
   */
  intelligencePriority: optionalType$1(numberType$1().min(0).max(1))
}).passthrough();
const SamplingMessageSchema = objectType$1({
  role: enumType$1(["user", "assistant"]),
  content: unionType$1([TextContentSchema, ImageContentSchema, AudioContentSchema])
}).passthrough();
const CreateMessageRequestSchema = RequestSchema.extend({
  method: literalType$1("sampling/createMessage"),
  params: BaseRequestParamsSchema.extend({
    messages: arrayType$1(SamplingMessageSchema),
    /**
     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
     */
    systemPrompt: optionalType$1(stringType$1()),
    /**
     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
     */
    includeContext: optionalType$1(enumType$1(["none", "thisServer", "allServers"])),
    temperature: optionalType$1(numberType$1()),
    /**
     * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
     */
    maxTokens: numberType$1().int(),
    stopSequences: optionalType$1(arrayType$1(stringType$1())),
    /**
     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
     */
    metadata: optionalType$1(objectType$1({}).passthrough()),
    /**
     * The server's preferences for which model to select.
     */
    modelPreferences: optionalType$1(ModelPreferencesSchema)
  })
});
const CreateMessageResultSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: stringType$1(),
  /**
   * The reason why sampling stopped.
   */
  stopReason: optionalType$1(enumType$1(["endTurn", "stopSequence", "maxTokens"]).or(stringType$1())),
  role: enumType$1(["user", "assistant"]),
  content: discriminatedUnionType$1("type", [
    TextContentSchema,
    ImageContentSchema,
    AudioContentSchema
  ])
});
const BooleanSchemaSchema = objectType$1({
  type: literalType$1("boolean"),
  title: optionalType$1(stringType$1()),
  description: optionalType$1(stringType$1()),
  default: optionalType$1(booleanType$1())
}).passthrough();
const StringSchemaSchema = objectType$1({
  type: literalType$1("string"),
  title: optionalType$1(stringType$1()),
  description: optionalType$1(stringType$1()),
  minLength: optionalType$1(numberType$1()),
  maxLength: optionalType$1(numberType$1()),
  format: optionalType$1(enumType$1(["email", "uri", "date", "date-time"]))
}).passthrough();
const NumberSchemaSchema = objectType$1({
  type: enumType$1(["number", "integer"]),
  title: optionalType$1(stringType$1()),
  description: optionalType$1(stringType$1()),
  minimum: optionalType$1(numberType$1()),
  maximum: optionalType$1(numberType$1())
}).passthrough();
const EnumSchemaSchema = objectType$1({
  type: literalType$1("string"),
  title: optionalType$1(stringType$1()),
  description: optionalType$1(stringType$1()),
  enum: arrayType$1(stringType$1()),
  enumNames: optionalType$1(arrayType$1(stringType$1()))
}).passthrough();
const PrimitiveSchemaDefinitionSchema = unionType$1([
  BooleanSchemaSchema,
  StringSchemaSchema,
  NumberSchemaSchema,
  EnumSchemaSchema
]);
const ElicitRequestSchema = RequestSchema.extend({
  method: literalType$1("elicitation/create"),
  params: BaseRequestParamsSchema.extend({
    /**
     * The message to present to the user.
     */
    message: stringType$1(),
    /**
     * The schema for the requested user input.
     */
    requestedSchema: objectType$1({
      type: literalType$1("object"),
      properties: recordType$1(stringType$1(), PrimitiveSchemaDefinitionSchema),
      required: optionalType$1(arrayType$1(stringType$1()))
    }).passthrough()
  })
});
const ElicitResultSchema = ResultSchema.extend({
  /**
   * The user's response action.
   */
  action: enumType$1(["accept", "decline", "cancel"]),
  /**
   * The collected user input content (only present if action is "accept").
   */
  content: optionalType$1(recordType$1(stringType$1(), unknownType$1()))
});
const ResourceTemplateReferenceSchema = objectType$1({
  type: literalType$1("ref/resource"),
  /**
   * The URI or URI template of the resource.
   */
  uri: stringType$1()
}).passthrough();
const PromptReferenceSchema = objectType$1({
  type: literalType$1("ref/prompt"),
  /**
   * The name of the prompt or prompt template
   */
  name: stringType$1()
}).passthrough();
const CompleteRequestSchema = RequestSchema.extend({
  method: literalType$1("completion/complete"),
  params: BaseRequestParamsSchema.extend({
    ref: unionType$1([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
    /**
     * The argument's information
     */
    argument: objectType$1({
      /**
       * The name of the argument
       */
      name: stringType$1(),
      /**
       * The value of the argument to use for completion matching.
       */
      value: stringType$1()
    }).passthrough(),
    context: optionalType$1(objectType$1({
      /**
       * Previously-resolved variables in a URI template or prompt.
       */
      arguments: optionalType$1(recordType$1(stringType$1(), stringType$1()))
    }))
  })
});
const CompleteResultSchema = ResultSchema.extend({
  completion: objectType$1({
    /**
     * An array of completion values. Must not exceed 100 items.
     */
    values: arrayType$1(stringType$1()).max(100),
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total: optionalType$1(numberType$1().int()),
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore: optionalType$1(booleanType$1())
  }).passthrough()
});
const RootSchema = objectType$1({
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   */
  uri: stringType$1().startsWith("file://"),
  /**
   * An optional name for the root.
   */
  name: optionalType$1(stringType$1()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optionalType$1(objectType$1({}).passthrough())
}).passthrough();
const ListRootsRequestSchema = RequestSchema.extend({
  method: literalType$1("roots/list")
});
const ListRootsResultSchema = ResultSchema.extend({
  roots: arrayType$1(RootSchema)
});
const RootsListChangedNotificationSchema = NotificationSchema.extend({
  method: literalType$1("notifications/roots/list_changed")
});
unionType$1([
  PingRequestSchema,
  InitializeRequestSchema,
  CompleteRequestSchema,
  SetLevelRequestSchema,
  GetPromptRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ReadResourceRequestSchema,
  SubscribeRequestSchema,
  UnsubscribeRequestSchema,
  CallToolRequestSchema,
  ListToolsRequestSchema
]);
unionType$1([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  InitializedNotificationSchema,
  RootsListChangedNotificationSchema
]);
unionType$1([
  EmptyResultSchema,
  CreateMessageResultSchema,
  ElicitResultSchema,
  ListRootsResultSchema
]);
unionType$1([
  PingRequestSchema,
  CreateMessageRequestSchema,
  ElicitRequestSchema,
  ListRootsRequestSchema
]);
unionType$1([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  LoggingMessageNotificationSchema,
  ResourceUpdatedNotificationSchema,
  ResourceListChangedNotificationSchema,
  ToolListChangedNotificationSchema,
  PromptListChangedNotificationSchema
]);
unionType$1([
  EmptyResultSchema,
  InitializeResultSchema,
  CompleteResultSchema,
  GetPromptResultSchema,
  ListPromptsResultSchema,
  ListResourcesResultSchema,
  ListResourceTemplatesResultSchema,
  ReadResourceResultSchema,
  CallToolResultSchema,
  ListToolsResultSchema
]);
class McpError extends Error {
  constructor(code, message, data2) {
    super(`MCP error ${code}: ${message}`);
    this.code = code;
    this.data = data2;
    this.name = "McpError";
  }
}
const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
class Protocol {
  constructor(_options) {
    this._options = _options;
    this._requestMessageId = 0;
    this._requestHandlers = /* @__PURE__ */ new Map();
    this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
    this._notificationHandlers = /* @__PURE__ */ new Map();
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers = /* @__PURE__ */ new Map();
    this._timeoutInfo = /* @__PURE__ */ new Map();
    this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
    this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
      const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
      controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
    });
    this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
      this._onprogress(notification);
    });
    this.setRequestHandler(
      PingRequestSchema,
      // Automatic pong by default.
      (_request) => ({})
    );
  }
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
    this._timeoutInfo.set(messageId, {
      timeoutId: setTimeout(onTimeout, timeout),
      startTime: Date.now(),
      timeout,
      maxTotalTimeout,
      resetTimeoutOnProgress,
      onTimeout
    });
  }
  _resetTimeout(messageId) {
    const info = this._timeoutInfo.get(messageId);
    if (!info)
      return false;
    const totalElapsed = Date.now() - info.startTime;
    if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
      this._timeoutInfo.delete(messageId);
      throw new McpError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { maxTotalTimeout: info.maxTotalTimeout, totalElapsed });
    }
    clearTimeout(info.timeoutId);
    info.timeoutId = setTimeout(info.onTimeout, info.timeout);
    return true;
  }
  _cleanupTimeout(messageId) {
    const info = this._timeoutInfo.get(messageId);
    if (info) {
      clearTimeout(info.timeoutId);
      this._timeoutInfo.delete(messageId);
    }
  }
  /**
   * Attaches to the given transport, starts it, and starts listening for messages.
   *
   * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
   */
  async connect(transport) {
    var _a3, _b2, _c2;
    this._transport = transport;
    const _onclose = (_a3 = this.transport) === null || _a3 === void 0 ? void 0 : _a3.onclose;
    this._transport.onclose = () => {
      _onclose === null || _onclose === void 0 ? void 0 : _onclose();
      this._onclose();
    };
    const _onerror = (_b2 = this.transport) === null || _b2 === void 0 ? void 0 : _b2.onerror;
    this._transport.onerror = (error) => {
      _onerror === null || _onerror === void 0 ? void 0 : _onerror(error);
      this._onerror(error);
    };
    const _onmessage = (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.onmessage;
    this._transport.onmessage = (message, extra) => {
      _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
      if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
        this._onresponse(message);
      } else if (isJSONRPCRequest(message)) {
        this._onrequest(message, extra);
      } else if (isJSONRPCNotification(message)) {
        this._onnotification(message);
      } else {
        this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
      }
    };
    await this._transport.start();
  }
  _onclose() {
    var _a3;
    const responseHandlers = this._responseHandlers;
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers.clear();
    this._pendingDebouncedNotifications.clear();
    this._transport = void 0;
    (_a3 = this.onclose) === null || _a3 === void 0 ? void 0 : _a3.call(this);
    const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
    for (const handler of responseHandlers.values()) {
      handler(error);
    }
  }
  _onerror(error) {
    var _a3;
    (_a3 = this.onerror) === null || _a3 === void 0 ? void 0 : _a3.call(this, error);
  }
  _onnotification(notification) {
    var _a3;
    const handler = (_a3 = this._notificationHandlers.get(notification.method)) !== null && _a3 !== void 0 ? _a3 : this.fallbackNotificationHandler;
    if (handler === void 0) {
      return;
    }
    Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
  }
  _onrequest(request, extra) {
    var _a3, _b2, _c2, _d2;
    const handler = (_a3 = this._requestHandlers.get(request.method)) !== null && _a3 !== void 0 ? _a3 : this.fallbackRequestHandler;
    if (handler === void 0) {
      (_b2 = this._transport) === null || _b2 === void 0 ? void 0 : _b2.send({
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: ErrorCode.MethodNotFound,
          message: "Method not found"
        }
      }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
      return;
    }
    const abortController = new AbortController();
    this._requestHandlerAbortControllers.set(request.id, abortController);
    const fullExtra = {
      signal: abortController.signal,
      sessionId: (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.sessionId,
      _meta: (_d2 = request.params) === null || _d2 === void 0 ? void 0 : _d2._meta,
      sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
      sendRequest: (r2, resultSchema, options2) => this.request(r2, resultSchema, { ...options2, relatedRequestId: request.id }),
      authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
      requestId: request.id,
      requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
    };
    Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
      var _a4;
      if (abortController.signal.aborted) {
        return;
      }
      return (_a4 = this._transport) === null || _a4 === void 0 ? void 0 : _a4.send({
        result,
        jsonrpc: "2.0",
        id: request.id
      });
    }, (error) => {
      var _a4, _b3;
      if (abortController.signal.aborted) {
        return;
      }
      return (_a4 = this._transport) === null || _a4 === void 0 ? void 0 : _a4.send({
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
          message: (_b3 = error.message) !== null && _b3 !== void 0 ? _b3 : "Internal error"
        }
      });
    }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
      this._requestHandlerAbortControllers.delete(request.id);
    });
  }
  _onprogress(notification) {
    const { progressToken, ...params } = notification.params;
    const messageId = Number(progressToken);
    const handler = this._progressHandlers.get(messageId);
    if (!handler) {
      this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
      return;
    }
    const responseHandler = this._responseHandlers.get(messageId);
    const timeoutInfo = this._timeoutInfo.get(messageId);
    if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
      try {
        this._resetTimeout(messageId);
      } catch (error) {
        responseHandler(error);
        return;
      }
    }
    handler(params);
  }
  _onresponse(response) {
    const messageId = Number(response.id);
    const handler = this._responseHandlers.get(messageId);
    if (handler === void 0) {
      this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
      return;
    }
    this._responseHandlers.delete(messageId);
    this._progressHandlers.delete(messageId);
    this._cleanupTimeout(messageId);
    if (isJSONRPCResponse(response)) {
      handler(response);
    } else {
      const error = new McpError(response.error.code, response.error.message, response.error.data);
      handler(error);
    }
  }
  get transport() {
    return this._transport;
  }
  /**
   * Closes the connection.
   */
  async close() {
    var _a3;
    await ((_a3 = this._transport) === null || _a3 === void 0 ? void 0 : _a3.close());
  }
  /**
   * Sends a request and wait for a response.
   *
   * Do not use this method to emit notifications! Use notification() instead.
   */
  request(request, resultSchema, options2) {
    const { relatedRequestId, resumptionToken, onresumptiontoken } = options2 !== null && options2 !== void 0 ? options2 : {};
    return new Promise((resolve2, reject2) => {
      var _a3, _b2, _c2, _d2, _e2, _f2;
      if (!this._transport) {
        reject2(new Error("Not connected"));
        return;
      }
      if (((_a3 = this._options) === null || _a3 === void 0 ? void 0 : _a3.enforceStrictCapabilities) === true) {
        this.assertCapabilityForMethod(request.method);
      }
      (_b2 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _b2 === void 0 ? void 0 : _b2.throwIfAborted();
      const messageId = this._requestMessageId++;
      const jsonrpcRequest = {
        ...request,
        jsonrpc: "2.0",
        id: messageId
      };
      if (options2 === null || options2 === void 0 ? void 0 : options2.onprogress) {
        this._progressHandlers.set(messageId, options2.onprogress);
        jsonrpcRequest.params = {
          ...request.params,
          _meta: {
            ...((_c2 = request.params) === null || _c2 === void 0 ? void 0 : _c2._meta) || {},
            progressToken: messageId
          }
        };
      }
      const cancel = (reason) => {
        var _a4;
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        (_a4 = this._transport) === null || _a4 === void 0 ? void 0 : _a4.send({
          jsonrpc: "2.0",
          method: "notifications/cancelled",
          params: {
            requestId: messageId,
            reason: String(reason)
          }
        }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
        reject2(reason);
      };
      this._responseHandlers.set(messageId, (response) => {
        var _a4;
        if ((_a4 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _a4 === void 0 ? void 0 : _a4.aborted) {
          return;
        }
        if (response instanceof Error) {
          return reject2(response);
        }
        try {
          const result = resultSchema.parse(response.result);
          resolve2(result);
        } catch (error) {
          reject2(error);
        }
      });
      (_d2 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _d2 === void 0 ? void 0 : _d2.addEventListener("abort", () => {
        var _a4;
        cancel((_a4 = options2 === null || options2 === void 0 ? void 0 : options2.signal) === null || _a4 === void 0 ? void 0 : _a4.reason);
      });
      const timeout = (_e2 = options2 === null || options2 === void 0 ? void 0 : options2.timeout) !== null && _e2 !== void 0 ? _e2 : DEFAULT_REQUEST_TIMEOUT_MSEC;
      const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
      this._setupTimeout(messageId, timeout, options2 === null || options2 === void 0 ? void 0 : options2.maxTotalTimeout, timeoutHandler, (_f2 = options2 === null || options2 === void 0 ? void 0 : options2.resetTimeoutOnProgress) !== null && _f2 !== void 0 ? _f2 : false);
      this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
        this._cleanupTimeout(messageId);
        reject2(error);
      });
    });
  }
  /**
   * Emits a notification, which is a one-way message that does not expect a response.
   */
  async notification(notification, options2) {
    var _a3, _b2;
    if (!this._transport) {
      throw new Error("Not connected");
    }
    this.assertNotificationCapability(notification.method);
    const debouncedMethods = (_b2 = (_a3 = this._options) === null || _a3 === void 0 ? void 0 : _a3.debouncedNotificationMethods) !== null && _b2 !== void 0 ? _b2 : [];
    const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options2 === null || options2 === void 0 ? void 0 : options2.relatedRequestId);
    if (canDebounce) {
      if (this._pendingDebouncedNotifications.has(notification.method)) {
        return;
      }
      this._pendingDebouncedNotifications.add(notification.method);
      Promise.resolve().then(() => {
        var _a4;
        this._pendingDebouncedNotifications.delete(notification.method);
        if (!this._transport) {
          return;
        }
        const jsonrpcNotification2 = {
          ...notification,
          jsonrpc: "2.0"
        };
        (_a4 = this._transport) === null || _a4 === void 0 ? void 0 : _a4.send(jsonrpcNotification2, options2).catch((error) => this._onerror(error));
      });
      return;
    }
    const jsonrpcNotification = {
      ...notification,
      jsonrpc: "2.0"
    };
    await this._transport.send(jsonrpcNotification, options2);
  }
  /**
   * Registers a handler to invoke when this protocol object receives a request with the given method.
   *
   * Note that this will replace any previous request handler for the same method.
   */
  setRequestHandler(requestSchema, handler) {
    const method = requestSchema.shape.method.value;
    this.assertRequestHandlerCapability(method);
    this._requestHandlers.set(method, (request, extra) => {
      return Promise.resolve(handler(requestSchema.parse(request), extra));
    });
  }
  /**
   * Removes the request handler for the given method.
   */
  removeRequestHandler(method) {
    this._requestHandlers.delete(method);
  }
  /**
   * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
   */
  assertCanSetRequestHandler(method) {
    if (this._requestHandlers.has(method)) {
      throw new Error(`A request handler for ${method} already exists, which would be overridden`);
    }
  }
  /**
   * Registers a handler to invoke when this protocol object receives a notification with the given method.
   *
   * Note that this will replace any previous notification handler for the same method.
   */
  setNotificationHandler(notificationSchema, handler) {
    this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
  }
  /**
   * Removes the notification handler for the given method.
   */
  removeNotificationHandler(method) {
    this._notificationHandlers.delete(method);
  }
}
function mergeCapabilities(base2, additional) {
  return Object.entries(additional).reduce((acc, [key2, value]) => {
    if (value && typeof value === "object") {
      acc[key2] = acc[key2] ? { ...acc[key2], ...value } : value;
    } else {
      acc[key2] = value;
    }
    return acc;
  }, { ...base2 });
}
var uri_all$1 = { exports: {} };
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
var uri_all = uri_all$1.exports;
var hasRequiredUri_all;
function requireUri_all() {
  if (hasRequiredUri_all) return uri_all$1.exports;
  hasRequiredUri_all = 1;
  (function(module2, exports) {
    (function(global2, factory) {
      factory(exports);
    })(uri_all, function(exports2) {
      function merge() {
        for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
          sets[_key] = arguments[_key];
        }
        if (sets.length > 1) {
          sets[0] = sets[0].slice(0, -1);
          var xl = sets.length - 1;
          for (var x2 = 1; x2 < xl; ++x2) {
            sets[x2] = sets[x2].slice(1, -1);
          }
          sets[xl] = sets[xl].slice(1);
          return sets.join("");
        } else {
          return sets[0];
        }
      }
      function subexp(str) {
        return "(?:" + str + ")";
      }
      function typeOf(o2) {
        return o2 === void 0 ? "undefined" : o2 === null ? "null" : Object.prototype.toString.call(o2).split(" ").pop().split("]").shift().toLowerCase();
      }
      function toUpperCase(str) {
        return str.toUpperCase();
      }
      function toArray(obj) {
        return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
      }
      function assign(target, source) {
        var obj = target;
        if (source) {
          for (var key2 in source) {
            obj[key2] = source[key2];
          }
        }
        return obj;
      }
      function buildExps(isIRI) {
        var ALPHA$$ = "[A-Za-z]", DIGIT$$ = "[0-9]", HEXDIG$$2 = merge(DIGIT$$, "[A-Fa-f]"), PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$);
        subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*");
        subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*");
        var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+");
        subexp("[vV]" + HEXDIG$$2 + "+\\." + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+");
        subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$)) + "*");
        var PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]"));
        subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+");
        subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*");
        return {
          NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
          NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
          NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
          ESCAPE: new RegExp(merge("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
          UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
          OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"),
          PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"),
          IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
          IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
          //RFC 6874, with relaxed parsing rules
        };
      }
      var URI_PROTOCOL = buildExps(false);
      var IRI_PROTOCOL = buildExps(true);
      var slicedToArray = /* @__PURE__ */ function() {
        function sliceIterator(arr, i2) {
          var _arr = [];
          var _n = true;
          var _d2 = false;
          var _e2 = void 0;
          try {
            for (var _i2 = arr[Symbol.iterator](), _s; !(_n = (_s = _i2.next()).done); _n = true) {
              _arr.push(_s.value);
              if (i2 && _arr.length === i2) break;
            }
          } catch (err) {
            _d2 = true;
            _e2 = err;
          } finally {
            try {
              if (!_n && _i2["return"]) _i2["return"]();
            } finally {
              if (_d2) throw _e2;
            }
          }
          return _arr;
        }
        return function(arr, i2) {
          if (Array.isArray(arr)) {
            return arr;
          } else if (Symbol.iterator in Object(arr)) {
            return sliceIterator(arr, i2);
          } else {
            throw new TypeError("Invalid attempt to destructure non-iterable instance");
          }
        };
      }();
      var toConsumableArray = function(arr) {
        if (Array.isArray(arr)) {
          for (var i2 = 0, arr2 = Array(arr.length); i2 < arr.length; i2++) arr2[i2] = arr[i2];
          return arr2;
        } else {
          return Array.from(arr);
        }
      };
      var maxInt = 2147483647;
      var base2 = 36;
      var tMin = 1;
      var tMax = 26;
      var skew = 38;
      var damp = 700;
      var initialBias = 72;
      var initialN = 128;
      var delimiter = "-";
      var regexPunycode = /^xn--/;
      var regexNonASCII = /[^\0-\x7E]/;
      var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
      var errors = {
        "overflow": "Overflow: input needs wider integers to process",
        "not-basic": "Illegal input >= 0x80 (not a basic code point)",
        "invalid-input": "Invalid input"
      };
      var baseMinusTMin = base2 - tMin;
      var floor2 = Math.floor;
      var stringFromCharCode = String.fromCharCode;
      function error$1(type2) {
        throw new RangeError(errors[type2]);
      }
      function map(array, fn) {
        var result = [];
        var length = array.length;
        while (length--) {
          result[length] = fn(array[length]);
        }
        return result;
      }
      function mapDomain(string, fn) {
        var parts = string.split("@");
        var result = "";
        if (parts.length > 1) {
          result = parts[0] + "@";
          string = parts[1];
        }
        string = string.replace(regexSeparators, ".");
        var labels = string.split(".");
        var encoded = map(labels, fn).join(".");
        return result + encoded;
      }
      function ucs2decode(string) {
        var output = [];
        var counter = 0;
        var length = string.length;
        while (counter < length) {
          var value = string.charCodeAt(counter++);
          if (value >= 55296 && value <= 56319 && counter < length) {
            var extra = string.charCodeAt(counter++);
            if ((extra & 64512) == 56320) {
              output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
            } else {
              output.push(value);
              counter--;
            }
          } else {
            output.push(value);
          }
        }
        return output;
      }
      var ucs2encode = function ucs2encode2(array) {
        return String.fromCodePoint.apply(String, toConsumableArray(array));
      };
      var basicToDigit = function basicToDigit2(codePoint) {
        if (codePoint - 48 < 10) {
          return codePoint - 22;
        }
        if (codePoint - 65 < 26) {
          return codePoint - 65;
        }
        if (codePoint - 97 < 26) {
          return codePoint - 97;
        }
        return base2;
      };
      var digitToBasic = function digitToBasic2(digit, flag) {
        return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
      };
      var adapt = function adapt2(delta, numPoints, firstTime) {
        var k2 = 0;
        delta = firstTime ? floor2(delta / damp) : delta >> 1;
        delta += floor2(delta / numPoints);
        for (
          ;
          /* no initialization */
          delta > baseMinusTMin * tMax >> 1;
          k2 += base2
        ) {
          delta = floor2(delta / baseMinusTMin);
        }
        return floor2(k2 + (baseMinusTMin + 1) * delta / (delta + skew));
      };
      var decode2 = function decode3(input) {
        var output = [];
        var inputLength = input.length;
        var i2 = 0;
        var n2 = initialN;
        var bias = initialBias;
        var basic = input.lastIndexOf(delimiter);
        if (basic < 0) {
          basic = 0;
        }
        for (var j = 0; j < basic; ++j) {
          if (input.charCodeAt(j) >= 128) {
            error$1("not-basic");
          }
          output.push(input.charCodeAt(j));
        }
        for (var index2 = basic > 0 ? basic + 1 : 0; index2 < inputLength; ) {
          var oldi = i2;
          for (
            var w = 1, k2 = base2;
            ;
            /* no condition */
            k2 += base2
          ) {
            if (index2 >= inputLength) {
              error$1("invalid-input");
            }
            var digit = basicToDigit(input.charCodeAt(index2++));
            if (digit >= base2 || digit > floor2((maxInt - i2) / w)) {
              error$1("overflow");
            }
            i2 += digit * w;
            var t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
            if (digit < t2) {
              break;
            }
            var baseMinusT = base2 - t2;
            if (w > floor2(maxInt / baseMinusT)) {
              error$1("overflow");
            }
            w *= baseMinusT;
          }
          var out = output.length + 1;
          bias = adapt(i2 - oldi, out, oldi == 0);
          if (floor2(i2 / out) > maxInt - n2) {
            error$1("overflow");
          }
          n2 += floor2(i2 / out);
          i2 %= out;
          output.splice(i2++, 0, n2);
        }
        return String.fromCodePoint.apply(String, output);
      };
      var encode2 = function encode3(input) {
        var output = [];
        input = ucs2decode(input);
        var inputLength = input.length;
        var n2 = initialN;
        var delta = 0;
        var bias = initialBias;
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = void 0;
        try {
          for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var _currentValue2 = _step.value;
            if (_currentValue2 < 128) {
              output.push(stringFromCharCode(_currentValue2));
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
        var basicLength = output.length;
        var handledCPCount = basicLength;
        if (basicLength) {
          output.push(delimiter);
        }
        while (handledCPCount < inputLength) {
          var m = maxInt;
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = void 0;
          try {
            for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              var currentValue = _step2.value;
              if (currentValue >= n2 && currentValue < m) {
                m = currentValue;
              }
            }
          } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2.return) {
                _iterator2.return();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }
          var handledCPCountPlusOne = handledCPCount + 1;
          if (m - n2 > floor2((maxInt - delta) / handledCPCountPlusOne)) {
            error$1("overflow");
          }
          delta += (m - n2) * handledCPCountPlusOne;
          n2 = m;
          var _iteratorNormalCompletion3 = true;
          var _didIteratorError3 = false;
          var _iteratorError3 = void 0;
          try {
            for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
              var _currentValue = _step3.value;
              if (_currentValue < n2 && ++delta > maxInt) {
                error$1("overflow");
              }
              if (_currentValue == n2) {
                var q = delta;
                for (
                  var k2 = base2;
                  ;
                  /* no condition */
                  k2 += base2
                ) {
                  var t2 = k2 <= bias ? tMin : k2 >= bias + tMax ? tMax : k2 - bias;
                  if (q < t2) {
                    break;
                  }
                  var qMinusT = q - t2;
                  var baseMinusT = base2 - t2;
                  output.push(stringFromCharCode(digitToBasic(t2 + qMinusT % baseMinusT, 0)));
                  q = floor2(qMinusT / baseMinusT);
                }
                output.push(stringFromCharCode(digitToBasic(q, 0)));
                bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
                delta = 0;
                ++handledCPCount;
              }
            }
          } catch (err) {
            _didIteratorError3 = true;
            _iteratorError3 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion3 && _iterator3.return) {
                _iterator3.return();
              }
            } finally {
              if (_didIteratorError3) {
                throw _iteratorError3;
              }
            }
          }
          ++delta;
          ++n2;
        }
        return output.join("");
      };
      var toUnicode = function toUnicode2(input) {
        return mapDomain(input, function(string) {
          return regexPunycode.test(string) ? decode2(string.slice(4).toLowerCase()) : string;
        });
      };
      var toASCII = function toASCII2(input) {
        return mapDomain(input, function(string) {
          return regexNonASCII.test(string) ? "xn--" + encode2(string) : string;
        });
      };
      var punycode = {
        /**
         * A string representing the current Punycode.js version number.
         * @memberOf punycode
         * @type String
         */
        "version": "2.1.0",
        /**
         * An object of methods to convert from JavaScript's internal character
         * representation (UCS-2) to Unicode code points, and back.
         * @see <https://mathiasbynens.be/notes/javascript-encoding>
         * @memberOf punycode
         * @type Object
         */
        "ucs2": {
          "decode": ucs2decode,
          "encode": ucs2encode
        },
        "decode": decode2,
        "encode": encode2,
        "toASCII": toASCII,
        "toUnicode": toUnicode
      };
      var SCHEMES = {};
      function pctEncChar(chr) {
        var c2 = chr.charCodeAt(0);
        var e4 = void 0;
        if (c2 < 16) e4 = "%0" + c2.toString(16).toUpperCase();
        else if (c2 < 128) e4 = "%" + c2.toString(16).toUpperCase();
        else if (c2 < 2048) e4 = "%" + (c2 >> 6 | 192).toString(16).toUpperCase() + "%" + (c2 & 63 | 128).toString(16).toUpperCase();
        else e4 = "%" + (c2 >> 12 | 224).toString(16).toUpperCase() + "%" + (c2 >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c2 & 63 | 128).toString(16).toUpperCase();
        return e4;
      }
      function pctDecChars(str) {
        var newStr = "";
        var i2 = 0;
        var il = str.length;
        while (i2 < il) {
          var c2 = parseInt(str.substr(i2 + 1, 2), 16);
          if (c2 < 128) {
            newStr += String.fromCharCode(c2);
            i2 += 3;
          } else if (c2 >= 194 && c2 < 224) {
            if (il - i2 >= 6) {
              var c22 = parseInt(str.substr(i2 + 4, 2), 16);
              newStr += String.fromCharCode((c2 & 31) << 6 | c22 & 63);
            } else {
              newStr += str.substr(i2, 6);
            }
            i2 += 6;
          } else if (c2 >= 224) {
            if (il - i2 >= 9) {
              var _c2 = parseInt(str.substr(i2 + 4, 2), 16);
              var c3 = parseInt(str.substr(i2 + 7, 2), 16);
              newStr += String.fromCharCode((c2 & 15) << 12 | (_c2 & 63) << 6 | c3 & 63);
            } else {
              newStr += str.substr(i2, 9);
            }
            i2 += 9;
          } else {
            newStr += str.substr(i2, 3);
            i2 += 3;
          }
        }
        return newStr;
      }
      function _normalizeComponentEncoding(components, protocol) {
        function decodeUnreserved2(str) {
          var decStr = pctDecChars(str);
          return !decStr.match(protocol.UNRESERVED) ? str : decStr;
        }
        if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, "");
        if (components.userinfo !== void 0) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.host !== void 0) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.path !== void 0) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.query !== void 0) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        if (components.fragment !== void 0) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
        return components;
      }
      function _stripLeadingZeros(str) {
        return str.replace(/^0*(.*)/, "$1") || "0";
      }
      function _normalizeIPv4(host, protocol) {
        var matches = host.match(protocol.IPV4ADDRESS) || [];
        var _matches = slicedToArray(matches, 2), address = _matches[1];
        if (address) {
          return address.split(".").map(_stripLeadingZeros).join(".");
        } else {
          return host;
        }
      }
      function _normalizeIPv6(host, protocol) {
        var matches = host.match(protocol.IPV6ADDRESS) || [];
        var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
        if (address) {
          var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1];
          var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
          var lastFields = last.split(":").map(_stripLeadingZeros);
          var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
          var fieldCount = isLastFieldIPv4Address ? 7 : 8;
          var lastFieldsStart = lastFields.length - fieldCount;
          var fields = Array(fieldCount);
          for (var x2 = 0; x2 < fieldCount; ++x2) {
            fields[x2] = firstFields[x2] || lastFields[lastFieldsStart + x2] || "";
          }
          if (isLastFieldIPv4Address) {
            fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
          }
          var allZeroFields = fields.reduce(function(acc, field, index2) {
            if (!field || field === "0") {
              var lastLongest = acc[acc.length - 1];
              if (lastLongest && lastLongest.index + lastLongest.length === index2) {
                lastLongest.length++;
              } else {
                acc.push({ index: index2, length: 1 });
              }
            }
            return acc;
          }, []);
          var longestZeroFields = allZeroFields.sort(function(a2, b2) {
            return b2.length - a2.length;
          })[0];
          var newHost = void 0;
          if (longestZeroFields && longestZeroFields.length > 1) {
            var newFirst = fields.slice(0, longestZeroFields.index);
            var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
            newHost = newFirst.join(":") + "::" + newLast.join(":");
          } else {
            newHost = fields.join(":");
          }
          if (zone) {
            newHost += "%" + zone;
          }
          return newHost;
        } else {
          return host;
        }
      }
      var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
      var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0;
      function parse(uriString) {
        var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var components = {};
        var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
        if (options2.reference === "suffix") uriString = (options2.scheme ? options2.scheme + ":" : "") + "//" + uriString;
        var matches = uriString.match(URI_PARSE);
        if (matches) {
          if (NO_MATCH_IS_UNDEFINED) {
            components.scheme = matches[1];
            components.userinfo = matches[3];
            components.host = matches[4];
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = matches[7];
            components.fragment = matches[8];
            if (isNaN(components.port)) {
              components.port = matches[5];
            }
          } else {
            components.scheme = matches[1] || void 0;
            components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0;
            components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0;
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0;
            components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0;
            if (isNaN(components.port)) {
              components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0;
            }
          }
          if (components.host) {
            components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
          }
          if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) {
            components.reference = "same-document";
          } else if (components.scheme === void 0) {
            components.reference = "relative";
          } else if (components.fragment === void 0) {
            components.reference = "absolute";
          } else {
            components.reference = "uri";
          }
          if (options2.reference && options2.reference !== "suffix" && options2.reference !== components.reference) {
            components.error = components.error || "URI is not a " + options2.reference + " reference.";
          }
          var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
          if (!options2.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
            if (components.host && (options2.domainHost || schemeHandler && schemeHandler.domainHost)) {
              try {
                components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
              } catch (e4) {
                components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e4;
              }
            }
            _normalizeComponentEncoding(components, URI_PROTOCOL);
          } else {
            _normalizeComponentEncoding(components, protocol);
          }
          if (schemeHandler && schemeHandler.parse) {
            schemeHandler.parse(components, options2);
          }
        } else {
          components.error = components.error || "URI can not be parsed.";
        }
        return components;
      }
      function _recomposeAuthority(components, options2) {
        var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
        var uriTokens = [];
        if (components.userinfo !== void 0) {
          uriTokens.push(components.userinfo);
          uriTokens.push("@");
        }
        if (components.host !== void 0) {
          uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_2, $1, $2) {
            return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
          }));
        }
        if (typeof components.port === "number" || typeof components.port === "string") {
          uriTokens.push(":");
          uriTokens.push(String(components.port));
        }
        return uriTokens.length ? uriTokens.join("") : void 0;
      }
      var RDS1 = /^\.\.?\//;
      var RDS2 = /^\/\.(\/|$)/;
      var RDS3 = /^\/\.\.(\/|$)/;
      var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
      function removeDotSegments(input) {
        var output = [];
        while (input.length) {
          if (input.match(RDS1)) {
            input = input.replace(RDS1, "");
          } else if (input.match(RDS2)) {
            input = input.replace(RDS2, "/");
          } else if (input.match(RDS3)) {
            input = input.replace(RDS3, "/");
            output.pop();
          } else if (input === "." || input === "..") {
            input = "";
          } else {
            var im = input.match(RDS5);
            if (im) {
              var s2 = im[0];
              input = input.slice(s2.length);
              output.push(s2);
            } else {
              throw new Error("Unexpected dot segment condition");
            }
          }
        }
        return output.join("");
      }
      function serialize2(components) {
        var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
        var protocol = options2.iri ? IRI_PROTOCOL : URI_PROTOCOL;
        var uriTokens = [];
        var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
        if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options2);
        if (components.host) {
          if (protocol.IPV6ADDRESS.test(components.host)) ;
          else if (options2.domainHost || schemeHandler && schemeHandler.domainHost) {
            try {
              components.host = !options2.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
            } catch (e4) {
              components.error = components.error || "Host's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e4;
            }
          }
        }
        _normalizeComponentEncoding(components, protocol);
        if (options2.reference !== "suffix" && components.scheme) {
          uriTokens.push(components.scheme);
          uriTokens.push(":");
        }
        var authority = _recomposeAuthority(components, options2);
        if (authority !== void 0) {
          if (options2.reference !== "suffix") {
            uriTokens.push("//");
          }
          uriTokens.push(authority);
          if (components.path && components.path.charAt(0) !== "/") {
            uriTokens.push("/");
          }
        }
        if (components.path !== void 0) {
          var s2 = components.path;
          if (!options2.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
            s2 = removeDotSegments(s2);
          }
          if (authority === void 0) {
            s2 = s2.replace(/^\/\//, "/%2F");
          }
          uriTokens.push(s2);
        }
        if (components.query !== void 0) {
          uriTokens.push("?");
          uriTokens.push(components.query);
        }
        if (components.fragment !== void 0) {
          uriTokens.push("#");
          uriTokens.push(components.fragment);
        }
        return uriTokens.join("");
      }
      function resolveComponents(base3, relative) {
        var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var skipNormalization = arguments[3];
        var target = {};
        if (!skipNormalization) {
          base3 = parse(serialize2(base3, options2), options2);
          relative = parse(serialize2(relative, options2), options2);
        }
        options2 = options2 || {};
        if (!options2.tolerant && relative.scheme) {
          target.scheme = relative.scheme;
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
            target.userinfo = relative.userinfo;
            target.host = relative.host;
            target.port = relative.port;
            target.path = removeDotSegments(relative.path || "");
            target.query = relative.query;
          } else {
            if (!relative.path) {
              target.path = base3.path;
              if (relative.query !== void 0) {
                target.query = relative.query;
              } else {
                target.query = base3.query;
              }
            } else {
              if (relative.path.charAt(0) === "/") {
                target.path = removeDotSegments(relative.path);
              } else {
                if ((base3.userinfo !== void 0 || base3.host !== void 0 || base3.port !== void 0) && !base3.path) {
                  target.path = "/" + relative.path;
                } else if (!base3.path) {
                  target.path = relative.path;
                } else {
                  target.path = base3.path.slice(0, base3.path.lastIndexOf("/") + 1) + relative.path;
                }
                target.path = removeDotSegments(target.path);
              }
              target.query = relative.query;
            }
            target.userinfo = base3.userinfo;
            target.host = base3.host;
            target.port = base3.port;
          }
          target.scheme = base3.scheme;
        }
        target.fragment = relative.fragment;
        return target;
      }
      function resolve2(baseURI, relativeURI, options2) {
        var schemelessOptions = assign({ scheme: "null" }, options2);
        return serialize2(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
      }
      function normalize(uri2, options2) {
        if (typeof uri2 === "string") {
          uri2 = serialize2(parse(uri2, options2), options2);
        } else if (typeOf(uri2) === "object") {
          uri2 = parse(serialize2(uri2, options2), options2);
        }
        return uri2;
      }
      function equal(uriA, uriB, options2) {
        if (typeof uriA === "string") {
          uriA = serialize2(parse(uriA, options2), options2);
        } else if (typeOf(uriA) === "object") {
          uriA = serialize2(uriA, options2);
        }
        if (typeof uriB === "string") {
          uriB = serialize2(parse(uriB, options2), options2);
        } else if (typeOf(uriB) === "object") {
          uriB = serialize2(uriB, options2);
        }
        return uriA === uriB;
      }
      function escapeComponent(str, options2) {
        return str && str.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
      }
      function unescapeComponent(str, options2) {
        return str && str.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
      }
      var handler = {
        scheme: "http",
        domainHost: true,
        parse: function parse2(components, options2) {
          if (!components.host) {
            components.error = components.error || "HTTP URIs must have a host.";
          }
          return components;
        },
        serialize: function serialize3(components, options2) {
          var secure = String(components.scheme).toLowerCase() === "https";
          if (components.port === (secure ? 443 : 80) || components.port === "") {
            components.port = void 0;
          }
          if (!components.path) {
            components.path = "/";
          }
          return components;
        }
      };
      var handler$1 = {
        scheme: "https",
        domainHost: handler.domainHost,
        parse: handler.parse,
        serialize: handler.serialize
      };
      function isSecure(wsComponents) {
        return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
      }
      var handler$2 = {
        scheme: "ws",
        domainHost: true,
        parse: function parse2(components, options2) {
          var wsComponents = components;
          wsComponents.secure = isSecure(wsComponents);
          wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
          wsComponents.path = void 0;
          wsComponents.query = void 0;
          return wsComponents;
        },
        serialize: function serialize3(wsComponents, options2) {
          if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
            wsComponents.port = void 0;
          }
          if (typeof wsComponents.secure === "boolean") {
            wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
            wsComponents.secure = void 0;
          }
          if (wsComponents.resourceName) {
            var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
            wsComponents.path = path && path !== "/" ? path : void 0;
            wsComponents.query = query;
            wsComponents.resourceName = void 0;
          }
          wsComponents.fragment = void 0;
          return wsComponents;
        }
      };
      var handler$3 = {
        scheme: "wss",
        domainHost: handler$2.domainHost,
        parse: handler$2.parse,
        serialize: handler$2.serialize
      };
      var O2 = {};
      var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]";
      var HEXDIG$$ = "[0-9A-Fa-f]";
      var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$));
      var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
      var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
      var VCHAR$$ = merge(QTEXT$$, '[\\"\\\\]');
      var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
      var UNRESERVED = new RegExp(UNRESERVED$$, "g");
      var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
      var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
      var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
      var NOT_HFVALUE = NOT_HFNAME;
      function decodeUnreserved(str) {
        var decStr = pctDecChars(str);
        return !decStr.match(UNRESERVED) ? str : decStr;
      }
      var handler$4 = {
        scheme: "mailto",
        parse: function parse$$1(components, options2) {
          var mailtoComponents = components;
          var to2 = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
          mailtoComponents.path = void 0;
          if (mailtoComponents.query) {
            var unknownHeaders = false;
            var headers = {};
            var hfields = mailtoComponents.query.split("&");
            for (var x2 = 0, xl = hfields.length; x2 < xl; ++x2) {
              var hfield = hfields[x2].split("=");
              switch (hfield[0]) {
                case "to":
                  var toAddrs = hfield[1].split(",");
                  for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                    to2.push(toAddrs[_x]);
                  }
                  break;
                case "subject":
                  mailtoComponents.subject = unescapeComponent(hfield[1], options2);
                  break;
                case "body":
                  mailtoComponents.body = unescapeComponent(hfield[1], options2);
                  break;
                default:
                  unknownHeaders = true;
                  headers[unescapeComponent(hfield[0], options2)] = unescapeComponent(hfield[1], options2);
                  break;
              }
            }
            if (unknownHeaders) mailtoComponents.headers = headers;
          }
          mailtoComponents.query = void 0;
          for (var _x2 = 0, _xl2 = to2.length; _x2 < _xl2; ++_x2) {
            var addr = to2[_x2].split("@");
            addr[0] = unescapeComponent(addr[0]);
            if (!options2.unicodeSupport) {
              try {
                addr[1] = punycode.toASCII(unescapeComponent(addr[1], options2).toLowerCase());
              } catch (e4) {
                mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e4;
              }
            } else {
              addr[1] = unescapeComponent(addr[1], options2).toLowerCase();
            }
            to2[_x2] = addr.join("@");
          }
          return mailtoComponents;
        },
        serialize: function serialize$$1(mailtoComponents, options2) {
          var components = mailtoComponents;
          var to2 = toArray(mailtoComponents.to);
          if (to2) {
            for (var x2 = 0, xl = to2.length; x2 < xl; ++x2) {
              var toAddr = String(to2[x2]);
              var atIdx = toAddr.lastIndexOf("@");
              var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
              var domain = toAddr.slice(atIdx + 1);
              try {
                domain = !options2.iri ? punycode.toASCII(unescapeComponent(domain, options2).toLowerCase()) : punycode.toUnicode(domain);
              } catch (e4) {
                components.error = components.error || "Email address's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e4;
              }
              to2[x2] = localPart + "@" + domain;
            }
            components.path = to2.join(",");
          }
          var headers = mailtoComponents.headers = mailtoComponents.headers || {};
          if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
          if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
          var fields = [];
          for (var name in headers) {
            if (headers[name] !== O2[name]) {
              fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
            }
          }
          if (fields.length) {
            components.query = fields.join("&");
          }
          return components;
        }
      };
      var URN_PARSE = /^([^\:]+)\:(.*)/;
      var handler$5 = {
        scheme: "urn",
        parse: function parse$$1(components, options2) {
          var matches = components.path && components.path.match(URN_PARSE);
          var urnComponents = components;
          if (matches) {
            var scheme = options2.scheme || urnComponents.scheme || "urn";
            var nid = matches[1].toLowerCase();
            var nss = matches[2];
            var urnScheme = scheme + ":" + (options2.nid || nid);
            var schemeHandler = SCHEMES[urnScheme];
            urnComponents.nid = nid;
            urnComponents.nss = nss;
            urnComponents.path = void 0;
            if (schemeHandler) {
              urnComponents = schemeHandler.parse(urnComponents, options2);
            }
          } else {
            urnComponents.error = urnComponents.error || "URN can not be parsed.";
          }
          return urnComponents;
        },
        serialize: function serialize$$1(urnComponents, options2) {
          var scheme = options2.scheme || urnComponents.scheme || "urn";
          var nid = urnComponents.nid;
          var urnScheme = scheme + ":" + (options2.nid || nid);
          var schemeHandler = SCHEMES[urnScheme];
          if (schemeHandler) {
            urnComponents = schemeHandler.serialize(urnComponents, options2);
          }
          var uriComponents = urnComponents;
          var nss = urnComponents.nss;
          uriComponents.path = (nid || options2.nid) + ":" + nss;
          return uriComponents;
        }
      };
      var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
      var handler$6 = {
        scheme: "urn:uuid",
        parse: function parse2(urnComponents, options2) {
          var uuidComponents = urnComponents;
          uuidComponents.uuid = uuidComponents.nss;
          uuidComponents.nss = void 0;
          if (!options2.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
            uuidComponents.error = uuidComponents.error || "UUID is not valid.";
          }
          return uuidComponents;
        },
        serialize: function serialize3(uuidComponents, options2) {
          var urnComponents = uuidComponents;
          urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
          return urnComponents;
        }
      };
      SCHEMES[handler.scheme] = handler;
      SCHEMES[handler$1.scheme] = handler$1;
      SCHEMES[handler$2.scheme] = handler$2;
      SCHEMES[handler$3.scheme] = handler$3;
      SCHEMES[handler$4.scheme] = handler$4;
      SCHEMES[handler$5.scheme] = handler$5;
      SCHEMES[handler$6.scheme] = handler$6;
      exports2.SCHEMES = SCHEMES;
      exports2.pctEncChar = pctEncChar;
      exports2.pctDecChars = pctDecChars;
      exports2.parse = parse;
      exports2.removeDotSegments = removeDotSegments;
      exports2.serialize = serialize2;
      exports2.resolveComponents = resolveComponents;
      exports2.resolve = resolve2;
      exports2.normalize = normalize;
      exports2.equal = equal;
      exports2.escapeComponent = escapeComponent;
      exports2.unescapeComponent = unescapeComponent;
      Object.defineProperty(exports2, "__esModule", { value: true });
    });
  })(uri_all$1, uri_all$1.exports);
  return uri_all$1.exports;
}
var fastDeepEqual;
var hasRequiredFastDeepEqual;
function requireFastDeepEqual() {
  if (hasRequiredFastDeepEqual) return fastDeepEqual;
  hasRequiredFastDeepEqual = 1;
  fastDeepEqual = function equal(a2, b2) {
    if (a2 === b2) return true;
    if (a2 && b2 && typeof a2 == "object" && typeof b2 == "object") {
      if (a2.constructor !== b2.constructor) return false;
      var length, i2, keys;
      if (Array.isArray(a2)) {
        length = a2.length;
        if (length != b2.length) return false;
        for (i2 = length; i2-- !== 0; )
          if (!equal(a2[i2], b2[i2])) return false;
        return true;
      }
      if (a2.constructor === RegExp) return a2.source === b2.source && a2.flags === b2.flags;
      if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b2.valueOf();
      if (a2.toString !== Object.prototype.toString) return a2.toString() === b2.toString();
      keys = Object.keys(a2);
      length = keys.length;
      if (length !== Object.keys(b2).length) return false;
      for (i2 = length; i2-- !== 0; )
        if (!Object.prototype.hasOwnProperty.call(b2, keys[i2])) return false;
      for (i2 = length; i2-- !== 0; ) {
        var key2 = keys[i2];
        if (!equal(a2[key2], b2[key2])) return false;
      }
      return true;
    }
    return a2 !== a2 && b2 !== b2;
  };
  return fastDeepEqual;
}
var ucs2length;
var hasRequiredUcs2length;
function requireUcs2length() {
  if (hasRequiredUcs2length) return ucs2length;
  hasRequiredUcs2length = 1;
  ucs2length = function ucs2length2(str) {
    var length = 0, len = str.length, pos = 0, value;
    while (pos < len) {
      length++;
      value = str.charCodeAt(pos++);
      if (value >= 55296 && value <= 56319 && pos < len) {
        value = str.charCodeAt(pos);
        if ((value & 64512) == 56320) pos++;
      }
    }
    return length;
  };
  return ucs2length;
}
var util$2;
var hasRequiredUtil;
function requireUtil() {
  if (hasRequiredUtil) return util$2;
  hasRequiredUtil = 1;
  util$2 = {
    copy: copy2,
    checkDataType,
    checkDataTypes,
    coerceToTypes,
    toHash,
    getProperty,
    escapeQuotes,
    equal: requireFastDeepEqual(),
    ucs2length: requireUcs2length(),
    varOccurences,
    varReplace,
    schemaHasRules,
    schemaHasRulesExcept,
    schemaUnknownRules,
    toQuotedString,
    getPathExpr,
    getPath: getPath2,
    getData,
    unescapeFragment,
    unescapeJsonPointer,
    escapeFragment,
    escapeJsonPointer
  };
  function copy2(o2, to2) {
    to2 = to2 || {};
    for (var key2 in o2) to2[key2] = o2[key2];
    return to2;
  }
  function checkDataType(dataType, data2, strictNumbers, negate) {
    var EQUAL = negate ? " !== " : " === ", AND = negate ? " || " : " && ", OK2 = negate ? "!" : "", NOT = negate ? "" : "!";
    switch (dataType) {
      case "null":
        return data2 + EQUAL + "null";
      case "array":
        return OK2 + "Array.isArray(" + data2 + ")";
      case "object":
        return "(" + OK2 + data2 + AND + "typeof " + data2 + EQUAL + '"object"' + AND + NOT + "Array.isArray(" + data2 + "))";
      case "integer":
        return "(typeof " + data2 + EQUAL + '"number"' + AND + NOT + "(" + data2 + " % 1)" + AND + data2 + EQUAL + data2 + (strictNumbers ? AND + OK2 + "isFinite(" + data2 + ")" : "") + ")";
      case "number":
        return "(typeof " + data2 + EQUAL + '"' + dataType + '"' + (strictNumbers ? AND + OK2 + "isFinite(" + data2 + ")" : "") + ")";
      default:
        return "typeof " + data2 + EQUAL + '"' + dataType + '"';
    }
  }
  function checkDataTypes(dataTypes, data2, strictNumbers) {
    switch (dataTypes.length) {
      case 1:
        return checkDataType(dataTypes[0], data2, strictNumbers, true);
      default:
        var code = "";
        var types = toHash(dataTypes);
        if (types.array && types.object) {
          code = types.null ? "(" : "(!" + data2 + " || ";
          code += "typeof " + data2 + ' !== "object")';
          delete types.null;
          delete types.array;
          delete types.object;
        }
        if (types.number) delete types.integer;
        for (var t2 in types)
          code += (code ? " && " : "") + checkDataType(t2, data2, strictNumbers, true);
        return code;
    }
  }
  var COERCE_TO_TYPES = toHash(["string", "number", "integer", "boolean", "null"]);
  function coerceToTypes(optionCoerceTypes, dataTypes) {
    if (Array.isArray(dataTypes)) {
      var types = [];
      for (var i2 = 0; i2 < dataTypes.length; i2++) {
        var t2 = dataTypes[i2];
        if (COERCE_TO_TYPES[t2]) types[types.length] = t2;
        else if (optionCoerceTypes === "array" && t2 === "array") types[types.length] = t2;
      }
      if (types.length) return types;
    } else if (COERCE_TO_TYPES[dataTypes]) {
      return [dataTypes];
    } else if (optionCoerceTypes === "array" && dataTypes === "array") {
      return ["array"];
    }
  }
  function toHash(arr) {
    var hash2 = {};
    for (var i2 = 0; i2 < arr.length; i2++) hash2[arr[i2]] = true;
    return hash2;
  }
  var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  var SINGLE_QUOTE = /'|\\/g;
  function getProperty(key2) {
    return typeof key2 == "number" ? "[" + key2 + "]" : IDENTIFIER.test(key2) ? "." + key2 : "['" + escapeQuotes(key2) + "']";
  }
  function escapeQuotes(str) {
    return str.replace(SINGLE_QUOTE, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\f/g, "\\f").replace(/\t/g, "\\t");
  }
  function varOccurences(str, dataVar) {
    dataVar += "[^0-9]";
    var matches = str.match(new RegExp(dataVar, "g"));
    return matches ? matches.length : 0;
  }
  function varReplace(str, dataVar, expr) {
    dataVar += "([^0-9])";
    expr = expr.replace(/\$/g, "$$$$");
    return str.replace(new RegExp(dataVar, "g"), expr + "$1");
  }
  function schemaHasRules(schema, rules2) {
    if (typeof schema == "boolean") return !schema;
    for (var key2 in schema) if (rules2[key2]) return true;
  }
  function schemaHasRulesExcept(schema, rules2, exceptKeyword) {
    if (typeof schema == "boolean") return !schema && exceptKeyword != "not";
    for (var key2 in schema) if (key2 != exceptKeyword && rules2[key2]) return true;
  }
  function schemaUnknownRules(schema, rules2) {
    if (typeof schema == "boolean") return;
    for (var key2 in schema) if (!rules2[key2]) return key2;
  }
  function toQuotedString(str) {
    return "'" + escapeQuotes(str) + "'";
  }
  function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
    var path = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
    return joinPaths(currentPath, path);
  }
  function getPath2(currentPath, prop, jsonPointers) {
    var path = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
    return joinPaths(currentPath, path);
  }
  var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
  var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  function getData($data, lvl, paths) {
    var up, jsonPointer, data2, matches;
    if ($data === "") return "rootData";
    if ($data[0] == "/") {
      if (!JSON_POINTER.test($data)) throw new Error("Invalid JSON-pointer: " + $data);
      jsonPointer = $data;
      data2 = "rootData";
    } else {
      matches = $data.match(RELATIVE_JSON_POINTER);
      if (!matches) throw new Error("Invalid JSON-pointer: " + $data);
      up = +matches[1];
      jsonPointer = matches[2];
      if (jsonPointer == "#") {
        if (up >= lvl) throw new Error("Cannot access property/index " + up + " levels up, current level is " + lvl);
        return paths[lvl - up];
      }
      if (up > lvl) throw new Error("Cannot access data " + up + " levels up, current level is " + lvl);
      data2 = "data" + (lvl - up || "");
      if (!jsonPointer) return data2;
    }
    var expr = data2;
    var segments = jsonPointer.split("/");
    for (var i2 = 0; i2 < segments.length; i2++) {
      var segment = segments[i2];
      if (segment) {
        data2 += getProperty(unescapeJsonPointer(segment));
        expr += " && " + data2;
      }
    }
    return expr;
  }
  function joinPaths(a2, b2) {
    if (a2 == '""') return b2;
    return (a2 + " + " + b2).replace(/([^\\])' \+ '/g, "$1");
  }
  function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
  }
  function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
  }
  function escapeJsonPointer(str) {
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
  }
  return util$2;
}
var schema_obj;
var hasRequiredSchema_obj;
function requireSchema_obj() {
  if (hasRequiredSchema_obj) return schema_obj;
  hasRequiredSchema_obj = 1;
  var util2 = requireUtil();
  schema_obj = SchemaObject;
  function SchemaObject(obj) {
    util2.copy(obj, this);
  }
  return schema_obj;
}
var jsonSchemaTraverse = { exports: {} };
var hasRequiredJsonSchemaTraverse;
function requireJsonSchemaTraverse() {
  if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports;
  hasRequiredJsonSchemaTraverse = 1;
  var traverse = jsonSchemaTraverse.exports = function(schema, opts, cb) {
    if (typeof opts == "function") {
      cb = opts;
      opts = {};
    }
    cb = opts.cb || cb;
    var pre = typeof cb == "function" ? cb : cb.pre || function() {
    };
    var post = cb.post || function() {
    };
    _traverse(opts, pre, post, schema, "", schema);
  };
  traverse.keywords = {
    additionalItems: true,
    items: true,
    contains: true,
    additionalProperties: true,
    propertyNames: true,
    not: true
  };
  traverse.arrayKeywords = {
    items: true,
    allOf: true,
    anyOf: true,
    oneOf: true
  };
  traverse.propsKeywords = {
    definitions: true,
    properties: true,
    patternProperties: true,
    dependencies: true
  };
  traverse.skipKeywords = {
    default: true,
    enum: true,
    const: true,
    required: true,
    maximum: true,
    minimum: true,
    exclusiveMaximum: true,
    exclusiveMinimum: true,
    multipleOf: true,
    maxLength: true,
    minLength: true,
    pattern: true,
    format: true,
    maxItems: true,
    minItems: true,
    uniqueItems: true,
    maxProperties: true,
    minProperties: true
  };
  function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (schema && typeof schema == "object" && !Array.isArray(schema)) {
      pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      for (var key2 in schema) {
        var sch = schema[key2];
        if (Array.isArray(sch)) {
          if (key2 in traverse.arrayKeywords) {
            for (var i2 = 0; i2 < sch.length; i2++)
              _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key2 + "/" + i2, rootSchema, jsonPtr, key2, schema, i2);
          }
        } else if (key2 in traverse.propsKeywords) {
          if (sch && typeof sch == "object") {
            for (var prop in sch)
              _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key2 + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key2, schema, prop);
          }
        } else if (key2 in traverse.keywords || opts.allKeys && !(key2 in traverse.skipKeywords)) {
          _traverse(opts, pre, post, sch, jsonPtr + "/" + key2, rootSchema, jsonPtr, key2, schema);
        }
      }
      post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    }
  }
  function escapeJsonPtr(str) {
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  return jsonSchemaTraverse.exports;
}
var resolve_1;
var hasRequiredResolve;
function requireResolve() {
  if (hasRequiredResolve) return resolve_1;
  hasRequiredResolve = 1;
  var URI = requireUri_all(), equal = requireFastDeepEqual(), util2 = requireUtil(), SchemaObject = requireSchema_obj(), traverse = requireJsonSchemaTraverse();
  resolve_1 = resolve2;
  resolve2.normalizeId = normalizeId;
  resolve2.fullPath = getFullPath;
  resolve2.url = resolveUrl;
  resolve2.ids = resolveIds;
  resolve2.inlineRef = inlineRef;
  resolve2.schema = resolveSchema;
  function resolve2(compile, root, ref2) {
    var refVal = this._refs[ref2];
    if (typeof refVal == "string") {
      if (this._refs[refVal]) refVal = this._refs[refVal];
      else return resolve2.call(this, compile, root, refVal);
    }
    refVal = refVal || this._schemas[ref2];
    if (refVal instanceof SchemaObject) {
      return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal);
    }
    var res = resolveSchema.call(this, root, ref2);
    var schema, v2, baseId;
    if (res) {
      schema = res.schema;
      root = res.root;
      baseId = res.baseId;
    }
    if (schema instanceof SchemaObject) {
      v2 = schema.validate || compile.call(this, schema.schema, root, void 0, baseId);
    } else if (schema !== void 0) {
      v2 = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, void 0, baseId);
    }
    return v2;
  }
  function resolveSchema(root, ref2) {
    var p2 = URI.parse(ref2), refPath = _getFullPath(p2), baseId = getFullPath(this._getId(root.schema));
    if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
      var id = normalizeId(refPath);
      var refVal = this._refs[id];
      if (typeof refVal == "string") {
        return resolveRecursive.call(this, root, refVal, p2);
      } else if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        root = refVal;
      } else {
        refVal = this._schemas[id];
        if (refVal instanceof SchemaObject) {
          if (!refVal.validate) this._compile(refVal);
          if (id == normalizeId(ref2))
            return { schema: refVal, root, baseId };
          root = refVal;
        } else {
          return;
        }
      }
      if (!root.schema) return;
      baseId = getFullPath(this._getId(root.schema));
    }
    return getJsonPointer.call(this, p2, baseId, root.schema, root);
  }
  function resolveRecursive(root, ref2, parsedRef) {
    var res = resolveSchema.call(this, root, ref2);
    if (res) {
      var schema = res.schema;
      var baseId = res.baseId;
      root = res.root;
      var id = this._getId(schema);
      if (id) baseId = resolveUrl(baseId, id);
      return getJsonPointer.call(this, parsedRef, baseId, schema, root);
    }
  }
  var PREVENT_SCOPE_CHANGE = util2.toHash(["properties", "patternProperties", "enum", "dependencies", "definitions"]);
  function getJsonPointer(parsedRef, baseId, schema, root) {
    parsedRef.fragment = parsedRef.fragment || "";
    if (parsedRef.fragment.slice(0, 1) != "/") return;
    var parts = parsedRef.fragment.split("/");
    for (var i2 = 1; i2 < parts.length; i2++) {
      var part = parts[i2];
      if (part) {
        part = util2.unescapeFragment(part);
        schema = schema[part];
        if (schema === void 0) break;
        var id;
        if (!PREVENT_SCOPE_CHANGE[part]) {
          id = this._getId(schema);
          if (id) baseId = resolveUrl(baseId, id);
          if (schema.$ref) {
            var $ref = resolveUrl(baseId, schema.$ref);
            var res = resolveSchema.call(this, root, $ref);
            if (res) {
              schema = res.schema;
              root = res.root;
              baseId = res.baseId;
            }
          }
        }
      }
    }
    if (schema !== void 0 && schema !== root.schema)
      return { schema, root, baseId };
  }
  var SIMPLE_INLINED = util2.toHash([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum"
  ]);
  function inlineRef(schema, limit) {
    if (limit === false) return false;
    if (limit === void 0 || limit === true) return checkNoRef(schema);
    else if (limit) return countKeys(schema) <= limit;
  }
  function checkNoRef(schema) {
    var item;
    if (Array.isArray(schema)) {
      for (var i2 = 0; i2 < schema.length; i2++) {
        item = schema[i2];
        if (typeof item == "object" && !checkNoRef(item)) return false;
      }
    } else {
      for (var key2 in schema) {
        if (key2 == "$ref") return false;
        item = schema[key2];
        if (typeof item == "object" && !checkNoRef(item)) return false;
      }
    }
    return true;
  }
  function countKeys(schema) {
    var count = 0, item;
    if (Array.isArray(schema)) {
      for (var i2 = 0; i2 < schema.length; i2++) {
        item = schema[i2];
        if (typeof item == "object") count += countKeys(item);
        if (count == Infinity) return Infinity;
      }
    } else {
      for (var key2 in schema) {
        if (key2 == "$ref") return Infinity;
        if (SIMPLE_INLINED[key2]) {
          count++;
        } else {
          item = schema[key2];
          if (typeof item == "object") count += countKeys(item) + 1;
          if (count == Infinity) return Infinity;
        }
      }
    }
    return count;
  }
  function getFullPath(id, normalize) {
    if (normalize !== false) id = normalizeId(id);
    var p2 = URI.parse(id);
    return _getFullPath(p2);
  }
  function _getFullPath(p2) {
    return URI.serialize(p2).split("#")[0] + "#";
  }
  var TRAILING_SLASH_HASH = /#\/?$/;
  function normalizeId(id) {
    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
  }
  function resolveUrl(baseId, id) {
    id = normalizeId(id);
    return URI.resolve(baseId, id);
  }
  function resolveIds(schema) {
    var schemaId = normalizeId(this._getId(schema));
    var baseIds = { "": schemaId };
    var fullPaths = { "": getFullPath(schemaId, false) };
    var localRefs = {};
    var self2 = this;
    traverse(schema, { allKeys: true }, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
      if (jsonPtr === "") return;
      var id = self2._getId(sch);
      var baseId = baseIds[parentJsonPtr];
      var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword;
      if (keyIndex !== void 0)
        fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : util2.escapeFragment(keyIndex));
      if (typeof id == "string") {
        id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
        var refVal = self2._refs[id];
        if (typeof refVal == "string") refVal = self2._refs[refVal];
        if (refVal && refVal.schema) {
          if (!equal(sch, refVal.schema))
            throw new Error('id "' + id + '" resolves to more than one schema');
        } else if (id != normalizeId(fullPath)) {
          if (id[0] == "#") {
            if (localRefs[id] && !equal(sch, localRefs[id]))
              throw new Error('id "' + id + '" resolves to more than one schema');
            localRefs[id] = sch;
          } else {
            self2._refs[id] = fullPath;
          }
        }
      }
      baseIds[jsonPtr] = baseId;
      fullPaths[jsonPtr] = fullPath;
    });
    return localRefs;
  }
  return resolve_1;
}
var error_classes;
var hasRequiredError_classes;
function requireError_classes() {
  if (hasRequiredError_classes) return error_classes;
  hasRequiredError_classes = 1;
  var resolve2 = requireResolve();
  error_classes = {
    Validation: errorSubclass(ValidationError),
    MissingRef: errorSubclass(MissingRefError)
  };
  function ValidationError(errors) {
    this.message = "validation failed";
    this.errors = errors;
    this.ajv = this.validation = true;
  }
  MissingRefError.message = function(baseId, ref2) {
    return "can't resolve reference " + ref2 + " from id " + baseId;
  };
  function MissingRefError(baseId, ref2, message) {
    this.message = message || MissingRefError.message(baseId, ref2);
    this.missingRef = resolve2.url(baseId, ref2);
    this.missingSchema = resolve2.normalizeId(resolve2.fullPath(this.missingRef));
  }
  function errorSubclass(Subclass) {
    Subclass.prototype = Object.create(Error.prototype);
    Subclass.prototype.constructor = Subclass;
    return Subclass;
  }
  return error_classes;
}
var fastJsonStableStringify;
var hasRequiredFastJsonStableStringify;
function requireFastJsonStableStringify() {
  if (hasRequiredFastJsonStableStringify) return fastJsonStableStringify;
  hasRequiredFastJsonStableStringify = 1;
  fastJsonStableStringify = function(data2, opts) {
    if (!opts) opts = {};
    if (typeof opts === "function") opts = { cmp: opts };
    var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false;
    var cmp = opts.cmp && /* @__PURE__ */ function(f2) {
      return function(node2) {
        return function(a2, b2) {
          var aobj = { key: a2, value: node2[a2] };
          var bobj = { key: b2, value: node2[b2] };
          return f2(aobj, bobj);
        };
      };
    }(opts.cmp);
    var seen2 = [];
    return function stringify(node2) {
      if (node2 && node2.toJSON && typeof node2.toJSON === "function") {
        node2 = node2.toJSON();
      }
      if (node2 === void 0) return;
      if (typeof node2 == "number") return isFinite(node2) ? "" + node2 : "null";
      if (typeof node2 !== "object") return JSON.stringify(node2);
      var i2, out;
      if (Array.isArray(node2)) {
        out = "[";
        for (i2 = 0; i2 < node2.length; i2++) {
          if (i2) out += ",";
          out += stringify(node2[i2]) || "null";
        }
        return out + "]";
      }
      if (node2 === null) return "null";
      if (seen2.indexOf(node2) !== -1) {
        if (cycles) return JSON.stringify("__cycle__");
        throw new TypeError("Converting circular structure to JSON");
      }
      var seenIndex = seen2.push(node2) - 1;
      var keys = Object.keys(node2).sort(cmp && cmp(node2));
      out = "";
      for (i2 = 0; i2 < keys.length; i2++) {
        var key2 = keys[i2];
        var value = stringify(node2[key2]);
        if (!value) continue;
        if (out) out += ",";
        out += JSON.stringify(key2) + ":" + value;
      }
      seen2.splice(seenIndex, 1);
      return "{" + out + "}";
    }(data2);
  };
  return fastJsonStableStringify;
}
var validate;
var hasRequiredValidate;
function requireValidate() {
  if (hasRequiredValidate) return validate;
  hasRequiredValidate = 1;
  validate = function generate_validate(it, $keyword, $ruleType) {
    var out = "";
    var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, "$ref"), $id2 = it.self._getId(it.schema);
    if (it.opts.strictKeywords) {
      var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
      if ($unknownKwd) {
        var $keywordsMsg = "unknown keyword: " + $unknownKwd;
        if (it.opts.strictKeywords === "log") it.logger.warn($keywordsMsg);
        else throw new Error($keywordsMsg);
      }
    }
    if (it.isTop) {
      out += " var validate = ";
      if ($async) {
        it.async = true;
        out += "async ";
      }
      out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";
      if ($id2 && (it.opts.sourceCode || it.opts.processCode)) {
        out += " " + ("/*# sourceURL=" + $id2 + " */") + " ";
      }
    }
    if (typeof it.schema == "boolean" || !($refKeywords || it.schema.$ref)) {
      var $keyword = "false schema";
      var $lvl = it.level;
      var $dataLvl = it.dataLevel;
      var $schema2 = it.schema[$keyword];
      var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
      var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
      var $breakOnError = !it.opts.allErrors;
      var $errorKeyword;
      var $data = "data" + ($dataLvl || "");
      var $valid = "valid" + $lvl;
      if (it.schema === false) {
        if (it.isTop) {
          $breakOnError = true;
        } else {
          out += " var " + $valid + " = false; ";
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
          if (it.opts.messages !== false) {
            out += " , message: 'boolean schema is false' ";
          }
          if (it.opts.verbose) {
            out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
      } else {
        if (it.isTop) {
          if ($async) {
            out += " return data; ";
          } else {
            out += " validate.errors = null; return true; ";
          }
        } else {
          out += " var " + $valid + " = true; ";
        }
      }
      if (it.isTop) {
        out += " }; return validate; ";
      }
      return out;
    }
    if (it.isTop) {
      var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = "data";
      it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
      it.baseId = it.baseId || it.rootId;
      delete it.isTop;
      it.dataPathArr = [""];
      if (it.schema.default !== void 0 && it.opts.useDefaults && it.opts.strictDefaults) {
        var $defaultMsg = "default is ignored in the schema root";
        if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
        else throw new Error($defaultMsg);
      }
      out += " var vErrors = null; ";
      out += " var errors = 0;     ";
      out += " if (rootData === undefined) rootData = data; ";
    } else {
      var $lvl = it.level, $dataLvl = it.dataLevel, $data = "data" + ($dataLvl || "");
      if ($id2) it.baseId = it.resolve.url(it.baseId, $id2);
      if ($async && !it.async) throw new Error("async schema in sync schema");
      out += " var errs_" + $lvl + " = errors;";
    }
    var $valid = "valid" + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = "", $closingBraces2 = "";
    var $errorKeyword;
    var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema);
    if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
      if ($typeIsArray) {
        if ($typeSchema.indexOf("null") == -1) $typeSchema = $typeSchema.concat("null");
      } else if ($typeSchema != "null") {
        $typeSchema = [$typeSchema, "null"];
        $typeIsArray = true;
      }
    }
    if ($typeIsArray && $typeSchema.length == 1) {
      $typeSchema = $typeSchema[0];
      $typeIsArray = false;
    }
    if (it.schema.$ref && $refKeywords) {
      if (it.opts.extendRefs == "fail") {
        throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
      } else if (it.opts.extendRefs !== true) {
        $refKeywords = false;
        it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
      }
    }
    if (it.schema.$comment && it.opts.$comment) {
      out += " " + it.RULES.all.$comment.code(it, "$comment");
    }
    if ($typeSchema) {
      if (it.opts.coerceTypes) {
        var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
      }
      var $rulesGroup = it.RULES.types[$typeSchema];
      if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
        var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
        var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType";
        out += " if (" + it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) + ") { ";
        if ($coerceToTypes) {
          var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl;
          out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; ";
          if (it.opts.coerceTypes == "array") {
            out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers) + ") " + $coerced + " = " + $data + "; } ";
          }
          out += " if (" + $coerced + " !== undefined) ; ";
          var arr1 = $coerceToTypes;
          if (arr1) {
            var $type, $i = -1, l1 = arr1.length - 1;
            while ($i < l1) {
              $type = arr1[$i += 1];
              if ($type == "string") {
                out += " else if (" + $dataType + " == 'number' || " + $dataType + " == 'boolean') " + $coerced + " = '' + " + $data + "; else if (" + $data + " === null) " + $coerced + " = ''; ";
              } else if ($type == "number" || $type == "integer") {
                out += " else if (" + $dataType + " == 'boolean' || " + $data + " === null || (" + $dataType + " == 'string' && " + $data + " && " + $data + " == +" + $data + " ";
                if ($type == "integer") {
                  out += " && !(" + $data + " % 1)";
                }
                out += ")) " + $coerced + " = +" + $data + "; ";
              } else if ($type == "boolean") {
                out += " else if (" + $data + " === 'false' || " + $data + " === 0 || " + $data + " === null) " + $coerced + " = false; else if (" + $data + " === 'true' || " + $data + " === 1) " + $coerced + " = true; ";
              } else if ($type == "null") {
                out += " else if (" + $data + " === '' || " + $data + " === 0 || " + $data + " === false) " + $coerced + " = null; ";
              } else if (it.opts.coerceTypes == "array" && $type == "array") {
                out += " else if (" + $dataType + " == 'string' || " + $dataType + " == 'number' || " + $dataType + " == 'boolean' || " + $data + " == null) " + $coerced + " = [" + $data + "]; ";
              }
            }
          }
          out += " else {   ";
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' } ";
            if (it.opts.messages !== false) {
              out += " , message: 'should be ";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          out += " } if (" + $coerced + " !== undefined) {  ";
          var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
          out += " " + $data + " = " + $coerced + "; ";
          if (!$dataLvl) {
            out += "if (" + $parentData + " !== undefined)";
          }
          out += " " + $parentData + "[" + $parentDataProperty + "] = " + $coerced + "; } ";
        } else {
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
            if ($typeIsArray) {
              out += "" + $typeSchema.join(",");
            } else {
              out += "" + $typeSchema;
            }
            out += "' } ";
            if (it.opts.messages !== false) {
              out += " , message: 'should be ";
              if ($typeIsArray) {
                out += "" + $typeSchema.join(",");
              } else {
                out += "" + $typeSchema;
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
        }
        out += " } ";
      }
    }
    if (it.schema.$ref && !$refKeywords) {
      out += " " + it.RULES.all.$ref.code(it, "$ref") + " ";
      if ($breakOnError) {
        out += " } if (errors === ";
        if ($top) {
          out += "0";
        } else {
          out += "errs_" + $lvl;
        }
        out += ") { ";
        $closingBraces2 += "}";
      }
    } else {
      var arr2 = it.RULES;
      if (arr2) {
        var $rulesGroup, i2 = -1, l2 = arr2.length - 1;
        while (i2 < l2) {
          $rulesGroup = arr2[i2 += 1];
          if ($shouldUseGroup($rulesGroup)) {
            if ($rulesGroup.type) {
              out += " if (" + it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) + ") { ";
            }
            if (it.opts.useDefaults) {
              if ($rulesGroup.type == "object" && it.schema.properties) {
                var $schema2 = it.schema.properties, $schemaKeys = Object.keys($schema2);
                var arr3 = $schemaKeys;
                if (arr3) {
                  var $propertyKey, i3 = -1, l3 = arr3.length - 1;
                  while (i3 < l3) {
                    $propertyKey = arr3[i3 += 1];
                    var $sch = $schema2[$propertyKey];
                    if ($sch.default !== void 0) {
                      var $passData = $data + it.util.getProperty($propertyKey);
                      if (it.compositeRule) {
                        if (it.opts.strictDefaults) {
                          var $defaultMsg = "default is ignored for: " + $passData;
                          if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
                          else throw new Error($defaultMsg);
                        }
                      } else {
                        out += " if (" + $passData + " === undefined ";
                        if (it.opts.useDefaults == "empty") {
                          out += " || " + $passData + " === null || " + $passData + " === '' ";
                        }
                        out += " ) " + $passData + " = ";
                        if (it.opts.useDefaults == "shared") {
                          out += " " + it.useDefault($sch.default) + " ";
                        } else {
                          out += " " + JSON.stringify($sch.default) + " ";
                        }
                        out += "; ";
                      }
                    }
                  }
                }
              } else if ($rulesGroup.type == "array" && Array.isArray(it.schema.items)) {
                var arr4 = it.schema.items;
                if (arr4) {
                  var $sch, $i = -1, l4 = arr4.length - 1;
                  while ($i < l4) {
                    $sch = arr4[$i += 1];
                    if ($sch.default !== void 0) {
                      var $passData = $data + "[" + $i + "]";
                      if (it.compositeRule) {
                        if (it.opts.strictDefaults) {
                          var $defaultMsg = "default is ignored for: " + $passData;
                          if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg);
                          else throw new Error($defaultMsg);
                        }
                      } else {
                        out += " if (" + $passData + " === undefined ";
                        if (it.opts.useDefaults == "empty") {
                          out += " || " + $passData + " === null || " + $passData + " === '' ";
                        }
                        out += " ) " + $passData + " = ";
                        if (it.opts.useDefaults == "shared") {
                          out += " " + it.useDefault($sch.default) + " ";
                        } else {
                          out += " " + JSON.stringify($sch.default) + " ";
                        }
                        out += "; ";
                      }
                    }
                  }
                }
              }
            }
            var arr5 = $rulesGroup.rules;
            if (arr5) {
              var $rule, i5 = -1, l5 = arr5.length - 1;
              while (i5 < l5) {
                $rule = arr5[i5 += 1];
                if ($shouldUseRule($rule)) {
                  var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                  if ($code) {
                    out += " " + $code + " ";
                    if ($breakOnError) {
                      $closingBraces1 += "}";
                    }
                  }
                }
              }
            }
            if ($breakOnError) {
              out += " " + $closingBraces1 + " ";
              $closingBraces1 = "";
            }
            if ($rulesGroup.type) {
              out += " } ";
              if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
                out += " else { ";
                var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type";
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = "";
                if (it.createErrors !== false) {
                  out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '";
                  if ($typeIsArray) {
                    out += "" + $typeSchema.join(",");
                  } else {
                    out += "" + $typeSchema;
                  }
                  out += "' } ";
                  if (it.opts.messages !== false) {
                    out += " , message: 'should be ";
                    if ($typeIsArray) {
                      out += "" + $typeSchema.join(",");
                    } else {
                      out += "" + $typeSchema;
                    }
                    out += "' ";
                  }
                  if (it.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it.compositeRule && $breakOnError) {
                  if (it.async) {
                    out += " throw new ValidationError([" + __err + "]); ";
                  } else {
                    out += " validate.errors = [" + __err + "]; return false; ";
                  }
                } else {
                  out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
                }
                out += " } ";
              }
            }
            if ($breakOnError) {
              out += " if (errors === ";
              if ($top) {
                out += "0";
              } else {
                out += "errs_" + $lvl;
              }
              out += ") { ";
              $closingBraces2 += "}";
            }
          }
        }
      }
    }
    if ($breakOnError) {
      out += " " + $closingBraces2 + " ";
    }
    if ($top) {
      if ($async) {
        out += " if (errors === 0) return data;           ";
        out += " else throw new ValidationError(vErrors); ";
      } else {
        out += " validate.errors = vErrors; ";
        out += " return errors === 0;       ";
      }
      out += " }; return validate;";
    } else {
      out += " var " + $valid + " = errors === errs_" + $lvl + ";";
    }
    function $shouldUseGroup($rulesGroup2) {
      var rules2 = $rulesGroup2.rules;
      for (var i4 = 0; i4 < rules2.length; i4++)
        if ($shouldUseRule(rules2[i4])) return true;
    }
    function $shouldUseRule($rule2) {
      return it.schema[$rule2.keyword] !== void 0 || $rule2.implements && $ruleImplementsSomeKeyword($rule2);
    }
    function $ruleImplementsSomeKeyword($rule2) {
      var impl = $rule2.implements;
      for (var i4 = 0; i4 < impl.length; i4++)
        if (it.schema[impl[i4]] !== void 0) return true;
    }
    return out;
  };
  return validate;
}
var compile_1;
var hasRequiredCompile;
function requireCompile() {
  if (hasRequiredCompile) return compile_1;
  hasRequiredCompile = 1;
  var resolve2 = requireResolve(), util2 = requireUtil(), errorClasses = requireError_classes(), stableStringify = requireFastJsonStableStringify();
  var validateGenerator = requireValidate();
  var ucs2length2 = util2.ucs2length;
  var equal = requireFastDeepEqual();
  var ValidationError = errorClasses.Validation;
  compile_1 = compile;
  function compile(schema, root, localRefs, baseId) {
    var self2 = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = [];
    root = root || { schema, refVal, refs };
    var c2 = checkCompiling.call(this, schema, root, baseId);
    var compilation = this._compilations[c2.index];
    if (c2.compiling) return compilation.callValidate = callValidate;
    var formats = this._formats;
    var RULES = this.RULES;
    try {
      var v2 = localCompile(schema, root, localRefs, baseId);
      compilation.validate = v2;
      var cv = compilation.callValidate;
      if (cv) {
        cv.schema = v2.schema;
        cv.errors = null;
        cv.refs = v2.refs;
        cv.refVal = v2.refVal;
        cv.root = v2.root;
        cv.$async = v2.$async;
        if (opts.sourceCode) cv.source = v2.source;
      }
      return v2;
    } finally {
      endCompiling.call(this, schema, root, baseId);
    }
    function callValidate() {
      var validate2 = compilation.validate;
      var result = validate2.apply(this, arguments);
      callValidate.errors = validate2.errors;
      return result;
    }
    function localCompile(_schema, _root, localRefs2, baseId2) {
      var isRoot = !_root || _root && _root.schema == _schema;
      if (_root.schema != root.schema)
        return compile.call(self2, _schema, _root, localRefs2, baseId2);
      var $async = _schema.$async === true;
      var sourceCode = validateGenerator({
        isTop: true,
        schema: _schema,
        isRoot,
        baseId: baseId2,
        root: _root,
        schemaPath: "",
        errSchemaPath: "#",
        errorPath: '""',
        MissingRefError: errorClasses.MissingRef,
        RULES,
        validate: validateGenerator,
        util: util2,
        resolve: resolve2,
        resolveRef,
        usePattern,
        useDefault,
        useCustomRule,
        opts,
        formats,
        logger: self2.logger,
        self: self2
      });
      sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode;
      if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
      var validate2;
      try {
        var makeValidate = new Function(
          "self",
          "RULES",
          "formats",
          "root",
          "refVal",
          "defaults",
          "customRules",
          "equal",
          "ucs2length",
          "ValidationError",
          sourceCode
        );
        validate2 = makeValidate(
          self2,
          RULES,
          formats,
          root,
          refVal,
          defaults,
          customRules,
          equal,
          ucs2length2,
          ValidationError
        );
        refVal[0] = validate2;
      } catch (e4) {
        self2.logger.error("Error compiling schema, function code:", sourceCode);
        throw e4;
      }
      validate2.schema = _schema;
      validate2.errors = null;
      validate2.refs = refs;
      validate2.refVal = refVal;
      validate2.root = isRoot ? validate2 : _root;
      if ($async) validate2.$async = true;
      if (opts.sourceCode === true) {
        validate2.source = {
          code: sourceCode,
          patterns,
          defaults
        };
      }
      return validate2;
    }
    function resolveRef(baseId2, ref2, isRoot) {
      ref2 = resolve2.url(baseId2, ref2);
      var refIndex = refs[ref2];
      var _refVal, refCode;
      if (refIndex !== void 0) {
        _refVal = refVal[refIndex];
        refCode = "refVal[" + refIndex + "]";
        return resolvedRef(_refVal, refCode);
      }
      if (!isRoot && root.refs) {
        var rootRefId = root.refs[ref2];
        if (rootRefId !== void 0) {
          _refVal = root.refVal[rootRefId];
          refCode = addLocalRef(ref2, _refVal);
          return resolvedRef(_refVal, refCode);
        }
      }
      refCode = addLocalRef(ref2);
      var v3 = resolve2.call(self2, localCompile, root, ref2);
      if (v3 === void 0) {
        var localSchema = localRefs && localRefs[ref2];
        if (localSchema) {
          v3 = resolve2.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self2, localSchema, root, localRefs, baseId2);
        }
      }
      if (v3 === void 0) {
        removeLocalRef(ref2);
      } else {
        replaceLocalRef(ref2, v3);
        return resolvedRef(v3, refCode);
      }
    }
    function addLocalRef(ref2, v3) {
      var refId = refVal.length;
      refVal[refId] = v3;
      refs[ref2] = refId;
      return "refVal" + refId;
    }
    function removeLocalRef(ref2) {
      delete refs[ref2];
    }
    function replaceLocalRef(ref2, v3) {
      var refId = refs[ref2];
      refVal[refId] = v3;
    }
    function resolvedRef(refVal2, code) {
      return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code, schema: refVal2, inline: true } : { code, $async: refVal2 && !!refVal2.$async };
    }
    function usePattern(regexStr) {
      var index2 = patternsHash[regexStr];
      if (index2 === void 0) {
        index2 = patternsHash[regexStr] = patterns.length;
        patterns[index2] = regexStr;
      }
      return "pattern" + index2;
    }
    function useDefault(value) {
      switch (typeof value) {
        case "boolean":
        case "number":
          return "" + value;
        case "string":
          return util2.toQuotedString(value);
        case "object":
          if (value === null) return "null";
          var valueStr = stableStringify(value);
          var index2 = defaultsHash[valueStr];
          if (index2 === void 0) {
            index2 = defaultsHash[valueStr] = defaults.length;
            defaults[index2] = value;
          }
          return "default" + index2;
      }
    }
    function useCustomRule(rule, schema2, parentSchema, it) {
      if (self2._opts.validateSchema !== false) {
        var deps = rule.definition.dependencies;
        if (deps && !deps.every(function(keyword2) {
          return Object.prototype.hasOwnProperty.call(parentSchema, keyword2);
        }))
          throw new Error("parent schema must have all required keywords: " + deps.join(","));
        var validateSchema = rule.definition.validateSchema;
        if (validateSchema) {
          var valid = validateSchema(schema2);
          if (!valid) {
            var message = "keyword schema is invalid: " + self2.errorsText(validateSchema.errors);
            if (self2._opts.validateSchema == "log") self2.logger.error(message);
            else throw new Error(message);
          }
        }
      }
      var compile2 = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
      var validate2;
      if (compile2) {
        validate2 = compile2.call(self2, schema2, parentSchema, it);
      } else if (macro) {
        validate2 = macro.call(self2, schema2, parentSchema, it);
        if (opts.validateSchema !== false) self2.validateSchema(validate2, true);
      } else if (inline) {
        validate2 = inline.call(self2, it, rule.keyword, schema2, parentSchema);
      } else {
        validate2 = rule.definition.validate;
        if (!validate2) return;
      }
      if (validate2 === void 0)
        throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
      var index2 = customRules.length;
      customRules[index2] = validate2;
      return {
        code: "customRule" + index2,
        validate: validate2
      };
    }
  }
  function checkCompiling(schema, root, baseId) {
    var index2 = compIndex.call(this, schema, root, baseId);
    if (index2 >= 0) return { index: index2, compiling: true };
    index2 = this._compilations.length;
    this._compilations[index2] = {
      schema,
      root,
      baseId
    };
    return { index: index2, compiling: false };
  }
  function endCompiling(schema, root, baseId) {
    var i2 = compIndex.call(this, schema, root, baseId);
    if (i2 >= 0) this._compilations.splice(i2, 1);
  }
  function compIndex(schema, root, baseId) {
    for (var i2 = 0; i2 < this._compilations.length; i2++) {
      var c2 = this._compilations[i2];
      if (c2.schema == schema && c2.root == root && c2.baseId == baseId) return i2;
    }
    return -1;
  }
  function patternCode(i2, patterns) {
    return "var pattern" + i2 + " = new RegExp(" + util2.toQuotedString(patterns[i2]) + ");";
  }
  function defaultCode(i2) {
    return "var default" + i2 + " = defaults[" + i2 + "];";
  }
  function refValCode(i2, refVal) {
    return refVal[i2] === void 0 ? "" : "var refVal" + i2 + " = refVal[" + i2 + "];";
  }
  function customRuleCode(i2) {
    return "var customRule" + i2 + " = customRules[" + i2 + "];";
  }
  function vars(arr, statement) {
    if (!arr.length) return "";
    var code = "";
    for (var i2 = 0; i2 < arr.length; i2++)
      code += statement(i2, arr);
    return code;
  }
  return compile_1;
}
var cache = { exports: {} };
var hasRequiredCache;
function requireCache() {
  if (hasRequiredCache) return cache.exports;
  hasRequiredCache = 1;
  var Cache = cache.exports = function Cache2() {
    this._cache = {};
  };
  Cache.prototype.put = function Cache_put(key2, value) {
    this._cache[key2] = value;
  };
  Cache.prototype.get = function Cache_get(key2) {
    return this._cache[key2];
  };
  Cache.prototype.del = function Cache_del(key2) {
    delete this._cache[key2];
  };
  Cache.prototype.clear = function Cache_clear() {
    this._cache = {};
  };
  return cache.exports;
}
var formats_1;
var hasRequiredFormats;
function requireFormats() {
  if (hasRequiredFormats) return formats_1;
  hasRequiredFormats = 1;
  var util2 = requireUtil();
  var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
  var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
  var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
  var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
  var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
  var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
  var URL2 = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
  var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
  var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
  var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
  var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
  formats_1 = formats;
  function formats(mode) {
    mode = mode == "full" ? "full" : "fast";
    return util2.copy(formats[mode]);
  }
  formats.fast = {
    // date: http://tools.ietf.org/html/rfc3339#section-5.6
    date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
    // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
    time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
    "date-time": /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
    // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
    uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
    "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
    "uri-template": URITEMPLATE,
    url: URL2,
    // email (sources from jsen validator):
    // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
    // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
    email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
    hostname: HOSTNAME,
    // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
    ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
    // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
    ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
    regex,
    // uuid: http://tools.ietf.org/html/rfc4122
    uuid: UUID,
    // JSON-pointer: https://tools.ietf.org/html/rfc6901
    // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
    "json-pointer": JSON_POINTER,
    "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
    // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
    "relative-json-pointer": RELATIVE_JSON_POINTER
  };
  formats.full = {
    date: date2,
    time,
    "date-time": date_time,
    uri: uri2,
    "uri-reference": URIREF,
    "uri-template": URITEMPLATE,
    url: URL2,
    email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
    hostname: HOSTNAME,
    ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
    ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
    regex,
    uuid: UUID,
    "json-pointer": JSON_POINTER,
    "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
    "relative-json-pointer": RELATIVE_JSON_POINTER
  };
  function isLeapYear(year) {
    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
  }
  function date2(str) {
    var matches = str.match(DATE);
    if (!matches) return false;
    var year = +matches[1];
    var month = +matches[2];
    var day = +matches[3];
    return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
  }
  function time(str, full) {
    var matches = str.match(TIME);
    if (!matches) return false;
    var hour = matches[1];
    var minute = matches[2];
    var second = matches[3];
    var timeZone = matches[5];
    return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone);
  }
  var DATE_TIME_SEPARATOR = /t|\s/i;
  function date_time(str) {
    var dateTime = str.split(DATE_TIME_SEPARATOR);
    return dateTime.length == 2 && date2(dateTime[0]) && time(dateTime[1], true);
  }
  var NOT_URI_FRAGMENT = /\/|:/;
  function uri2(str) {
    return NOT_URI_FRAGMENT.test(str) && URI.test(str);
  }
  var Z_ANCHOR = /[^\\]\\Z/;
  function regex(str) {
    if (Z_ANCHOR.test(str)) return false;
    try {
      new RegExp(str);
      return true;
    } catch (e4) {
      return false;
    }
  }
  return formats_1;
}
var ref;
var hasRequiredRef;
function requireRef() {
  if (hasRequiredRef) return ref;
  hasRequiredRef = 1;
  ref = function generate_ref(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $async, $refCode;
    if ($schema2 == "#" || $schema2 == "#/") {
      if (it.isRoot) {
        $async = it.async;
        $refCode = "validate";
      } else {
        $async = it.root.schema.$async === true;
        $refCode = "root.refVal[0]";
      }
    } else {
      var $refVal = it.resolveRef(it.baseId, $schema2, it.isRoot);
      if ($refVal === void 0) {
        var $message = it.MissingRefError.message(it.baseId, $schema2);
        if (it.opts.missingRefs == "fail") {
          it.logger.error($message);
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it.util.escapeQuotes($schema2) + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: 'can\\'t resolve reference " + it.util.escapeQuotes($schema2) + "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: " + it.util.toQuotedString($schema2) + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          if ($breakOnError) {
            out += " if (false) { ";
          }
        } else if (it.opts.missingRefs == "ignore") {
          it.logger.warn($message);
          if ($breakOnError) {
            out += " if (true) { ";
          }
        } else {
          throw new it.MissingRefError(it.baseId, $schema2, $message);
        }
      } else if ($refVal.inline) {
        var $it = it.util.copy(it);
        $it.level++;
        var $nextValid = "valid" + $it.level;
        $it.schema = $refVal.schema;
        $it.schemaPath = "";
        $it.errSchemaPath = $schema2;
        var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
        out += " " + $code + " ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
        }
      } else {
        $async = $refVal.$async === true || it.async && $refVal.$async !== false;
        $refCode = $refVal.code;
      }
    }
    if ($refCode) {
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.opts.passContext) {
        out += " " + $refCode + ".call(this, ";
      } else {
        out += " " + $refCode + "( ";
      }
      out += " " + $data + ", (dataPath || '')";
      if (it.errorPath != '""') {
        out += " + " + it.errorPath;
      }
      var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
      out += " , " + $parentData + " , " + $parentDataProperty + ", rootData)  ";
      var __callValidate = out;
      out = $$outStack.pop();
      if ($async) {
        if (!it.async) throw new Error("async schema referenced by sync schema");
        if ($breakOnError) {
          out += " var " + $valid + "; ";
        }
        out += " try { await " + __callValidate + "; ";
        if ($breakOnError) {
          out += " " + $valid + " = true; ";
        }
        out += " } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ";
        if ($breakOnError) {
          out += " " + $valid + " = false; ";
        }
        out += " } ";
        if ($breakOnError) {
          out += " if (" + $valid + ") { ";
        }
      } else {
        out += " if (!" + __callValidate + ") { if (vErrors === null) vErrors = " + $refCode + ".errors; else vErrors = vErrors.concat(" + $refCode + ".errors); errors = vErrors.length; } ";
        if ($breakOnError) {
          out += " else { ";
        }
      }
    }
    return out;
  };
  return ref;
}
var allOf;
var hasRequiredAllOf;
function requireAllOf() {
  if (hasRequiredAllOf) return allOf;
  hasRequiredAllOf = 1;
  allOf = function generate_allOf(it, $keyword, $ruleType) {
    var out = " ";
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i = -1, l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          $allSchemasEmpty = false;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i;
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      }
    }
    if ($breakOnError) {
      if ($allSchemasEmpty) {
        out += " if (true) { ";
      } else {
        out += " " + $closingBraces.slice(0, -1) + " ";
      }
    }
    return out;
  };
  return allOf;
}
var anyOf;
var hasRequiredAnyOf;
function requireAnyOf() {
  if (hasRequiredAnyOf) return anyOf;
  hasRequiredAnyOf = 1;
  anyOf = function generate_anyOf(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $noEmptySchema = $schema2.every(function($sch2) {
      return it.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it.util.schemaHasRules($sch2, it.RULES.all);
    });
    if ($noEmptySchema) {
      var $currentBaseId = $it.baseId;
      out += " var " + $errs + " = errors; var " + $valid + " = false;  ";
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      var arr1 = $schema2;
      if (arr1) {
        var $sch, $i = -1, l1 = arr1.length - 1;
        while ($i < l1) {
          $sch = arr1[$i += 1];
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i;
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
          out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { ";
          $closingBraces += "}";
        }
      }
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $closingBraces + " if (!" + $valid + ") {   var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: 'should match some schema in anyOf' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; return false; ";
        }
      }
      out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
      if (it.opts.allErrors) {
        out += " } ";
      }
    } else {
      if ($breakOnError) {
        out += " if (true) { ";
      }
    }
    return out;
  };
  return anyOf;
}
var comment;
var hasRequiredComment;
function requireComment() {
  if (hasRequiredComment) return comment;
  hasRequiredComment = 1;
  comment = function generate_comment(it, $keyword, $ruleType) {
    var out = " ";
    var $schema2 = it.schema[$keyword];
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    !it.opts.allErrors;
    var $comment = it.util.toQuotedString($schema2);
    if (it.opts.$comment === true) {
      out += " console.log(" + $comment + ");";
    } else if (typeof it.opts.$comment == "function") {
      out += " self._opts.$comment(" + $comment + ", " + it.util.toQuotedString($errSchemaPath) + ", validate.root.schema);";
    }
    return out;
  };
  return comment;
}
var _const;
var hasRequired_const;
function require_const() {
  if (hasRequired_const) return _const;
  hasRequired_const = 1;
  _const = function generate_const(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    }
    if (!$isData) {
      out += " var schema" + $lvl + " = validate.schema" + $schemaPath + ";";
    }
    out += "var " + $valid + " = equal(" + $data + ", schema" + $lvl + "); if (!" + $valid + ") {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should be equal to constant' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " }";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _const;
}
var contains;
var hasRequiredContains;
function requireContains() {
  if (hasRequiredContains) return contains;
  hasRequiredContains = 1;
  contains = function generate_contains(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all);
    out += "var " + $errs + " = errors;var " + $valid + ";";
    if ($nonEmptySchema) {
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += " var " + $nextValid + " = false; for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + "[" + $idx + "]";
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      out += " if (" + $nextValid + ") break; }  ";
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $closingBraces + " if (!" + $nextValid + ") {";
    } else {
      out += " if (" + $data + ".length == 0) {";
    }
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
      if (it.opts.messages !== false) {
        out += " , message: 'should contain a valid item' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } else { ";
    if ($nonEmptySchema) {
      out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
    }
    if (it.opts.allErrors) {
      out += " } ";
    }
    return out;
  };
  return contains;
}
var dependencies;
var hasRequiredDependencies;
function requireDependencies() {
  if (hasRequiredDependencies) return dependencies;
  hasRequiredDependencies = 1;
  dependencies = function generate_dependencies(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties;
    for ($property in $schema2) {
      if ($property == "__proto__") continue;
      var $sch = $schema2[$property];
      var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
      $deps[$property] = $sch;
    }
    out += "var " + $errs + " = errors;";
    var $currentErrorPath = it.errorPath;
    out += "var missing" + $lvl + ";";
    for (var $property in $propertyDeps) {
      $deps = $propertyDeps[$property];
      if ($deps.length) {
        out += " if ( " + $data + it.util.getProperty($property) + " !== undefined ";
        if ($ownProperties) {
          out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
        }
        if ($breakOnError) {
          out += " && ( ";
          var arr1 = $deps;
          if (arr1) {
            var $propertyKey, $i = -1, l1 = arr1.length - 1;
            while ($i < l1) {
              $propertyKey = arr1[$i += 1];
              if ($i) {
                out += " || ";
              }
              var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
              out += " ( ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
            }
          }
          out += ")) {  ";
          var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
          }
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: 'should have ";
              if ($deps.length == 1) {
                out += "property " + it.util.escapeQuotes($deps[0]);
              } else {
                out += "properties " + it.util.escapeQuotes($deps.join(", "));
              }
              out += " when property " + it.util.escapeQuotes($property) + " is present' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
        } else {
          out += " ) { ";
          var arr2 = $deps;
          if (arr2) {
            var $propertyKey, i2 = -1, l2 = arr2.length - 1;
            while (i2 < l2) {
              $propertyKey = arr2[i2 += 1];
              var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              out += " if ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") {  var err =   ";
              if (it.createErrors !== false) {
                out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: 'should have ";
                  if ($deps.length == 1) {
                    out += "property " + it.util.escapeQuotes($deps[0]);
                  } else {
                    out += "properties " + it.util.escapeQuotes($deps.join(", "));
                  }
                  out += " when property " + it.util.escapeQuotes($property) + " is present' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
            }
          }
        }
        out += " }   ";
        if ($breakOnError) {
          $closingBraces += "}";
          out += " else { ";
        }
      }
    }
    it.errorPath = $currentErrorPath;
    var $currentBaseId = $it.baseId;
    for (var $property in $schemaDeps) {
      var $sch = $schemaDeps[$property];
      if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
        out += " " + $nextValid + " = true; if ( " + $data + it.util.getProperty($property) + " !== undefined ";
        if ($ownProperties) {
          out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') ";
        }
        out += ") { ";
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + it.util.getProperty($property);
        $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($property);
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        out += " }  ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
    }
    if ($breakOnError) {
      out += "   " + $closingBraces + " if (" + $errs + " == errors) {";
    }
    return out;
  };
  return dependencies;
}
var _enum;
var hasRequired_enum;
function require_enum() {
  if (hasRequired_enum) return _enum;
  hasRequired_enum = 1;
  _enum = function generate_enum(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    }
    var $i = "i" + $lvl, $vSchema = "schema" + $lvl;
    if (!$isData) {
      out += " var " + $vSchema + " = validate.schema" + $schemaPath + ";";
    }
    out += "var " + $valid + ";";
    if ($isData) {
      out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
    }
    out += "" + $valid + " = false;for (var " + $i + "=0; " + $i + "<" + $vSchema + ".length; " + $i + "++) if (equal(" + $data + ", " + $vSchema + "[" + $i + "])) { " + $valid + " = true; break; }";
    if ($isData) {
      out += "  }  ";
    }
    out += " if (!" + $valid + ") {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should be equal to one of the allowed values' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " }";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _enum;
}
var format;
var hasRequiredFormat;
function requireFormat() {
  if (hasRequiredFormat) return format;
  hasRequiredFormat = 1;
  format = function generate_format(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    if (it.opts.format === false) {
      if ($breakOnError) {
        out += " if (true) { ";
      }
      return out;
    }
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats);
    if ($isData) {
      var $format = "format" + $lvl, $isObject = "isObject" + $lvl, $formatType = "formatType" + $lvl;
      out += " var " + $format + " = formats[" + $schemaValue + "]; var " + $isObject + " = typeof " + $format + " == 'object' && !(" + $format + " instanceof RegExp) && " + $format + ".validate; var " + $formatType + " = " + $isObject + " && " + $format + ".type || 'string'; if (" + $isObject + ") { ";
      if (it.async) {
        out += " var async" + $lvl + " = " + $format + ".async; ";
      }
      out += " " + $format + " = " + $format + ".validate; } if (  ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
      }
      out += " (";
      if ($unknownFormats != "ignore") {
        out += " (" + $schemaValue + " && !" + $format + " ";
        if ($allowUnknown) {
          out += " && self._opts.unknownFormats.indexOf(" + $schemaValue + ") == -1 ";
        }
        out += ") || ";
      }
      out += " (" + $format + " && " + $formatType + " == '" + $ruleType + "' && !(typeof " + $format + " == 'function' ? ";
      if (it.async) {
        out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) ";
      } else {
        out += " " + $format + "(" + $data + ") ";
      }
      out += " : " + $format + ".test(" + $data + "))))) {";
    } else {
      var $format = it.formats[$schema2];
      if (!$format) {
        if ($unknownFormats == "ignore") {
          it.logger.warn('unknown format "' + $schema2 + '" ignored in schema at path "' + it.errSchemaPath + '"');
          if ($breakOnError) {
            out += " if (true) { ";
          }
          return out;
        } else if ($allowUnknown && $unknownFormats.indexOf($schema2) >= 0) {
          if ($breakOnError) {
            out += " if (true) { ";
          }
          return out;
        } else {
          throw new Error('unknown format "' + $schema2 + '" is used in schema at path "' + it.errSchemaPath + '"');
        }
      }
      var $isObject = typeof $format == "object" && !($format instanceof RegExp) && $format.validate;
      var $formatType = $isObject && $format.type || "string";
      if ($isObject) {
        var $async = $format.async === true;
        $format = $format.validate;
      }
      if ($formatType != $ruleType) {
        if ($breakOnError) {
          out += " if (true) { ";
        }
        return out;
      }
      if ($async) {
        if (!it.async) throw new Error("async format in sync schema");
        var $formatRef = "formats" + it.util.getProperty($schema2) + ".validate";
        out += " if (!(await " + $formatRef + "(" + $data + "))) { ";
      } else {
        out += " if (! ";
        var $formatRef = "formats" + it.util.getProperty($schema2);
        if ($isObject) $formatRef += ".validate";
        if (typeof $format == "function") {
          out += " " + $formatRef + "(" + $data + ") ";
        } else {
          out += " " + $formatRef + ".test(" + $data + ") ";
        }
        out += ") { ";
      }
    }
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { format:  ";
      if ($isData) {
        out += "" + $schemaValue;
      } else {
        out += "" + it.util.toQuotedString($schema2);
      }
      out += "  } ";
      if (it.opts.messages !== false) {
        out += ` , message: 'should match format "`;
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + it.util.escapeQuotes($schema2);
        }
        out += `"' `;
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + it.util.toQuotedString($schema2);
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return format;
}
var _if;
var hasRequired_if;
function require_if() {
  if (hasRequired_if) return _if;
  hasRequired_if = 1;
  _if = function generate_if(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $thenSch = it.schema["then"], $elseSch = it.schema["else"], $thenPresent = $thenSch !== void 0 && (it.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== void 0 && (it.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId;
    if ($thenPresent || $elsePresent) {
      var $ifClause;
      $it.createErrors = false;
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += " var " + $errs + " = errors; var " + $valid + " = true;  ";
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      out += "  " + it.validate($it) + " ";
      $it.baseId = $currentBaseId;
      $it.createErrors = true;
      out += "  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }  ";
      it.compositeRule = $it.compositeRule = $wasComposite;
      if ($thenPresent) {
        out += " if (" + $nextValid + ") {  ";
        $it.schema = it.schema["then"];
        $it.schemaPath = it.schemaPath + ".then";
        $it.errSchemaPath = it.errSchemaPath + "/then";
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        out += " " + $valid + " = " + $nextValid + "; ";
        if ($thenPresent && $elsePresent) {
          $ifClause = "ifClause" + $lvl;
          out += " var " + $ifClause + " = 'then'; ";
        } else {
          $ifClause = "'then'";
        }
        out += " } ";
        if ($elsePresent) {
          out += " else { ";
        }
      } else {
        out += " if (!" + $nextValid + ") { ";
      }
      if ($elsePresent) {
        $it.schema = it.schema["else"];
        $it.schemaPath = it.schemaPath + ".else";
        $it.errSchemaPath = it.errSchemaPath + "/else";
        out += "  " + it.validate($it) + " ";
        $it.baseId = $currentBaseId;
        out += " " + $valid + " = " + $nextValid + "; ";
        if ($thenPresent && $elsePresent) {
          $ifClause = "ifClause" + $lvl;
          out += " var " + $ifClause + " = 'else'; ";
        } else {
          $ifClause = "'else'";
        }
        out += " } ";
      }
      out += " if (!" + $valid + ") {   var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } ";
        if (it.opts.messages !== false) {
          out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `;
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; return false; ";
        }
      }
      out += " }   ";
      if ($breakOnError) {
        out += " else { ";
      }
    } else {
      if ($breakOnError) {
        out += " if (true) { ";
      }
    }
    return out;
  };
  return _if;
}
var items;
var hasRequiredItems;
function requireItems() {
  if (hasRequiredItems) return items;
  hasRequiredItems = 1;
  items = function generate_items(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId;
    out += "var " + $errs + " = errors;var " + $valid + ";";
    if (Array.isArray($schema2)) {
      var $additionalItems = it.schema.additionalItems;
      if ($additionalItems === false) {
        out += " " + $valid + " = " + $data + ".length <= " + $schema2.length + "; ";
        var $currErrSchemaPath = $errSchemaPath;
        $errSchemaPath = it.errSchemaPath + "/additionalItems";
        out += "  if (!" + $valid + ") {   ";
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = "";
        if (it.createErrors !== false) {
          out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema2.length + " } ";
          if (it.opts.messages !== false) {
            out += " , message: 'should NOT have more than " + $schema2.length + " items' ";
          }
          if (it.opts.verbose) {
            out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError([" + __err + "]); ";
          } else {
            out += " validate.errors = [" + __err + "]; return false; ";
          }
        } else {
          out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        }
        out += " } ";
        $errSchemaPath = $currErrSchemaPath;
        if ($breakOnError) {
          $closingBraces += "}";
          out += " else { ";
        }
      }
      var arr1 = $schema2;
      if (arr1) {
        var $sch, $i = -1, l1 = arr1.length - 1;
        while ($i < l1) {
          $sch = arr1[$i += 1];
          if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
            out += " " + $nextValid + " = true; if (" + $data + ".length > " + $i + ") { ";
            var $passData = $data + "[" + $i + "]";
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + "[" + $i + "]";
            $it.errSchemaPath = $errSchemaPath + "/" + $i;
            $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
            $it.dataPathArr[$dataNxt] = $i;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
              out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            out += " }  ";
            if ($breakOnError) {
              out += " if (" + $nextValid + ") { ";
              $closingBraces += "}";
            }
          }
        }
      }
      if (typeof $additionalItems == "object" && (it.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
        $it.schema = $additionalItems;
        $it.schemaPath = it.schemaPath + ".additionalItems";
        $it.errSchemaPath = it.errSchemaPath + "/additionalItems";
        out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema2.length + ") {  for (var " + $idx + " = " + $schema2.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
        $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
        var $passData = $data + "[" + $idx + "]";
        $it.dataPathArr[$dataNxt] = $idx;
        var $code = it.validate($it);
        $it.baseId = $currentBaseId;
        if (it.util.varOccurences($code, $nextData) < 2) {
          out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
        } else {
          out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
        }
        if ($breakOnError) {
          out += " if (!" + $nextValid + ") break; ";
        }
        out += " } }  ";
        if ($breakOnError) {
          out += " if (" + $nextValid + ") { ";
          $closingBraces += "}";
        }
      }
    } else if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += "  for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + "[" + $idx + "]";
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      if ($breakOnError) {
        out += " if (!" + $nextValid + ") break; ";
      }
      out += " }";
    }
    if ($breakOnError) {
      out += " " + $closingBraces + " if (" + $errs + " == errors) {";
    }
    return out;
  };
  return items;
}
var _limit;
var hasRequired_limit;
function require_limit() {
  if (hasRequired_limit) return _limit;
  hasRequired_limit = 1;
  _limit = function generate__limit(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? "<" : ">", $notOp = $isMax ? ">" : "<", $errorKeyword = void 0;
    if (!($isData || typeof $schema2 == "number" || $schema2 === void 0)) {
      throw new Error($keyword + " must be number");
    }
    if (!($isDataExcl || $schemaExcl === void 0 || typeof $schemaExcl == "number" || typeof $schemaExcl == "boolean")) {
      throw new Error($exclusiveKeyword + " must be number or boolean");
    }
    if ($isDataExcl) {
      var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = "exclusive" + $lvl, $exclType = "exclType" + $lvl, $exclIsNumber = "exclIsNumber" + $lvl, $opExpr = "op" + $lvl, $opStr = "' + " + $opExpr + " + '";
      out += " var schemaExcl" + $lvl + " = " + $schemaValueExcl + "; ";
      $schemaValueExcl = "schemaExcl" + $lvl;
      out += " var " + $exclusive + "; var " + $exclType + " = typeof " + $schemaValueExcl + "; if (" + $exclType + " != 'boolean' && " + $exclType + " != 'undefined' && " + $exclType + " != 'number') { ";
      var $errorKeyword = $exclusiveKeyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: '" + $exclusiveKeyword + " should be boolean' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } else if ( ";
      if ($isData) {
        out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
      }
      out += " " + $exclType + " == 'number' ? ( (" + $exclusive + " = " + $schemaValue + " === undefined || " + $schemaValueExcl + " " + $op + "= " + $schemaValue + ") ? " + $data + " " + $notOp + "= " + $schemaValueExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) : ( (" + $exclusive + " = " + $schemaValueExcl + " === true) ? " + $data + " " + $notOp + "= " + $schemaValue + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { var op" + $lvl + " = " + $exclusive + " ? '" + $op + "' : '" + $op + "='; ";
      if ($schema2 === void 0) {
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
        $schemaValue = $schemaValueExcl;
        $isData = $isDataExcl;
      }
    } else {
      var $exclIsNumber = typeof $schemaExcl == "number", $opStr = $op;
      if ($exclIsNumber && $isData) {
        var $opExpr = "'" + $opStr + "'";
        out += " if ( ";
        if ($isData) {
          out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
        }
        out += " ( " + $schemaValue + " === undefined || " + $schemaExcl + " " + $op + "= " + $schemaValue + " ? " + $data + " " + $notOp + "= " + $schemaExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { ";
      } else {
        if ($exclIsNumber && $schema2 === void 0) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
          $schemaValue = $schemaExcl;
          $notOp += "=";
        } else {
          if ($exclIsNumber) $schemaValue = Math[$isMax ? "min" : "max"]($schemaExcl, $schema2);
          if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
            $exclusive = true;
            $errorKeyword = $exclusiveKeyword;
            $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword;
            $notOp += "=";
          } else {
            $exclusive = false;
            $opStr += "=";
          }
        }
        var $opExpr = "'" + $opStr + "'";
        out += " if ( ";
        if ($isData) {
          out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
        }
        out += " " + $data + " " + $notOp + " " + $schemaValue + " || " + $data + " !== " + $data + ") { ";
      }
    }
    $errorKeyword = $errorKeyword || $keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should be " + $opStr + " ";
        if ($isData) {
          out += "' + " + $schemaValue;
        } else {
          out += "" + $schemaValue + "'";
        }
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += " } ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _limit;
}
var _limitItems;
var hasRequired_limitItems;
function require_limitItems() {
  if (hasRequired_limitItems) return _limitItems;
  hasRequired_limitItems = 1;
  _limitItems = function generate__limitItems(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (!($isData || typeof $schema2 == "number")) {
      throw new Error($keyword + " must be number");
    }
    var $op = $keyword == "maxItems" ? ">" : "<";
    out += "if ( ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
    }
    out += " " + $data + ".length " + $op + " " + $schemaValue + ") { ";
    var $errorKeyword = $keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT have ";
        if ($keyword == "maxItems") {
          out += "more";
        } else {
          out += "fewer";
        }
        out += " than ";
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + $schema2;
        }
        out += " items' ";
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += "} ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _limitItems;
}
var _limitLength;
var hasRequired_limitLength;
function require_limitLength() {
  if (hasRequired_limitLength) return _limitLength;
  hasRequired_limitLength = 1;
  _limitLength = function generate__limitLength(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (!($isData || typeof $schema2 == "number")) {
      throw new Error($keyword + " must be number");
    }
    var $op = $keyword == "maxLength" ? ">" : "<";
    out += "if ( ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
    }
    if (it.opts.unicode === false) {
      out += " " + $data + ".length ";
    } else {
      out += " ucs2length(" + $data + ") ";
    }
    out += " " + $op + " " + $schemaValue + ") { ";
    var $errorKeyword = $keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT be ";
        if ($keyword == "maxLength") {
          out += "longer";
        } else {
          out += "shorter";
        }
        out += " than ";
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + $schema2;
        }
        out += " characters' ";
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += "} ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _limitLength;
}
var _limitProperties;
var hasRequired_limitProperties;
function require_limitProperties() {
  if (hasRequired_limitProperties) return _limitProperties;
  hasRequired_limitProperties = 1;
  _limitProperties = function generate__limitProperties(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (!($isData || typeof $schema2 == "number")) {
      throw new Error($keyword + " must be number");
    }
    var $op = $keyword == "maxProperties" ? ">" : "<";
    out += "if ( ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
    }
    out += " Object.keys(" + $data + ").length " + $op + " " + $schemaValue + ") { ";
    var $errorKeyword = $keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should NOT have ";
        if ($keyword == "maxProperties") {
          out += "more";
        } else {
          out += "fewer";
        }
        out += " than ";
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + $schema2;
        }
        out += " properties' ";
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += "} ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return _limitProperties;
}
var multipleOf;
var hasRequiredMultipleOf;
function requireMultipleOf() {
  if (hasRequiredMultipleOf) return multipleOf;
  hasRequiredMultipleOf = 1;
  multipleOf = function generate_multipleOf(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (!($isData || typeof $schema2 == "number")) {
      throw new Error($keyword + " must be number");
    }
    out += "var division" + $lvl + ";if (";
    if ($isData) {
      out += " " + $schemaValue + " !== undefined && ( typeof " + $schemaValue + " != 'number' || ";
    }
    out += " (division" + $lvl + " = " + $data + " / " + $schemaValue + ", ";
    if (it.opts.multipleOfPrecision) {
      out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it.opts.multipleOfPrecision + " ";
    } else {
      out += " division" + $lvl + " !== parseInt(division" + $lvl + ") ";
    }
    out += " ) ";
    if ($isData) {
      out += "  )  ";
    }
    out += " ) {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should be multiple of ";
        if ($isData) {
          out += "' + " + $schemaValue;
        } else {
          out += "" + $schemaValue + "'";
        }
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + $schema2;
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += "} ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return multipleOf;
}
var not;
var hasRequiredNot;
function requireNot() {
  if (hasRequiredNot) return not;
  hasRequiredNot = 1;
  not = function generate_not(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    $it.level++;
    var $nextValid = "valid" + $it.level;
    if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      out += " var " + $errs + " = errors;  ";
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      $it.createErrors = false;
      var $allErrorsOption;
      if ($it.opts.allErrors) {
        $allErrorsOption = $it.opts.allErrors;
        $it.opts.allErrors = false;
      }
      out += " " + it.validate($it) + " ";
      $it.createErrors = true;
      if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += " if (" + $nextValid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT be valid' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
      if (it.opts.allErrors) {
        out += " } ";
      }
    } else {
      out += "  var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT be valid' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if ($breakOnError) {
        out += " if (false) { ";
      }
    }
    return out;
  };
  return not;
}
var oneOf;
var hasRequiredOneOf;
function requireOneOf() {
  if (hasRequiredOneOf) return oneOf;
  hasRequiredOneOf = 1;
  oneOf = function generate_oneOf(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $currentBaseId = $it.baseId, $prevValid = "prevValid" + $lvl, $passingSchemas = "passingSchemas" + $lvl;
    out += "var " + $errs + " = errors , " + $prevValid + " = false , " + $valid + " = false , " + $passingSchemas + " = null; ";
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema2;
    if (arr1) {
      var $sch, $i = -1, l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + "[" + $i + "]";
          $it.errSchemaPath = $errSchemaPath + "/" + $i;
          out += "  " + it.validate($it) + " ";
          $it.baseId = $currentBaseId;
        } else {
          out += " var " + $nextValid + " = true; ";
        }
        if ($i) {
          out += " if (" + $nextValid + " && " + $prevValid + ") { " + $valid + " = false; " + $passingSchemas + " = [" + $passingSchemas + ", " + $i + "]; } else { ";
          $closingBraces += "}";
        }
        out += " if (" + $nextValid + ") { " + $valid + " = " + $prevValid + " = true; " + $passingSchemas + " = " + $i + "; }";
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += "" + $closingBraces + "if (!" + $valid + ") {   var err =   ";
    if (it.createErrors !== false) {
      out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } ";
      if (it.opts.messages !== false) {
        out += " , message: 'should match exactly one schema in oneOf' ";
      }
      if (it.opts.verbose) {
        out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError(vErrors); ";
      } else {
        out += " validate.errors = vErrors; return false; ";
      }
    }
    out += "} else {  errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }";
    if (it.opts.allErrors) {
      out += " } ";
    }
    return out;
  };
  return oneOf;
}
var pattern;
var hasRequiredPattern;
function requirePattern() {
  if (hasRequiredPattern) return pattern;
  hasRequiredPattern = 1;
  pattern = function generate_pattern(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $regexp = $isData ? "(new RegExp(" + $schemaValue + "))" : it.usePattern($schema2);
    out += "if ( ";
    if ($isData) {
      out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
    }
    out += " !" + $regexp + ".test(" + $data + ") ) {   ";
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = "";
    if (it.createErrors !== false) {
      out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { pattern:  ";
      if ($isData) {
        out += "" + $schemaValue;
      } else {
        out += "" + it.util.toQuotedString($schema2);
      }
      out += "  } ";
      if (it.opts.messages !== false) {
        out += ` , message: 'should match pattern "`;
        if ($isData) {
          out += "' + " + $schemaValue + " + '";
        } else {
          out += "" + it.util.escapeQuotes($schema2);
        }
        out += `"' `;
      }
      if (it.opts.verbose) {
        out += " , schema:  ";
        if ($isData) {
          out += "validate.schema" + $schemaPath;
        } else {
          out += "" + it.util.toQuotedString($schema2);
        }
        out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
      }
      out += " } ";
    } else {
      out += " {} ";
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      if (it.async) {
        out += " throw new ValidationError([" + __err + "]); ";
      } else {
        out += " validate.errors = [" + __err + "]; return false; ";
      }
    } else {
      out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
    }
    out += "} ";
    if ($breakOnError) {
      out += " else { ";
    }
    return out;
  };
  return pattern;
}
var properties$2;
var hasRequiredProperties;
function requireProperties() {
  if (hasRequiredProperties) return properties$2;
  hasRequiredProperties = 1;
  properties$2 = function generate_properties(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl;
    var $schemaKeys = Object.keys($schema2 || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
    var $required = it.schema.required;
    if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
      var $requiredHash = it.util.toHash($required);
    }
    function notProto(p2) {
      return p2 !== "__proto__";
    }
    out += "var " + $errs + " = errors;var " + $nextValid + " = true;";
    if ($ownProperties) {
      out += " var " + $dataProperties + " = undefined;";
    }
    if ($checkAdditional) {
      if ($ownProperties) {
        out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
      } else {
        out += " for (var " + $key + " in " + $data + ") { ";
      }
      if ($someProperties) {
        out += " var isAdditional" + $lvl + " = !(false ";
        if ($schemaKeys.length) {
          if ($schemaKeys.length > 8) {
            out += " || validate.schema" + $schemaPath + ".hasOwnProperty(" + $key + ") ";
          } else {
            var arr1 = $schemaKeys;
            if (arr1) {
              var $propertyKey, i1 = -1, l1 = arr1.length - 1;
              while (i1 < l1) {
                $propertyKey = arr1[i1 += 1];
                out += " || " + $key + " == " + it.util.toQuotedString($propertyKey) + " ";
              }
            }
          }
        }
        if ($pPropertyKeys.length) {
          var arr2 = $pPropertyKeys;
          if (arr2) {
            var $pProperty, $i = -1, l2 = arr2.length - 1;
            while ($i < l2) {
              $pProperty = arr2[$i += 1];
              out += " || " + it.usePattern($pProperty) + ".test(" + $key + ") ";
            }
          }
        }
        out += " ); if (isAdditional" + $lvl + ") { ";
      }
      if ($removeAdditional == "all") {
        out += " delete " + $data + "[" + $key + "]; ";
      } else {
        var $currentErrorPath = it.errorPath;
        var $additionalProperty = "' + " + $key + " + '";
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
        }
        if ($noAdditional) {
          if ($removeAdditional) {
            out += " delete " + $data + "[" + $key + "]; ";
          } else {
            out += " " + $nextValid + " = false; ";
            var $currErrSchemaPath = $errSchemaPath;
            $errSchemaPath = it.errSchemaPath + "/additionalProperties";
            var $$outStack = $$outStack || [];
            $$outStack.push(out);
            out = "";
            if (it.createErrors !== false) {
              out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is an invalid additional property";
                } else {
                  out += "should NOT have additional properties";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            var __err = out;
            out = $$outStack.pop();
            if (!it.compositeRule && $breakOnError) {
              if (it.async) {
                out += " throw new ValidationError([" + __err + "]); ";
              } else {
                out += " validate.errors = [" + __err + "]; return false; ";
              }
            } else {
              out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
            }
            $errSchemaPath = $currErrSchemaPath;
            if ($breakOnError) {
              out += " break; ";
            }
          }
        } else if ($additionalIsSchema) {
          if ($removeAdditional == "failing") {
            out += " var " + $errs + " = errors;  ";
            var $wasComposite = it.compositeRule;
            it.compositeRule = $it.compositeRule = true;
            $it.schema = $aProperties;
            $it.schemaPath = it.schemaPath + ".additionalProperties";
            $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
            $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
              out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            out += " if (!" + $nextValid + ") { errors = " + $errs + "; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete " + $data + "[" + $key + "]; }  ";
            it.compositeRule = $it.compositeRule = $wasComposite;
          } else {
            $it.schema = $aProperties;
            $it.schemaPath = it.schemaPath + ".additionalProperties";
            $it.errSchemaPath = it.errSchemaPath + "/additionalProperties";
            $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
              out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            if ($breakOnError) {
              out += " if (!" + $nextValid + ") break; ";
            }
          }
        }
        it.errorPath = $currentErrorPath;
      }
      if ($someProperties) {
        out += " } ";
      }
      out += " }  ";
      if ($breakOnError) {
        out += " if (" + $nextValid + ") { ";
        $closingBraces += "}";
      }
    }
    var $useDefaults = it.opts.useDefaults && !it.compositeRule;
    if ($schemaKeys.length) {
      var arr3 = $schemaKeys;
      if (arr3) {
        var $propertyKey, i3 = -1, l3 = arr3.length - 1;
        while (i3 < l3) {
          $propertyKey = arr3[i3 += 1];
          var $sch = $schema2[$propertyKey];
          if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
            var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0;
            $it.schema = $sch;
            $it.schemaPath = $schemaPath + $prop;
            $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($propertyKey);
            $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
            $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
              $code = it.util.varReplace($code, $nextData, $passData);
              var $useData = $passData;
            } else {
              var $useData = $nextData;
              out += " var " + $nextData + " = " + $passData + "; ";
            }
            if ($hasDefault) {
              out += " " + $code + " ";
            } else {
              if ($requiredHash && $requiredHash[$propertyKey]) {
                out += " if ( " + $useData + " === undefined ";
                if ($ownProperties) {
                  out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                }
                out += ") { " + $nextValid + " = false; ";
                var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey);
                if (it.opts._errorDataPathProperty) {
                  it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
                }
                $errSchemaPath = it.errSchemaPath + "/required";
                var $$outStack = $$outStack || [];
                $$outStack.push(out);
                out = "";
                if (it.createErrors !== false) {
                  out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                  if (it.opts.messages !== false) {
                    out += " , message: '";
                    if (it.opts._errorDataPathProperty) {
                      out += "is a required property";
                    } else {
                      out += "should have required property \\'" + $missingProperty + "\\'";
                    }
                    out += "' ";
                  }
                  if (it.opts.verbose) {
                    out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                  }
                  out += " } ";
                } else {
                  out += " {} ";
                }
                var __err = out;
                out = $$outStack.pop();
                if (!it.compositeRule && $breakOnError) {
                  if (it.async) {
                    out += " throw new ValidationError([" + __err + "]); ";
                  } else {
                    out += " validate.errors = [" + __err + "]; return false; ";
                  }
                } else {
                  out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
                }
                $errSchemaPath = $currErrSchemaPath;
                it.errorPath = $currentErrorPath;
                out += " } else { ";
              } else {
                if ($breakOnError) {
                  out += " if ( " + $useData + " === undefined ";
                  if ($ownProperties) {
                    out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                  }
                  out += ") { " + $nextValid + " = true; } else { ";
                } else {
                  out += " if (" + $useData + " !== undefined ";
                  if ($ownProperties) {
                    out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
                  }
                  out += " ) { ";
                }
              }
              out += " " + $code + " } ";
            }
          }
          if ($breakOnError) {
            out += " if (" + $nextValid + ") { ";
            $closingBraces += "}";
          }
        }
      }
    }
    if ($pPropertyKeys.length) {
      var arr4 = $pPropertyKeys;
      if (arr4) {
        var $pProperty, i4 = -1, l4 = arr4.length - 1;
        while (i4 < l4) {
          $pProperty = arr4[i4 += 1];
          var $sch = $pProperties[$pProperty];
          if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) {
            $it.schema = $sch;
            $it.schemaPath = it.schemaPath + ".patternProperties" + it.util.getProperty($pProperty);
            $it.errSchemaPath = it.errSchemaPath + "/patternProperties/" + it.util.escapeFragment($pProperty);
            if ($ownProperties) {
              out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
            } else {
              out += " for (var " + $key + " in " + $data + ") { ";
            }
            out += " if (" + it.usePattern($pProperty) + ".test(" + $key + ")) { ";
            $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
            var $passData = $data + "[" + $key + "]";
            $it.dataPathArr[$dataNxt] = $key;
            var $code = it.validate($it);
            $it.baseId = $currentBaseId;
            if (it.util.varOccurences($code, $nextData) < 2) {
              out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
            } else {
              out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
            }
            if ($breakOnError) {
              out += " if (!" + $nextValid + ") break; ";
            }
            out += " } ";
            if ($breakOnError) {
              out += " else " + $nextValid + " = true; ";
            }
            out += " }  ";
            if ($breakOnError) {
              out += " if (" + $nextValid + ") { ";
              $closingBraces += "}";
            }
          }
        }
      }
    }
    if ($breakOnError) {
      out += " " + $closingBraces + " if (" + $errs + " == errors) {";
    }
    return out;
  };
  return properties$2;
}
var propertyNames;
var hasRequiredPropertyNames;
function requirePropertyNames() {
  if (hasRequiredPropertyNames) return propertyNames;
  hasRequiredPropertyNames = 1;
  propertyNames = function generate_propertyNames(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $errs = "errs__" + $lvl;
    var $it = it.util.copy(it);
    var $closingBraces = "";
    $it.level++;
    var $nextValid = "valid" + $it.level;
    out += "var " + $errs + " = errors;";
    if (it.opts.strictKeywords ? typeof $schema2 == "object" && Object.keys($schema2).length > 0 || $schema2 === false : it.util.schemaHasRules($schema2, it.RULES.all)) {
      $it.schema = $schema2;
      $it.schemaPath = $schemaPath;
      $it.errSchemaPath = $errSchemaPath;
      var $key = "key" + $lvl, $idx = "idx" + $lvl, $i = "i" + $lvl, $invalidName = "' + " + $key + " + '", $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
      if ($ownProperties) {
        out += " var " + $dataProperties + " = undefined; ";
      }
      if ($ownProperties) {
        out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; ";
      } else {
        out += " for (var " + $key + " in " + $data + ") { ";
      }
      out += " var startErrs" + $lvl + " = errors; ";
      var $passData = $key;
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += " " + it.util.varReplace($code, $nextData, $passData) + " ";
      } else {
        out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
      }
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += " if (!" + $nextValid + ") { for (var " + $i + "=startErrs" + $lvl + "; " + $i + "<errors; " + $i + "++) { vErrors[" + $i + "].propertyName = " + $key + "; }   var err =   ";
      if (it.createErrors !== false) {
        out += " { keyword: 'propertyNames' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { propertyName: '" + $invalidName + "' } ";
        if (it.opts.messages !== false) {
          out += " , message: 'property name \\'" + $invalidName + "\\' is invalid' ";
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError(vErrors); ";
        } else {
          out += " validate.errors = vErrors; return false; ";
        }
      }
      if ($breakOnError) {
        out += " break; ";
      }
      out += " } }";
    }
    if ($breakOnError) {
      out += " " + $closingBraces + " if (" + $errs + " == errors) {";
    }
    return out;
  };
  return propertyNames;
}
var required$1;
var hasRequiredRequired;
function requireRequired() {
  if (hasRequiredRequired) return required$1;
  hasRequiredRequired = 1;
  required$1 = function generate_required(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it.opts.$data && $schema2 && $schema2.$data;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
    }
    var $vSchema = "schema" + $lvl;
    if (!$isData) {
      if ($schema2.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
        var $required = [];
        var arr1 = $schema2;
        if (arr1) {
          var $property, i1 = -1, l1 = arr1.length - 1;
          while (i1 < l1) {
            $property = arr1[i1 += 1];
            var $propertySch = it.schema.properties[$property];
            if (!($propertySch && (it.opts.strictKeywords ? typeof $propertySch == "object" && Object.keys($propertySch).length > 0 || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
              $required[$required.length] = $property;
            }
          }
        }
      } else {
        var $required = $schema2;
      }
    }
    if ($isData || $required.length) {
      var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties;
      if ($breakOnError) {
        out += " var missing" + $lvl + "; ";
        if ($loopRequired) {
          if (!$isData) {
            out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
          }
          var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
          }
          out += " var " + $valid + " = true; ";
          if ($isData) {
            out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {";
          }
          out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { " + $valid + " = " + $data + "[" + $vSchema + "[" + $i + "]] !== undefined ";
          if ($ownProperties) {
            out += " &&   Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
          }
          out += "; if (!" + $valid + ") break; } ";
          if ($isData) {
            out += "  }  ";
          }
          out += "  if (!" + $valid + ") {   ";
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: '";
              if (it.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          out += " } else { ";
        } else {
          out += " if ( ";
          var arr2 = $required;
          if (arr2) {
            var $propertyKey, $i = -1, l2 = arr2.length - 1;
            while ($i < l2) {
              $propertyKey = arr2[$i += 1];
              if ($i) {
                out += " || ";
              }
              var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
              out += " ( ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
            }
          }
          out += ") {  ";
          var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
          }
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = "";
          if (it.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: '";
              if (it.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            if (it.async) {
              out += " throw new ValidationError([" + __err + "]); ";
            } else {
              out += " validate.errors = [" + __err + "]; return false; ";
            }
          } else {
            out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
          }
          out += " } else { ";
        }
      } else {
        if ($loopRequired) {
          if (!$isData) {
            out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; ";
          }
          var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '";
          if (it.opts._errorDataPathProperty) {
            it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
          }
          if ($isData) {
            out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) {  var err =   ";
            if (it.createErrors !== false) {
              out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
              if (it.opts.messages !== false) {
                out += " , message: '";
                if (it.opts._errorDataPathProperty) {
                  out += "is a required property";
                } else {
                  out += "should have required property \\'" + $missingProperty + "\\'";
                }
                out += "' ";
              }
              if (it.opts.verbose) {
                out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
              }
              out += " } ";
            } else {
              out += " {} ";
            }
            out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (" + $vSchema + " !== undefined) { ";
          }
          out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { if (" + $data + "[" + $vSchema + "[" + $i + "]] === undefined ";
          if ($ownProperties) {
            out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) ";
          }
          out += ") {  var err =   ";
          if (it.createErrors !== false) {
            out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
            if (it.opts.messages !== false) {
              out += " , message: '";
              if (it.opts._errorDataPathProperty) {
                out += "is a required property";
              } else {
                out += "should have required property \\'" + $missingProperty + "\\'";
              }
              out += "' ";
            }
            if (it.opts.verbose) {
              out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
            }
            out += " } ";
          } else {
            out += " {} ";
          }
          out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ";
          if ($isData) {
            out += "  }  ";
          }
        } else {
          var arr3 = $required;
          if (arr3) {
            var $propertyKey, i3 = -1, l3 = arr3.length - 1;
            while (i3 < l3) {
              $propertyKey = arr3[i3 += 1];
              var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              out += " if ( " + $useData + " === undefined ";
              if ($ownProperties) {
                out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') ";
              }
              out += ") {  var err =   ";
              if (it.createErrors !== false) {
                out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
                if (it.opts.messages !== false) {
                  out += " , message: '";
                  if (it.opts._errorDataPathProperty) {
                    out += "is a required property";
                  } else {
                    out += "should have required property \\'" + $missingProperty + "\\'";
                  }
                  out += "' ";
                }
                if (it.opts.verbose) {
                  out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
                }
                out += " } ";
              } else {
                out += " {} ";
              }
              out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
            }
          }
        }
      }
      it.errorPath = $currentErrorPath;
    } else if ($breakOnError) {
      out += " if (true) {";
    }
    return out;
  };
  return required$1;
}
var uniqueItems;
var hasRequiredUniqueItems;
function requireUniqueItems() {
  if (hasRequiredUniqueItems) return uniqueItems;
  hasRequiredUniqueItems = 1;
  uniqueItems = function generate_uniqueItems(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    if (($schema2 || $isData) && it.opts.uniqueItems !== false) {
      if ($isData) {
        out += " var " + $valid + "; if (" + $schemaValue + " === false || " + $schemaValue + " === undefined) " + $valid + " = true; else if (typeof " + $schemaValue + " != 'boolean') " + $valid + " = false; else { ";
      }
      out += " var i = " + $data + ".length , " + $valid + " = true , j; if (i > 1) { ";
      var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType);
      if (!$itemType || $itemType == "object" || $itemType == "array" || $typeIsArray && ($itemType.indexOf("object") >= 0 || $itemType.indexOf("array") >= 0)) {
        out += " outer: for (;i--;) { for (j = i; j--;) { if (equal(" + $data + "[i], " + $data + "[j])) { " + $valid + " = false; break outer; } } } ";
      } else {
        out += " var itemIndices = {}, item; for (;i--;) { var item = " + $data + "[i]; ";
        var $method = "checkDataType" + ($typeIsArray ? "s" : "");
        out += " if (" + it.util[$method]($itemType, "item", it.opts.strictNumbers, true) + ") continue; ";
        if ($typeIsArray) {
          out += ` if (typeof item == 'string') item = '"' + item; `;
        }
        out += " if (typeof itemIndices[item] == 'number') { " + $valid + " = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ";
      }
      out += " } ";
      if ($isData) {
        out += "  }  ";
      }
      out += " if (!" + $valid + ") {   ";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } ";
        if (it.opts.messages !== false) {
          out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";
        }
        if (it.opts.verbose) {
          out += " , schema:  ";
          if ($isData) {
            out += "validate.schema" + $schemaPath;
          } else {
            out += "" + $schema2;
          }
          out += "         , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      out += " } ";
      if ($breakOnError) {
        out += " else { ";
      }
    } else {
      if ($breakOnError) {
        out += " if (true) { ";
      }
    }
    return out;
  };
  return uniqueItems;
}
var dotjs;
var hasRequiredDotjs;
function requireDotjs() {
  if (hasRequiredDotjs) return dotjs;
  hasRequiredDotjs = 1;
  dotjs = {
    "$ref": requireRef(),
    allOf: requireAllOf(),
    anyOf: requireAnyOf(),
    "$comment": requireComment(),
    const: require_const(),
    contains: requireContains(),
    dependencies: requireDependencies(),
    "enum": require_enum(),
    format: requireFormat(),
    "if": require_if(),
    items: requireItems(),
    maximum: require_limit(),
    minimum: require_limit(),
    maxItems: require_limitItems(),
    minItems: require_limitItems(),
    maxLength: require_limitLength(),
    minLength: require_limitLength(),
    maxProperties: require_limitProperties(),
    minProperties: require_limitProperties(),
    multipleOf: requireMultipleOf(),
    not: requireNot(),
    oneOf: requireOneOf(),
    pattern: requirePattern(),
    properties: requireProperties(),
    propertyNames: requirePropertyNames(),
    required: requireRequired(),
    uniqueItems: requireUniqueItems(),
    validate: requireValidate()
  };
  return dotjs;
}
var rules;
var hasRequiredRules;
function requireRules() {
  if (hasRequiredRules) return rules;
  hasRequiredRules = 1;
  var ruleModules = requireDotjs(), toHash = requireUtil().toHash;
  rules = function rules2() {
    var RULES = [
      {
        type: "number",
        rules: [
          { "maximum": ["exclusiveMaximum"] },
          { "minimum": ["exclusiveMinimum"] },
          "multipleOf",
          "format"
        ]
      },
      {
        type: "string",
        rules: ["maxLength", "minLength", "pattern", "format"]
      },
      {
        type: "array",
        rules: ["maxItems", "minItems", "items", "contains", "uniqueItems"]
      },
      {
        type: "object",
        rules: [
          "maxProperties",
          "minProperties",
          "required",
          "dependencies",
          "propertyNames",
          { "properties": ["additionalProperties", "patternProperties"] }
        ]
      },
      { rules: ["$ref", "const", "enum", "not", "anyOf", "oneOf", "allOf", "if"] }
    ];
    var ALL = ["type", "$comment"];
    var KEYWORDS = [
      "$schema",
      "$id",
      "id",
      "$data",
      "$async",
      "title",
      "description",
      "default",
      "definitions",
      "examples",
      "readOnly",
      "writeOnly",
      "contentMediaType",
      "contentEncoding",
      "additionalItems",
      "then",
      "else"
    ];
    var TYPES = ["number", "integer", "string", "array", "object", "boolean", "null"];
    RULES.all = toHash(ALL);
    RULES.types = toHash(TYPES);
    RULES.forEach(function(group) {
      group.rules = group.rules.map(function(keyword2) {
        var implKeywords;
        if (typeof keyword2 == "object") {
          var key2 = Object.keys(keyword2)[0];
          implKeywords = keyword2[key2];
          keyword2 = key2;
          implKeywords.forEach(function(k2) {
            ALL.push(k2);
            RULES.all[k2] = true;
          });
        }
        ALL.push(keyword2);
        var rule = RULES.all[keyword2] = {
          keyword: keyword2,
          code: ruleModules[keyword2],
          implements: implKeywords
        };
        return rule;
      });
      RULES.all.$comment = {
        keyword: "$comment",
        code: ruleModules.$comment
      };
      if (group.type) RULES.types[group.type] = group;
    });
    RULES.keywords = toHash(ALL.concat(KEYWORDS));
    RULES.custom = {};
    return RULES;
  };
  return rules;
}
var data;
var hasRequiredData;
function requireData() {
  if (hasRequiredData) return data;
  hasRequiredData = 1;
  var KEYWORDS = [
    "multipleOf",
    "maximum",
    "exclusiveMaximum",
    "minimum",
    "exclusiveMinimum",
    "maxLength",
    "minLength",
    "pattern",
    "additionalItems",
    "maxItems",
    "minItems",
    "uniqueItems",
    "maxProperties",
    "minProperties",
    "required",
    "additionalProperties",
    "enum",
    "format",
    "const"
  ];
  data = function(metaSchema, keywordsJsonPointers) {
    for (var i2 = 0; i2 < keywordsJsonPointers.length; i2++) {
      metaSchema = JSON.parse(JSON.stringify(metaSchema));
      var segments = keywordsJsonPointers[i2].split("/");
      var keywords = metaSchema;
      var j;
      for (j = 1; j < segments.length; j++)
        keywords = keywords[segments[j]];
      for (j = 0; j < KEYWORDS.length; j++) {
        var key2 = KEYWORDS[j];
        var schema = keywords[key2];
        if (schema) {
          keywords[key2] = {
            anyOf: [
              schema,
              { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
            ]
          };
        }
      }
    }
    return metaSchema;
  };
  return data;
}
var async;
var hasRequiredAsync;
function requireAsync() {
  if (hasRequiredAsync) return async;
  hasRequiredAsync = 1;
  var MissingRefError = requireError_classes().MissingRef;
  async = compileAsync;
  function compileAsync(schema, meta, callback) {
    var self2 = this;
    if (typeof this._opts.loadSchema != "function")
      throw new Error("options.loadSchema should be a function");
    if (typeof meta == "function") {
      callback = meta;
      meta = void 0;
    }
    var p2 = loadMetaSchemaOf(schema).then(function() {
      var schemaObj = self2._addSchema(schema, void 0, meta);
      return schemaObj.validate || _compileAsync(schemaObj);
    });
    if (callback) {
      p2.then(
        function(v2) {
          callback(null, v2);
        },
        callback
      );
    }
    return p2;
    function loadMetaSchemaOf(sch) {
      var $schema2 = sch.$schema;
      return $schema2 && !self2.getSchema($schema2) ? compileAsync.call(self2, { $ref: $schema2 }, true) : Promise.resolve();
    }
    function _compileAsync(schemaObj) {
      try {
        return self2._compile(schemaObj);
      } catch (e4) {
        if (e4 instanceof MissingRefError) return loadMissingSchema(e4);
        throw e4;
      }
      function loadMissingSchema(e4) {
        var ref2 = e4.missingSchema;
        if (added(ref2)) throw new Error("Schema " + ref2 + " is loaded but " + e4.missingRef + " cannot be resolved");
        var schemaPromise = self2._loadingSchemas[ref2];
        if (!schemaPromise) {
          schemaPromise = self2._loadingSchemas[ref2] = self2._opts.loadSchema(ref2);
          schemaPromise.then(removePromise, removePromise);
        }
        return schemaPromise.then(function(sch) {
          if (!added(ref2)) {
            return loadMetaSchemaOf(sch).then(function() {
              if (!added(ref2)) self2.addSchema(sch, ref2, void 0, meta);
            });
          }
        }).then(function() {
          return _compileAsync(schemaObj);
        });
        function removePromise() {
          delete self2._loadingSchemas[ref2];
        }
        function added(ref3) {
          return self2._refs[ref3] || self2._schemas[ref3];
        }
      }
    }
  }
  return async;
}
var custom$1;
var hasRequiredCustom;
function requireCustom() {
  if (hasRequiredCustom) return custom$1;
  hasRequiredCustom = 1;
  custom$1 = function generate_custom(it, $keyword, $ruleType) {
    var out = " ";
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema2 = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + "/" + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = "data" + ($dataLvl || "");
    var $valid = "valid" + $lvl;
    var $errs = "errs__" + $lvl;
    var $isData = it.opts.$data && $schema2 && $schema2.$data, $schemaValue;
    if ($isData) {
      out += " var schema" + $lvl + " = " + it.util.getData($schema2.$data, $dataLvl, it.dataPathArr) + "; ";
      $schemaValue = "schema" + $lvl;
    } else {
      $schemaValue = $schema2;
    }
    var $rule = this, $definition = "definition" + $lvl, $rDef = $rule.definition, $closingBraces = "";
    var $compile, $inline, $macro, $ruleValidate, $validateCode;
    if ($isData && $rDef.$data) {
      $validateCode = "keywordValidate" + $lvl;
      var $validateSchema = $rDef.validateSchema;
      out += " var " + $definition + " = RULES.custom['" + $keyword + "'].definition; var " + $validateCode + " = " + $definition + ".validate;";
    } else {
      $ruleValidate = it.useCustomRule($rule, $schema2, it.schema, it);
      if (!$ruleValidate) return;
      $schemaValue = "validate.schema" + $schemaPath;
      $validateCode = $ruleValidate.code;
      $compile = $rDef.compile;
      $inline = $rDef.inline;
      $macro = $rDef.macro;
    }
    var $ruleErrs = $validateCode + ".errors", $i = "i" + $lvl, $ruleErr = "ruleErr" + $lvl, $asyncKeyword = $rDef.async;
    if ($asyncKeyword && !it.async) throw new Error("async keyword in sync schema");
    if (!($inline || $macro)) {
      out += "" + $ruleErrs + " = null;";
    }
    out += "var " + $errs + " = errors;var " + $valid + ";";
    if ($isData && $rDef.$data) {
      $closingBraces += "}";
      out += " if (" + $schemaValue + " === undefined) { " + $valid + " = true; } else { ";
      if ($validateSchema) {
        $closingBraces += "}";
        out += " " + $valid + " = " + $definition + ".validateSchema(" + $schemaValue + "); if (" + $valid + ") { ";
      }
    }
    if ($inline) {
      if ($rDef.statements) {
        out += " " + $ruleValidate.validate + " ";
      } else {
        out += " " + $valid + " = " + $ruleValidate.validate + "; ";
      }
    } else if ($macro) {
      var $it = it.util.copy(it);
      var $closingBraces = "";
      $it.level++;
      var $nextValid = "valid" + $it.level;
      $it.schema = $ruleValidate.validate;
      $it.schemaPath = "";
      var $wasComposite = it.compositeRule;
      it.compositeRule = $it.compositeRule = true;
      var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
      it.compositeRule = $it.compositeRule = $wasComposite;
      out += " " + $code;
    } else {
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      out += "  " + $validateCode + ".call( ";
      if (it.opts.passContext) {
        out += "this";
      } else {
        out += "self";
      }
      if ($compile || $rDef.schema === false) {
        out += " , " + $data + " ";
      } else {
        out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it.schemaPath + " ";
      }
      out += " , (dataPath || '')";
      if (it.errorPath != '""') {
        out += " + " + it.errorPath;
      }
      var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty";
      out += " , " + $parentData + " , " + $parentDataProperty + " , rootData )  ";
      var def_callRuleValidate = out;
      out = $$outStack.pop();
      if ($rDef.errors === false) {
        out += " " + $valid + " = ";
        if ($asyncKeyword) {
          out += "await ";
        }
        out += "" + def_callRuleValidate + "; ";
      } else {
        if ($asyncKeyword) {
          $ruleErrs = "customErrors" + $lvl;
          out += " var " + $ruleErrs + " = null; try { " + $valid + " = await " + def_callRuleValidate + "; } catch (e) { " + $valid + " = false; if (e instanceof ValidationError) " + $ruleErrs + " = e.errors; else throw e; } ";
        } else {
          out += " " + $ruleErrs + " = null; " + $valid + " = " + def_callRuleValidate + "; ";
        }
      }
    }
    if ($rDef.modifying) {
      out += " if (" + $parentData + ") " + $data + " = " + $parentData + "[" + $parentDataProperty + "];";
    }
    out += "" + $closingBraces;
    if ($rDef.valid) {
      if ($breakOnError) {
        out += " if (true) { ";
      }
    } else {
      out += " if ( ";
      if ($rDef.valid === void 0) {
        out += " !";
        if ($macro) {
          out += "" + $nextValid;
        } else {
          out += "" + $valid;
        }
      } else {
        out += " " + !$rDef.valid + " ";
      }
      out += ") { ";
      $errorKeyword = $rule.keyword;
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = "";
      if (it.createErrors !== false) {
        out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
        if (it.opts.messages !== false) {
          out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
        }
        if (it.opts.verbose) {
          out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
        }
        out += " } ";
      } else {
        out += " {} ";
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        if (it.async) {
          out += " throw new ValidationError([" + __err + "]); ";
        } else {
          out += " validate.errors = [" + __err + "]; return false; ";
        }
      } else {
        out += " var err = " + __err + ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
      }
      var def_customError = out;
      out = $$outStack.pop();
      if ($inline) {
        if ($rDef.errors) {
          if ($rDef.errors != "full") {
            out += "  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
            if (it.opts.verbose) {
              out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
            }
            out += " } ";
          }
        } else {
          if ($rDef.errors === false) {
            out += " " + def_customError + " ";
          } else {
            out += " if (" + $errs + " == errors) { " + def_customError + " } else {  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + "; if (" + $ruleErr + ".schemaPath === undefined) { " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
            if (it.opts.verbose) {
              out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
            }
            out += " } } ";
          }
        }
      } else if ($macro) {
        out += "   var err =   ";
        if (it.createErrors !== false) {
          out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
          if (it.opts.messages !== false) {
            out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
          }
          if (it.opts.verbose) {
            out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " ";
          }
          out += " } ";
        } else {
          out += " {} ";
        }
        out += ";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
        if (!it.compositeRule && $breakOnError) {
          if (it.async) {
            out += " throw new ValidationError(vErrors); ";
          } else {
            out += " validate.errors = vErrors; return false; ";
          }
        }
      } else {
        if ($rDef.errors === false) {
          out += " " + def_customError + " ";
        } else {
          out += " if (Array.isArray(" + $ruleErrs + ")) { if (vErrors === null) vErrors = " + $ruleErrs + "; else vErrors = vErrors.concat(" + $ruleErrs + "); errors = vErrors.length;  for (var " + $i + "=" + $errs + "; " + $i + "<errors; " + $i + "++) { var " + $ruleErr + " = vErrors[" + $i + "]; if (" + $ruleErr + ".dataPath === undefined) " + $ruleErr + ".dataPath = (dataPath || '') + " + it.errorPath + ";  " + $ruleErr + '.schemaPath = "' + $errSchemaPath + '";  ';
          if (it.opts.verbose) {
            out += " " + $ruleErr + ".schema = " + $schemaValue + "; " + $ruleErr + ".data = " + $data + "; ";
          }
          out += " } } else { " + def_customError + " } ";
        }
      }
      out += " } ";
      if ($breakOnError) {
        out += " else { ";
      }
    }
    return out;
  };
  return custom$1;
}
const $schema$1 = "http://json-schema.org/draft-07/schema#";
const $id$1 = "http://json-schema.org/draft-07/schema#";
const title = "Core schema meta-schema";
const definitions = { "schemaArray": { "type": "array", "minItems": 1, "items": { "$ref": "#" } }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": { "type": "string" }, "uniqueItems": true, "default": [] } };
const type$1 = ["object", "boolean"];
const properties$1 = { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "$ref": "#" }, "items": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], "default": true }, "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "uniqueItems": { "type": "boolean", "default": false }, "contains": { "$ref": "#" }, "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "required": { "$ref": "#/definitions/stringArray" }, "additionalProperties": { "$ref": "#" }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "properties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": { "$ref": "#" }, "propertyNames": { "format": "regex" }, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } }, "propertyNames": { "$ref": "#" }, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { "type": "array", "items": { "$ref": "#/definitions/simpleTypes" }, "minItems": 1, "uniqueItems": true }] }, "format": { "type": "string" }, "contentMediaType": { "type": "string" }, "contentEncoding": { "type": "string" }, "if": { "$ref": "#" }, "then": { "$ref": "#" }, "else": { "$ref": "#" }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" } };
const require$$13 = {
  $schema: $schema$1,
  $id: $id$1,
  title,
  definitions,
  type: type$1,
  properties: properties$1,
  "default": true
};
var definition_schema;
var hasRequiredDefinition_schema;
function requireDefinition_schema() {
  if (hasRequiredDefinition_schema) return definition_schema;
  hasRequiredDefinition_schema = 1;
  var metaSchema = require$$13;
  definition_schema = {
    $id: "https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",
    definitions: {
      simpleTypes: metaSchema.definitions.simpleTypes
    },
    type: "object",
    dependencies: {
      schema: ["validate"],
      $data: ["validate"],
      statements: ["inline"],
      valid: { not: { required: ["macro"] } }
    },
    properties: {
      type: metaSchema.properties.type,
      schema: { type: "boolean" },
      statements: { type: "boolean" },
      dependencies: {
        type: "array",
        items: { type: "string" }
      },
      metaSchema: { type: "object" },
      modifying: { type: "boolean" },
      valid: { type: "boolean" },
      $data: { type: "boolean" },
      async: { type: "boolean" },
      errors: {
        anyOf: [
          { type: "boolean" },
          { const: "full" }
        ]
      }
    }
  };
  return definition_schema;
}
var keyword;
var hasRequiredKeyword;
function requireKeyword() {
  if (hasRequiredKeyword) return keyword;
  hasRequiredKeyword = 1;
  var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
  var customRuleCode = requireCustom();
  var definitionSchema = requireDefinition_schema();
  keyword = {
    add: addKeyword,
    get: getKeyword,
    remove: removeKeyword,
    validate: validateKeyword
  };
  function addKeyword(keyword2, definition) {
    var RULES = this.RULES;
    if (RULES.keywords[keyword2])
      throw new Error("Keyword " + keyword2 + " is already defined");
    if (!IDENTIFIER.test(keyword2))
      throw new Error("Keyword " + keyword2 + " is not a valid identifier");
    if (definition) {
      this.validateKeyword(definition, true);
      var dataType = definition.type;
      if (Array.isArray(dataType)) {
        for (var i2 = 0; i2 < dataType.length; i2++)
          _addRule(keyword2, dataType[i2], definition);
      } else {
        _addRule(keyword2, dataType, definition);
      }
      var metaSchema = definition.metaSchema;
      if (metaSchema) {
        if (definition.$data && this._opts.$data) {
          metaSchema = {
            anyOf: [
              metaSchema,
              { "$ref": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }
            ]
          };
        }
        definition.validateSchema = this.compile(metaSchema, true);
      }
    }
    RULES.keywords[keyword2] = RULES.all[keyword2] = true;
    function _addRule(keyword3, dataType2, definition2) {
      var ruleGroup;
      for (var i3 = 0; i3 < RULES.length; i3++) {
        var rg = RULES[i3];
        if (rg.type == dataType2) {
          ruleGroup = rg;
          break;
        }
      }
      if (!ruleGroup) {
        ruleGroup = { type: dataType2, rules: [] };
        RULES.push(ruleGroup);
      }
      var rule = {
        keyword: keyword3,
        definition: definition2,
        custom: true,
        code: customRuleCode,
        implements: definition2.implements
      };
      ruleGroup.rules.push(rule);
      RULES.custom[keyword3] = rule;
    }
    return this;
  }
  function getKeyword(keyword2) {
    var rule = this.RULES.custom[keyword2];
    return rule ? rule.definition : this.RULES.keywords[keyword2] || false;
  }
  function removeKeyword(keyword2) {
    var RULES = this.RULES;
    delete RULES.keywords[keyword2];
    delete RULES.all[keyword2];
    delete RULES.custom[keyword2];
    for (var i2 = 0; i2 < RULES.length; i2++) {
      var rules2 = RULES[i2].rules;
      for (var j = 0; j < rules2.length; j++) {
        if (rules2[j].keyword == keyword2) {
          rules2.splice(j, 1);
          break;
        }
      }
    }
    return this;
  }
  function validateKeyword(definition, throwError) {
    validateKeyword.errors = null;
    var v2 = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true);
    if (v2(definition)) return true;
    validateKeyword.errors = v2.errors;
    if (throwError)
      throw new Error("custom keyword definition is invalid: " + this.errorsText(v2.errors));
    else
      return false;
  }
  return keyword;
}
const $schema = "http://json-schema.org/draft-07/schema#";
const $id = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description = "Meta-schema for $data reference (JSON Schema extension proposal)";
const type = "object";
const required = ["$data"];
const properties = { "$data": { "type": "string", "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] } };
const additionalProperties = false;
const require$$12 = {
  $schema,
  $id,
  description,
  type,
  required,
  properties,
  additionalProperties
};
var ajv;
var hasRequiredAjv;
function requireAjv() {
  if (hasRequiredAjv) return ajv;
  hasRequiredAjv = 1;
  var compileSchema = requireCompile(), resolve2 = requireResolve(), Cache = requireCache(), SchemaObject = requireSchema_obj(), stableStringify = requireFastJsonStableStringify(), formats = requireFormats(), rules2 = requireRules(), $dataMetaSchema = requireData(), util2 = requireUtil();
  ajv = Ajv2;
  Ajv2.prototype.validate = validate2;
  Ajv2.prototype.compile = compile;
  Ajv2.prototype.addSchema = addSchema;
  Ajv2.prototype.addMetaSchema = addMetaSchema;
  Ajv2.prototype.validateSchema = validateSchema;
  Ajv2.prototype.getSchema = getSchema;
  Ajv2.prototype.removeSchema = removeSchema;
  Ajv2.prototype.addFormat = addFormat;
  Ajv2.prototype.errorsText = errorsText;
  Ajv2.prototype._addSchema = _addSchema;
  Ajv2.prototype._compile = _compile;
  Ajv2.prototype.compileAsync = requireAsync();
  var customKeyword = requireKeyword();
  Ajv2.prototype.addKeyword = customKeyword.add;
  Ajv2.prototype.getKeyword = customKeyword.get;
  Ajv2.prototype.removeKeyword = customKeyword.remove;
  Ajv2.prototype.validateKeyword = customKeyword.validate;
  var errorClasses = requireError_classes();
  Ajv2.ValidationError = errorClasses.Validation;
  Ajv2.MissingRefError = errorClasses.MissingRef;
  Ajv2.$dataMetaSchema = $dataMetaSchema;
  var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
  var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes", "strictDefaults"];
  var META_SUPPORT_DATA = ["/properties"];
  function Ajv2(opts) {
    if (!(this instanceof Ajv2)) return new Ajv2(opts);
    opts = this._opts = util2.copy(opts) || {};
    setLogger(this);
    this._schemas = {};
    this._refs = {};
    this._fragments = {};
    this._formats = formats(opts.format);
    this._cache = opts.cache || new Cache();
    this._loadingSchemas = {};
    this._compilations = [];
    this.RULES = rules2();
    this._getId = chooseGetId(opts);
    opts.loopRequired = opts.loopRequired || Infinity;
    if (opts.errorDataPath == "property") opts._errorDataPathProperty = true;
    if (opts.serialize === void 0) opts.serialize = stableStringify;
    this._metaOpts = getMetaSchemaOptions(this);
    if (opts.formats) addInitialFormats(this);
    if (opts.keywords) addInitialKeywords(this);
    addDefaultMetaSchema(this);
    if (typeof opts.meta == "object") this.addMetaSchema(opts.meta);
    if (opts.nullable) this.addKeyword("nullable", { metaSchema: { type: "boolean" } });
    addInitialSchemas(this);
  }
  function validate2(schemaKeyRef, data2) {
    var v2;
    if (typeof schemaKeyRef == "string") {
      v2 = this.getSchema(schemaKeyRef);
      if (!v2) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
    } else {
      var schemaObj = this._addSchema(schemaKeyRef);
      v2 = schemaObj.validate || this._compile(schemaObj);
    }
    var valid = v2(data2);
    if (v2.$async !== true) this.errors = v2.errors;
    return valid;
  }
  function compile(schema, _meta) {
    var schemaObj = this._addSchema(schema, void 0, _meta);
    return schemaObj.validate || this._compile(schemaObj);
  }
  function addSchema(schema, key2, _skipValidation, _meta) {
    if (Array.isArray(schema)) {
      for (var i2 = 0; i2 < schema.length; i2++) this.addSchema(schema[i2], void 0, _skipValidation, _meta);
      return this;
    }
    var id = this._getId(schema);
    if (id !== void 0 && typeof id != "string")
      throw new Error("schema id must be string");
    key2 = resolve2.normalizeId(key2 || id);
    checkUnique(this, key2);
    this._schemas[key2] = this._addSchema(schema, _skipValidation, _meta, true);
    return this;
  }
  function addMetaSchema(schema, key2, skipValidation) {
    this.addSchema(schema, key2, skipValidation, true);
    return this;
  }
  function validateSchema(schema, throwOrLogError) {
    var $schema2 = schema.$schema;
    if ($schema2 !== void 0 && typeof $schema2 != "string")
      throw new Error("$schema must be a string");
    $schema2 = $schema2 || this._opts.defaultMeta || defaultMeta(this);
    if (!$schema2) {
      this.logger.warn("meta-schema not available");
      this.errors = null;
      return true;
    }
    var valid = this.validate($schema2, schema);
    if (!valid && throwOrLogError) {
      var message = "schema is invalid: " + this.errorsText();
      if (this._opts.validateSchema == "log") this.logger.error(message);
      else throw new Error(message);
    }
    return valid;
  }
  function defaultMeta(self2) {
    var meta = self2._opts.meta;
    self2._opts.defaultMeta = typeof meta == "object" ? self2._getId(meta) || meta : self2.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0;
    return self2._opts.defaultMeta;
  }
  function getSchema(keyRef) {
    var schemaObj = _getSchemaObj(this, keyRef);
    switch (typeof schemaObj) {
      case "object":
        return schemaObj.validate || this._compile(schemaObj);
      case "string":
        return this.getSchema(schemaObj);
      case "undefined":
        return _getSchemaFragment(this, keyRef);
    }
  }
  function _getSchemaFragment(self2, ref2) {
    var res = resolve2.schema.call(self2, { schema: {} }, ref2);
    if (res) {
      var schema = res.schema, root = res.root, baseId = res.baseId;
      var v2 = compileSchema.call(self2, schema, root, void 0, baseId);
      self2._fragments[ref2] = new SchemaObject({
        ref: ref2,
        fragment: true,
        schema,
        root,
        baseId,
        validate: v2
      });
      return v2;
    }
  }
  function _getSchemaObj(self2, keyRef) {
    keyRef = resolve2.normalizeId(keyRef);
    return self2._schemas[keyRef] || self2._refs[keyRef] || self2._fragments[keyRef];
  }
  function removeSchema(schemaKeyRef) {
    if (schemaKeyRef instanceof RegExp) {
      _removeAllSchemas(this, this._schemas, schemaKeyRef);
      _removeAllSchemas(this, this._refs, schemaKeyRef);
      return this;
    }
    switch (typeof schemaKeyRef) {
      case "undefined":
        _removeAllSchemas(this, this._schemas);
        _removeAllSchemas(this, this._refs);
        this._cache.clear();
        return this;
      case "string":
        var schemaObj = _getSchemaObj(this, schemaKeyRef);
        if (schemaObj) this._cache.del(schemaObj.cacheKey);
        delete this._schemas[schemaKeyRef];
        delete this._refs[schemaKeyRef];
        return this;
      case "object":
        var serialize2 = this._opts.serialize;
        var cacheKey = serialize2 ? serialize2(schemaKeyRef) : schemaKeyRef;
        this._cache.del(cacheKey);
        var id = this._getId(schemaKeyRef);
        if (id) {
          id = resolve2.normalizeId(id);
          delete this._schemas[id];
          delete this._refs[id];
        }
    }
    return this;
  }
  function _removeAllSchemas(self2, schemas, regex) {
    for (var keyRef in schemas) {
      var schemaObj = schemas[keyRef];
      if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
        self2._cache.del(schemaObj.cacheKey);
        delete schemas[keyRef];
      }
    }
  }
  function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
    if (typeof schema != "object" && typeof schema != "boolean")
      throw new Error("schema should be object or boolean");
    var serialize2 = this._opts.serialize;
    var cacheKey = serialize2 ? serialize2(schema) : schema;
    var cached = this._cache.get(cacheKey);
    if (cached) return cached;
    shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
    var id = resolve2.normalizeId(this._getId(schema));
    if (id && shouldAddSchema) checkUnique(this, id);
    var willValidate = this._opts.validateSchema !== false && !skipValidation;
    var recursiveMeta;
    if (willValidate && !(recursiveMeta = id && id == resolve2.normalizeId(schema.$schema)))
      this.validateSchema(schema, true);
    var localRefs = resolve2.ids.call(this, schema);
    var schemaObj = new SchemaObject({
      id,
      schema,
      localRefs,
      cacheKey,
      meta
    });
    if (id[0] != "#" && shouldAddSchema) this._refs[id] = schemaObj;
    this._cache.put(cacheKey, schemaObj);
    if (willValidate && recursiveMeta) this.validateSchema(schema, true);
    return schemaObj;
  }
  function _compile(schemaObj, root) {
    if (schemaObj.compiling) {
      schemaObj.validate = callValidate;
      callValidate.schema = schemaObj.schema;
      callValidate.errors = null;
      callValidate.root = root ? root : callValidate;
      if (schemaObj.schema.$async === true)
        callValidate.$async = true;
      return callValidate;
    }
    schemaObj.compiling = true;
    var currentOpts;
    if (schemaObj.meta) {
      currentOpts = this._opts;
      this._opts = this._metaOpts;
    }
    var v2;
    try {
      v2 = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
    } catch (e4) {
      delete schemaObj.validate;
      throw e4;
    } finally {
      schemaObj.compiling = false;
      if (schemaObj.meta) this._opts = currentOpts;
    }
    schemaObj.validate = v2;
    schemaObj.refs = v2.refs;
    schemaObj.refVal = v2.refVal;
    schemaObj.root = v2.root;
    return v2;
    function callValidate() {
      var _validate = schemaObj.validate;
      var result = _validate.apply(this, arguments);
      callValidate.errors = _validate.errors;
      return result;
    }
  }
  function chooseGetId(opts) {
    switch (opts.schemaId) {
      case "auto":
        return _get$IdOrId;
      case "id":
        return _getId;
      default:
        return _get$Id;
    }
  }
  function _getId(schema) {
    if (schema.$id) this.logger.warn("schema $id ignored", schema.$id);
    return schema.id;
  }
  function _get$Id(schema) {
    if (schema.id) this.logger.warn("schema id ignored", schema.id);
    return schema.$id;
  }
  function _get$IdOrId(schema) {
    if (schema.$id && schema.id && schema.$id != schema.id)
      throw new Error("schema $id is different from id");
    return schema.$id || schema.id;
  }
  function errorsText(errors, options2) {
    errors = errors || this.errors;
    if (!errors) return "No errors";
    options2 = options2 || {};
    var separator = options2.separator === void 0 ? ", " : options2.separator;
    var dataVar = options2.dataVar === void 0 ? "data" : options2.dataVar;
    var text = "";
    for (var i2 = 0; i2 < errors.length; i2++) {
      var e4 = errors[i2];
      if (e4) text += dataVar + e4.dataPath + " " + e4.message + separator;
    }
    return text.slice(0, -separator.length);
  }
  function addFormat(name, format2) {
    if (typeof format2 == "string") format2 = new RegExp(format2);
    this._formats[name] = format2;
    return this;
  }
  function addDefaultMetaSchema(self2) {
    var $dataSchema;
    if (self2._opts.$data) {
      $dataSchema = require$$12;
      self2.addMetaSchema($dataSchema, $dataSchema.$id, true);
    }
    if (self2._opts.meta === false) return;
    var metaSchema = require$$13;
    if (self2._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
    self2.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
    self2._refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
  }
  function addInitialSchemas(self2) {
    var optsSchemas = self2._opts.schemas;
    if (!optsSchemas) return;
    if (Array.isArray(optsSchemas)) self2.addSchema(optsSchemas);
    else for (var key2 in optsSchemas) self2.addSchema(optsSchemas[key2], key2);
  }
  function addInitialFormats(self2) {
    for (var name in self2._opts.formats) {
      var format2 = self2._opts.formats[name];
      self2.addFormat(name, format2);
    }
  }
  function addInitialKeywords(self2) {
    for (var name in self2._opts.keywords) {
      var keyword2 = self2._opts.keywords[name];
      self2.addKeyword(name, keyword2);
    }
  }
  function checkUnique(self2, id) {
    if (self2._schemas[id] || self2._refs[id])
      throw new Error('schema with key or id "' + id + '" already exists');
  }
  function getMetaSchemaOptions(self2) {
    var metaOpts = util2.copy(self2._opts);
    for (var i2 = 0; i2 < META_IGNORE_OPTIONS.length; i2++)
      delete metaOpts[META_IGNORE_OPTIONS[i2]];
    return metaOpts;
  }
  function setLogger(self2) {
    var logger = self2._opts.logger;
    if (logger === false) {
      self2.logger = { log: noop2, warn: noop2, error: noop2 };
    } else {
      if (logger === void 0) logger = console;
      if (!(typeof logger == "object" && logger.log && logger.warn && logger.error))
        throw new Error("logger must implement log, warn and error methods");
      self2.logger = logger;
    }
  }
  function noop2() {
  }
  return ajv;
}
var ajvExports = requireAjv();
const Ajv = /* @__PURE__ */ getDefaultExportFromCjs$1(ajvExports);
class Client extends Protocol {
  /**
   * Initializes this client with the given name and version information.
   */
  constructor(_clientInfo, options2) {
    var _a3;
    super(options2);
    this._clientInfo = _clientInfo;
    this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
    this._capabilities = (_a3 = options2 === null || options2 === void 0 ? void 0 : options2.capabilities) !== null && _a3 !== void 0 ? _a3 : {};
    this._ajv = new Ajv();
  }
  /**
   * Registers new capabilities. This can only be called before connecting to a transport.
   *
   * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
   */
  registerCapabilities(capabilities) {
    if (this.transport) {
      throw new Error("Cannot register capabilities after connecting to transport");
    }
    this._capabilities = mergeCapabilities(this._capabilities, capabilities);
  }
  assertCapability(capability, method) {
    var _a3;
    if (!((_a3 = this._serverCapabilities) === null || _a3 === void 0 ? void 0 : _a3[capability])) {
      throw new Error(`Server does not support ${capability} (required for ${method})`);
    }
  }
  async connect(transport, options2) {
    await super.connect(transport);
    if (transport.sessionId !== void 0) {
      return;
    }
    try {
      const result = await this.request({
        method: "initialize",
        params: {
          protocolVersion: LATEST_PROTOCOL_VERSION,
          capabilities: this._capabilities,
          clientInfo: this._clientInfo
        }
      }, InitializeResultSchema, options2);
      if (result === void 0) {
        throw new Error(`Server sent invalid initialize result: ${result}`);
      }
      if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
        throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
      }
      this._serverCapabilities = result.capabilities;
      this._serverVersion = result.serverInfo;
      if (transport.setProtocolVersion) {
        transport.setProtocolVersion(result.protocolVersion);
      }
      this._instructions = result.instructions;
      await this.notification({
        method: "notifications/initialized"
      });
    } catch (error) {
      void this.close();
      throw error;
    }
  }
  /**
   * After initialization has completed, this will be populated with the server's reported capabilities.
   */
  getServerCapabilities() {
    return this._serverCapabilities;
  }
  /**
   * After initialization has completed, this will be populated with information about the server's name and version.
   */
  getServerVersion() {
    return this._serverVersion;
  }
  /**
   * After initialization has completed, this may be populated with information about the server's instructions.
   */
  getInstructions() {
    return this._instructions;
  }
  assertCapabilityForMethod(method) {
    var _a3, _b2, _c2, _d2, _e2;
    switch (method) {
      case "logging/setLevel":
        if (!((_a3 = this._serverCapabilities) === null || _a3 === void 0 ? void 0 : _a3.logging)) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!((_b2 = this._serverCapabilities) === null || _b2 === void 0 ? void 0 : _b2.prompts)) {
          throw new Error(`Server does not support prompts (required for ${method})`);
        }
        break;
      case "resources/list":
      case "resources/templates/list":
      case "resources/read":
      case "resources/subscribe":
      case "resources/unsubscribe":
        if (!((_c2 = this._serverCapabilities) === null || _c2 === void 0 ? void 0 : _c2.resources)) {
          throw new Error(`Server does not support resources (required for ${method})`);
        }
        if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
          throw new Error(`Server does not support resource subscriptions (required for ${method})`);
        }
        break;
      case "tools/call":
      case "tools/list":
        if (!((_d2 = this._serverCapabilities) === null || _d2 === void 0 ? void 0 : _d2.tools)) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "completion/complete":
        if (!((_e2 = this._serverCapabilities) === null || _e2 === void 0 ? void 0 : _e2.completions)) {
          throw new Error(`Server does not support completions (required for ${method})`);
        }
        break;
    }
  }
  assertNotificationCapability(method) {
    var _a3;
    switch (method) {
      case "notifications/roots/list_changed":
        if (!((_a3 = this._capabilities.roots) === null || _a3 === void 0 ? void 0 : _a3.listChanged)) {
          throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
        }
        break;
    }
  }
  assertRequestHandlerCapability(method) {
    switch (method) {
      case "sampling/createMessage":
        if (!this._capabilities.sampling) {
          throw new Error(`Client does not support sampling capability (required for ${method})`);
        }
        break;
      case "elicitation/create":
        if (!this._capabilities.elicitation) {
          throw new Error(`Client does not support elicitation capability (required for ${method})`);
        }
        break;
      case "roots/list":
        if (!this._capabilities.roots) {
          throw new Error(`Client does not support roots capability (required for ${method})`);
        }
        break;
    }
  }
  async ping(options2) {
    return this.request({ method: "ping" }, EmptyResultSchema, options2);
  }
  async complete(params, options2) {
    return this.request({ method: "completion/complete", params }, CompleteResultSchema, options2);
  }
  async setLoggingLevel(level, options2) {
    return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options2);
  }
  async getPrompt(params, options2) {
    return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options2);
  }
  async listPrompts(params, options2) {
    return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options2);
  }
  async listResources(params, options2) {
    return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options2);
  }
  async listResourceTemplates(params, options2) {
    return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options2);
  }
  async readResource(params, options2) {
    return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options2);
  }
  async subscribeResource(params, options2) {
    return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options2);
  }
  async unsubscribeResource(params, options2) {
    return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options2);
  }
  async callTool(params, resultSchema = CallToolResultSchema, options2) {
    const result = await this.request({ method: "tools/call", params }, resultSchema, options2);
    const validator2 = this.getToolOutputValidator(params.name);
    if (validator2) {
      if (!result.structuredContent && !result.isError) {
        throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
      }
      if (result.structuredContent) {
        try {
          const isValid2 = validator2(result.structuredContent);
          if (!isValid2) {
            throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${this._ajv.errorsText(validator2.errors)}`);
          }
        } catch (error) {
          if (error instanceof McpError) {
            throw error;
          }
          throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    }
    return result;
  }
  cacheToolOutputSchemas(tools) {
    this._cachedToolOutputValidators.clear();
    for (const tool of tools) {
      if (tool.outputSchema) {
        try {
          const validator2 = this._ajv.compile(tool.outputSchema);
          this._cachedToolOutputValidators.set(tool.name, validator2);
        } catch (_a3) {
        }
      }
    }
  }
  getToolOutputValidator(toolName) {
    return this._cachedToolOutputValidators.get(toolName);
  }
  async listTools(params, options2) {
    const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options2);
    this.cacheToolOutputSchemas(result.tools);
    return result;
  }
  async sendRootsListChanged() {
    return this.notification({ method: "notifications/roots/list_changed" });
  }
}
class Server extends Protocol {
  /**
   * Initializes this server with the given name and version information.
   */
  constructor(_serverInfo, options2) {
    var _a3;
    super(options2);
    this._serverInfo = _serverInfo;
    this._capabilities = (_a3 = options2 === null || options2 === void 0 ? void 0 : options2.capabilities) !== null && _a3 !== void 0 ? _a3 : {};
    this._instructions = options2 === null || options2 === void 0 ? void 0 : options2.instructions;
    this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
    this.setNotificationHandler(InitializedNotificationSchema, () => {
      var _a4;
      return (_a4 = this.oninitialized) === null || _a4 === void 0 ? void 0 : _a4.call(this);
    });
  }
  /**
   * Registers new capabilities. This can only be called before connecting to a transport.
   *
   * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
   */
  registerCapabilities(capabilities) {
    if (this.transport) {
      throw new Error("Cannot register capabilities after connecting to transport");
    }
    this._capabilities = mergeCapabilities(this._capabilities, capabilities);
  }
  assertCapabilityForMethod(method) {
    var _a3, _b2, _c2;
    switch (method) {
      case "sampling/createMessage":
        if (!((_a3 = this._clientCapabilities) === null || _a3 === void 0 ? void 0 : _a3.sampling)) {
          throw new Error(`Client does not support sampling (required for ${method})`);
        }
        break;
      case "elicitation/create":
        if (!((_b2 = this._clientCapabilities) === null || _b2 === void 0 ? void 0 : _b2.elicitation)) {
          throw new Error(`Client does not support elicitation (required for ${method})`);
        }
        break;
      case "roots/list":
        if (!((_c2 = this._clientCapabilities) === null || _c2 === void 0 ? void 0 : _c2.roots)) {
          throw new Error(`Client does not support listing roots (required for ${method})`);
        }
        break;
    }
  }
  assertNotificationCapability(method) {
    switch (method) {
      case "notifications/message":
        if (!this._capabilities.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "notifications/resources/updated":
      case "notifications/resources/list_changed":
        if (!this._capabilities.resources) {
          throw new Error(`Server does not support notifying about resources (required for ${method})`);
        }
        break;
      case "notifications/tools/list_changed":
        if (!this._capabilities.tools) {
          throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
        }
        break;
      case "notifications/prompts/list_changed":
        if (!this._capabilities.prompts) {
          throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
        }
        break;
    }
  }
  assertRequestHandlerCapability(method) {
    switch (method) {
      case "sampling/createMessage":
        if (!this._capabilities.sampling) {
          throw new Error(`Server does not support sampling (required for ${method})`);
        }
        break;
      case "logging/setLevel":
        if (!this._capabilities.logging) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!this._capabilities.prompts) {
          throw new Error(`Server does not support prompts (required for ${method})`);
        }
        break;
      case "resources/list":
      case "resources/templates/list":
      case "resources/read":
        if (!this._capabilities.resources) {
          throw new Error(`Server does not support resources (required for ${method})`);
        }
        break;
      case "tools/call":
      case "tools/list":
        if (!this._capabilities.tools) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
    }
  }
  async _oninitialize(request) {
    const requestedVersion = request.params.protocolVersion;
    this._clientCapabilities = request.params.capabilities;
    this._clientVersion = request.params.clientInfo;
    const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
    return {
      protocolVersion,
      capabilities: this.getCapabilities(),
      serverInfo: this._serverInfo,
      ...this._instructions && { instructions: this._instructions }
    };
  }
  /**
   * After initialization has completed, this will be populated with the client's reported capabilities.
   */
  getClientCapabilities() {
    return this._clientCapabilities;
  }
  /**
   * After initialization has completed, this will be populated with information about the client's name and version.
   */
  getClientVersion() {
    return this._clientVersion;
  }
  getCapabilities() {
    return this._capabilities;
  }
  async ping() {
    return this.request({ method: "ping" }, EmptyResultSchema);
  }
  async createMessage(params, options2) {
    return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options2);
  }
  async elicitInput(params, options2) {
    const result = await this.request({ method: "elicitation/create", params }, ElicitResultSchema, options2);
    if (result.action === "accept" && result.content) {
      try {
        const ajv2 = new Ajv();
        const validate2 = ajv2.compile(params.requestedSchema);
        const isValid2 = validate2(result.content);
        if (!isValid2) {
          throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${ajv2.errorsText(validate2.errors)}`);
        }
      } catch (error) {
        if (error instanceof McpError) {
          throw error;
        }
        throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error}`);
      }
    }
    return result;
  }
  async listRoots(params, options2) {
    return this.request({ method: "roots/list", params }, ListRootsResultSchema, options2);
  }
  async sendLoggingMessage(params) {
    return this.notification({ method: "notifications/message", params });
  }
  async sendResourceUpdated(params) {
    return this.notification({
      method: "notifications/resources/updated",
      params
    });
  }
  async sendResourceListChanged() {
    return this.notification({
      method: "notifications/resources/list_changed"
    });
  }
  async sendToolListChanged() {
    return this.notification({ method: "notifications/tools/list_changed" });
  }
  async sendPromptListChanged() {
    return this.notification({ method: "notifications/prompts/list_changed" });
  }
}
const scriptRel = /* @__PURE__ */ function detectScriptRel() {
  const relList = typeof document !== "undefined" && document.createElement("link").relList;
  return relList && relList.supports && relList.supports("modulepreload") ? "modulepreload" : "preload";
}();
const assetsURL = function(dep) {
  return "/sdppp/" + dep;
};
const seen = {};
const __vitePreload = function preload(baseModule, deps, importerUrl) {
  let promise = Promise.resolve();
  if (false) {
    let allSettled2 = function(promises) {
      return Promise.all(
        promises.map(
          (p2) => Promise.resolve(p2).then(
            (value) => ({ status: "fulfilled", value }),
            (reason) => ({ status: "rejected", reason })
          )
        )
      );
    };
    document.getElementsByTagName("link");
    const cspNonceMeta = document.querySelector(
      "meta[property=csp-nonce]"
    );
    const cspNonce = (cspNonceMeta == null ? void 0 : cspNonceMeta.nonce) || (cspNonceMeta == null ? void 0 : cspNonceMeta.getAttribute("nonce"));
    promise = allSettled2(
      deps.map((dep) => {
        dep = assetsURL(dep);
        if (dep in seen) return;
        seen[dep] = true;
        const isCss = dep.endsWith(".css");
        const cssSelector = isCss ? '[rel="stylesheet"]' : "";
        if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
          return;
        }
        const link = document.createElement("link");
        link.rel = isCss ? "stylesheet" : scriptRel;
        if (!isCss) {
          link.as = "script";
        }
        link.crossOrigin = "";
        link.href = dep;
        if (cspNonce) {
          link.setAttribute("nonce", cspNonce);
        }
        document.head.appendChild(link);
        if (isCss) {
          return new Promise((res, rej) => {
            link.addEventListener("load", res);
            link.addEventListener(
              "error",
              () => rej(new Error(`Unable to preload CSS for ${dep}`))
            );
          });
        }
      })
    );
  }
  function handlePreloadError(err) {
    const e4 = new Event("vite:preloadError", {
      cancelable: true
    });
    e4.payload = err;
    window.dispatchEvent(e4);
    if (!e4.defaultPrevented) {
      throw err;
    }
  }
  return promise.then((res) => {
    for (const item of res || []) {
      if (item.status !== "rejected") continue;
      handlePreloadError(item.reason);
    }
    return baseModule().catch(handlePreloadError);
  });
};
var browser$2 = { exports: {} };
var ms;
var hasRequiredMs;
function requireMs() {
  if (hasRequiredMs) return ms;
  hasRequiredMs = 1;
  var s2 = 1e3;
  var m = s2 * 60;
  var h2 = m * 60;
  var d = h2 * 24;
  var w = d * 7;
  var y2 = d * 365.25;
  ms = function(val, options2) {
    options2 = options2 || {};
    var type2 = typeof val;
    if (type2 === "string" && val.length > 0) {
      return parse(val);
    } else if (type2 === "number" && isFinite(val)) {
      return options2.long ? fmtLong(val) : fmtShort(val);
    }
    throw new Error(
      "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
    );
  };
  function parse(str) {
    str = String(str);
    if (str.length > 100) {
      return;
    }
    var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
      str
    );
    if (!match) {
      return;
    }
    var n2 = parseFloat(match[1]);
    var type2 = (match[2] || "ms").toLowerCase();
    switch (type2) {
      case "years":
      case "year":
      case "yrs":
      case "yr":
      case "y":
        return n2 * y2;
      case "weeks":
      case "week":
      case "w":
        return n2 * w;
      case "days":
      case "day":
      case "d":
        return n2 * d;
      case "hours":
      case "hour":
      case "hrs":
      case "hr":
      case "h":
        return n2 * h2;
      case "minutes":
      case "minute":
      case "mins":
      case "min":
      case "m":
        return n2 * m;
      case "seconds":
      case "second":
      case "secs":
      case "sec":
      case "s":
        return n2 * s2;
      case "milliseconds":
      case "millisecond":
      case "msecs":
      case "msec":
      case "ms":
        return n2;
      default:
        return void 0;
    }
  }
  function fmtShort(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return Math.round(ms2 / d) + "d";
    }
    if (msAbs >= h2) {
      return Math.round(ms2 / h2) + "h";
    }
    if (msAbs >= m) {
      return Math.round(ms2 / m) + "m";
    }
    if (msAbs >= s2) {
      return Math.round(ms2 / s2) + "s";
    }
    return ms2 + "ms";
  }
  function fmtLong(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return plural(ms2, msAbs, d, "day");
    }
    if (msAbs >= h2) {
      return plural(ms2, msAbs, h2, "hour");
    }
    if (msAbs >= m) {
      return plural(ms2, msAbs, m, "minute");
    }
    if (msAbs >= s2) {
      return plural(ms2, msAbs, s2, "second");
    }
    return ms2 + " ms";
  }
  function plural(ms2, msAbs, n2, name) {
    var isPlural = msAbs >= n2 * 1.5;
    return Math.round(ms2 / n2) + " " + name + (isPlural ? "s" : "");
  }
  return ms;
}
var common$1;
var hasRequiredCommon$1;
function requireCommon$1() {
  if (hasRequiredCommon$1) return common$1;
  hasRequiredCommon$1 = 1;
  function setup(env) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce2;
    createDebug.disable = disable;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = requireMs();
    createDebug.destroy = destroy;
    Object.keys(env).forEach((key2) => {
      createDebug[key2] = env[key2];
    });
    createDebug.names = [];
    createDebug.skips = [];
    createDebug.formatters = {};
    function selectColor(namespace) {
      let hash2 = 0;
      for (let i2 = 0; i2 < namespace.length; i2++) {
        hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i2);
        hash2 |= 0;
      }
      return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
    }
    createDebug.selectColor = selectColor;
    function createDebug(namespace) {
      let prevTime;
      let enableOverride = null;
      let namespacesCache;
      let enabledCache;
      function debug2(...args) {
        if (!debug2.enabled) {
          return;
        }
        const self2 = debug2;
        const curr = Number(/* @__PURE__ */ new Date());
        const ms2 = curr - (prevTime || curr);
        self2.diff = ms2;
        self2.prev = prevTime;
        self2.curr = curr;
        prevTime = curr;
        args[0] = createDebug.coerce(args[0]);
        if (typeof args[0] !== "string") {
          args.unshift("%O");
        }
        let index2 = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format2) => {
          if (match === "%%") {
            return "%";
          }
          index2++;
          const formatter = createDebug.formatters[format2];
          if (typeof formatter === "function") {
            const val = args[index2];
            match = formatter.call(self2, val);
            args.splice(index2, 1);
            index2--;
          }
          return match;
        });
        createDebug.formatArgs.call(self2, args);
        const logFn = self2.log || createDebug.log;
        logFn.apply(self2, args);
      }
      debug2.namespace = namespace;
      debug2.useColors = createDebug.useColors();
      debug2.color = createDebug.selectColor(namespace);
      debug2.extend = extend;
      debug2.destroy = createDebug.destroy;
      Object.defineProperty(debug2, "enabled", {
        enumerable: true,
        configurable: false,
        get: () => {
          if (enableOverride !== null) {
            return enableOverride;
          }
          if (namespacesCache !== createDebug.namespaces) {
            namespacesCache = createDebug.namespaces;
            enabledCache = createDebug.enabled(namespace);
          }
          return enabledCache;
        },
        set: (v2) => {
          enableOverride = v2;
        }
      });
      if (typeof createDebug.init === "function") {
        createDebug.init(debug2);
      }
      return debug2;
    }
    function extend(namespace, delimiter) {
      const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
      newDebug.log = this.log;
      return newDebug;
    }
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.namespaces = namespaces;
      createDebug.names = [];
      createDebug.skips = [];
      const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
      for (const ns of split) {
        if (ns[0] === "-") {
          createDebug.skips.push(ns.slice(1));
        } else {
          createDebug.names.push(ns);
        }
      }
    }
    function matchesTemplate(search, template) {
      let searchIndex = 0;
      let templateIndex = 0;
      let starIndex = -1;
      let matchIndex = 0;
      while (searchIndex < search.length) {
        if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
          if (template[templateIndex] === "*") {
            starIndex = templateIndex;
            matchIndex = searchIndex;
            templateIndex++;
          } else {
            searchIndex++;
            templateIndex++;
          }
        } else if (starIndex !== -1) {
          templateIndex = starIndex + 1;
          matchIndex++;
          searchIndex = matchIndex;
        } else {
          return false;
        }
      }
      while (templateIndex < template.length && template[templateIndex] === "*") {
        templateIndex++;
      }
      return templateIndex === template.length;
    }
    function disable() {
      const namespaces = [
        ...createDebug.names,
        ...createDebug.skips.map((namespace) => "-" + namespace)
      ].join(",");
      createDebug.enable("");
      return namespaces;
    }
    function enabled(name) {
      for (const skip of createDebug.skips) {
        if (matchesTemplate(name, skip)) {
          return false;
        }
      }
      for (const ns of createDebug.names) {
        if (matchesTemplate(name, ns)) {
          return true;
        }
      }
      return false;
    }
    function coerce2(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
      return val;
    }
    function destroy() {
      console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
    }
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  common$1 = setup;
  return common$1;
}
var hasRequiredBrowser;
function requireBrowser() {
  if (hasRequiredBrowser) return browser$2.exports;
  hasRequiredBrowser = 1;
  (function(module2, exports) {
    var define_process_env_default = {};
    exports.formatArgs = formatArgs;
    exports.save = save;
    exports.load = load2;
    exports.useColors = useColors;
    exports.storage = localstorage();
    exports.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c2 = "color: " + this.color;
      args.splice(1, 0, c2, "color: inherit");
      let index2 = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index2++;
        if (match === "%c") {
          lastC = index2;
        }
      });
      args.splice(lastC, 0, c2);
    }
    exports.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports.storage.setItem("debug", namespaces);
        } else {
          exports.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load2() {
      let r2;
      try {
        r2 = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r2 && typeof process !== "undefined" && "env" in process) {
        r2 = define_process_env_default.DEBUG;
      }
      return r2;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module2.exports = requireCommon$1()(exports);
    const { formatters } = module2.exports;
    formatters.j = function(v2) {
      try {
        return JSON.stringify(v2);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  })(browser$2, browser$2.exports);
  return browser$2.exports;
}
var browserExports$1 = requireBrowser();
const debug = /* @__PURE__ */ getDefaultExportFromCjs$1(browserExports$1);
debug.enable("*");
function makeLogger(name, meshLog) {
  const logger = debug(name);
  const createLogMethod = (level, originFn) => {
    return async function(...args) {
      try {
        await meshLog({
          level,
          messages: args
        });
      } catch (error) {
      }
    };
  };
  logger.log = createLogMethod("log");
  return logger;
}
const sdpppLogger = makeLogger("mesh:uxp", async ({
  level,
  messages: messages2
}) => {
  const { mcpMesh: mcpMesh2 } = await __vitePreload(async () => {
    const { mcpMesh: mcpMesh3 } = await Promise.resolve().then(() => index);
    return { mcpMesh: mcpMesh3 };
  }, false ? __VITE_PRELOAD__ : void 0);
  await mcpMesh2.actions.log({
    level,
    messages: messages2
  });
});
const log$2 = sdpppLogger.extend("mesh");
const mcpMesh = meshDef.joinAs("uxp");
globalThis.mcpMesh = mcpMesh;
function createTransport(posterIdentifier, webview) {
  const transport = new PostMessageClientTransport({
    posterIdentifier,
    messagePoster: (message) => {
      webview.postMessage(message, "*");
    },
    addMessageEventListener: (originListener) => {
      const listener = (payload) => {
        originListener(payload.data);
      };
      window.addEventListener("message", listener);
      return listener;
    },
    removeMessageEventListener: (listener) => {
      window.removeEventListener("message", listener);
    }
    // debugDisableHeartbeatResponse: true
  });
  return transport;
}
async function connectSDK(webview) {
  const transport = createTransport("sdk-uxp", webview);
  let afterMeshConnect = false;
  transport.onconnectionstatechange = (state) => {
    mcpMesh.store.setState({
      sdkWebviewConnectStatus: state === "connected" && afterMeshConnect ? "connected" : state === "reconnecting" ? "connecting" : "disconnected"
    });
  };
  transport.onerror = (error) => {
    if (error.name === "HeartbeatTimeoutError") {
      log$2("SDK heartbeat timeout detected:", error.message);
    }
    log$2("sdk transport.onerror", error);
  };
  const server = new Server({
    name: "uxp-server",
    version: "1.0.0"
  }, {});
  const session = new MCPSDPPPSessionAdaptor(server);
  await session.connect(transport);
  await mcpMesh.connect("sdk", session);
  afterMeshConnect = true;
}
async function connectComfy(webview) {
  const transport = createTransport("comfy-uxp", webview);
  let afterMeshConnect = false;
  transport.onconnectionstatechange = (state) => {
    mcpMesh.store.setState({
      comfyWebviewConnectStatus: state === "connected" && afterMeshConnect ? "connected" : state === "reconnecting" ? "connecting" : "disconnected"
    });
  };
  transport.onerror = (error) => {
    if (error.name === "HeartbeatTimeoutError") {
      log$2("Comfy heartbeat timeout detected:", error.message);
    }
    log$2("comfy transport.onerror", error);
  };
  const client2 = new Client({
    name: "uxp-client",
    version: "1.0.0"
  }, {});
  const session = new MCPSDPPPSessionAdaptor(client2);
  log$2("comfy session connect");
  await session.connect(transport);
  log$2("comfy session connected, connect comfy mesh");
  await mcpMesh.connect("comfy", session);
  log$2("comfy mesh connected");
  let resolvedVersion = null;
  try {
    const comfyActions = mcpMesh.getNode("comfy").actions;
    if (typeof (comfyActions == null ? void 0 : comfyActions.sdpppHandshake) !== "function") {
      throw new Error("sdpppHandshake action not implemented on comfy node");
    }
    const handshake = await comfyActions.sdpppHandshake({ hostVersion: "510" });
    if ((handshake == null ? void 0 : handshake.comfyVersion) && typeof handshake.comfyVersion === "string") {
      resolvedVersion = handshake.comfyVersion.trim();
      if (!resolvedVersion) {
        throw new Error("Handshake returned empty version string");
      }
    } else {
      throw new Error("Handshake response missing comfyVersion");
    }
  } catch (error) {
    log$2("comfy version handshake failed", error);
  }
  if (resolvedVersion) {
    mcpMesh.store.setState({
      comfyWebviewVersion: resolvedVersion,
      comfyHTTPCode: 200,
      comfyWebviewLoadError: ""
    });
  } else {
    mcpMesh.store.setState({
      comfyWebviewVersion: "unknown",
      comfyHTTPCode: 0,
      comfyWebviewLoadError: ""
    });
  }
  afterMeshConnect = true;
}
class LocalStorageAdapter {
  async getItem(key2) {
    try {
      if (typeof window === "undefined") return null;
      return localStorage.getItem(key2);
    } catch (error) {
      console.warn("[vite-remote-config-loader] Failed to get item from localStorage:", error);
      return null;
    }
  }
  async setItem(key2, value) {
    try {
      if (typeof window === "undefined") return;
      localStorage.setItem(key2, value);
    } catch (error) {
      console.warn("[vite-remote-config-loader] Failed to set item to localStorage:", error);
    }
  }
  async removeItem(key2) {
    try {
      if (typeof window === "undefined") return;
      localStorage.removeItem(key2);
    } catch (error) {
      console.warn("[vite-remote-config-loader] Failed to remove item from localStorage:", error);
    }
  }
}
let storageAdapter = new LocalStorageAdapter();
let cachedConfigMeta = null;
let cachedFallbackData = null;
const memoryCache = /* @__PURE__ */ new Map();
const updatingConfigs = /* @__PURE__ */ new Set();
const lastUpdateTimes = /* @__PURE__ */ new Map();
let isInitialized = false;
function getConfigMeta() {
  if (cachedConfigMeta) {
    return cachedConfigMeta;
  }
  if (typeof window !== "undefined" && window.__VITE_REMOTE_CONFIG_META__) {
    cachedConfigMeta = window.__VITE_REMOTE_CONFIG_META__;
    return cachedConfigMeta;
  }
  console.warn("[vite-remote-config-loader] Config meta not available. Make sure the plugin is configured in vite.config.ts");
  return {};
}
function getFallbackData() {
  if (cachedFallbackData) {
    return cachedFallbackData;
  }
  if (typeof window !== "undefined" && window.__VITE_REMOTE_CONFIG_FALLBACK__) {
    cachedFallbackData = window.__VITE_REMOTE_CONFIG_FALLBACK__;
    return cachedFallbackData;
  }
  console.warn("[vite-remote-config-loader] Fallback data not available. Make sure the plugin is configured in vite.config.ts");
  return {};
}
function getCachedData(key2) {
  return memoryCache.get(key2) ?? null;
}
async function loadCachedDataToMemory(key2) {
  try {
    const cached = await storageAdapter.getItem(key2);
    if (cached) {
      const data2 = JSON.parse(cached);
      memoryCache.set(key2, data2);
    }
  } catch (error) {
    console.warn("[vite-remote-config-loader] Failed to load cached data:", error);
  }
}
async function setCachedData(key2, data2) {
  try {
    memoryCache.set(key2, data2);
    await storageAdapter.setItem(key2, JSON.stringify(data2));
  } catch (error) {
    console.warn("[vite-remote-config-loader] Failed to cache data:", error);
  }
}
async function updateConfigInBackground(id, url, localStorageKey) {
  if (updatingConfigs.has(id)) {
    return;
  }
  const now = Date.now();
  const lastUpdateTime = lastUpdateTimes.get(id);
  const oneHour = 60 * 60 * 1e3;
  if (lastUpdateTime && now - lastUpdateTime < oneHour) {
    console.log(`[vite-remote-config-loader] Config "${id}" was updated recently, skipping remote fetch`);
    return;
  }
  updatingConfigs.add(id);
  try {
    console.log(`[vite-remote-config-loader] Background updating config: ${id} from ${url}`);
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    const data2 = await response.json();
    await setCachedData(localStorageKey, data2);
    lastUpdateTimes.set(id, now);
    console.log(`[vite-remote-config-loader] Successfully updated config: ${id}`);
  } catch (error) {
    console.warn(`[vite-remote-config-loader] Failed to update config: ${id}`, error);
  } finally {
    updatingConfigs.delete(id);
  }
}
async function init$1() {
  if (isInitialized) {
    return;
  }
  console.log("[vite-remote-config-loader] Initializing cache...");
  try {
    const configMeta = getConfigMeta();
    const loadPromises = Object.values(configMeta).map(
      (meta) => loadCachedDataToMemory(meta.localStorageKey)
    );
    await Promise.all(loadPromises);
    isInitialized = true;
    console.log("[vite-remote-config-loader] Cache initialization completed");
  } catch (error) {
    console.warn("[vite-remote-config-loader] Cache initialization failed:", error);
    isInitialized = true;
  }
}
function loadRemoteConfig(id, options2 = {}) {
  const configMeta = getConfigMeta();
  const meta = configMeta[id];
  if (!meta) {
    console.warn(`[vite-remote-config-loader] Configuration "${id}" not found. Available configs:`, Object.keys(configMeta));
    throw new Error(`Configuration with id "${id}" not found. Make sure it's defined in your Vite config.`);
  }
  const localStorageKey = options2.localStorageKey ?? meta.localStorageKey;
  const cachedData = getCachedData(localStorageKey);
  if (cachedData !== null) {
    console.log(`[vite-remote-config-loader] Using cached data for config: ${id}`);
    updateConfigInBackground(id, meta.url, localStorageKey);
    return cachedData;
  }
  const fallbackData = getFallbackData();
  const fallback = fallbackData[id];
  if (fallback !== void 0) {
    console.log(`[vite-remote-config-loader] Using fallback data for config: ${id}`);
    updateConfigInBackground(id, meta.url, localStorageKey);
    return fallback;
  }
  throw new Error(`No data available for config: ${id}`);
}
async function execute$1() {
  const tenantid = mcpMesh.store.getState().sdpppX.tenantid;
  if (!tenantid) {
    return;
  }
  const tenantInfo = loadRemoteConfig("tenant");
  if (tenantInfo.name_chn) {
    PSUXPInternalStore.setState({
      headerTitle: tenantInfo.name_chn
    });
  }
  if (!tenantInfo.authing_id) {
    throw new Error("tenantInfo.authing_id is required");
  }
  const provider = new SDPPPLoginProvider(tenantInfo.authing_id);
  PSUXPInternalStore.setState({
    loginProvider: provider
  });
  console.log("🐦 登录Provider已设置");
}
const hasPlugins = true;
const pluginCount$1 = 1;
const pluginNames$1 = ["@sdppp/auth"];
const pluginFiles$1 = ["capabilities/auth/@uxp/ps-uxp-store-provider.ts"];
async function executeAllPlugins$1() {
  console.log(`🎯 执行 ${pluginCount$1} 个插件:`);
  pluginNames$1.forEach((name, index2) => {
    console.log(`   ${index2 + 1}. ${name} (${pluginFiles$1[index2]})`);
  });
  try {
    const results = await Promise.all([
      execute$1 && await execute$1()
    ]);
    console.log("✅ 所有插件执行完成");
    return results.filter((r2) => r2 !== void 0);
  } catch (error) {
    console.error("❌ 插件执行失败:", error);
    throw error;
  }
}
async function initLoginProviders() {
  try {
    if (hasPlugins) {
      await executeAllPlugins$1();
    }
  } catch (error) {
    console.error("❌ 登录Provider初始化失败:", error);
    PSUXPInternalStore.setState({ loginProvider: new DefaultLoginProvider() });
  }
}
async function initPlugins() {
  await initLoginProviders();
}
globalThis.sdpppX = globalThis.sdpppX || {};
const sdpppX = globalThis.sdpppX;
if (!("settings.imaging.defaultImagesSizeLimit" in sdpppX) || isNaN(sdpppX["settings.imaging.defaultImagesSizeLimit"])) {
  sdpppX["settings.imaging.defaultImagesSizeLimit"] = 2048;
}
const sdpppXLog = [];
sdpppX.__getLogs__ = () => {
  return sdpppXLog;
};
var client = {};
var reactDom = { exports: {} };
var reactDom_development = {};
var scheduler = { exports: {} };
var scheduler_development = {};
var hasRequiredScheduler_development;
function requireScheduler_development() {
  if (hasRequiredScheduler_development) return scheduler_development;
  hasRequiredScheduler_development = 1;
  (function(exports) {
    /**
     * @license React
     * scheduler.development.js
     *
     * Copyright (c) Facebook, Inc. and its affiliates.
     *
     * This source code is licensed under the MIT license found in the
     * LICENSE file in the root directory of this source tree.
     */
    {
      (function() {
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
        }
        var enableProfiling = false;
        var frameYieldMs = 5;
        function push(heap, node2) {
          var index2 = heap.length;
          heap.push(node2);
          siftUp(heap, node2, index2);
        }
        function peek(heap) {
          return heap.length === 0 ? null : heap[0];
        }
        function pop(heap) {
          if (heap.length === 0) {
            return null;
          }
          var first = heap[0];
          var last = heap.pop();
          if (last !== first) {
            heap[0] = last;
            siftDown(heap, last, 0);
          }
          return first;
        }
        function siftUp(heap, node2, i2) {
          var index2 = i2;
          while (index2 > 0) {
            var parentIndex = index2 - 1 >>> 1;
            var parent = heap[parentIndex];
            if (compare(parent, node2) > 0) {
              heap[parentIndex] = node2;
              heap[index2] = parent;
              index2 = parentIndex;
            } else {
              return;
            }
          }
        }
        function siftDown(heap, node2, i2) {
          var index2 = i2;
          var length = heap.length;
          var halfLength = length >>> 1;
          while (index2 < halfLength) {
            var leftIndex = (index2 + 1) * 2 - 1;
            var left = heap[leftIndex];
            var rightIndex = leftIndex + 1;
            var right = heap[rightIndex];
            if (compare(left, node2) < 0) {
              if (rightIndex < length && compare(right, left) < 0) {
                heap[index2] = right;
                heap[rightIndex] = node2;
                index2 = rightIndex;
              } else {
                heap[index2] = left;
                heap[leftIndex] = node2;
                index2 = leftIndex;
              }
            } else if (rightIndex < length && compare(right, node2) < 0) {
              heap[index2] = right;
              heap[rightIndex] = node2;
              index2 = rightIndex;
            } else {
              return;
            }
          }
        }
        function compare(a2, b2) {
          var diff = a2.sortIndex - b2.sortIndex;
          return diff !== 0 ? diff : a2.id - b2.id;
        }
        var ImmediatePriority = 1;
        var UserBlockingPriority = 2;
        var NormalPriority = 3;
        var LowPriority = 4;
        var IdlePriority = 5;
        function markTaskErrored(task, ms2) {
        }
        var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function";
        if (hasPerformanceNow) {
          var localPerformance = performance;
          exports.unstable_now = function() {
            return localPerformance.now();
          };
        } else {
          var localDate = Date;
          var initialTime = localDate.now();
          exports.unstable_now = function() {
            return localDate.now() - initialTime;
          };
        }
        var maxSigned31BitInt = 1073741823;
        var IMMEDIATE_PRIORITY_TIMEOUT = -1;
        var USER_BLOCKING_PRIORITY_TIMEOUT = 250;
        var NORMAL_PRIORITY_TIMEOUT = 5e3;
        var LOW_PRIORITY_TIMEOUT = 1e4;
        var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt;
        var taskQueue = [];
        var timerQueue = [];
        var taskIdCounter = 1;
        var currentTask = null;
        var currentPriorityLevel = NormalPriority;
        var isPerformingWork = false;
        var isHostCallbackScheduled = false;
        var isHostTimeoutScheduled = false;
        var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null;
        var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null;
        var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null;
        typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null;
        function advanceTimers(currentTime) {
          var timer = peek(timerQueue);
          while (timer !== null) {
            if (timer.callback === null) {
              pop(timerQueue);
            } else if (timer.startTime <= currentTime) {
              pop(timerQueue);
              timer.sortIndex = timer.expirationTime;
              push(taskQueue, timer);
            } else {
              return;
            }
            timer = peek(timerQueue);
          }
        }
        function handleTimeout(currentTime) {
          isHostTimeoutScheduled = false;
          advanceTimers(currentTime);
          if (!isHostCallbackScheduled) {
            if (peek(taskQueue) !== null) {
              isHostCallbackScheduled = true;
              requestHostCallback(flushWork);
            } else {
              var firstTimer = peek(timerQueue);
              if (firstTimer !== null) {
                requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
              }
            }
          }
        }
        function flushWork(hasTimeRemaining, initialTime2) {
          isHostCallbackScheduled = false;
          if (isHostTimeoutScheduled) {
            isHostTimeoutScheduled = false;
            cancelHostTimeout();
          }
          isPerformingWork = true;
          var previousPriorityLevel = currentPriorityLevel;
          try {
            var currentTime;
            if (enableProfiling) ;
            else {
              return workLoop(hasTimeRemaining, initialTime2);
            }
          } finally {
            currentTask = null;
            currentPriorityLevel = previousPriorityLevel;
            isPerformingWork = false;
          }
        }
        function workLoop(hasTimeRemaining, initialTime2) {
          var currentTime = initialTime2;
          advanceTimers(currentTime);
          currentTask = peek(taskQueue);
          while (currentTask !== null && true) {
            if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
              break;
            }
            var callback = currentTask.callback;
            if (typeof callback === "function") {
              currentTask.callback = null;
              currentPriorityLevel = currentTask.priorityLevel;
              var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
              var continuationCallback = callback(didUserCallbackTimeout);
              currentTime = exports.unstable_now();
              if (typeof continuationCallback === "function") {
                currentTask.callback = continuationCallback;
              } else {
                if (currentTask === peek(taskQueue)) {
                  pop(taskQueue);
                }
              }
              advanceTimers(currentTime);
            } else {
              pop(taskQueue);
            }
            currentTask = peek(taskQueue);
          }
          if (currentTask !== null) {
            return true;
          } else {
            var firstTimer = peek(timerQueue);
            if (firstTimer !== null) {
              requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
            }
            return false;
          }
        }
        function unstable_runWithPriority(priorityLevel, eventHandler) {
          switch (priorityLevel) {
            case ImmediatePriority:
            case UserBlockingPriority:
            case NormalPriority:
            case LowPriority:
            case IdlePriority:
              break;
            default:
              priorityLevel = NormalPriority;
          }
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = priorityLevel;
          try {
            return eventHandler();
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        }
        function unstable_next(eventHandler) {
          var priorityLevel;
          switch (currentPriorityLevel) {
            case ImmediatePriority:
            case UserBlockingPriority:
            case NormalPriority:
              priorityLevel = NormalPriority;
              break;
            default:
              priorityLevel = currentPriorityLevel;
              break;
          }
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = priorityLevel;
          try {
            return eventHandler();
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        }
        function unstable_wrapCallback(callback) {
          var parentPriorityLevel = currentPriorityLevel;
          return function() {
            var previousPriorityLevel = currentPriorityLevel;
            currentPriorityLevel = parentPriorityLevel;
            try {
              return callback.apply(this, arguments);
            } finally {
              currentPriorityLevel = previousPriorityLevel;
            }
          };
        }
        function unstable_scheduleCallback(priorityLevel, callback, options2) {
          var currentTime = exports.unstable_now();
          var startTime2;
          if (typeof options2 === "object" && options2 !== null) {
            var delay = options2.delay;
            if (typeof delay === "number" && delay > 0) {
              startTime2 = currentTime + delay;
            } else {
              startTime2 = currentTime;
            }
          } else {
            startTime2 = currentTime;
          }
          var timeout;
          switch (priorityLevel) {
            case ImmediatePriority:
              timeout = IMMEDIATE_PRIORITY_TIMEOUT;
              break;
            case UserBlockingPriority:
              timeout = USER_BLOCKING_PRIORITY_TIMEOUT;
              break;
            case IdlePriority:
              timeout = IDLE_PRIORITY_TIMEOUT;
              break;
            case LowPriority:
              timeout = LOW_PRIORITY_TIMEOUT;
              break;
            case NormalPriority:
            default:
              timeout = NORMAL_PRIORITY_TIMEOUT;
              break;
          }
          var expirationTime = startTime2 + timeout;
          var newTask = {
            id: taskIdCounter++,
            callback,
            priorityLevel,
            startTime: startTime2,
            expirationTime,
            sortIndex: -1
          };
          if (startTime2 > currentTime) {
            newTask.sortIndex = startTime2;
            push(timerQueue, newTask);
            if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
              if (isHostTimeoutScheduled) {
                cancelHostTimeout();
              } else {
                isHostTimeoutScheduled = true;
              }
              requestHostTimeout(handleTimeout, startTime2 - currentTime);
            }
          } else {
            newTask.sortIndex = expirationTime;
            push(taskQueue, newTask);
            if (!isHostCallbackScheduled && !isPerformingWork) {
              isHostCallbackScheduled = true;
              requestHostCallback(flushWork);
            }
          }
          return newTask;
        }
        function unstable_pauseExecution() {
        }
        function unstable_continueExecution() {
          if (!isHostCallbackScheduled && !isPerformingWork) {
            isHostCallbackScheduled = true;
            requestHostCallback(flushWork);
          }
        }
        function unstable_getFirstCallbackNode() {
          return peek(taskQueue);
        }
        function unstable_cancelCallback(task) {
          task.callback = null;
        }
        function unstable_getCurrentPriorityLevel() {
          return currentPriorityLevel;
        }
        var isMessageLoopRunning = false;
        var scheduledHostCallback = null;
        var taskTimeoutID = -1;
        var frameInterval = frameYieldMs;
        var startTime = -1;
        function shouldYieldToHost() {
          var timeElapsed = exports.unstable_now() - startTime;
          if (timeElapsed < frameInterval) {
            return false;
          }
          return true;
        }
        function requestPaint() {
        }
        function forceFrameRate(fps) {
          if (fps < 0 || fps > 125) {
            console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported");
            return;
          }
          if (fps > 0) {
            frameInterval = Math.floor(1e3 / fps);
          } else {
            frameInterval = frameYieldMs;
          }
        }
        var performWorkUntilDeadline = function() {
          if (scheduledHostCallback !== null) {
            var currentTime = exports.unstable_now();
            startTime = currentTime;
            var hasTimeRemaining = true;
            var hasMoreWork = true;
            try {
              hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
            } finally {
              if (hasMoreWork) {
                schedulePerformWorkUntilDeadline();
              } else {
                isMessageLoopRunning = false;
                scheduledHostCallback = null;
              }
            }
          } else {
            isMessageLoopRunning = false;
          }
        };
        var schedulePerformWorkUntilDeadline;
        if (typeof localSetImmediate === "function") {
          schedulePerformWorkUntilDeadline = function() {
            localSetImmediate(performWorkUntilDeadline);
          };
        } else if (typeof MessageChannel !== "undefined") {
          var channel = new MessageChannel();
          var port = channel.port2;
          channel.port1.onmessage = performWorkUntilDeadline;
          schedulePerformWorkUntilDeadline = function() {
            port.postMessage(null);
          };
        } else {
          schedulePerformWorkUntilDeadline = function() {
            localSetTimeout(performWorkUntilDeadline, 0);
          };
        }
        function requestHostCallback(callback) {
          scheduledHostCallback = callback;
          if (!isMessageLoopRunning) {
            isMessageLoopRunning = true;
            schedulePerformWorkUntilDeadline();
          }
        }
        function requestHostTimeout(callback, ms2) {
          taskTimeoutID = localSetTimeout(function() {
            callback(exports.unstable_now());
          }, ms2);
        }
        function cancelHostTimeout() {
          localClearTimeout(taskTimeoutID);
          taskTimeoutID = -1;
        }
        var unstable_requestPaint = requestPaint;
        var unstable_Profiling = null;
        exports.unstable_IdlePriority = IdlePriority;
        exports.unstable_ImmediatePriority = ImmediatePriority;
        exports.unstable_LowPriority = LowPriority;
        exports.unstable_NormalPriority = NormalPriority;
        exports.unstable_Profiling = unstable_Profiling;
        exports.unstable_UserBlockingPriority = UserBlockingPriority;
        exports.unstable_cancelCallback = unstable_cancelCallback;
        exports.unstable_continueExecution = unstable_continueExecution;
        exports.unstable_forceFrameRate = forceFrameRate;
        exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;
        exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;
        exports.unstable_next = unstable_next;
        exports.unstable_pauseExecution = unstable_pauseExecution;
        exports.unstable_requestPaint = unstable_requestPaint;
        exports.unstable_runWithPriority = unstable_runWithPriority;
        exports.unstable_scheduleCallback = unstable_scheduleCallback;
        exports.unstable_shouldYield = shouldYieldToHost;
        exports.unstable_wrapCallback = unstable_wrapCallback;
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
          __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
        }
      })();
    }
  })(scheduler_development);
  return scheduler_development;
}
var hasRequiredScheduler;
function requireScheduler() {
  if (hasRequiredScheduler) return scheduler.exports;
  hasRequiredScheduler = 1;
  {
    scheduler.exports = requireScheduler_development();
  }
  return scheduler.exports;
}
var hasRequiredReactDom_development;
function requireReactDom_development() {
  if (hasRequiredReactDom_development) return reactDom_development;
  hasRequiredReactDom_development = 1;
  /**
   * @license React
   * react-dom.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  {
    (function() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
      }
      var React2 = requireReact();
      var Scheduler = requireScheduler();
      var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      var suppressWarning = false;
      function setSuppressWarning(newSuppressWarning) {
        {
          suppressWarning = newSuppressWarning;
        }
      }
      function warn(format2) {
        {
          if (!suppressWarning) {
            for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
              args[_key - 1] = arguments[_key];
            }
            printWarning("warn", format2, args);
          }
        }
      }
      function error(format2) {
        {
          if (!suppressWarning) {
            for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }
            printWarning("error", format2, args);
          }
        }
      }
      function printWarning(level, format2, args) {
        {
          var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame2.getStackAddendum();
          if (stack !== "") {
            format2 += "%s";
            args = args.concat([stack]);
          }
          var argsWithFormat = args.map(function(item) {
            return String(item);
          });
          argsWithFormat.unshift("Warning: " + format2);
          Function.prototype.apply.call(console[level], console, argsWithFormat);
        }
      }
      var FunctionComponent = 0;
      var ClassComponent = 1;
      var IndeterminateComponent = 2;
      var HostRoot = 3;
      var HostPortal = 4;
      var HostComponent = 5;
      var HostText = 6;
      var Fragment = 7;
      var Mode2 = 8;
      var ContextConsumer = 9;
      var ContextProvider = 10;
      var ForwardRef = 11;
      var Profiler = 12;
      var SuspenseComponent = 13;
      var MemoComponent = 14;
      var SimpleMemoComponent = 15;
      var LazyComponent = 16;
      var IncompleteClassComponent = 17;
      var DehydratedFragment = 18;
      var SuspenseListComponent = 19;
      var ScopeComponent = 21;
      var OffscreenComponent = 22;
      var LegacyHiddenComponent = 23;
      var CacheComponent = 24;
      var TracingMarkerComponent = 25;
      var enableClientRenderFallbackOnTextMismatch = true;
      var enableNewReconciler = false;
      var enableLazyContextPropagation = false;
      var enableLegacyHidden = false;
      var enableCustomElementPropertySupport = false;
      var warnAboutStringRefs = true;
      var enableSchedulingProfiler = true;
      var enableProfilerTimer = true;
      var enableProfilerCommitHooks = true;
      var allNativeEvents = /* @__PURE__ */ new Set();
      var registrationNameDependencies = {};
      var possibleRegistrationNames = {};
      function registerTwoPhaseEvent(registrationName, dependencies2) {
        registerDirectEvent(registrationName, dependencies2);
        registerDirectEvent(registrationName + "Capture", dependencies2);
      }
      function registerDirectEvent(registrationName, dependencies2) {
        {
          if (registrationNameDependencies[registrationName]) {
            error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName);
          }
        }
        registrationNameDependencies[registrationName] = dependencies2;
        {
          var lowerCasedName = registrationName.toLowerCase();
          possibleRegistrationNames[lowerCasedName] = registrationName;
          if (registrationName === "onDoubleClick") {
            possibleRegistrationNames.ondblclick = registrationName;
          }
        }
        for (var i2 = 0; i2 < dependencies2.length; i2++) {
          allNativeEvents.add(dependencies2[i2]);
        }
      }
      var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
      var hasOwnProperty = Object.prototype.hasOwnProperty;
      function typeName(value) {
        {
          var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
          var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          return type2;
        }
      }
      function willCoercionThrow(value) {
        {
          try {
            testStringCoercion(value);
            return false;
          } catch (e4) {
            return true;
          }
        }
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkAttributeStringCoercion(value, attributeName) {
        {
          if (willCoercionThrow(value)) {
            error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      function checkKeyStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      function checkPropStringCoercion(value, propName) {
        {
          if (willCoercionThrow(value)) {
            error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      function checkCSSPropertyStringCoercion(value, propName) {
        {
          if (willCoercionThrow(value)) {
            error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      function checkHtmlStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      function checkFormFieldValueStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      var RESERVED = 0;
      var STRING = 1;
      var BOOLEANISH_STRING = 2;
      var BOOLEAN = 3;
      var OVERLOADED_BOOLEAN = 4;
      var NUMERIC = 5;
      var POSITIVE_NUMERIC = 6;
      var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
      var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
      var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$");
      var illegalAttributeNameCache = {};
      var validatedAttributeNameCache = {};
      function isAttributeNameSafe(attributeName) {
        if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
          return true;
        }
        if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
          return false;
        }
        if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
          validatedAttributeNameCache[attributeName] = true;
          return true;
        }
        illegalAttributeNameCache[attributeName] = true;
        {
          error("Invalid attribute name: `%s`", attributeName);
        }
        return false;
      }
      function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
        if (propertyInfo !== null) {
          return propertyInfo.type === RESERVED;
        }
        if (isCustomComponentTag) {
          return false;
        }
        if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) {
          return true;
        }
        return false;
      }
      function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
        if (propertyInfo !== null && propertyInfo.type === RESERVED) {
          return false;
        }
        switch (typeof value) {
          case "function":
          // $FlowIssue symbol is perfectly valid here
          case "symbol":
            return true;
          case "boolean": {
            if (isCustomComponentTag) {
              return false;
            }
            if (propertyInfo !== null) {
              return !propertyInfo.acceptsBooleans;
            } else {
              var prefix2 = name.toLowerCase().slice(0, 5);
              return prefix2 !== "data-" && prefix2 !== "aria-";
            }
          }
          default:
            return false;
        }
      }
      function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
        if (value === null || typeof value === "undefined") {
          return true;
        }
        if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
          return true;
        }
        if (isCustomComponentTag) {
          return false;
        }
        if (propertyInfo !== null) {
          switch (propertyInfo.type) {
            case BOOLEAN:
              return !value;
            case OVERLOADED_BOOLEAN:
              return value === false;
            case NUMERIC:
              return isNaN(value);
            case POSITIVE_NUMERIC:
              return isNaN(value) || value < 1;
          }
        }
        return false;
      }
      function getPropertyInfo(name) {
        return properties2.hasOwnProperty(name) ? properties2[name] : null;
      }
      function PropertyInfoRecord(name, type2, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) {
        this.acceptsBooleans = type2 === BOOLEANISH_STRING || type2 === BOOLEAN || type2 === OVERLOADED_BOOLEAN;
        this.attributeName = attributeName;
        this.attributeNamespace = attributeNamespace;
        this.mustUseProperty = mustUseProperty;
        this.propertyName = name;
        this.type = type2;
        this.sanitizeURL = sanitizeURL2;
        this.removeEmptyString = removeEmptyString;
      }
      var properties2 = {};
      var reservedProps = [
        "children",
        "dangerouslySetInnerHTML",
        // TODO: This prevents the assignment of defaultValue to regular
        // elements (not just inputs). Now that ReactDOMInput assigns to the
        // defaultValue property -- do we need this?
        "defaultValue",
        "defaultChecked",
        "innerHTML",
        "suppressContentEditableWarning",
        "suppressHydrationWarning",
        "style"
      ];
      reservedProps.forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          RESERVED,
          false,
          // mustUseProperty
          name,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) {
        var name = _ref[0], attributeName = _ref[1];
        properties2[name] = new PropertyInfoRecord(
          name,
          STRING,
          false,
          // mustUseProperty
          attributeName,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          BOOLEANISH_STRING,
          false,
          // mustUseProperty
          name.toLowerCase(),
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          BOOLEANISH_STRING,
          false,
          // mustUseProperty
          name,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [
        "allowFullScreen",
        "async",
        // Note: there is a special case that prevents it from being written to the DOM
        // on the client side because the browsers are inconsistent. Instead we call focus().
        "autoFocus",
        "autoPlay",
        "controls",
        "default",
        "defer",
        "disabled",
        "disablePictureInPicture",
        "disableRemotePlayback",
        "formNoValidate",
        "hidden",
        "loop",
        "noModule",
        "noValidate",
        "open",
        "playsInline",
        "readOnly",
        "required",
        "reversed",
        "scoped",
        "seamless",
        // Microdata
        "itemScope"
      ].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          BOOLEAN,
          false,
          // mustUseProperty
          name.toLowerCase(),
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [
        "checked",
        // Note: `option.selected` is not updated if `select.multiple` is
        // disabled with `removeAttribute`. We have special logic for handling this.
        "multiple",
        "muted",
        "selected"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          BOOLEAN,
          true,
          // mustUseProperty
          name,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [
        "capture",
        "download"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          OVERLOADED_BOOLEAN,
          false,
          // mustUseProperty
          name,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [
        "cols",
        "rows",
        "size",
        "span"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          POSITIVE_NUMERIC,
          false,
          // mustUseProperty
          name,
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      ["rowSpan", "start"].forEach(function(name) {
        properties2[name] = new PropertyInfoRecord(
          name,
          NUMERIC,
          false,
          // mustUseProperty
          name.toLowerCase(),
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      var CAMELIZE = /[\-\:]([a-z])/g;
      var capitalize = function(token) {
        return token[1].toUpperCase();
      };
      [
        "accent-height",
        "alignment-baseline",
        "arabic-form",
        "baseline-shift",
        "cap-height",
        "clip-path",
        "clip-rule",
        "color-interpolation",
        "color-interpolation-filters",
        "color-profile",
        "color-rendering",
        "dominant-baseline",
        "enable-background",
        "fill-opacity",
        "fill-rule",
        "flood-color",
        "flood-opacity",
        "font-family",
        "font-size",
        "font-size-adjust",
        "font-stretch",
        "font-style",
        "font-variant",
        "font-weight",
        "glyph-name",
        "glyph-orientation-horizontal",
        "glyph-orientation-vertical",
        "horiz-adv-x",
        "horiz-origin-x",
        "image-rendering",
        "letter-spacing",
        "lighting-color",
        "marker-end",
        "marker-mid",
        "marker-start",
        "overline-position",
        "overline-thickness",
        "paint-order",
        "panose-1",
        "pointer-events",
        "rendering-intent",
        "shape-rendering",
        "stop-color",
        "stop-opacity",
        "strikethrough-position",
        "strikethrough-thickness",
        "stroke-dasharray",
        "stroke-dashoffset",
        "stroke-linecap",
        "stroke-linejoin",
        "stroke-miterlimit",
        "stroke-opacity",
        "stroke-width",
        "text-anchor",
        "text-decoration",
        "text-rendering",
        "underline-position",
        "underline-thickness",
        "unicode-bidi",
        "unicode-range",
        "units-per-em",
        "v-alphabetic",
        "v-hanging",
        "v-ideographic",
        "v-mathematical",
        "vector-effect",
        "vert-adv-y",
        "vert-origin-x",
        "vert-origin-y",
        "word-spacing",
        "writing-mode",
        "xmlns:xlink",
        "x-height"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(attributeName) {
        var name = attributeName.replace(CAMELIZE, capitalize);
        properties2[name] = new PropertyInfoRecord(
          name,
          STRING,
          false,
          // mustUseProperty
          attributeName,
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      [
        "xlink:actuate",
        "xlink:arcrole",
        "xlink:role",
        "xlink:show",
        "xlink:title",
        "xlink:type"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(attributeName) {
        var name = attributeName.replace(CAMELIZE, capitalize);
        properties2[name] = new PropertyInfoRecord(
          name,
          STRING,
          false,
          // mustUseProperty
          attributeName,
          "http://www.w3.org/1999/xlink",
          false,
          // sanitizeURL
          false
        );
      });
      [
        "xml:base",
        "xml:lang",
        "xml:space"
        // NOTE: if you add a camelCased prop to this list,
        // you'll need to set attributeName to name.toLowerCase()
        // instead in the assignment below.
      ].forEach(function(attributeName) {
        var name = attributeName.replace(CAMELIZE, capitalize);
        properties2[name] = new PropertyInfoRecord(
          name,
          STRING,
          false,
          // mustUseProperty
          attributeName,
          "http://www.w3.org/XML/1998/namespace",
          false,
          // sanitizeURL
          false
        );
      });
      ["tabIndex", "crossOrigin"].forEach(function(attributeName) {
        properties2[attributeName] = new PropertyInfoRecord(
          attributeName,
          STRING,
          false,
          // mustUseProperty
          attributeName.toLowerCase(),
          // attributeName
          null,
          // attributeNamespace
          false,
          // sanitizeURL
          false
        );
      });
      var xlinkHref = "xlinkHref";
      properties2[xlinkHref] = new PropertyInfoRecord(
        "xlinkHref",
        STRING,
        false,
        // mustUseProperty
        "xlink:href",
        "http://www.w3.org/1999/xlink",
        true,
        // sanitizeURL
        false
      );
      ["src", "href", "action", "formAction"].forEach(function(attributeName) {
        properties2[attributeName] = new PropertyInfoRecord(
          attributeName,
          STRING,
          false,
          // mustUseProperty
          attributeName.toLowerCase(),
          // attributeName
          null,
          // attributeNamespace
          true,
          // sanitizeURL
          true
        );
      });
      var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
      var didWarn = false;
      function sanitizeURL(url) {
        {
          if (!didWarn && isJavaScriptProtocol.test(url)) {
            didWarn = true;
            error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url));
          }
        }
      }
      function getValueForProperty(node2, name, expected, propertyInfo) {
        {
          if (propertyInfo.mustUseProperty) {
            var propertyName = propertyInfo.propertyName;
            return node2[propertyName];
          } else {
            {
              checkAttributeStringCoercion(expected, name);
            }
            if (propertyInfo.sanitizeURL) {
              sanitizeURL("" + expected);
            }
            var attributeName = propertyInfo.attributeName;
            var stringValue = null;
            if (propertyInfo.type === OVERLOADED_BOOLEAN) {
              if (node2.hasAttribute(attributeName)) {
                var value = node2.getAttribute(attributeName);
                if (value === "") {
                  return true;
                }
                if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                  return value;
                }
                if (value === "" + expected) {
                  return expected;
                }
                return value;
              }
            } else if (node2.hasAttribute(attributeName)) {
              if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
                return node2.getAttribute(attributeName);
              }
              if (propertyInfo.type === BOOLEAN) {
                return expected;
              }
              stringValue = node2.getAttribute(attributeName);
            }
            if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
              return stringValue === null ? expected : stringValue;
            } else if (stringValue === "" + expected) {
              return expected;
            } else {
              return stringValue;
            }
          }
        }
      }
      function getValueForAttribute(node2, name, expected, isCustomComponentTag) {
        {
          if (!isAttributeNameSafe(name)) {
            return;
          }
          if (!node2.hasAttribute(name)) {
            return expected === void 0 ? void 0 : null;
          }
          var value = node2.getAttribute(name);
          {
            checkAttributeStringCoercion(expected, name);
          }
          if (value === "" + expected) {
            return expected;
          }
          return value;
        }
      }
      function setValueForProperty(node2, name, value, isCustomComponentTag) {
        var propertyInfo = getPropertyInfo(name);
        if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
          return;
        }
        if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
          value = null;
        }
        if (isCustomComponentTag || propertyInfo === null) {
          if (isAttributeNameSafe(name)) {
            var _attributeName = name;
            if (value === null) {
              node2.removeAttribute(_attributeName);
            } else {
              {
                checkAttributeStringCoercion(value, name);
              }
              node2.setAttribute(_attributeName, "" + value);
            }
          }
          return;
        }
        var mustUseProperty = propertyInfo.mustUseProperty;
        if (mustUseProperty) {
          var propertyName = propertyInfo.propertyName;
          if (value === null) {
            var type2 = propertyInfo.type;
            node2[propertyName] = type2 === BOOLEAN ? false : "";
          } else {
            node2[propertyName] = value;
          }
          return;
        }
        var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace;
        if (value === null) {
          node2.removeAttribute(attributeName);
        } else {
          var _type = propertyInfo.type;
          var attributeValue;
          if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
            attributeValue = "";
          } else {
            {
              {
                checkAttributeStringCoercion(value, attributeName);
              }
              attributeValue = "" + value;
            }
            if (propertyInfo.sanitizeURL) {
              sanitizeURL(attributeValue.toString());
            }
          }
          if (attributeNamespace) {
            node2.setAttributeNS(attributeNamespace, attributeName, attributeValue);
          } else {
            node2.setAttribute(attributeName, attributeValue);
          }
        }
      }
      var REACT_ELEMENT_TYPE = Symbol.for("react.element");
      var REACT_PORTAL_TYPE = Symbol.for("react.portal");
      var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
      var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
      var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
      var REACT_CONTEXT_TYPE = Symbol.for("react.context");
      var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
      var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
      var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
      var REACT_MEMO_TYPE = Symbol.for("react.memo");
      var REACT_LAZY_TYPE = Symbol.for("react.lazy");
      var REACT_SCOPE_TYPE = Symbol.for("react.scope");
      var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode");
      var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
      var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden");
      var REACT_CACHE_TYPE = Symbol.for("react.cache");
      var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        if (maybeIterable === null || typeof maybeIterable !== "object") {
          return null;
        }
        var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
        if (typeof maybeIterator === "function") {
          return maybeIterator;
        }
        return null;
      }
      var assign = Object.assign;
      var disabledDepth = 0;
      var prevLog;
      var prevInfo;
      var prevWarn;
      var prevError;
      var prevGroup;
      var prevGroupCollapsed;
      var prevGroupEnd;
      function disabledLog() {
      }
      disabledLog.__reactDisabledLog = true;
      function disableLogs() {
        {
          if (disabledDepth === 0) {
            prevLog = console.log;
            prevInfo = console.info;
            prevWarn = console.warn;
            prevError = console.error;
            prevGroup = console.group;
            prevGroupCollapsed = console.groupCollapsed;
            prevGroupEnd = console.groupEnd;
            var props = {
              configurable: true,
              enumerable: true,
              value: disabledLog,
              writable: true
            };
            Object.defineProperties(console, {
              info: props,
              log: props,
              warn: props,
              error: props,
              group: props,
              groupCollapsed: props,
              groupEnd: props
            });
          }
          disabledDepth++;
        }
      }
      function reenableLogs() {
        {
          disabledDepth--;
          if (disabledDepth === 0) {
            var props = {
              configurable: true,
              enumerable: true,
              writable: true
            };
            Object.defineProperties(console, {
              log: assign({}, props, {
                value: prevLog
              }),
              info: assign({}, props, {
                value: prevInfo
              }),
              warn: assign({}, props, {
                value: prevWarn
              }),
              error: assign({}, props, {
                value: prevError
              }),
              group: assign({}, props, {
                value: prevGroup
              }),
              groupCollapsed: assign({}, props, {
                value: prevGroupCollapsed
              }),
              groupEnd: assign({}, props, {
                value: prevGroupEnd
              })
            });
          }
          if (disabledDepth < 0) {
            error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
          }
        }
      }
      var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
      var prefix;
      function describeBuiltInComponentFrame(name, source, ownerFn) {
        {
          if (prefix === void 0) {
            try {
              throw Error();
            } catch (x2) {
              var match = x2.stack.trim().match(/\n( *(at )?)/);
              prefix = match && match[1] || "";
            }
          }
          return "\n" + prefix + name;
        }
      }
      var reentry = false;
      var componentFrameCache;
      {
        var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
        componentFrameCache = new PossiblyWeakMap();
      }
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) {
          return "";
        }
        {
          var frame = componentFrameCache.get(fn);
          if (frame !== void 0) {
            return frame;
          }
        }
        var control;
        reentry = true;
        var previousPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher;
        {
          previousDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = null;
          disableLogs();
        }
        try {
          if (construct) {
            var Fake = function() {
              throw Error();
            };
            Object.defineProperty(Fake.prototype, "props", {
              set: function() {
                throw Error();
              }
            });
            if (typeof Reflect === "object" && Reflect.construct) {
              try {
                Reflect.construct(Fake, []);
              } catch (x2) {
                control = x2;
              }
              Reflect.construct(fn, [], Fake);
            } else {
              try {
                Fake.call();
              } catch (x2) {
                control = x2;
              }
              fn.call(Fake.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (x2) {
              control = x2;
            }
            fn();
          }
        } catch (sample) {
          if (sample && control && typeof sample.stack === "string") {
            var sampleLines = sample.stack.split("\n");
            var controlLines = control.stack.split("\n");
            var s2 = sampleLines.length - 1;
            var c2 = controlLines.length - 1;
            while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) {
              c2--;
            }
            for (; s2 >= 1 && c2 >= 0; s2--, c2--) {
              if (sampleLines[s2] !== controlLines[c2]) {
                if (s2 !== 1 || c2 !== 1) {
                  do {
                    s2--;
                    c2--;
                    if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) {
                      var _frame = "\n" + sampleLines[s2].replace(" at new ", " at ");
                      if (fn.displayName && _frame.includes("<anonymous>")) {
                        _frame = _frame.replace("<anonymous>", fn.displayName);
                      }
                      {
                        if (typeof fn === "function") {
                          componentFrameCache.set(fn, _frame);
                        }
                      }
                      return _frame;
                    }
                  } while (s2 >= 1 && c2 >= 0);
                }
                break;
              }
            }
          }
        } finally {
          reentry = false;
          {
            ReactCurrentDispatcher.current = previousDispatcher;
            reenableLogs();
          }
          Error.prepareStackTrace = previousPrepareStackTrace;
        }
        var name = fn ? fn.displayName || fn.name : "";
        var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
        {
          if (typeof fn === "function") {
            componentFrameCache.set(fn, syntheticFrame);
          }
        }
        return syntheticFrame;
      }
      function describeClassComponentFrame(ctor, source, ownerFn) {
        {
          return describeNativeComponentFrame(ctor, true);
        }
      }
      function describeFunctionComponentFrame(fn, source, ownerFn) {
        {
          return describeNativeComponentFrame(fn, false);
        }
      }
      function shouldConstruct(Component) {
        var prototype = Component.prototype;
        return !!(prototype && prototype.isReactComponent);
      }
      function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) {
        if (type2 == null) {
          return "";
        }
        if (typeof type2 === "function") {
          {
            return describeNativeComponentFrame(type2, shouldConstruct(type2));
          }
        }
        if (typeof type2 === "string") {
          return describeBuiltInComponentFrame(type2);
        }
        switch (type2) {
          case REACT_SUSPENSE_TYPE:
            return describeBuiltInComponentFrame("Suspense");
          case REACT_SUSPENSE_LIST_TYPE:
            return describeBuiltInComponentFrame("SuspenseList");
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              return describeFunctionComponentFrame(type2.render);
            case REACT_MEMO_TYPE:
              return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn);
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn);
              } catch (x2) {
              }
            }
          }
        }
        return "";
      }
      function describeFiber(fiber) {
        fiber._debugOwner ? fiber._debugOwner.type : null;
        fiber._debugSource;
        switch (fiber.tag) {
          case HostComponent:
            return describeBuiltInComponentFrame(fiber.type);
          case LazyComponent:
            return describeBuiltInComponentFrame("Lazy");
          case SuspenseComponent:
            return describeBuiltInComponentFrame("Suspense");
          case SuspenseListComponent:
            return describeBuiltInComponentFrame("SuspenseList");
          case FunctionComponent:
          case IndeterminateComponent:
          case SimpleMemoComponent:
            return describeFunctionComponentFrame(fiber.type);
          case ForwardRef:
            return describeFunctionComponentFrame(fiber.type.render);
          case ClassComponent:
            return describeClassComponentFrame(fiber.type);
          default:
            return "";
        }
      }
      function getStackByFiberInDevAndProd(workInProgress2) {
        try {
          var info = "";
          var node2 = workInProgress2;
          do {
            info += describeFiber(node2);
            node2 = node2.return;
          } while (node2);
          return info;
        } catch (x2) {
          return "\nError generating stack: " + x2.message + "\n" + x2.stack;
        }
      }
      function getWrappedName(outerType, innerType, wrapperName) {
        var displayName = outerType.displayName;
        if (displayName) {
          return displayName;
        }
        var functionName = innerType.displayName || innerType.name || "";
        return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
      }
      function getContextName(type2) {
        return type2.displayName || "Context";
      }
      function getComponentNameFromType(type2) {
        if (type2 == null) {
          return null;
        }
        {
          if (typeof type2.tag === "number") {
            error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
          }
        }
        if (typeof type2 === "function") {
          return type2.displayName || type2.name || null;
        }
        if (typeof type2 === "string") {
          return type2;
        }
        switch (type2) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_CONTEXT_TYPE:
              var context = type2;
              return getContextName(context) + ".Consumer";
            case REACT_PROVIDER_TYPE:
              var provider = type2;
              return getContextName(provider._context) + ".Provider";
            case REACT_FORWARD_REF_TYPE:
              return getWrappedName(type2, type2.render, "ForwardRef");
            case REACT_MEMO_TYPE:
              var outerName = type2.displayName || null;
              if (outerName !== null) {
                return outerName;
              }
              return getComponentNameFromType(type2.type) || "Memo";
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return getComponentNameFromType(init2(payload));
              } catch (x2) {
                return null;
              }
            }
          }
        }
        return null;
      }
      function getWrappedName$1(outerType, innerType, wrapperName) {
        var functionName = innerType.displayName || innerType.name || "";
        return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName);
      }
      function getContextName$1(type2) {
        return type2.displayName || "Context";
      }
      function getComponentNameFromFiber(fiber) {
        var tag = fiber.tag, type2 = fiber.type;
        switch (tag) {
          case CacheComponent:
            return "Cache";
          case ContextConsumer:
            var context = type2;
            return getContextName$1(context) + ".Consumer";
          case ContextProvider:
            var provider = type2;
            return getContextName$1(provider._context) + ".Provider";
          case DehydratedFragment:
            return "DehydratedFragment";
          case ForwardRef:
            return getWrappedName$1(type2, type2.render, "ForwardRef");
          case Fragment:
            return "Fragment";
          case HostComponent:
            return type2;
          case HostPortal:
            return "Portal";
          case HostRoot:
            return "Root";
          case HostText:
            return "Text";
          case LazyComponent:
            return getComponentNameFromType(type2);
          case Mode2:
            if (type2 === REACT_STRICT_MODE_TYPE) {
              return "StrictMode";
            }
            return "Mode";
          case OffscreenComponent:
            return "Offscreen";
          case Profiler:
            return "Profiler";
          case ScopeComponent:
            return "Scope";
          case SuspenseComponent:
            return "Suspense";
          case SuspenseListComponent:
            return "SuspenseList";
          case TracingMarkerComponent:
            return "TracingMarker";
          // The display name for this tags come from the user-provided type:
          case ClassComponent:
          case FunctionComponent:
          case IncompleteClassComponent:
          case IndeterminateComponent:
          case MemoComponent:
          case SimpleMemoComponent:
            if (typeof type2 === "function") {
              return type2.displayName || type2.name || null;
            }
            if (typeof type2 === "string") {
              return type2;
            }
            break;
        }
        return null;
      }
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      var current = null;
      var isRendering = false;
      function getCurrentFiberOwnerNameInDevOrNull() {
        {
          if (current === null) {
            return null;
          }
          var owner = current._debugOwner;
          if (owner !== null && typeof owner !== "undefined") {
            return getComponentNameFromFiber(owner);
          }
        }
        return null;
      }
      function getCurrentFiberStackInDev() {
        {
          if (current === null) {
            return "";
          }
          return getStackByFiberInDevAndProd(current);
        }
      }
      function resetCurrentFiber() {
        {
          ReactDebugCurrentFrame.getCurrentStack = null;
          current = null;
          isRendering = false;
        }
      }
      function setCurrentFiber(fiber) {
        {
          ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev;
          current = fiber;
          isRendering = false;
        }
      }
      function getCurrentFiber() {
        {
          return current;
        }
      }
      function setIsRendering(rendering) {
        {
          isRendering = rendering;
        }
      }
      function toString2(value) {
        return "" + value;
      }
      function getToStringValue(value) {
        switch (typeof value) {
          case "boolean":
          case "number":
          case "string":
          case "undefined":
            return value;
          case "object":
            {
              checkFormFieldValueStringCoercion(value);
            }
            return value;
          default:
            return "";
        }
      }
      var hasReadOnlyValue = {
        button: true,
        checkbox: true,
        image: true,
        hidden: true,
        radio: true,
        reset: true,
        submit: true
      };
      function checkControlledValueProps(tagName, props) {
        {
          if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) {
            error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.");
          }
          if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) {
            error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.");
          }
        }
      }
      function isCheckable(elem) {
        var type2 = elem.type;
        var nodeName = elem.nodeName;
        return nodeName && nodeName.toLowerCase() === "input" && (type2 === "checkbox" || type2 === "radio");
      }
      function getTracker(node2) {
        return node2._valueTracker;
      }
      function detachTracker(node2) {
        node2._valueTracker = null;
      }
      function getValueFromNode(node2) {
        var value = "";
        if (!node2) {
          return value;
        }
        if (isCheckable(node2)) {
          value = node2.checked ? "true" : "false";
        } else {
          value = node2.value;
        }
        return value;
      }
      function trackValueOnNode(node2) {
        var valueField = isCheckable(node2) ? "checked" : "value";
        var descriptor = Object.getOwnPropertyDescriptor(node2.constructor.prototype, valueField);
        {
          checkFormFieldValueStringCoercion(node2[valueField]);
        }
        var currentValue = "" + node2[valueField];
        if (node2.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") {
          return;
        }
        var get22 = descriptor.get, set2 = descriptor.set;
        Object.defineProperty(node2, valueField, {
          configurable: true,
          get: function() {
            return get22.call(this);
          },
          set: function(value) {
            {
              checkFormFieldValueStringCoercion(value);
            }
            currentValue = "" + value;
            set2.call(this, value);
          }
        });
        Object.defineProperty(node2, valueField, {
          enumerable: descriptor.enumerable
        });
        var tracker = {
          getValue: function() {
            return currentValue;
          },
          setValue: function(value) {
            {
              checkFormFieldValueStringCoercion(value);
            }
            currentValue = "" + value;
          },
          stopTracking: function() {
            detachTracker(node2);
            delete node2[valueField];
          }
        };
        return tracker;
      }
      function track(node2) {
        if (getTracker(node2)) {
          return;
        }
        node2._valueTracker = trackValueOnNode(node2);
      }
      function updateValueIfChanged(node2) {
        if (!node2) {
          return false;
        }
        var tracker = getTracker(node2);
        if (!tracker) {
          return true;
        }
        var lastValue = tracker.getValue();
        var nextValue = getValueFromNode(node2);
        if (nextValue !== lastValue) {
          tracker.setValue(nextValue);
          return true;
        }
        return false;
      }
      function getActiveElement(doc) {
        doc = doc || (typeof document !== "undefined" ? document : void 0);
        if (typeof doc === "undefined") {
          return null;
        }
        try {
          return doc.activeElement || doc.body;
        } catch (e4) {
          return doc.body;
        }
      }
      var didWarnValueDefaultValue = false;
      var didWarnCheckedDefaultChecked = false;
      var didWarnControlledToUncontrolled = false;
      var didWarnUncontrolledToControlled = false;
      function isControlled(props) {
        var usesChecked = props.type === "checkbox" || props.type === "radio";
        return usesChecked ? props.checked != null : props.value != null;
      }
      function getHostProps(element, props) {
        var node2 = element;
        var checked2 = props.checked;
        var hostProps = assign({}, props, {
          defaultChecked: void 0,
          defaultValue: void 0,
          value: void 0,
          checked: checked2 != null ? checked2 : node2._wrapperState.initialChecked
        });
        return hostProps;
      }
      function initWrapperState(element, props) {
        {
          checkControlledValueProps("input", props);
          if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) {
            error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
            didWarnCheckedDefaultChecked = true;
          }
          if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) {
            error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type);
            didWarnValueDefaultValue = true;
          }
        }
        var node2 = element;
        var defaultValue = props.defaultValue == null ? "" : props.defaultValue;
        node2._wrapperState = {
          initialChecked: props.checked != null ? props.checked : props.defaultChecked,
          initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
          controlled: isControlled(props)
        };
      }
      function updateChecked(element, props) {
        var node2 = element;
        var checked2 = props.checked;
        if (checked2 != null) {
          setValueForProperty(node2, "checked", checked2, false);
        }
      }
      function updateWrapper(element, props) {
        var node2 = element;
        {
          var controlled = isControlled(props);
          if (!node2._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
            error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
            didWarnUncontrolledToControlled = true;
          }
          if (node2._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
            error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components");
            didWarnControlledToUncontrolled = true;
          }
        }
        updateChecked(element, props);
        var value = getToStringValue(props.value);
        var type2 = props.type;
        if (value != null) {
          if (type2 === "number") {
            if (value === 0 && node2.value === "" || // We explicitly want to coerce to number here if possible.
            // eslint-disable-next-line
            node2.value != value) {
              node2.value = toString2(value);
            }
          } else if (node2.value !== toString2(value)) {
            node2.value = toString2(value);
          }
        } else if (type2 === "submit" || type2 === "reset") {
          node2.removeAttribute("value");
          return;
        }
        {
          if (props.hasOwnProperty("value")) {
            setDefaultValue(node2, props.type, value);
          } else if (props.hasOwnProperty("defaultValue")) {
            setDefaultValue(node2, props.type, getToStringValue(props.defaultValue));
          }
        }
        {
          if (props.checked == null && props.defaultChecked != null) {
            node2.defaultChecked = !!props.defaultChecked;
          }
        }
      }
      function postMountWrapper(element, props, isHydrating2) {
        var node2 = element;
        if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) {
          var type2 = props.type;
          var isButton = type2 === "submit" || type2 === "reset";
          if (isButton && (props.value === void 0 || props.value === null)) {
            return;
          }
          var initialValue = toString2(node2._wrapperState.initialValue);
          if (!isHydrating2) {
            {
              if (initialValue !== node2.value) {
                node2.value = initialValue;
              }
            }
          }
          {
            node2.defaultValue = initialValue;
          }
        }
        var name = node2.name;
        if (name !== "") {
          node2.name = "";
        }
        {
          node2.defaultChecked = !node2.defaultChecked;
          node2.defaultChecked = !!node2._wrapperState.initialChecked;
        }
        if (name !== "") {
          node2.name = name;
        }
      }
      function restoreControlledState(element, props) {
        var node2 = element;
        updateWrapper(node2, props);
        updateNamedCousins(node2, props);
      }
      function updateNamedCousins(rootNode, props) {
        var name = props.name;
        if (props.type === "radio" && name != null) {
          var queryRoot = rootNode;
          while (queryRoot.parentNode) {
            queryRoot = queryRoot.parentNode;
          }
          {
            checkAttributeStringCoercion(name, "name");
          }
          var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]');
          for (var i2 = 0; i2 < group.length; i2++) {
            var otherNode = group[i2];
            if (otherNode === rootNode || otherNode.form !== rootNode.form) {
              continue;
            }
            var otherProps = getFiberCurrentPropsFromNode(otherNode);
            if (!otherProps) {
              throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.");
            }
            updateValueIfChanged(otherNode);
            updateWrapper(otherNode, otherProps);
          }
        }
      }
      function setDefaultValue(node2, type2, value) {
        if (
          // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
          type2 !== "number" || getActiveElement(node2.ownerDocument) !== node2
        ) {
          if (value == null) {
            node2.defaultValue = toString2(node2._wrapperState.initialValue);
          } else if (node2.defaultValue !== toString2(value)) {
            node2.defaultValue = toString2(value);
          }
        }
      }
      var didWarnSelectedSetOnOption = false;
      var didWarnInvalidChild = false;
      var didWarnInvalidInnerHTML = false;
      function validateProps(element, props) {
        {
          if (props.value == null) {
            if (typeof props.children === "object" && props.children !== null) {
              React2.Children.forEach(props.children, function(child) {
                if (child == null) {
                  return;
                }
                if (typeof child === "string" || typeof child === "number") {
                  return;
                }
                if (!didWarnInvalidChild) {
                  didWarnInvalidChild = true;
                  error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>.");
                }
              });
            } else if (props.dangerouslySetInnerHTML != null) {
              if (!didWarnInvalidInnerHTML) {
                didWarnInvalidInnerHTML = true;
                error("Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected.");
              }
            }
          }
          if (props.selected != null && !didWarnSelectedSetOnOption) {
            error("Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.");
            didWarnSelectedSetOnOption = true;
          }
        }
      }
      function postMountWrapper$1(element, props) {
        if (props.value != null) {
          element.setAttribute("value", toString2(getToStringValue(props.value)));
        }
      }
      var isArrayImpl = Array.isArray;
      function isArray2(a2) {
        return isArrayImpl(a2);
      }
      var didWarnValueDefaultValue$1;
      {
        didWarnValueDefaultValue$1 = false;
      }
      function getDeclarationErrorAddendum() {
        var ownerName = getCurrentFiberOwnerNameInDevOrNull();
        if (ownerName) {
          return "\n\nCheck the render method of `" + ownerName + "`.";
        }
        return "";
      }
      var valuePropNames = ["value", "defaultValue"];
      function checkSelectPropTypes(props) {
        {
          checkControlledValueProps("select", props);
          for (var i2 = 0; i2 < valuePropNames.length; i2++) {
            var propName = valuePropNames[i2];
            if (props[propName] == null) {
              continue;
            }
            var propNameIsArray = isArray2(props[propName]);
            if (props.multiple && !propNameIsArray) {
              error("The `%s` prop supplied to <select> must be an array if `multiple` is true.%s", propName, getDeclarationErrorAddendum());
            } else if (!props.multiple && propNameIsArray) {
              error("The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s", propName, getDeclarationErrorAddendum());
            }
          }
        }
      }
      function updateOptions(node2, multiple, propValue, setDefaultSelected) {
        var options22 = node2.options;
        if (multiple) {
          var selectedValues = propValue;
          var selectedValue = {};
          for (var i2 = 0; i2 < selectedValues.length; i2++) {
            selectedValue["$" + selectedValues[i2]] = true;
          }
          for (var _i2 = 0; _i2 < options22.length; _i2++) {
            var selected = selectedValue.hasOwnProperty("$" + options22[_i2].value);
            if (options22[_i2].selected !== selected) {
              options22[_i2].selected = selected;
            }
            if (selected && setDefaultSelected) {
              options22[_i2].defaultSelected = true;
            }
          }
        } else {
          var _selectedValue = toString2(getToStringValue(propValue));
          var defaultSelected = null;
          for (var _i22 = 0; _i22 < options22.length; _i22++) {
            if (options22[_i22].value === _selectedValue) {
              options22[_i22].selected = true;
              if (setDefaultSelected) {
                options22[_i22].defaultSelected = true;
              }
              return;
            }
            if (defaultSelected === null && !options22[_i22].disabled) {
              defaultSelected = options22[_i22];
            }
          }
          if (defaultSelected !== null) {
            defaultSelected.selected = true;
          }
        }
      }
      function getHostProps$1(element, props) {
        return assign({}, props, {
          value: void 0
        });
      }
      function initWrapperState$1(element, props) {
        var node2 = element;
        {
          checkSelectPropTypes(props);
        }
        node2._wrapperState = {
          wasMultiple: !!props.multiple
        };
        {
          if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue$1) {
            error("Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://reactjs.org/link/controlled-components");
            didWarnValueDefaultValue$1 = true;
          }
        }
      }
      function postMountWrapper$2(element, props) {
        var node2 = element;
        node2.multiple = !!props.multiple;
        var value = props.value;
        if (value != null) {
          updateOptions(node2, !!props.multiple, value, false);
        } else if (props.defaultValue != null) {
          updateOptions(node2, !!props.multiple, props.defaultValue, true);
        }
      }
      function postUpdateWrapper(element, props) {
        var node2 = element;
        var wasMultiple = node2._wrapperState.wasMultiple;
        node2._wrapperState.wasMultiple = !!props.multiple;
        var value = props.value;
        if (value != null) {
          updateOptions(node2, !!props.multiple, value, false);
        } else if (wasMultiple !== !!props.multiple) {
          if (props.defaultValue != null) {
            updateOptions(node2, !!props.multiple, props.defaultValue, true);
          } else {
            updateOptions(node2, !!props.multiple, props.multiple ? [] : "", false);
          }
        }
      }
      function restoreControlledState$1(element, props) {
        var node2 = element;
        var value = props.value;
        if (value != null) {
          updateOptions(node2, !!props.multiple, value, false);
        }
      }
      var didWarnValDefaultVal = false;
      function getHostProps$2(element, props) {
        var node2 = element;
        if (props.dangerouslySetInnerHTML != null) {
          throw new Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");
        }
        var hostProps = assign({}, props, {
          value: void 0,
          defaultValue: void 0,
          children: toString2(node2._wrapperState.initialValue)
        });
        return hostProps;
      }
      function initWrapperState$2(element, props) {
        var node2 = element;
        {
          checkControlledValueProps("textarea", props);
          if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValDefaultVal) {
            error("%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component");
            didWarnValDefaultVal = true;
          }
        }
        var initialValue = props.value;
        if (initialValue == null) {
          var children = props.children, defaultValue = props.defaultValue;
          if (children != null) {
            {
              error("Use the `defaultValue` or `value` props instead of setting children on <textarea>.");
            }
            {
              if (defaultValue != null) {
                throw new Error("If you supply `defaultValue` on a <textarea>, do not pass children.");
              }
              if (isArray2(children)) {
                if (children.length > 1) {
                  throw new Error("<textarea> can only have at most one child.");
                }
                children = children[0];
              }
              defaultValue = children;
            }
          }
          if (defaultValue == null) {
            defaultValue = "";
          }
          initialValue = defaultValue;
        }
        node2._wrapperState = {
          initialValue: getToStringValue(initialValue)
        };
      }
      function updateWrapper$1(element, props) {
        var node2 = element;
        var value = getToStringValue(props.value);
        var defaultValue = getToStringValue(props.defaultValue);
        if (value != null) {
          var newValue = toString2(value);
          if (newValue !== node2.value) {
            node2.value = newValue;
          }
          if (props.defaultValue == null && node2.defaultValue !== newValue) {
            node2.defaultValue = newValue;
          }
        }
        if (defaultValue != null) {
          node2.defaultValue = toString2(defaultValue);
        }
      }
      function postMountWrapper$3(element, props) {
        var node2 = element;
        var textContent = node2.textContent;
        if (textContent === node2._wrapperState.initialValue) {
          if (textContent !== "" && textContent !== null) {
            node2.value = textContent;
          }
        }
      }
      function restoreControlledState$2(element, props) {
        updateWrapper$1(element, props);
      }
      var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
      var MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
      var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
      function getIntrinsicNamespace(type2) {
        switch (type2) {
          case "svg":
            return SVG_NAMESPACE;
          case "math":
            return MATH_NAMESPACE;
          default:
            return HTML_NAMESPACE;
        }
      }
      function getChildNamespace(parentNamespace, type2) {
        if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
          return getIntrinsicNamespace(type2);
        }
        if (parentNamespace === SVG_NAMESPACE && type2 === "foreignObject") {
          return HTML_NAMESPACE;
        }
        return parentNamespace;
      }
      var createMicrosoftUnsafeLocalFunction = function(func) {
        if (typeof MSApp !== "undefined" && MSApp.execUnsafeLocalFunction) {
          return function(arg0, arg1, arg2, arg3) {
            MSApp.execUnsafeLocalFunction(function() {
              return func(arg0, arg1, arg2, arg3);
            });
          };
        } else {
          return func;
        }
      };
      var reusableSVGContainer;
      var setInnerHTML = createMicrosoftUnsafeLocalFunction(function(node2, html) {
        if (node2.namespaceURI === SVG_NAMESPACE) {
          if (!("innerHTML" in node2)) {
            reusableSVGContainer = reusableSVGContainer || document.createElement("div");
            reusableSVGContainer.innerHTML = "<svg>" + html.valueOf().toString() + "</svg>";
            var svgNode = reusableSVGContainer.firstChild;
            while (node2.firstChild) {
              node2.removeChild(node2.firstChild);
            }
            while (svgNode.firstChild) {
              node2.appendChild(svgNode.firstChild);
            }
            return;
          }
        }
        node2.innerHTML = html;
      });
      var ELEMENT_NODE = 1;
      var TEXT_NODE = 3;
      var COMMENT_NODE = 8;
      var DOCUMENT_NODE = 9;
      var DOCUMENT_FRAGMENT_NODE = 11;
      var setTextContent = function(node2, text) {
        if (text) {
          var firstChild = node2.firstChild;
          if (firstChild && firstChild === node2.lastChild && firstChild.nodeType === TEXT_NODE) {
            firstChild.nodeValue = text;
            return;
          }
        }
        node2.textContent = text;
      };
      var shorthandToLonghand = {
        animation: ["animationDelay", "animationDirection", "animationDuration", "animationFillMode", "animationIterationCount", "animationName", "animationPlayState", "animationTimingFunction"],
        background: ["backgroundAttachment", "backgroundClip", "backgroundColor", "backgroundImage", "backgroundOrigin", "backgroundPositionX", "backgroundPositionY", "backgroundRepeat", "backgroundSize"],
        backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
        border: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth", "borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth", "borderLeftColor", "borderLeftStyle", "borderLeftWidth", "borderRightColor", "borderRightStyle", "borderRightWidth", "borderTopColor", "borderTopStyle", "borderTopWidth"],
        borderBlockEnd: ["borderBlockEndColor", "borderBlockEndStyle", "borderBlockEndWidth"],
        borderBlockStart: ["borderBlockStartColor", "borderBlockStartStyle", "borderBlockStartWidth"],
        borderBottom: ["borderBottomColor", "borderBottomStyle", "borderBottomWidth"],
        borderColor: ["borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor"],
        borderImage: ["borderImageOutset", "borderImageRepeat", "borderImageSlice", "borderImageSource", "borderImageWidth"],
        borderInlineEnd: ["borderInlineEndColor", "borderInlineEndStyle", "borderInlineEndWidth"],
        borderInlineStart: ["borderInlineStartColor", "borderInlineStartStyle", "borderInlineStartWidth"],
        borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
        borderRadius: ["borderBottomLeftRadius", "borderBottomRightRadius", "borderTopLeftRadius", "borderTopRightRadius"],
        borderRight: ["borderRightColor", "borderRightStyle", "borderRightWidth"],
        borderStyle: ["borderBottomStyle", "borderLeftStyle", "borderRightStyle", "borderTopStyle"],
        borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
        borderWidth: ["borderBottomWidth", "borderLeftWidth", "borderRightWidth", "borderTopWidth"],
        columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
        columns: ["columnCount", "columnWidth"],
        flex: ["flexBasis", "flexGrow", "flexShrink"],
        flexFlow: ["flexDirection", "flexWrap"],
        font: ["fontFamily", "fontFeatureSettings", "fontKerning", "fontLanguageOverride", "fontSize", "fontSizeAdjust", "fontStretch", "fontStyle", "fontVariant", "fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition", "fontWeight", "lineHeight"],
        fontVariant: ["fontVariantAlternates", "fontVariantCaps", "fontVariantEastAsian", "fontVariantLigatures", "fontVariantNumeric", "fontVariantPosition"],
        gap: ["columnGap", "rowGap"],
        grid: ["gridAutoColumns", "gridAutoFlow", "gridAutoRows", "gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
        gridArea: ["gridColumnEnd", "gridColumnStart", "gridRowEnd", "gridRowStart"],
        gridColumn: ["gridColumnEnd", "gridColumnStart"],
        gridColumnGap: ["columnGap"],
        gridGap: ["columnGap", "rowGap"],
        gridRow: ["gridRowEnd", "gridRowStart"],
        gridRowGap: ["rowGap"],
        gridTemplate: ["gridTemplateAreas", "gridTemplateColumns", "gridTemplateRows"],
        listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
        margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
        marker: ["markerEnd", "markerMid", "markerStart"],
        mask: ["maskClip", "maskComposite", "maskImage", "maskMode", "maskOrigin", "maskPositionX", "maskPositionY", "maskRepeat", "maskSize"],
        maskPosition: ["maskPositionX", "maskPositionY"],
        outline: ["outlineColor", "outlineStyle", "outlineWidth"],
        overflow: ["overflowX", "overflowY"],
        padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
        placeContent: ["alignContent", "justifyContent"],
        placeItems: ["alignItems", "justifyItems"],
        placeSelf: ["alignSelf", "justifySelf"],
        textDecoration: ["textDecorationColor", "textDecorationLine", "textDecorationStyle"],
        textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
        transition: ["transitionDelay", "transitionDuration", "transitionProperty", "transitionTimingFunction"],
        wordWrap: ["overflowWrap"]
      };
      var isUnitlessNumber = {
        animationIterationCount: true,
        aspectRatio: true,
        borderImageOutset: true,
        borderImageSlice: true,
        borderImageWidth: true,
        boxFlex: true,
        boxFlexGroup: true,
        boxOrdinalGroup: true,
        columnCount: true,
        columns: true,
        flex: true,
        flexGrow: true,
        flexPositive: true,
        flexShrink: true,
        flexNegative: true,
        flexOrder: true,
        gridArea: true,
        gridRow: true,
        gridRowEnd: true,
        gridRowSpan: true,
        gridRowStart: true,
        gridColumn: true,
        gridColumnEnd: true,
        gridColumnSpan: true,
        gridColumnStart: true,
        fontWeight: true,
        lineClamp: true,
        lineHeight: true,
        opacity: true,
        order: true,
        orphans: true,
        tabSize: true,
        widows: true,
        zIndex: true,
        zoom: true,
        // SVG-related properties
        fillOpacity: true,
        floodOpacity: true,
        stopOpacity: true,
        strokeDasharray: true,
        strokeDashoffset: true,
        strokeMiterlimit: true,
        strokeOpacity: true,
        strokeWidth: true
      };
      function prefixKey(prefix2, key2) {
        return prefix2 + key2.charAt(0).toUpperCase() + key2.substring(1);
      }
      var prefixes = ["Webkit", "ms", "Moz", "O"];
      Object.keys(isUnitlessNumber).forEach(function(prop) {
        prefixes.forEach(function(prefix2) {
          isUnitlessNumber[prefixKey(prefix2, prop)] = isUnitlessNumber[prop];
        });
      });
      function dangerousStyleValue(name, value, isCustomProperty) {
        var isEmpty = value == null || typeof value === "boolean" || value === "";
        if (isEmpty) {
          return "";
        }
        if (!isCustomProperty && typeof value === "number" && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
          return value + "px";
        }
        {
          checkCSSPropertyStringCoercion(value, name);
        }
        return ("" + value).trim();
      }
      var uppercasePattern = /([A-Z])/g;
      var msPattern = /^ms-/;
      function hyphenateStyleName(name) {
        return name.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-");
      }
      var warnValidStyle = function() {
      };
      {
        var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
        var msPattern$1 = /^-ms-/;
        var hyphenPattern = /-(.)/g;
        var badStyleValueWithSemicolonPattern = /;\s*$/;
        var warnedStyleNames = {};
        var warnedStyleValues = {};
        var warnedForNaNValue = false;
        var warnedForInfinityValue = false;
        var camelize = function(string) {
          return string.replace(hyphenPattern, function(_2, character) {
            return character.toUpperCase();
          });
        };
        var warnHyphenatedStyleName = function(name) {
          if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
            return;
          }
          warnedStyleNames[name] = true;
          error(
            "Unsupported style property %s. Did you mean %s?",
            name,
            // As Andi Smith suggests
            // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
            // is converted to lowercase `ms`.
            camelize(name.replace(msPattern$1, "ms-"))
          );
        };
        var warnBadVendoredStyleName = function(name) {
          if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
            return;
          }
          warnedStyleNames[name] = true;
          error("Unsupported vendor-prefixed style property %s. Did you mean %s?", name, name.charAt(0).toUpperCase() + name.slice(1));
        };
        var warnStyleValueWithSemicolon = function(name, value) {
          if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
            return;
          }
          warnedStyleValues[value] = true;
          error(`Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`, name, value.replace(badStyleValueWithSemicolonPattern, ""));
        };
        var warnStyleValueIsNaN = function(name, value) {
          if (warnedForNaNValue) {
            return;
          }
          warnedForNaNValue = true;
          error("`NaN` is an invalid value for the `%s` css style property.", name);
        };
        var warnStyleValueIsInfinity = function(name, value) {
          if (warnedForInfinityValue) {
            return;
          }
          warnedForInfinityValue = true;
          error("`Infinity` is an invalid value for the `%s` css style property.", name);
        };
        warnValidStyle = function(name, value) {
          if (name.indexOf("-") > -1) {
            warnHyphenatedStyleName(name);
          } else if (badVendoredStyleNamePattern.test(name)) {
            warnBadVendoredStyleName(name);
          } else if (badStyleValueWithSemicolonPattern.test(value)) {
            warnStyleValueWithSemicolon(name, value);
          }
          if (typeof value === "number") {
            if (isNaN(value)) {
              warnStyleValueIsNaN(name, value);
            } else if (!isFinite(value)) {
              warnStyleValueIsInfinity(name, value);
            }
          }
        };
      }
      var warnValidStyle$1 = warnValidStyle;
      function createDangerousStringForStyles(styles) {
        {
          var serialized = "";
          var delimiter = "";
          for (var styleName in styles) {
            if (!styles.hasOwnProperty(styleName)) {
              continue;
            }
            var styleValue = styles[styleName];
            if (styleValue != null) {
              var isCustomProperty = styleName.indexOf("--") === 0;
              serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ":";
              serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
              delimiter = ";";
            }
          }
          return serialized || null;
        }
      }
      function setValueForStyles(node2, styles) {
        var style2 = node2.style;
        for (var styleName in styles) {
          if (!styles.hasOwnProperty(styleName)) {
            continue;
          }
          var isCustomProperty = styleName.indexOf("--") === 0;
          {
            if (!isCustomProperty) {
              warnValidStyle$1(styleName, styles[styleName]);
            }
          }
          var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
          if (styleName === "float") {
            styleName = "cssFloat";
          }
          if (isCustomProperty) {
            style2.setProperty(styleName, styleValue);
          } else {
            style2[styleName] = styleValue;
          }
        }
      }
      function isValueEmpty(value) {
        return value == null || typeof value === "boolean" || value === "";
      }
      function expandShorthandMap(styles) {
        var expanded = {};
        for (var key2 in styles) {
          var longhands = shorthandToLonghand[key2] || [key2];
          for (var i2 = 0; i2 < longhands.length; i2++) {
            expanded[longhands[i2]] = key2;
          }
        }
        return expanded;
      }
      function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
        {
          if (!nextStyles) {
            return;
          }
          var expandedUpdates = expandShorthandMap(styleUpdates);
          var expandedStyles = expandShorthandMap(nextStyles);
          var warnedAbout = {};
          for (var key2 in expandedUpdates) {
            var originalKey = expandedUpdates[key2];
            var correctOriginalKey = expandedStyles[key2];
            if (correctOriginalKey && originalKey !== correctOriginalKey) {
              var warningKey = originalKey + "," + correctOriginalKey;
              if (warnedAbout[warningKey]) {
                continue;
              }
              warnedAbout[warningKey] = true;
              error("%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.", isValueEmpty(styleUpdates[originalKey]) ? "Removing" : "Updating", originalKey, correctOriginalKey);
            }
          }
        }
      }
      var omittedCloseTags = {
        area: true,
        base: true,
        br: true,
        col: true,
        embed: true,
        hr: true,
        img: true,
        input: true,
        keygen: true,
        link: true,
        meta: true,
        param: true,
        source: true,
        track: true,
        wbr: true
        // NOTE: menuitem's close tag should be omitted, but that causes problems.
      };
      var voidElementTags = assign({
        menuitem: true
      }, omittedCloseTags);
      var HTML = "__html";
      function assertValidProps(tag, props) {
        if (!props) {
          return;
        }
        if (voidElementTags[tag]) {
          if (props.children != null || props.dangerouslySetInnerHTML != null) {
            throw new Error(tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");
          }
        }
        if (props.dangerouslySetInnerHTML != null) {
          if (props.children != null) {
            throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
          }
          if (typeof props.dangerouslySetInnerHTML !== "object" || !(HTML in props.dangerouslySetInnerHTML)) {
            throw new Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://reactjs.org/link/dangerously-set-inner-html for more information.");
          }
        }
        {
          if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
            error("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional.");
          }
        }
        if (props.style != null && typeof props.style !== "object") {
          throw new Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");
        }
      }
      function isCustomComponent(tagName, props) {
        if (tagName.indexOf("-") === -1) {
          return typeof props.is === "string";
        }
        switch (tagName) {
          // These are reserved SVG and MathML elements.
          // We don't mind this list too much because we expect it to never grow.
          // The alternative is to track the namespace in a few places which is convoluted.
          // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
          case "annotation-xml":
          case "color-profile":
          case "font-face":
          case "font-face-src":
          case "font-face-uri":
          case "font-face-format":
          case "font-face-name":
          case "missing-glyph":
            return false;
          default:
            return true;
        }
      }
      var possibleStandardNames = {
        // HTML
        accept: "accept",
        acceptcharset: "acceptCharset",
        "accept-charset": "acceptCharset",
        accesskey: "accessKey",
        action: "action",
        allowfullscreen: "allowFullScreen",
        alt: "alt",
        as: "as",
        async: "async",
        autocapitalize: "autoCapitalize",
        autocomplete: "autoComplete",
        autocorrect: "autoCorrect",
        autofocus: "autoFocus",
        autoplay: "autoPlay",
        autosave: "autoSave",
        capture: "capture",
        cellpadding: "cellPadding",
        cellspacing: "cellSpacing",
        challenge: "challenge",
        charset: "charSet",
        checked: "checked",
        children: "children",
        cite: "cite",
        class: "className",
        classid: "classID",
        classname: "className",
        cols: "cols",
        colspan: "colSpan",
        content: "content",
        contenteditable: "contentEditable",
        contextmenu: "contextMenu",
        controls: "controls",
        controlslist: "controlsList",
        coords: "coords",
        crossorigin: "crossOrigin",
        dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
        data: "data",
        datetime: "dateTime",
        default: "default",
        defaultchecked: "defaultChecked",
        defaultvalue: "defaultValue",
        defer: "defer",
        dir: "dir",
        disabled: "disabled",
        disablepictureinpicture: "disablePictureInPicture",
        disableremoteplayback: "disableRemotePlayback",
        download: "download",
        draggable: "draggable",
        enctype: "encType",
        enterkeyhint: "enterKeyHint",
        for: "htmlFor",
        form: "form",
        formmethod: "formMethod",
        formaction: "formAction",
        formenctype: "formEncType",
        formnovalidate: "formNoValidate",
        formtarget: "formTarget",
        frameborder: "frameBorder",
        headers: "headers",
        height: "height",
        hidden: "hidden",
        high: "high",
        href: "href",
        hreflang: "hrefLang",
        htmlfor: "htmlFor",
        httpequiv: "httpEquiv",
        "http-equiv": "httpEquiv",
        icon: "icon",
        id: "id",
        imagesizes: "imageSizes",
        imagesrcset: "imageSrcSet",
        innerhtml: "innerHTML",
        inputmode: "inputMode",
        integrity: "integrity",
        is: "is",
        itemid: "itemID",
        itemprop: "itemProp",
        itemref: "itemRef",
        itemscope: "itemScope",
        itemtype: "itemType",
        keyparams: "keyParams",
        keytype: "keyType",
        kind: "kind",
        label: "label",
        lang: "lang",
        list: "list",
        loop: "loop",
        low: "low",
        manifest: "manifest",
        marginwidth: "marginWidth",
        marginheight: "marginHeight",
        max: "max",
        maxlength: "maxLength",
        media: "media",
        mediagroup: "mediaGroup",
        method: "method",
        min: "min",
        minlength: "minLength",
        multiple: "multiple",
        muted: "muted",
        name: "name",
        nomodule: "noModule",
        nonce: "nonce",
        novalidate: "noValidate",
        open: "open",
        optimum: "optimum",
        pattern: "pattern",
        placeholder: "placeholder",
        playsinline: "playsInline",
        poster: "poster",
        preload: "preload",
        profile: "profile",
        radiogroup: "radioGroup",
        readonly: "readOnly",
        referrerpolicy: "referrerPolicy",
        rel: "rel",
        required: "required",
        reversed: "reversed",
        role: "role",
        rows: "rows",
        rowspan: "rowSpan",
        sandbox: "sandbox",
        scope: "scope",
        scoped: "scoped",
        scrolling: "scrolling",
        seamless: "seamless",
        selected: "selected",
        shape: "shape",
        size: "size",
        sizes: "sizes",
        span: "span",
        spellcheck: "spellCheck",
        src: "src",
        srcdoc: "srcDoc",
        srclang: "srcLang",
        srcset: "srcSet",
        start: "start",
        step: "step",
        style: "style",
        summary: "summary",
        tabindex: "tabIndex",
        target: "target",
        title: "title",
        type: "type",
        usemap: "useMap",
        value: "value",
        width: "width",
        wmode: "wmode",
        wrap: "wrap",
        // SVG
        about: "about",
        accentheight: "accentHeight",
        "accent-height": "accentHeight",
        accumulate: "accumulate",
        additive: "additive",
        alignmentbaseline: "alignmentBaseline",
        "alignment-baseline": "alignmentBaseline",
        allowreorder: "allowReorder",
        alphabetic: "alphabetic",
        amplitude: "amplitude",
        arabicform: "arabicForm",
        "arabic-form": "arabicForm",
        ascent: "ascent",
        attributename: "attributeName",
        attributetype: "attributeType",
        autoreverse: "autoReverse",
        azimuth: "azimuth",
        basefrequency: "baseFrequency",
        baselineshift: "baselineShift",
        "baseline-shift": "baselineShift",
        baseprofile: "baseProfile",
        bbox: "bbox",
        begin: "begin",
        bias: "bias",
        by: "by",
        calcmode: "calcMode",
        capheight: "capHeight",
        "cap-height": "capHeight",
        clip: "clip",
        clippath: "clipPath",
        "clip-path": "clipPath",
        clippathunits: "clipPathUnits",
        cliprule: "clipRule",
        "clip-rule": "clipRule",
        color: "color",
        colorinterpolation: "colorInterpolation",
        "color-interpolation": "colorInterpolation",
        colorinterpolationfilters: "colorInterpolationFilters",
        "color-interpolation-filters": "colorInterpolationFilters",
        colorprofile: "colorProfile",
        "color-profile": "colorProfile",
        colorrendering: "colorRendering",
        "color-rendering": "colorRendering",
        contentscripttype: "contentScriptType",
        contentstyletype: "contentStyleType",
        cursor: "cursor",
        cx: "cx",
        cy: "cy",
        d: "d",
        datatype: "datatype",
        decelerate: "decelerate",
        descent: "descent",
        diffuseconstant: "diffuseConstant",
        direction: "direction",
        display: "display",
        divisor: "divisor",
        dominantbaseline: "dominantBaseline",
        "dominant-baseline": "dominantBaseline",
        dur: "dur",
        dx: "dx",
        dy: "dy",
        edgemode: "edgeMode",
        elevation: "elevation",
        enablebackground: "enableBackground",
        "enable-background": "enableBackground",
        end: "end",
        exponent: "exponent",
        externalresourcesrequired: "externalResourcesRequired",
        fill: "fill",
        fillopacity: "fillOpacity",
        "fill-opacity": "fillOpacity",
        fillrule: "fillRule",
        "fill-rule": "fillRule",
        filter: "filter",
        filterres: "filterRes",
        filterunits: "filterUnits",
        floodopacity: "floodOpacity",
        "flood-opacity": "floodOpacity",
        floodcolor: "floodColor",
        "flood-color": "floodColor",
        focusable: "focusable",
        fontfamily: "fontFamily",
        "font-family": "fontFamily",
        fontsize: "fontSize",
        "font-size": "fontSize",
        fontsizeadjust: "fontSizeAdjust",
        "font-size-adjust": "fontSizeAdjust",
        fontstretch: "fontStretch",
        "font-stretch": "fontStretch",
        fontstyle: "fontStyle",
        "font-style": "fontStyle",
        fontvariant: "fontVariant",
        "font-variant": "fontVariant",
        fontweight: "fontWeight",
        "font-weight": "fontWeight",
        format: "format",
        from: "from",
        fx: "fx",
        fy: "fy",
        g1: "g1",
        g2: "g2",
        glyphname: "glyphName",
        "glyph-name": "glyphName",
        glyphorientationhorizontal: "glyphOrientationHorizontal",
        "glyph-orientation-horizontal": "glyphOrientationHorizontal",
        glyphorientationvertical: "glyphOrientationVertical",
        "glyph-orientation-vertical": "glyphOrientationVertical",
        glyphref: "glyphRef",
        gradienttransform: "gradientTransform",
        gradientunits: "gradientUnits",
        hanging: "hanging",
        horizadvx: "horizAdvX",
        "horiz-adv-x": "horizAdvX",
        horizoriginx: "horizOriginX",
        "horiz-origin-x": "horizOriginX",
        ideographic: "ideographic",
        imagerendering: "imageRendering",
        "image-rendering": "imageRendering",
        in2: "in2",
        in: "in",
        inlist: "inlist",
        intercept: "intercept",
        k1: "k1",
        k2: "k2",
        k3: "k3",
        k4: "k4",
        k: "k",
        kernelmatrix: "kernelMatrix",
        kernelunitlength: "kernelUnitLength",
        kerning: "kerning",
        keypoints: "keyPoints",
        keysplines: "keySplines",
        keytimes: "keyTimes",
        lengthadjust: "lengthAdjust",
        letterspacing: "letterSpacing",
        "letter-spacing": "letterSpacing",
        lightingcolor: "lightingColor",
        "lighting-color": "lightingColor",
        limitingconeangle: "limitingConeAngle",
        local: "local",
        markerend: "markerEnd",
        "marker-end": "markerEnd",
        markerheight: "markerHeight",
        markermid: "markerMid",
        "marker-mid": "markerMid",
        markerstart: "markerStart",
        "marker-start": "markerStart",
        markerunits: "markerUnits",
        markerwidth: "markerWidth",
        mask: "mask",
        maskcontentunits: "maskContentUnits",
        maskunits: "maskUnits",
        mathematical: "mathematical",
        mode: "mode",
        numoctaves: "numOctaves",
        offset: "offset",
        opacity: "opacity",
        operator: "operator",
        order: "order",
        orient: "orient",
        orientation: "orientation",
        origin: "origin",
        overflow: "overflow",
        overlineposition: "overlinePosition",
        "overline-position": "overlinePosition",
        overlinethickness: "overlineThickness",
        "overline-thickness": "overlineThickness",
        paintorder: "paintOrder",
        "paint-order": "paintOrder",
        panose1: "panose1",
        "panose-1": "panose1",
        pathlength: "pathLength",
        patterncontentunits: "patternContentUnits",
        patterntransform: "patternTransform",
        patternunits: "patternUnits",
        pointerevents: "pointerEvents",
        "pointer-events": "pointerEvents",
        points: "points",
        pointsatx: "pointsAtX",
        pointsaty: "pointsAtY",
        pointsatz: "pointsAtZ",
        prefix: "prefix",
        preservealpha: "preserveAlpha",
        preserveaspectratio: "preserveAspectRatio",
        primitiveunits: "primitiveUnits",
        property: "property",
        r: "r",
        radius: "radius",
        refx: "refX",
        refy: "refY",
        renderingintent: "renderingIntent",
        "rendering-intent": "renderingIntent",
        repeatcount: "repeatCount",
        repeatdur: "repeatDur",
        requiredextensions: "requiredExtensions",
        requiredfeatures: "requiredFeatures",
        resource: "resource",
        restart: "restart",
        result: "result",
        results: "results",
        rotate: "rotate",
        rx: "rx",
        ry: "ry",
        scale: "scale",
        security: "security",
        seed: "seed",
        shaperendering: "shapeRendering",
        "shape-rendering": "shapeRendering",
        slope: "slope",
        spacing: "spacing",
        specularconstant: "specularConstant",
        specularexponent: "specularExponent",
        speed: "speed",
        spreadmethod: "spreadMethod",
        startoffset: "startOffset",
        stddeviation: "stdDeviation",
        stemh: "stemh",
        stemv: "stemv",
        stitchtiles: "stitchTiles",
        stopcolor: "stopColor",
        "stop-color": "stopColor",
        stopopacity: "stopOpacity",
        "stop-opacity": "stopOpacity",
        strikethroughposition: "strikethroughPosition",
        "strikethrough-position": "strikethroughPosition",
        strikethroughthickness: "strikethroughThickness",
        "strikethrough-thickness": "strikethroughThickness",
        string: "string",
        stroke: "stroke",
        strokedasharray: "strokeDasharray",
        "stroke-dasharray": "strokeDasharray",
        strokedashoffset: "strokeDashoffset",
        "stroke-dashoffset": "strokeDashoffset",
        strokelinecap: "strokeLinecap",
        "stroke-linecap": "strokeLinecap",
        strokelinejoin: "strokeLinejoin",
        "stroke-linejoin": "strokeLinejoin",
        strokemiterlimit: "strokeMiterlimit",
        "stroke-miterlimit": "strokeMiterlimit",
        strokewidth: "strokeWidth",
        "stroke-width": "strokeWidth",
        strokeopacity: "strokeOpacity",
        "stroke-opacity": "strokeOpacity",
        suppresscontenteditablewarning: "suppressContentEditableWarning",
        suppresshydrationwarning: "suppressHydrationWarning",
        surfacescale: "surfaceScale",
        systemlanguage: "systemLanguage",
        tablevalues: "tableValues",
        targetx: "targetX",
        targety: "targetY",
        textanchor: "textAnchor",
        "text-anchor": "textAnchor",
        textdecoration: "textDecoration",
        "text-decoration": "textDecoration",
        textlength: "textLength",
        textrendering: "textRendering",
        "text-rendering": "textRendering",
        to: "to",
        transform: "transform",
        typeof: "typeof",
        u1: "u1",
        u2: "u2",
        underlineposition: "underlinePosition",
        "underline-position": "underlinePosition",
        underlinethickness: "underlineThickness",
        "underline-thickness": "underlineThickness",
        unicode: "unicode",
        unicodebidi: "unicodeBidi",
        "unicode-bidi": "unicodeBidi",
        unicoderange: "unicodeRange",
        "unicode-range": "unicodeRange",
        unitsperem: "unitsPerEm",
        "units-per-em": "unitsPerEm",
        unselectable: "unselectable",
        valphabetic: "vAlphabetic",
        "v-alphabetic": "vAlphabetic",
        values: "values",
        vectoreffect: "vectorEffect",
        "vector-effect": "vectorEffect",
        version: "version",
        vertadvy: "vertAdvY",
        "vert-adv-y": "vertAdvY",
        vertoriginx: "vertOriginX",
        "vert-origin-x": "vertOriginX",
        vertoriginy: "vertOriginY",
        "vert-origin-y": "vertOriginY",
        vhanging: "vHanging",
        "v-hanging": "vHanging",
        videographic: "vIdeographic",
        "v-ideographic": "vIdeographic",
        viewbox: "viewBox",
        viewtarget: "viewTarget",
        visibility: "visibility",
        vmathematical: "vMathematical",
        "v-mathematical": "vMathematical",
        vocab: "vocab",
        widths: "widths",
        wordspacing: "wordSpacing",
        "word-spacing": "wordSpacing",
        writingmode: "writingMode",
        "writing-mode": "writingMode",
        x1: "x1",
        x2: "x2",
        x: "x",
        xchannelselector: "xChannelSelector",
        xheight: "xHeight",
        "x-height": "xHeight",
        xlinkactuate: "xlinkActuate",
        "xlink:actuate": "xlinkActuate",
        xlinkarcrole: "xlinkArcrole",
        "xlink:arcrole": "xlinkArcrole",
        xlinkhref: "xlinkHref",
        "xlink:href": "xlinkHref",
        xlinkrole: "xlinkRole",
        "xlink:role": "xlinkRole",
        xlinkshow: "xlinkShow",
        "xlink:show": "xlinkShow",
        xlinktitle: "xlinkTitle",
        "xlink:title": "xlinkTitle",
        xlinktype: "xlinkType",
        "xlink:type": "xlinkType",
        xmlbase: "xmlBase",
        "xml:base": "xmlBase",
        xmllang: "xmlLang",
        "xml:lang": "xmlLang",
        xmlns: "xmlns",
        "xml:space": "xmlSpace",
        xmlnsxlink: "xmlnsXlink",
        "xmlns:xlink": "xmlnsXlink",
        xmlspace: "xmlSpace",
        y1: "y1",
        y2: "y2",
        y: "y",
        ychannelselector: "yChannelSelector",
        z: "z",
        zoomandpan: "zoomAndPan"
      };
      var ariaProperties = {
        "aria-current": 0,
        // state
        "aria-description": 0,
        "aria-details": 0,
        "aria-disabled": 0,
        // state
        "aria-hidden": 0,
        // state
        "aria-invalid": 0,
        // state
        "aria-keyshortcuts": 0,
        "aria-label": 0,
        "aria-roledescription": 0,
        // Widget Attributes
        "aria-autocomplete": 0,
        "aria-checked": 0,
        "aria-expanded": 0,
        "aria-haspopup": 0,
        "aria-level": 0,
        "aria-modal": 0,
        "aria-multiline": 0,
        "aria-multiselectable": 0,
        "aria-orientation": 0,
        "aria-placeholder": 0,
        "aria-pressed": 0,
        "aria-readonly": 0,
        "aria-required": 0,
        "aria-selected": 0,
        "aria-sort": 0,
        "aria-valuemax": 0,
        "aria-valuemin": 0,
        "aria-valuenow": 0,
        "aria-valuetext": 0,
        // Live Region Attributes
        "aria-atomic": 0,
        "aria-busy": 0,
        "aria-live": 0,
        "aria-relevant": 0,
        // Drag-and-Drop Attributes
        "aria-dropeffect": 0,
        "aria-grabbed": 0,
        // Relationship Attributes
        "aria-activedescendant": 0,
        "aria-colcount": 0,
        "aria-colindex": 0,
        "aria-colspan": 0,
        "aria-controls": 0,
        "aria-describedby": 0,
        "aria-errormessage": 0,
        "aria-flowto": 0,
        "aria-labelledby": 0,
        "aria-owns": 0,
        "aria-posinset": 0,
        "aria-rowcount": 0,
        "aria-rowindex": 0,
        "aria-rowspan": 0,
        "aria-setsize": 0
      };
      var warnedProperties = {};
      var rARIA = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
      var rARIACamel = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
      function validateProperty(tagName, name) {
        {
          if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) {
            return true;
          }
          if (rARIACamel.test(name)) {
            var ariaName = "aria-" + name.slice(4).toLowerCase();
            var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null;
            if (correctName == null) {
              error("Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.", name);
              warnedProperties[name] = true;
              return true;
            }
            if (name !== correctName) {
              error("Invalid ARIA attribute `%s`. Did you mean `%s`?", name, correctName);
              warnedProperties[name] = true;
              return true;
            }
          }
          if (rARIA.test(name)) {
            var lowerCasedName = name.toLowerCase();
            var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null;
            if (standardName == null) {
              warnedProperties[name] = true;
              return false;
            }
            if (name !== standardName) {
              error("Unknown ARIA attribute `%s`. Did you mean `%s`?", name, standardName);
              warnedProperties[name] = true;
              return true;
            }
          }
        }
        return true;
      }
      function warnInvalidARIAProps(type2, props) {
        {
          var invalidProps = [];
          for (var key2 in props) {
            var isValid2 = validateProperty(type2, key2);
            if (!isValid2) {
              invalidProps.push(key2);
            }
          }
          var unknownPropString = invalidProps.map(function(prop) {
            return "`" + prop + "`";
          }).join(", ");
          if (invalidProps.length === 1) {
            error("Invalid aria prop %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type2);
          } else if (invalidProps.length > 1) {
            error("Invalid aria props %s on <%s> tag. For details, see https://reactjs.org/link/invalid-aria-props", unknownPropString, type2);
          }
        }
      }
      function validateProperties(type2, props) {
        if (isCustomComponent(type2, props)) {
          return;
        }
        warnInvalidARIAProps(type2, props);
      }
      var didWarnValueNull = false;
      function validateProperties$1(type2, props) {
        {
          if (type2 !== "input" && type2 !== "textarea" && type2 !== "select") {
            return;
          }
          if (props != null && props.value === null && !didWarnValueNull) {
            didWarnValueNull = true;
            if (type2 === "select" && props.multiple) {
              error("`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.", type2);
            } else {
              error("`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.", type2);
            }
          }
        }
      }
      var validateProperty$1 = function() {
      };
      {
        var warnedProperties$1 = {};
        var EVENT_NAME_REGEX = /^on./;
        var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
        var rARIA$1 = new RegExp("^(aria)-[" + ATTRIBUTE_NAME_CHAR + "]*$");
        var rARIACamel$1 = new RegExp("^(aria)[A-Z][" + ATTRIBUTE_NAME_CHAR + "]*$");
        validateProperty$1 = function(tagName, name, value, eventRegistry) {
          if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
            return true;
          }
          var lowerCasedName = name.toLowerCase();
          if (lowerCasedName === "onfocusin" || lowerCasedName === "onfocusout") {
            error("React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React.");
            warnedProperties$1[name] = true;
            return true;
          }
          if (eventRegistry != null) {
            var registrationNameDependencies2 = eventRegistry.registrationNameDependencies, possibleRegistrationNames2 = eventRegistry.possibleRegistrationNames;
            if (registrationNameDependencies2.hasOwnProperty(name)) {
              return true;
            }
            var registrationName = possibleRegistrationNames2.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames2[lowerCasedName] : null;
            if (registrationName != null) {
              error("Invalid event handler property `%s`. Did you mean `%s`?", name, registrationName);
              warnedProperties$1[name] = true;
              return true;
            }
            if (EVENT_NAME_REGEX.test(name)) {
              error("Unknown event handler property `%s`. It will be ignored.", name);
              warnedProperties$1[name] = true;
              return true;
            }
          } else if (EVENT_NAME_REGEX.test(name)) {
            if (INVALID_EVENT_NAME_REGEX.test(name)) {
              error("Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.", name);
            }
            warnedProperties$1[name] = true;
            return true;
          }
          if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
            return true;
          }
          if (lowerCasedName === "innerhtml") {
            error("Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`.");
            warnedProperties$1[name] = true;
            return true;
          }
          if (lowerCasedName === "aria") {
            error("The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead.");
            warnedProperties$1[name] = true;
            return true;
          }
          if (lowerCasedName === "is" && value !== null && value !== void 0 && typeof value !== "string") {
            error("Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.", typeof value);
            warnedProperties$1[name] = true;
            return true;
          }
          if (typeof value === "number" && isNaN(value)) {
            error("Received NaN for the `%s` attribute. If this is expected, cast the value to a string.", name);
            warnedProperties$1[name] = true;
            return true;
          }
          var propertyInfo = getPropertyInfo(name);
          var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED;
          if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
            var standardName = possibleStandardNames[lowerCasedName];
            if (standardName !== name) {
              error("Invalid DOM property `%s`. Did you mean `%s`?", name, standardName);
              warnedProperties$1[name] = true;
              return true;
            }
          } else if (!isReserved && name !== lowerCasedName) {
            error("React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.", name, lowerCasedName);
            warnedProperties$1[name] = true;
            return true;
          }
          if (typeof value === "boolean" && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
            if (value) {
              error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.', value, name, name, value, name);
            } else {
              error('Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
            }
            warnedProperties$1[name] = true;
            return true;
          }
          if (isReserved) {
            return true;
          }
          if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
            warnedProperties$1[name] = true;
            return false;
          }
          if ((value === "false" || value === "true") && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
            error("Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?", value, name, value === "false" ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
            warnedProperties$1[name] = true;
            return true;
          }
          return true;
        };
      }
      var warnUnknownProperties = function(type2, props, eventRegistry) {
        {
          var unknownProps = [];
          for (var key2 in props) {
            var isValid2 = validateProperty$1(type2, key2, props[key2], eventRegistry);
            if (!isValid2) {
              unknownProps.push(key2);
            }
          }
          var unknownPropString = unknownProps.map(function(prop) {
            return "`" + prop + "`";
          }).join(", ");
          if (unknownProps.length === 1) {
            error("Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type2);
          } else if (unknownProps.length > 1) {
            error("Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://reactjs.org/link/attribute-behavior ", unknownPropString, type2);
          }
        }
      };
      function validateProperties$2(type2, props, eventRegistry) {
        if (isCustomComponent(type2, props)) {
          return;
        }
        warnUnknownProperties(type2, props, eventRegistry);
      }
      var IS_EVENT_HANDLE_NON_MANAGED_NODE = 1;
      var IS_NON_DELEGATED = 1 << 1;
      var IS_CAPTURE_PHASE = 1 << 2;
      var SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS = IS_EVENT_HANDLE_NON_MANAGED_NODE | IS_NON_DELEGATED | IS_CAPTURE_PHASE;
      var currentReplayingEvent = null;
      function setReplayingEvent(event) {
        {
          if (currentReplayingEvent !== null) {
            error("Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        currentReplayingEvent = event;
      }
      function resetReplayingEvent() {
        {
          if (currentReplayingEvent === null) {
            error("Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        currentReplayingEvent = null;
      }
      function isReplayingEvent(event) {
        return event === currentReplayingEvent;
      }
      function getEventTarget(nativeEvent) {
        var target = nativeEvent.target || nativeEvent.srcElement || window;
        if (target.correspondingUseElement) {
          target = target.correspondingUseElement;
        }
        return target.nodeType === TEXT_NODE ? target.parentNode : target;
      }
      var restoreImpl = null;
      var restoreTarget = null;
      var restoreQueue = null;
      function restoreStateOfTarget(target) {
        var internalInstance = getInstanceFromNode(target);
        if (!internalInstance) {
          return;
        }
        if (typeof restoreImpl !== "function") {
          throw new Error("setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.");
        }
        var stateNode = internalInstance.stateNode;
        if (stateNode) {
          var _props = getFiberCurrentPropsFromNode(stateNode);
          restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
        }
      }
      function setRestoreImplementation(impl) {
        restoreImpl = impl;
      }
      function enqueueStateRestore(target) {
        if (restoreTarget) {
          if (restoreQueue) {
            restoreQueue.push(target);
          } else {
            restoreQueue = [target];
          }
        } else {
          restoreTarget = target;
        }
      }
      function needsStateRestore() {
        return restoreTarget !== null || restoreQueue !== null;
      }
      function restoreStateIfNeeded() {
        if (!restoreTarget) {
          return;
        }
        var target = restoreTarget;
        var queuedTargets = restoreQueue;
        restoreTarget = null;
        restoreQueue = null;
        restoreStateOfTarget(target);
        if (queuedTargets) {
          for (var i2 = 0; i2 < queuedTargets.length; i2++) {
            restoreStateOfTarget(queuedTargets[i2]);
          }
        }
      }
      var batchedUpdatesImpl = function(fn, bookkeeping) {
        return fn(bookkeeping);
      };
      var flushSyncImpl = function() {
      };
      var isInsideEventHandler = false;
      function finishEventHandler() {
        var controlledComponentsHavePendingUpdates = needsStateRestore();
        if (controlledComponentsHavePendingUpdates) {
          flushSyncImpl();
          restoreStateIfNeeded();
        }
      }
      function batchedUpdates(fn, a2, b2) {
        if (isInsideEventHandler) {
          return fn(a2, b2);
        }
        isInsideEventHandler = true;
        try {
          return batchedUpdatesImpl(fn, a2, b2);
        } finally {
          isInsideEventHandler = false;
          finishEventHandler();
        }
      }
      function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushSyncImpl) {
        batchedUpdatesImpl = _batchedUpdatesImpl;
        flushSyncImpl = _flushSyncImpl;
      }
      function isInteractive(tag) {
        return tag === "button" || tag === "input" || tag === "select" || tag === "textarea";
      }
      function shouldPreventMouseEvent(name, type2, props) {
        switch (name) {
          case "onClick":
          case "onClickCapture":
          case "onDoubleClick":
          case "onDoubleClickCapture":
          case "onMouseDown":
          case "onMouseDownCapture":
          case "onMouseMove":
          case "onMouseMoveCapture":
          case "onMouseUp":
          case "onMouseUpCapture":
          case "onMouseEnter":
            return !!(props.disabled && isInteractive(type2));
          default:
            return false;
        }
      }
      function getListener(inst, registrationName) {
        var stateNode = inst.stateNode;
        if (stateNode === null) {
          return null;
        }
        var props = getFiberCurrentPropsFromNode(stateNode);
        if (props === null) {
          return null;
        }
        var listener = props[registrationName];
        if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
          return null;
        }
        if (listener && typeof listener !== "function") {
          throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
        }
        return listener;
      }
      var passiveBrowserEventsSupported = false;
      if (canUseDOM) {
        try {
          var options2 = {};
          Object.defineProperty(options2, "passive", {
            get: function() {
              passiveBrowserEventsSupported = true;
            }
          });
          window.addEventListener("test", options2, options2);
          window.removeEventListener("test", options2, options2);
        } catch (e4) {
          passiveBrowserEventsSupported = false;
        }
      }
      function invokeGuardedCallbackProd(name, func, context, a2, b2, c2, d, e4, f2) {
        var funcArgs = Array.prototype.slice.call(arguments, 3);
        try {
          func.apply(context, funcArgs);
        } catch (error2) {
          this.onError(error2);
        }
      }
      var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
      {
        if (typeof window !== "undefined" && typeof window.dispatchEvent === "function" && typeof document !== "undefined" && typeof document.createEvent === "function") {
          var fakeNode = document.createElement("react");
          invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a2, b2, c2, d, e4, f2) {
            if (typeof document === "undefined" || document === null) {
              throw new Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");
            }
            var evt = document.createEvent("Event");
            var didCall = false;
            var didError = true;
            var windowEvent = window.event;
            var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, "event");
            function restoreAfterDispatch() {
              fakeNode.removeEventListener(evtType, callCallback2, false);
              if (typeof window.event !== "undefined" && window.hasOwnProperty("event")) {
                window.event = windowEvent;
              }
            }
            var funcArgs = Array.prototype.slice.call(arguments, 3);
            function callCallback2() {
              didCall = true;
              restoreAfterDispatch();
              func.apply(context, funcArgs);
              didError = false;
            }
            var error2;
            var didSetError = false;
            var isCrossOriginError = false;
            function handleWindowError(event) {
              error2 = event.error;
              didSetError = true;
              if (error2 === null && event.colno === 0 && event.lineno === 0) {
                isCrossOriginError = true;
              }
              if (event.defaultPrevented) {
                if (error2 != null && typeof error2 === "object") {
                  try {
                    error2._suppressLogging = true;
                  } catch (inner) {
                  }
                }
              }
            }
            var evtType = "react-" + (name ? name : "invokeguardedcallback");
            window.addEventListener("error", handleWindowError);
            fakeNode.addEventListener(evtType, callCallback2, false);
            evt.initEvent(evtType, false, false);
            fakeNode.dispatchEvent(evt);
            if (windowEventDescriptor) {
              Object.defineProperty(window, "event", windowEventDescriptor);
            }
            if (didCall && didError) {
              if (!didSetError) {
                error2 = new Error(`An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the "Pause on exceptions" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue.`);
              } else if (isCrossOriginError) {
                error2 = new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.");
              }
              this.onError(error2);
            }
            window.removeEventListener("error", handleWindowError);
            if (!didCall) {
              restoreAfterDispatch();
              return invokeGuardedCallbackProd.apply(this, arguments);
            }
          };
        }
      }
      var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
      var hasError = false;
      var caughtError = null;
      var hasRethrowError = false;
      var rethrowError = null;
      var reporter2 = {
        onError: function(error2) {
          hasError = true;
          caughtError = error2;
        }
      };
      function invokeGuardedCallback(name, func, context, a2, b2, c2, d, e4, f2) {
        hasError = false;
        caughtError = null;
        invokeGuardedCallbackImpl$1.apply(reporter2, arguments);
      }
      function invokeGuardedCallbackAndCatchFirstError(name, func, context, a2, b2, c2, d, e4, f2) {
        invokeGuardedCallback.apply(this, arguments);
        if (hasError) {
          var error2 = clearCaughtError();
          if (!hasRethrowError) {
            hasRethrowError = true;
            rethrowError = error2;
          }
        }
      }
      function rethrowCaughtError() {
        if (hasRethrowError) {
          var error2 = rethrowError;
          hasRethrowError = false;
          rethrowError = null;
          throw error2;
        }
      }
      function hasCaughtError() {
        return hasError;
      }
      function clearCaughtError() {
        if (hasError) {
          var error2 = caughtError;
          hasError = false;
          caughtError = null;
          return error2;
        } else {
          throw new Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
      function get2(key2) {
        return key2._reactInternals;
      }
      function has(key2) {
        return key2._reactInternals !== void 0;
      }
      function set(key2, value) {
        key2._reactInternals = value;
      }
      var NoFlags = (
        /*                      */
        0
      );
      var PerformedWork = (
        /*                */
        1
      );
      var Placement = (
        /*                    */
        2
      );
      var Update = (
        /*                       */
        4
      );
      var ChildDeletion = (
        /*                */
        16
      );
      var ContentReset = (
        /*                 */
        32
      );
      var Callback = (
        /*                     */
        64
      );
      var DidCapture = (
        /*                   */
        128
      );
      var ForceClientRender = (
        /*            */
        256
      );
      var Ref = (
        /*                          */
        512
      );
      var Snapshot = (
        /*                     */
        1024
      );
      var Passive = (
        /*                      */
        2048
      );
      var Hydrating = (
        /*                    */
        4096
      );
      var Visibility = (
        /*                   */
        8192
      );
      var StoreConsistency = (
        /*             */
        16384
      );
      var HostEffectMask = (
        /*               */
        32767
      );
      var Incomplete = (
        /*                   */
        32768
      );
      var ShouldCapture = (
        /*                */
        65536
      );
      var ForceUpdateForLegacySuspense = (
        /* */
        131072
      );
      var Forked = (
        /*                       */
        1048576
      );
      var RefStatic = (
        /*                    */
        2097152
      );
      var LayoutStatic = (
        /*                 */
        4194304
      );
      var PassiveStatic = (
        /*                */
        8388608
      );
      var MountLayoutDev = (
        /*               */
        16777216
      );
      var MountPassiveDev = (
        /*              */
        33554432
      );
      var BeforeMutationMask = (
        // TODO: Remove Update flag from before mutation phase by re-landing Visibility
        // flag logic (see #20043)
        Update | Snapshot | 0
      );
      var MutationMask = Placement | Update | ChildDeletion | ContentReset | Ref | Hydrating | Visibility;
      var LayoutMask = Update | Callback | Ref | Visibility;
      var PassiveMask = Passive | ChildDeletion;
      var StaticMask = LayoutStatic | PassiveStatic | RefStatic;
      var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
      function getNearestMountedFiber(fiber) {
        var node2 = fiber;
        var nearestMounted = fiber;
        if (!fiber.alternate) {
          var nextNode = node2;
          do {
            node2 = nextNode;
            if ((node2.flags & (Placement | Hydrating)) !== NoFlags) {
              nearestMounted = node2.return;
            }
            nextNode = node2.return;
          } while (nextNode);
        } else {
          while (node2.return) {
            node2 = node2.return;
          }
        }
        if (node2.tag === HostRoot) {
          return nearestMounted;
        }
        return null;
      }
      function getSuspenseInstanceFromFiber(fiber) {
        if (fiber.tag === SuspenseComponent) {
          var suspenseState = fiber.memoizedState;
          if (suspenseState === null) {
            var current2 = fiber.alternate;
            if (current2 !== null) {
              suspenseState = current2.memoizedState;
            }
          }
          if (suspenseState !== null) {
            return suspenseState.dehydrated;
          }
        }
        return null;
      }
      function getContainerFromFiber(fiber) {
        return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
      }
      function isFiberMounted(fiber) {
        return getNearestMountedFiber(fiber) === fiber;
      }
      function isMounted(component) {
        {
          var owner = ReactCurrentOwner.current;
          if (owner !== null && owner.tag === ClassComponent) {
            var ownerFiber = owner;
            var instance2 = ownerFiber.stateNode;
            if (!instance2._warnedAboutRefsInRender) {
              error("%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromFiber(ownerFiber) || "A component");
            }
            instance2._warnedAboutRefsInRender = true;
          }
        }
        var fiber = get2(component);
        if (!fiber) {
          return false;
        }
        return getNearestMountedFiber(fiber) === fiber;
      }
      function assertIsMounted(fiber) {
        if (getNearestMountedFiber(fiber) !== fiber) {
          throw new Error("Unable to find node on an unmounted component.");
        }
      }
      function findCurrentFiberUsingSlowPath(fiber) {
        var alternate = fiber.alternate;
        if (!alternate) {
          var nearestMounted = getNearestMountedFiber(fiber);
          if (nearestMounted === null) {
            throw new Error("Unable to find node on an unmounted component.");
          }
          if (nearestMounted !== fiber) {
            return null;
          }
          return fiber;
        }
        var a2 = fiber;
        var b2 = alternate;
        while (true) {
          var parentA = a2.return;
          if (parentA === null) {
            break;
          }
          var parentB = parentA.alternate;
          if (parentB === null) {
            var nextParent = parentA.return;
            if (nextParent !== null) {
              a2 = b2 = nextParent;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            var child = parentA.child;
            while (child) {
              if (child === a2) {
                assertIsMounted(parentA);
                return fiber;
              }
              if (child === b2) {
                assertIsMounted(parentA);
                return alternate;
              }
              child = child.sibling;
            }
            throw new Error("Unable to find node on an unmounted component.");
          }
          if (a2.return !== b2.return) {
            a2 = parentA;
            b2 = parentB;
          } else {
            var didFindChild = false;
            var _child = parentA.child;
            while (_child) {
              if (_child === a2) {
                didFindChild = true;
                a2 = parentA;
                b2 = parentB;
                break;
              }
              if (_child === b2) {
                didFindChild = true;
                b2 = parentA;
                a2 = parentB;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild) {
              _child = parentB.child;
              while (_child) {
                if (_child === a2) {
                  didFindChild = true;
                  a2 = parentB;
                  b2 = parentA;
                  break;
                }
                if (_child === b2) {
                  didFindChild = true;
                  b2 = parentB;
                  a2 = parentA;
                  break;
                }
                _child = _child.sibling;
              }
              if (!didFindChild) {
                throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
              }
            }
          }
          if (a2.alternate !== b2) {
            throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        if (a2.tag !== HostRoot) {
          throw new Error("Unable to find node on an unmounted component.");
        }
        if (a2.stateNode.current === a2) {
          return fiber;
        }
        return alternate;
      }
      function findCurrentHostFiber(parent) {
        var currentParent = findCurrentFiberUsingSlowPath(parent);
        return currentParent !== null ? findCurrentHostFiberImpl(currentParent) : null;
      }
      function findCurrentHostFiberImpl(node2) {
        if (node2.tag === HostComponent || node2.tag === HostText) {
          return node2;
        }
        var child = node2.child;
        while (child !== null) {
          var match = findCurrentHostFiberImpl(child);
          if (match !== null) {
            return match;
          }
          child = child.sibling;
        }
        return null;
      }
      function findCurrentHostFiberWithNoPortals(parent) {
        var currentParent = findCurrentFiberUsingSlowPath(parent);
        return currentParent !== null ? findCurrentHostFiberWithNoPortalsImpl(currentParent) : null;
      }
      function findCurrentHostFiberWithNoPortalsImpl(node2) {
        if (node2.tag === HostComponent || node2.tag === HostText) {
          return node2;
        }
        var child = node2.child;
        while (child !== null) {
          if (child.tag !== HostPortal) {
            var match = findCurrentHostFiberWithNoPortalsImpl(child);
            if (match !== null) {
              return match;
            }
          }
          child = child.sibling;
        }
        return null;
      }
      var scheduleCallback = Scheduler.unstable_scheduleCallback;
      var cancelCallback = Scheduler.unstable_cancelCallback;
      var shouldYield = Scheduler.unstable_shouldYield;
      var requestPaint = Scheduler.unstable_requestPaint;
      var now = Scheduler.unstable_now;
      var getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel;
      var ImmediatePriority = Scheduler.unstable_ImmediatePriority;
      var UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
      var NormalPriority = Scheduler.unstable_NormalPriority;
      var LowPriority = Scheduler.unstable_LowPriority;
      var IdlePriority = Scheduler.unstable_IdlePriority;
      var unstable_yieldValue = Scheduler.unstable_yieldValue;
      var unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue;
      var rendererID = null;
      var injectedHook = null;
      var injectedProfilingHooks = null;
      var hasLoggedError = false;
      var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined";
      function injectInternals(internals) {
        if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined") {
          return false;
        }
        var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (hook.isDisabled) {
          return true;
        }
        if (!hook.supportsFiber) {
          {
            error("The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://reactjs.org/link/react-devtools");
          }
          return true;
        }
        try {
          if (enableSchedulingProfiler) {
            internals = assign({}, internals, {
              getLaneLabelMap,
              injectProfilingHooks
            });
          }
          rendererID = hook.inject(internals);
          injectedHook = hook;
        } catch (err) {
          {
            error("React instrumentation encountered an error: %s.", err);
          }
        }
        if (hook.checkDCE) {
          return true;
        } else {
          return false;
        }
      }
      function onScheduleRoot(root2, children) {
        {
          if (injectedHook && typeof injectedHook.onScheduleFiberRoot === "function") {
            try {
              injectedHook.onScheduleFiberRoot(rendererID, root2, children);
            } catch (err) {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error("React instrumentation encountered an error: %s", err);
              }
            }
          }
        }
      }
      function onCommitRoot(root2, eventPriority) {
        if (injectedHook && typeof injectedHook.onCommitFiberRoot === "function") {
          try {
            var didError = (root2.current.flags & DidCapture) === DidCapture;
            if (enableProfilerTimer) {
              var schedulerPriority;
              switch (eventPriority) {
                case DiscreteEventPriority:
                  schedulerPriority = ImmediatePriority;
                  break;
                case ContinuousEventPriority:
                  schedulerPriority = UserBlockingPriority;
                  break;
                case DefaultEventPriority:
                  schedulerPriority = NormalPriority;
                  break;
                case IdleEventPriority:
                  schedulerPriority = IdlePriority;
                  break;
                default:
                  schedulerPriority = NormalPriority;
                  break;
              }
              injectedHook.onCommitFiberRoot(rendererID, root2, schedulerPriority, didError);
            }
          } catch (err) {
            {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error("React instrumentation encountered an error: %s", err);
              }
            }
          }
        }
      }
      function onPostCommitRoot(root2) {
        if (injectedHook && typeof injectedHook.onPostCommitFiberRoot === "function") {
          try {
            injectedHook.onPostCommitFiberRoot(rendererID, root2);
          } catch (err) {
            {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error("React instrumentation encountered an error: %s", err);
              }
            }
          }
        }
      }
      function onCommitUnmount(fiber) {
        if (injectedHook && typeof injectedHook.onCommitFiberUnmount === "function") {
          try {
            injectedHook.onCommitFiberUnmount(rendererID, fiber);
          } catch (err) {
            {
              if (!hasLoggedError) {
                hasLoggedError = true;
                error("React instrumentation encountered an error: %s", err);
              }
            }
          }
        }
      }
      function setIsStrictModeForDevtools(newIsStrictMode) {
        {
          if (typeof unstable_yieldValue === "function") {
            unstable_setDisableYieldValue(newIsStrictMode);
            setSuppressWarning(newIsStrictMode);
          }
          if (injectedHook && typeof injectedHook.setStrictMode === "function") {
            try {
              injectedHook.setStrictMode(rendererID, newIsStrictMode);
            } catch (err) {
              {
                if (!hasLoggedError) {
                  hasLoggedError = true;
                  error("React instrumentation encountered an error: %s", err);
                }
              }
            }
          }
        }
      }
      function injectProfilingHooks(profilingHooks) {
        injectedProfilingHooks = profilingHooks;
      }
      function getLaneLabelMap() {
        {
          var map = /* @__PURE__ */ new Map();
          var lane = 1;
          for (var index22 = 0; index22 < TotalLanes; index22++) {
            var label = getLabelForLane(lane);
            map.set(lane, label);
            lane *= 2;
          }
          return map;
        }
      }
      function markCommitStarted(lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === "function") {
            injectedProfilingHooks.markCommitStarted(lanes);
          }
        }
      }
      function markCommitStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStopped === "function") {
            injectedProfilingHooks.markCommitStopped();
          }
        }
      }
      function markComponentRenderStarted(fiber) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === "function") {
            injectedProfilingHooks.markComponentRenderStarted(fiber);
          }
        }
      }
      function markComponentRenderStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStopped === "function") {
            injectedProfilingHooks.markComponentRenderStopped();
          }
        }
      }
      function markComponentPassiveEffectMountStarted(fiber) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === "function") {
            injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber);
          }
        }
      }
      function markComponentPassiveEffectMountStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStopped === "function") {
            injectedProfilingHooks.markComponentPassiveEffectMountStopped();
          }
        }
      }
      function markComponentPassiveEffectUnmountStarted(fiber) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === "function") {
            injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber);
          }
        }
      }
      function markComponentPassiveEffectUnmountStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStopped === "function") {
            injectedProfilingHooks.markComponentPassiveEffectUnmountStopped();
          }
        }
      }
      function markComponentLayoutEffectMountStarted(fiber) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === "function") {
            injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber);
          }
        }
      }
      function markComponentLayoutEffectMountStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStopped === "function") {
            injectedProfilingHooks.markComponentLayoutEffectMountStopped();
          }
        }
      }
      function markComponentLayoutEffectUnmountStarted(fiber) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === "function") {
            injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber);
          }
        }
      }
      function markComponentLayoutEffectUnmountStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStopped === "function") {
            injectedProfilingHooks.markComponentLayoutEffectUnmountStopped();
          }
        }
      }
      function markComponentErrored(fiber, thrownValue, lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentErrored === "function") {
            injectedProfilingHooks.markComponentErrored(fiber, thrownValue, lanes);
          }
        }
      }
      function markComponentSuspended(fiber, wakeable, lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentSuspended === "function") {
            injectedProfilingHooks.markComponentSuspended(fiber, wakeable, lanes);
          }
        }
      }
      function markLayoutEffectsStarted(lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === "function") {
            injectedProfilingHooks.markLayoutEffectsStarted(lanes);
          }
        }
      }
      function markLayoutEffectsStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStopped === "function") {
            injectedProfilingHooks.markLayoutEffectsStopped();
          }
        }
      }
      function markPassiveEffectsStarted(lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === "function") {
            injectedProfilingHooks.markPassiveEffectsStarted(lanes);
          }
        }
      }
      function markPassiveEffectsStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStopped === "function") {
            injectedProfilingHooks.markPassiveEffectsStopped();
          }
        }
      }
      function markRenderStarted(lanes) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === "function") {
            injectedProfilingHooks.markRenderStarted(lanes);
          }
        }
      }
      function markRenderYielded() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderYielded === "function") {
            injectedProfilingHooks.markRenderYielded();
          }
        }
      }
      function markRenderStopped() {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStopped === "function") {
            injectedProfilingHooks.markRenderStopped();
          }
        }
      }
      function markRenderScheduled(lane) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderScheduled === "function") {
            injectedProfilingHooks.markRenderScheduled(lane);
          }
        }
      }
      function markForceUpdateScheduled(fiber, lane) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markForceUpdateScheduled === "function") {
            injectedProfilingHooks.markForceUpdateScheduled(fiber, lane);
          }
        }
      }
      function markStateUpdateScheduled(fiber, lane) {
        {
          if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markStateUpdateScheduled === "function") {
            injectedProfilingHooks.markStateUpdateScheduled(fiber, lane);
          }
        }
      }
      var NoMode = (
        /*                         */
        0
      );
      var ConcurrentMode = (
        /*                 */
        1
      );
      var ProfileMode = (
        /*                    */
        2
      );
      var StrictLegacyMode = (
        /*               */
        8
      );
      var StrictEffectsMode = (
        /*              */
        16
      );
      var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback;
      var log2 = Math.log;
      var LN2 = Math.LN2;
      function clz32Fallback(x2) {
        var asUint = x2 >>> 0;
        if (asUint === 0) {
          return 32;
        }
        return 31 - (log2(asUint) / LN2 | 0) | 0;
      }
      var TotalLanes = 31;
      var NoLanes = (
        /*                        */
        0
      );
      var NoLane = (
        /*                          */
        0
      );
      var SyncLane = (
        /*                        */
        1
      );
      var InputContinuousHydrationLane = (
        /*    */
        2
      );
      var InputContinuousLane = (
        /*             */
        4
      );
      var DefaultHydrationLane = (
        /*            */
        8
      );
      var DefaultLane = (
        /*                     */
        16
      );
      var TransitionHydrationLane = (
        /*                */
        32
      );
      var TransitionLanes = (
        /*                       */
        4194240
      );
      var TransitionLane1 = (
        /*                        */
        64
      );
      var TransitionLane2 = (
        /*                        */
        128
      );
      var TransitionLane3 = (
        /*                        */
        256
      );
      var TransitionLane4 = (
        /*                        */
        512
      );
      var TransitionLane5 = (
        /*                        */
        1024
      );
      var TransitionLane6 = (
        /*                        */
        2048
      );
      var TransitionLane7 = (
        /*                        */
        4096
      );
      var TransitionLane8 = (
        /*                        */
        8192
      );
      var TransitionLane9 = (
        /*                        */
        16384
      );
      var TransitionLane10 = (
        /*                       */
        32768
      );
      var TransitionLane11 = (
        /*                       */
        65536
      );
      var TransitionLane12 = (
        /*                       */
        131072
      );
      var TransitionLane13 = (
        /*                       */
        262144
      );
      var TransitionLane14 = (
        /*                       */
        524288
      );
      var TransitionLane15 = (
        /*                       */
        1048576
      );
      var TransitionLane16 = (
        /*                       */
        2097152
      );
      var RetryLanes = (
        /*                            */
        130023424
      );
      var RetryLane1 = (
        /*                             */
        4194304
      );
      var RetryLane2 = (
        /*                             */
        8388608
      );
      var RetryLane3 = (
        /*                             */
        16777216
      );
      var RetryLane4 = (
        /*                             */
        33554432
      );
      var RetryLane5 = (
        /*                             */
        67108864
      );
      var SomeRetryLane = RetryLane1;
      var SelectiveHydrationLane = (
        /*          */
        134217728
      );
      var NonIdleLanes = (
        /*                          */
        268435455
      );
      var IdleHydrationLane = (
        /*               */
        268435456
      );
      var IdleLane = (
        /*                        */
        536870912
      );
      var OffscreenLane = (
        /*                   */
        1073741824
      );
      function getLabelForLane(lane) {
        {
          if (lane & SyncLane) {
            return "Sync";
          }
          if (lane & InputContinuousHydrationLane) {
            return "InputContinuousHydration";
          }
          if (lane & InputContinuousLane) {
            return "InputContinuous";
          }
          if (lane & DefaultHydrationLane) {
            return "DefaultHydration";
          }
          if (lane & DefaultLane) {
            return "Default";
          }
          if (lane & TransitionHydrationLane) {
            return "TransitionHydration";
          }
          if (lane & TransitionLanes) {
            return "Transition";
          }
          if (lane & RetryLanes) {
            return "Retry";
          }
          if (lane & SelectiveHydrationLane) {
            return "SelectiveHydration";
          }
          if (lane & IdleHydrationLane) {
            return "IdleHydration";
          }
          if (lane & IdleLane) {
            return "Idle";
          }
          if (lane & OffscreenLane) {
            return "Offscreen";
          }
        }
      }
      var NoTimestamp = -1;
      var nextTransitionLane = TransitionLane1;
      var nextRetryLane = RetryLane1;
      function getHighestPriorityLanes(lanes) {
        switch (getHighestPriorityLane(lanes)) {
          case SyncLane:
            return SyncLane;
          case InputContinuousHydrationLane:
            return InputContinuousHydrationLane;
          case InputContinuousLane:
            return InputContinuousLane;
          case DefaultHydrationLane:
            return DefaultHydrationLane;
          case DefaultLane:
            return DefaultLane;
          case TransitionHydrationLane:
            return TransitionHydrationLane;
          case TransitionLane1:
          case TransitionLane2:
          case TransitionLane3:
          case TransitionLane4:
          case TransitionLane5:
          case TransitionLane6:
          case TransitionLane7:
          case TransitionLane8:
          case TransitionLane9:
          case TransitionLane10:
          case TransitionLane11:
          case TransitionLane12:
          case TransitionLane13:
          case TransitionLane14:
          case TransitionLane15:
          case TransitionLane16:
            return lanes & TransitionLanes;
          case RetryLane1:
          case RetryLane2:
          case RetryLane3:
          case RetryLane4:
          case RetryLane5:
            return lanes & RetryLanes;
          case SelectiveHydrationLane:
            return SelectiveHydrationLane;
          case IdleHydrationLane:
            return IdleHydrationLane;
          case IdleLane:
            return IdleLane;
          case OffscreenLane:
            return OffscreenLane;
          default:
            {
              error("Should have found matching lanes. This is a bug in React.");
            }
            return lanes;
        }
      }
      function getNextLanes(root2, wipLanes) {
        var pendingLanes = root2.pendingLanes;
        if (pendingLanes === NoLanes) {
          return NoLanes;
        }
        var nextLanes = NoLanes;
        var suspendedLanes = root2.suspendedLanes;
        var pingedLanes = root2.pingedLanes;
        var nonIdlePendingLanes = pendingLanes & NonIdleLanes;
        if (nonIdlePendingLanes !== NoLanes) {
          var nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes;
          if (nonIdleUnblockedLanes !== NoLanes) {
            nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes);
          } else {
            var nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes;
            if (nonIdlePingedLanes !== NoLanes) {
              nextLanes = getHighestPriorityLanes(nonIdlePingedLanes);
            }
          }
        } else {
          var unblockedLanes = pendingLanes & ~suspendedLanes;
          if (unblockedLanes !== NoLanes) {
            nextLanes = getHighestPriorityLanes(unblockedLanes);
          } else {
            if (pingedLanes !== NoLanes) {
              nextLanes = getHighestPriorityLanes(pingedLanes);
            }
          }
        }
        if (nextLanes === NoLanes) {
          return NoLanes;
        }
        if (wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't
        // bother waiting until the root is complete.
        (wipLanes & suspendedLanes) === NoLanes) {
          var nextLane = getHighestPriorityLane(nextLanes);
          var wipLane = getHighestPriorityLane(wipLanes);
          if (
            // Tests whether the next lane is equal or lower priority than the wip
            // one. This works because the bits decrease in priority as you go left.
            nextLane >= wipLane || // Default priority updates should not interrupt transition updates. The
            // only difference between default updates and transition updates is that
            // default updates do not support refresh transitions.
            nextLane === DefaultLane && (wipLane & TransitionLanes) !== NoLanes
          ) {
            return wipLanes;
          }
        }
        if ((nextLanes & InputContinuousLane) !== NoLanes) {
          nextLanes |= pendingLanes & DefaultLane;
        }
        var entangledLanes = root2.entangledLanes;
        if (entangledLanes !== NoLanes) {
          var entanglements = root2.entanglements;
          var lanes = nextLanes & entangledLanes;
          while (lanes > 0) {
            var index22 = pickArbitraryLaneIndex(lanes);
            var lane = 1 << index22;
            nextLanes |= entanglements[index22];
            lanes &= ~lane;
          }
        }
        return nextLanes;
      }
      function getMostRecentEventTime(root2, lanes) {
        var eventTimes = root2.eventTimes;
        var mostRecentEventTime = NoTimestamp;
        while (lanes > 0) {
          var index22 = pickArbitraryLaneIndex(lanes);
          var lane = 1 << index22;
          var eventTime = eventTimes[index22];
          if (eventTime > mostRecentEventTime) {
            mostRecentEventTime = eventTime;
          }
          lanes &= ~lane;
        }
        return mostRecentEventTime;
      }
      function computeExpirationTime(lane, currentTime) {
        switch (lane) {
          case SyncLane:
          case InputContinuousHydrationLane:
          case InputContinuousLane:
            return currentTime + 250;
          case DefaultHydrationLane:
          case DefaultLane:
          case TransitionHydrationLane:
          case TransitionLane1:
          case TransitionLane2:
          case TransitionLane3:
          case TransitionLane4:
          case TransitionLane5:
          case TransitionLane6:
          case TransitionLane7:
          case TransitionLane8:
          case TransitionLane9:
          case TransitionLane10:
          case TransitionLane11:
          case TransitionLane12:
          case TransitionLane13:
          case TransitionLane14:
          case TransitionLane15:
          case TransitionLane16:
            return currentTime + 5e3;
          case RetryLane1:
          case RetryLane2:
          case RetryLane3:
          case RetryLane4:
          case RetryLane5:
            return NoTimestamp;
          case SelectiveHydrationLane:
          case IdleHydrationLane:
          case IdleLane:
          case OffscreenLane:
            return NoTimestamp;
          default:
            {
              error("Should have found matching lanes. This is a bug in React.");
            }
            return NoTimestamp;
        }
      }
      function markStarvedLanesAsExpired(root2, currentTime) {
        var pendingLanes = root2.pendingLanes;
        var suspendedLanes = root2.suspendedLanes;
        var pingedLanes = root2.pingedLanes;
        var expirationTimes = root2.expirationTimes;
        var lanes = pendingLanes;
        while (lanes > 0) {
          var index22 = pickArbitraryLaneIndex(lanes);
          var lane = 1 << index22;
          var expirationTime = expirationTimes[index22];
          if (expirationTime === NoTimestamp) {
            if ((lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes) {
              expirationTimes[index22] = computeExpirationTime(lane, currentTime);
            }
          } else if (expirationTime <= currentTime) {
            root2.expiredLanes |= lane;
          }
          lanes &= ~lane;
        }
      }
      function getHighestPriorityPendingLanes(root2) {
        return getHighestPriorityLanes(root2.pendingLanes);
      }
      function getLanesToRetrySynchronouslyOnError(root2) {
        var everythingButOffscreen = root2.pendingLanes & -1073741825;
        if (everythingButOffscreen !== NoLanes) {
          return everythingButOffscreen;
        }
        if (everythingButOffscreen & OffscreenLane) {
          return OffscreenLane;
        }
        return NoLanes;
      }
      function includesSyncLane(lanes) {
        return (lanes & SyncLane) !== NoLanes;
      }
      function includesNonIdleWork(lanes) {
        return (lanes & NonIdleLanes) !== NoLanes;
      }
      function includesOnlyRetries(lanes) {
        return (lanes & RetryLanes) === lanes;
      }
      function includesOnlyNonUrgentLanes(lanes) {
        var UrgentLanes = SyncLane | InputContinuousLane | DefaultLane;
        return (lanes & UrgentLanes) === NoLanes;
      }
      function includesOnlyTransitions(lanes) {
        return (lanes & TransitionLanes) === lanes;
      }
      function includesBlockingLane(root2, lanes) {
        var SyncDefaultLanes = InputContinuousHydrationLane | InputContinuousLane | DefaultHydrationLane | DefaultLane;
        return (lanes & SyncDefaultLanes) !== NoLanes;
      }
      function includesExpiredLane(root2, lanes) {
        return (lanes & root2.expiredLanes) !== NoLanes;
      }
      function isTransitionLane(lane) {
        return (lane & TransitionLanes) !== NoLanes;
      }
      function claimNextTransitionLane() {
        var lane = nextTransitionLane;
        nextTransitionLane <<= 1;
        if ((nextTransitionLane & TransitionLanes) === NoLanes) {
          nextTransitionLane = TransitionLane1;
        }
        return lane;
      }
      function claimNextRetryLane() {
        var lane = nextRetryLane;
        nextRetryLane <<= 1;
        if ((nextRetryLane & RetryLanes) === NoLanes) {
          nextRetryLane = RetryLane1;
        }
        return lane;
      }
      function getHighestPriorityLane(lanes) {
        return lanes & -lanes;
      }
      function pickArbitraryLane(lanes) {
        return getHighestPriorityLane(lanes);
      }
      function pickArbitraryLaneIndex(lanes) {
        return 31 - clz32(lanes);
      }
      function laneToIndex(lane) {
        return pickArbitraryLaneIndex(lane);
      }
      function includesSomeLane(a2, b2) {
        return (a2 & b2) !== NoLanes;
      }
      function isSubsetOfLanes(set2, subset) {
        return (set2 & subset) === subset;
      }
      function mergeLanes(a2, b2) {
        return a2 | b2;
      }
      function removeLanes(set2, subset) {
        return set2 & ~subset;
      }
      function intersectLanes(a2, b2) {
        return a2 & b2;
      }
      function laneToLanes(lane) {
        return lane;
      }
      function higherPriorityLane(a2, b2) {
        return a2 !== NoLane && a2 < b2 ? a2 : b2;
      }
      function createLaneMap(initial) {
        var laneMap = [];
        for (var i2 = 0; i2 < TotalLanes; i2++) {
          laneMap.push(initial);
        }
        return laneMap;
      }
      function markRootUpdated(root2, updateLane, eventTime) {
        root2.pendingLanes |= updateLane;
        if (updateLane !== IdleLane) {
          root2.suspendedLanes = NoLanes;
          root2.pingedLanes = NoLanes;
        }
        var eventTimes = root2.eventTimes;
        var index22 = laneToIndex(updateLane);
        eventTimes[index22] = eventTime;
      }
      function markRootSuspended(root2, suspendedLanes) {
        root2.suspendedLanes |= suspendedLanes;
        root2.pingedLanes &= ~suspendedLanes;
        var expirationTimes = root2.expirationTimes;
        var lanes = suspendedLanes;
        while (lanes > 0) {
          var index22 = pickArbitraryLaneIndex(lanes);
          var lane = 1 << index22;
          expirationTimes[index22] = NoTimestamp;
          lanes &= ~lane;
        }
      }
      function markRootPinged(root2, pingedLanes, eventTime) {
        root2.pingedLanes |= root2.suspendedLanes & pingedLanes;
      }
      function markRootFinished(root2, remainingLanes) {
        var noLongerPendingLanes = root2.pendingLanes & ~remainingLanes;
        root2.pendingLanes = remainingLanes;
        root2.suspendedLanes = NoLanes;
        root2.pingedLanes = NoLanes;
        root2.expiredLanes &= remainingLanes;
        root2.mutableReadLanes &= remainingLanes;
        root2.entangledLanes &= remainingLanes;
        var entanglements = root2.entanglements;
        var eventTimes = root2.eventTimes;
        var expirationTimes = root2.expirationTimes;
        var lanes = noLongerPendingLanes;
        while (lanes > 0) {
          var index22 = pickArbitraryLaneIndex(lanes);
          var lane = 1 << index22;
          entanglements[index22] = NoLanes;
          eventTimes[index22] = NoTimestamp;
          expirationTimes[index22] = NoTimestamp;
          lanes &= ~lane;
        }
      }
      function markRootEntangled(root2, entangledLanes) {
        var rootEntangledLanes = root2.entangledLanes |= entangledLanes;
        var entanglements = root2.entanglements;
        var lanes = rootEntangledLanes;
        while (lanes) {
          var index22 = pickArbitraryLaneIndex(lanes);
          var lane = 1 << index22;
          if (
            // Is this one of the newly entangled lanes?
            lane & entangledLanes | // Is this lane transitively entangled with the newly entangled lanes?
            entanglements[index22] & entangledLanes
          ) {
            entanglements[index22] |= entangledLanes;
          }
          lanes &= ~lane;
        }
      }
      function getBumpedLaneForHydration(root2, renderLanes2) {
        var renderLane = getHighestPriorityLane(renderLanes2);
        var lane;
        switch (renderLane) {
          case InputContinuousLane:
            lane = InputContinuousHydrationLane;
            break;
          case DefaultLane:
            lane = DefaultHydrationLane;
            break;
          case TransitionLane1:
          case TransitionLane2:
          case TransitionLane3:
          case TransitionLane4:
          case TransitionLane5:
          case TransitionLane6:
          case TransitionLane7:
          case TransitionLane8:
          case TransitionLane9:
          case TransitionLane10:
          case TransitionLane11:
          case TransitionLane12:
          case TransitionLane13:
          case TransitionLane14:
          case TransitionLane15:
          case TransitionLane16:
          case RetryLane1:
          case RetryLane2:
          case RetryLane3:
          case RetryLane4:
          case RetryLane5:
            lane = TransitionHydrationLane;
            break;
          case IdleLane:
            lane = IdleHydrationLane;
            break;
          default:
            lane = NoLane;
            break;
        }
        if ((lane & (root2.suspendedLanes | renderLanes2)) !== NoLane) {
          return NoLane;
        }
        return lane;
      }
      function addFiberToLanesMap(root2, fiber, lanes) {
        if (!isDevToolsPresent) {
          return;
        }
        var pendingUpdatersLaneMap = root2.pendingUpdatersLaneMap;
        while (lanes > 0) {
          var index22 = laneToIndex(lanes);
          var lane = 1 << index22;
          var updaters = pendingUpdatersLaneMap[index22];
          updaters.add(fiber);
          lanes &= ~lane;
        }
      }
      function movePendingFibersToMemoized(root2, lanes) {
        if (!isDevToolsPresent) {
          return;
        }
        var pendingUpdatersLaneMap = root2.pendingUpdatersLaneMap;
        var memoizedUpdaters = root2.memoizedUpdaters;
        while (lanes > 0) {
          var index22 = laneToIndex(lanes);
          var lane = 1 << index22;
          var updaters = pendingUpdatersLaneMap[index22];
          if (updaters.size > 0) {
            updaters.forEach(function(fiber) {
              var alternate = fiber.alternate;
              if (alternate === null || !memoizedUpdaters.has(alternate)) {
                memoizedUpdaters.add(fiber);
              }
            });
            updaters.clear();
          }
          lanes &= ~lane;
        }
      }
      function getTransitionsForLanes(root2, lanes) {
        {
          return null;
        }
      }
      var DiscreteEventPriority = SyncLane;
      var ContinuousEventPriority = InputContinuousLane;
      var DefaultEventPriority = DefaultLane;
      var IdleEventPriority = IdleLane;
      var currentUpdatePriority = NoLane;
      function getCurrentUpdatePriority() {
        return currentUpdatePriority;
      }
      function setCurrentUpdatePriority(newPriority) {
        currentUpdatePriority = newPriority;
      }
      function runWithPriority(priority, fn) {
        var previousPriority = currentUpdatePriority;
        try {
          currentUpdatePriority = priority;
          return fn();
        } finally {
          currentUpdatePriority = previousPriority;
        }
      }
      function higherEventPriority(a2, b2) {
        return a2 !== 0 && a2 < b2 ? a2 : b2;
      }
      function lowerEventPriority(a2, b2) {
        return a2 > b2 ? a2 : b2;
      }
      function isHigherEventPriority(a2, b2) {
        return a2 !== 0 && a2 < b2;
      }
      function lanesToEventPriority(lanes) {
        var lane = getHighestPriorityLane(lanes);
        if (!isHigherEventPriority(DiscreteEventPriority, lane)) {
          return DiscreteEventPriority;
        }
        if (!isHigherEventPriority(ContinuousEventPriority, lane)) {
          return ContinuousEventPriority;
        }
        if (includesNonIdleWork(lane)) {
          return DefaultEventPriority;
        }
        return IdleEventPriority;
      }
      function isRootDehydrated(root2) {
        var currentState = root2.current.memoizedState;
        return currentState.isDehydrated;
      }
      var _attemptSynchronousHydration;
      function setAttemptSynchronousHydration(fn) {
        _attemptSynchronousHydration = fn;
      }
      function attemptSynchronousHydration(fiber) {
        _attemptSynchronousHydration(fiber);
      }
      var attemptContinuousHydration;
      function setAttemptContinuousHydration(fn) {
        attemptContinuousHydration = fn;
      }
      var attemptHydrationAtCurrentPriority;
      function setAttemptHydrationAtCurrentPriority(fn) {
        attemptHydrationAtCurrentPriority = fn;
      }
      var getCurrentUpdatePriority$1;
      function setGetCurrentUpdatePriority(fn) {
        getCurrentUpdatePriority$1 = fn;
      }
      var attemptHydrationAtPriority;
      function setAttemptHydrationAtPriority(fn) {
        attemptHydrationAtPriority = fn;
      }
      var hasScheduledReplayAttempt = false;
      var queuedDiscreteEvents = [];
      var queuedFocus = null;
      var queuedDrag = null;
      var queuedMouse = null;
      var queuedPointers = /* @__PURE__ */ new Map();
      var queuedPointerCaptures = /* @__PURE__ */ new Map();
      var queuedExplicitHydrationTargets = [];
      var discreteReplayableEvents = [
        "mousedown",
        "mouseup",
        "touchcancel",
        "touchend",
        "touchstart",
        "auxclick",
        "dblclick",
        "pointercancel",
        "pointerdown",
        "pointerup",
        "dragend",
        "dragstart",
        "drop",
        "compositionend",
        "compositionstart",
        "keydown",
        "keypress",
        "keyup",
        "input",
        "textInput",
        // Intentionally camelCase
        "copy",
        "cut",
        "paste",
        "click",
        "change",
        "contextmenu",
        "reset",
        "submit"
      ];
      function isDiscreteEventThatRequiresHydration(eventType) {
        return discreteReplayableEvents.indexOf(eventType) > -1;
      }
      function createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        return {
          blockedOn,
          domEventName,
          eventSystemFlags,
          nativeEvent,
          targetContainers: [targetContainer]
        };
      }
      function clearIfContinuousEvent(domEventName, nativeEvent) {
        switch (domEventName) {
          case "focusin":
          case "focusout":
            queuedFocus = null;
            break;
          case "dragenter":
          case "dragleave":
            queuedDrag = null;
            break;
          case "mouseover":
          case "mouseout":
            queuedMouse = null;
            break;
          case "pointerover":
          case "pointerout": {
            var pointerId = nativeEvent.pointerId;
            queuedPointers.delete(pointerId);
            break;
          }
          case "gotpointercapture":
          case "lostpointercapture": {
            var _pointerId = nativeEvent.pointerId;
            queuedPointerCaptures.delete(_pointerId);
            break;
          }
        }
      }
      function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
          var queuedEvent = createQueuedReplayableEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent);
          if (blockedOn !== null) {
            var _fiber2 = getInstanceFromNode(blockedOn);
            if (_fiber2 !== null) {
              attemptContinuousHydration(_fiber2);
            }
          }
          return queuedEvent;
        }
        existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
        var targetContainers = existingQueuedEvent.targetContainers;
        if (targetContainer !== null && targetContainers.indexOf(targetContainer) === -1) {
          targetContainers.push(targetContainer);
        }
        return existingQueuedEvent;
      }
      function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        switch (domEventName) {
          case "focusin": {
            var focusEvent = nativeEvent;
            queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, domEventName, eventSystemFlags, targetContainer, focusEvent);
            return true;
          }
          case "dragenter": {
            var dragEvent = nativeEvent;
            queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, domEventName, eventSystemFlags, targetContainer, dragEvent);
            return true;
          }
          case "mouseover": {
            var mouseEvent = nativeEvent;
            queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, domEventName, eventSystemFlags, targetContainer, mouseEvent);
            return true;
          }
          case "pointerover": {
            var pointerEvent = nativeEvent;
            var pointerId = pointerEvent.pointerId;
            queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, pointerEvent));
            return true;
          }
          case "gotpointercapture": {
            var _pointerEvent = nativeEvent;
            var _pointerId2 = _pointerEvent.pointerId;
            queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, domEventName, eventSystemFlags, targetContainer, _pointerEvent));
            return true;
          }
        }
        return false;
      }
      function attemptExplicitHydrationTarget(queuedTarget) {
        var targetInst = getClosestInstanceFromNode(queuedTarget.target);
        if (targetInst !== null) {
          var nearestMounted = getNearestMountedFiber(targetInst);
          if (nearestMounted !== null) {
            var tag = nearestMounted.tag;
            if (tag === SuspenseComponent) {
              var instance2 = getSuspenseInstanceFromFiber(nearestMounted);
              if (instance2 !== null) {
                queuedTarget.blockedOn = instance2;
                attemptHydrationAtPriority(queuedTarget.priority, function() {
                  attemptHydrationAtCurrentPriority(nearestMounted);
                });
                return;
              }
            } else if (tag === HostRoot) {
              var root2 = nearestMounted.stateNode;
              if (isRootDehydrated(root2)) {
                queuedTarget.blockedOn = getContainerFromFiber(nearestMounted);
                return;
              }
            }
          }
        }
        queuedTarget.blockedOn = null;
      }
      function queueExplicitHydrationTarget(target) {
        var updatePriority = getCurrentUpdatePriority$1();
        var queuedTarget = {
          blockedOn: null,
          target,
          priority: updatePriority
        };
        var i2 = 0;
        for (; i2 < queuedExplicitHydrationTargets.length; i2++) {
          if (!isHigherEventPriority(updatePriority, queuedExplicitHydrationTargets[i2].priority)) {
            break;
          }
        }
        queuedExplicitHydrationTargets.splice(i2, 0, queuedTarget);
        if (i2 === 0) {
          attemptExplicitHydrationTarget(queuedTarget);
        }
      }
      function attemptReplayContinuousQueuedEvent(queuedEvent) {
        if (queuedEvent.blockedOn !== null) {
          return false;
        }
        var targetContainers = queuedEvent.targetContainers;
        while (targetContainers.length > 0) {
          var targetContainer = targetContainers[0];
          var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.domEventName, queuedEvent.eventSystemFlags, targetContainer, queuedEvent.nativeEvent);
          if (nextBlockedOn === null) {
            {
              var nativeEvent = queuedEvent.nativeEvent;
              var nativeEventClone = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
              setReplayingEvent(nativeEventClone);
              nativeEvent.target.dispatchEvent(nativeEventClone);
              resetReplayingEvent();
            }
          } else {
            var _fiber3 = getInstanceFromNode(nextBlockedOn);
            if (_fiber3 !== null) {
              attemptContinuousHydration(_fiber3);
            }
            queuedEvent.blockedOn = nextBlockedOn;
            return false;
          }
          targetContainers.shift();
        }
        return true;
      }
      function attemptReplayContinuousQueuedEventInMap(queuedEvent, key2, map) {
        if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
          map.delete(key2);
        }
      }
      function replayUnblockedEvents() {
        hasScheduledReplayAttempt = false;
        if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
          queuedFocus = null;
        }
        if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
          queuedDrag = null;
        }
        if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
          queuedMouse = null;
        }
        queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
        queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
      }
      function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
        if (queuedEvent.blockedOn === unblocked) {
          queuedEvent.blockedOn = null;
          if (!hasScheduledReplayAttempt) {
            hasScheduledReplayAttempt = true;
            Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);
          }
        }
      }
      function retryIfBlockedOn(unblocked) {
        if (queuedDiscreteEvents.length > 0) {
          scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked);
          for (var i2 = 1; i2 < queuedDiscreteEvents.length; i2++) {
            var queuedEvent = queuedDiscreteEvents[i2];
            if (queuedEvent.blockedOn === unblocked) {
              queuedEvent.blockedOn = null;
            }
          }
        }
        if (queuedFocus !== null) {
          scheduleCallbackIfUnblocked(queuedFocus, unblocked);
        }
        if (queuedDrag !== null) {
          scheduleCallbackIfUnblocked(queuedDrag, unblocked);
        }
        if (queuedMouse !== null) {
          scheduleCallbackIfUnblocked(queuedMouse, unblocked);
        }
        var unblock = function(queuedEvent2) {
          return scheduleCallbackIfUnblocked(queuedEvent2, unblocked);
        };
        queuedPointers.forEach(unblock);
        queuedPointerCaptures.forEach(unblock);
        for (var _i2 = 0; _i2 < queuedExplicitHydrationTargets.length; _i2++) {
          var queuedTarget = queuedExplicitHydrationTargets[_i2];
          if (queuedTarget.blockedOn === unblocked) {
            queuedTarget.blockedOn = null;
          }
        }
        while (queuedExplicitHydrationTargets.length > 0) {
          var nextExplicitTarget = queuedExplicitHydrationTargets[0];
          if (nextExplicitTarget.blockedOn !== null) {
            break;
          } else {
            attemptExplicitHydrationTarget(nextExplicitTarget);
            if (nextExplicitTarget.blockedOn === null) {
              queuedExplicitHydrationTargets.shift();
            }
          }
        }
      }
      var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
      var _enabled = true;
      function setEnabled(enabled) {
        _enabled = !!enabled;
      }
      function isEnabled() {
        return _enabled;
      }
      function createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags) {
        var eventPriority = getEventPriority(domEventName);
        var listenerWrapper;
        switch (eventPriority) {
          case DiscreteEventPriority:
            listenerWrapper = dispatchDiscreteEvent;
            break;
          case ContinuousEventPriority:
            listenerWrapper = dispatchContinuousEvent;
            break;
          case DefaultEventPriority:
          default:
            listenerWrapper = dispatchEvent;
            break;
        }
        return listenerWrapper.bind(null, domEventName, eventSystemFlags, targetContainer);
      }
      function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
        var previousPriority = getCurrentUpdatePriority();
        var prevTransition = ReactCurrentBatchConfig.transition;
        ReactCurrentBatchConfig.transition = null;
        try {
          setCurrentUpdatePriority(DiscreteEventPriority);
          dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
        } finally {
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig.transition = prevTransition;
        }
      }
      function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
        var previousPriority = getCurrentUpdatePriority();
        var prevTransition = ReactCurrentBatchConfig.transition;
        ReactCurrentBatchConfig.transition = null;
        try {
          setCurrentUpdatePriority(ContinuousEventPriority);
          dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
        } finally {
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig.transition = prevTransition;
        }
      }
      function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        if (!_enabled) {
          return;
        }
        {
          dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent);
        }
      }
      function dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        var blockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
        if (blockedOn === null) {
          dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
          clearIfContinuousEvent(domEventName, nativeEvent);
          return;
        }
        if (queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent)) {
          nativeEvent.stopPropagation();
          return;
        }
        clearIfContinuousEvent(domEventName, nativeEvent);
        if (eventSystemFlags & IS_CAPTURE_PHASE && isDiscreteEventThatRequiresHydration(domEventName)) {
          while (blockedOn !== null) {
            var fiber = getInstanceFromNode(blockedOn);
            if (fiber !== null) {
              attemptSynchronousHydration(fiber);
            }
            var nextBlockedOn = findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent);
            if (nextBlockedOn === null) {
              dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, return_targetInst, targetContainer);
            }
            if (nextBlockedOn === blockedOn) {
              break;
            }
            blockedOn = nextBlockedOn;
          }
          if (blockedOn !== null) {
            nativeEvent.stopPropagation();
          }
          return;
        }
        dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, null, targetContainer);
      }
      var return_targetInst = null;
      function findInstanceBlockingEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        return_targetInst = null;
        var nativeEventTarget = getEventTarget(nativeEvent);
        var targetInst = getClosestInstanceFromNode(nativeEventTarget);
        if (targetInst !== null) {
          var nearestMounted = getNearestMountedFiber(targetInst);
          if (nearestMounted === null) {
            targetInst = null;
          } else {
            var tag = nearestMounted.tag;
            if (tag === SuspenseComponent) {
              var instance2 = getSuspenseInstanceFromFiber(nearestMounted);
              if (instance2 !== null) {
                return instance2;
              }
              targetInst = null;
            } else if (tag === HostRoot) {
              var root2 = nearestMounted.stateNode;
              if (isRootDehydrated(root2)) {
                return getContainerFromFiber(nearestMounted);
              }
              targetInst = null;
            } else if (nearestMounted !== targetInst) {
              targetInst = null;
            }
          }
        }
        return_targetInst = targetInst;
        return null;
      }
      function getEventPriority(domEventName) {
        switch (domEventName) {
          // Used by SimpleEventPlugin:
          case "cancel":
          case "click":
          case "close":
          case "contextmenu":
          case "copy":
          case "cut":
          case "auxclick":
          case "dblclick":
          case "dragend":
          case "dragstart":
          case "drop":
          case "focusin":
          case "focusout":
          case "input":
          case "invalid":
          case "keydown":
          case "keypress":
          case "keyup":
          case "mousedown":
          case "mouseup":
          case "paste":
          case "pause":
          case "play":
          case "pointercancel":
          case "pointerdown":
          case "pointerup":
          case "ratechange":
          case "reset":
          case "resize":
          case "seeked":
          case "submit":
          case "touchcancel":
          case "touchend":
          case "touchstart":
          case "volumechange":
          // Used by polyfills:
          // eslint-disable-next-line no-fallthrough
          case "change":
          case "selectionchange":
          case "textInput":
          case "compositionstart":
          case "compositionend":
          case "compositionupdate":
          // Only enableCreateEventHandleAPI:
          // eslint-disable-next-line no-fallthrough
          case "beforeblur":
          case "afterblur":
          // Not used by React but could be by user code:
          // eslint-disable-next-line no-fallthrough
          case "beforeinput":
          case "blur":
          case "fullscreenchange":
          case "focus":
          case "hashchange":
          case "popstate":
          case "select":
          case "selectstart":
            return DiscreteEventPriority;
          case "drag":
          case "dragenter":
          case "dragexit":
          case "dragleave":
          case "dragover":
          case "mousemove":
          case "mouseout":
          case "mouseover":
          case "pointermove":
          case "pointerout":
          case "pointerover":
          case "scroll":
          case "toggle":
          case "touchmove":
          case "wheel":
          // Not used by React but could be by user code:
          // eslint-disable-next-line no-fallthrough
          case "mouseenter":
          case "mouseleave":
          case "pointerenter":
          case "pointerleave":
            return ContinuousEventPriority;
          case "message": {
            var schedulerPriority = getCurrentPriorityLevel();
            switch (schedulerPriority) {
              case ImmediatePriority:
                return DiscreteEventPriority;
              case UserBlockingPriority:
                return ContinuousEventPriority;
              case NormalPriority:
              case LowPriority:
                return DefaultEventPriority;
              case IdlePriority:
                return IdleEventPriority;
              default:
                return DefaultEventPriority;
            }
          }
          default:
            return DefaultEventPriority;
        }
      }
      function addEventBubbleListener(target, eventType, listener) {
        target.addEventListener(eventType, listener, false);
        return listener;
      }
      function addEventCaptureListener(target, eventType, listener) {
        target.addEventListener(eventType, listener, true);
        return listener;
      }
      function addEventCaptureListenerWithPassiveFlag(target, eventType, listener, passive) {
        target.addEventListener(eventType, listener, {
          capture: true,
          passive
        });
        return listener;
      }
      function addEventBubbleListenerWithPassiveFlag(target, eventType, listener, passive) {
        target.addEventListener(eventType, listener, {
          passive
        });
        return listener;
      }
      var root = null;
      var startText = null;
      var fallbackText = null;
      function initialize(nativeEventTarget) {
        root = nativeEventTarget;
        startText = getText();
        return true;
      }
      function reset() {
        root = null;
        startText = null;
        fallbackText = null;
      }
      function getData() {
        if (fallbackText) {
          return fallbackText;
        }
        var start;
        var startValue = startText;
        var startLength = startValue.length;
        var end;
        var endValue = getText();
        var endLength = endValue.length;
        for (start = 0; start < startLength; start++) {
          if (startValue[start] !== endValue[start]) {
            break;
          }
        }
        var minEnd = startLength - start;
        for (end = 1; end <= minEnd; end++) {
          if (startValue[startLength - end] !== endValue[endLength - end]) {
            break;
          }
        }
        var sliceTail = end > 1 ? 1 - end : void 0;
        fallbackText = endValue.slice(start, sliceTail);
        return fallbackText;
      }
      function getText() {
        if ("value" in root) {
          return root.value;
        }
        return root.textContent;
      }
      function getEventCharCode(nativeEvent) {
        var charCode;
        var keyCode = nativeEvent.keyCode;
        if ("charCode" in nativeEvent) {
          charCode = nativeEvent.charCode;
          if (charCode === 0 && keyCode === 13) {
            charCode = 13;
          }
        } else {
          charCode = keyCode;
        }
        if (charCode === 10) {
          charCode = 13;
        }
        if (charCode >= 32 || charCode === 13) {
          return charCode;
        }
        return 0;
      }
      function functionThatReturnsTrue() {
        return true;
      }
      function functionThatReturnsFalse() {
        return false;
      }
      function createSyntheticEvent(Interface) {
        function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
          this._reactName = reactName;
          this._targetInst = targetInst;
          this.type = reactEventType;
          this.nativeEvent = nativeEvent;
          this.target = nativeEventTarget;
          this.currentTarget = null;
          for (var _propName in Interface) {
            if (!Interface.hasOwnProperty(_propName)) {
              continue;
            }
            var normalize = Interface[_propName];
            if (normalize) {
              this[_propName] = normalize(nativeEvent);
            } else {
              this[_propName] = nativeEvent[_propName];
            }
          }
          var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
          if (defaultPrevented) {
            this.isDefaultPrevented = functionThatReturnsTrue;
          } else {
            this.isDefaultPrevented = functionThatReturnsFalse;
          }
          this.isPropagationStopped = functionThatReturnsFalse;
          return this;
        }
        assign(SyntheticBaseEvent.prototype, {
          preventDefault: function() {
            this.defaultPrevented = true;
            var event = this.nativeEvent;
            if (!event) {
              return;
            }
            if (event.preventDefault) {
              event.preventDefault();
            } else if (typeof event.returnValue !== "unknown") {
              event.returnValue = false;
            }
            this.isDefaultPrevented = functionThatReturnsTrue;
          },
          stopPropagation: function() {
            var event = this.nativeEvent;
            if (!event) {
              return;
            }
            if (event.stopPropagation) {
              event.stopPropagation();
            } else if (typeof event.cancelBubble !== "unknown") {
              event.cancelBubble = true;
            }
            this.isPropagationStopped = functionThatReturnsTrue;
          },
          /**
           * We release all dispatched `SyntheticEvent`s after each event loop, adding
           * them back into the pool. This allows a way to hold onto a reference that
           * won't be added back into the pool.
           */
          persist: function() {
          },
          /**
           * Checks if this event should be released back into the pool.
           *
           * @return {boolean} True if this should not be released, false otherwise.
           */
          isPersistent: functionThatReturnsTrue
        });
        return SyntheticBaseEvent;
      }
      var EventInterface = {
        eventPhase: 0,
        bubbles: 0,
        cancelable: 0,
        timeStamp: function(event) {
          return event.timeStamp || Date.now();
        },
        defaultPrevented: 0,
        isTrusted: 0
      };
      var SyntheticEvent = createSyntheticEvent(EventInterface);
      var UIEventInterface = assign({}, EventInterface, {
        view: 0,
        detail: 0
      });
      var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
      var lastMovementX;
      var lastMovementY;
      var lastMouseEvent;
      function updateMouseMovementPolyfillState(event) {
        if (event !== lastMouseEvent) {
          if (lastMouseEvent && event.type === "mousemove") {
            lastMovementX = event.screenX - lastMouseEvent.screenX;
            lastMovementY = event.screenY - lastMouseEvent.screenY;
          } else {
            lastMovementX = 0;
            lastMovementY = 0;
          }
          lastMouseEvent = event;
        }
      }
      var MouseEventInterface = assign({}, UIEventInterface, {
        screenX: 0,
        screenY: 0,
        clientX: 0,
        clientY: 0,
        pageX: 0,
        pageY: 0,
        ctrlKey: 0,
        shiftKey: 0,
        altKey: 0,
        metaKey: 0,
        getModifierState: getEventModifierState,
        button: 0,
        buttons: 0,
        relatedTarget: function(event) {
          if (event.relatedTarget === void 0) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
          return event.relatedTarget;
        },
        movementX: function(event) {
          if ("movementX" in event) {
            return event.movementX;
          }
          updateMouseMovementPolyfillState(event);
          return lastMovementX;
        },
        movementY: function(event) {
          if ("movementY" in event) {
            return event.movementY;
          }
          return lastMovementY;
        }
      });
      var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
      var DragEventInterface = assign({}, MouseEventInterface, {
        dataTransfer: 0
      });
      var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
      var FocusEventInterface = assign({}, UIEventInterface, {
        relatedTarget: 0
      });
      var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
      var AnimationEventInterface = assign({}, EventInterface, {
        animationName: 0,
        elapsedTime: 0,
        pseudoElement: 0
      });
      var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
      var ClipboardEventInterface = assign({}, EventInterface, {
        clipboardData: function(event) {
          return "clipboardData" in event ? event.clipboardData : window.clipboardData;
        }
      });
      var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
      var CompositionEventInterface = assign({}, EventInterface, {
        data: 0
      });
      var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
      var SyntheticInputEvent = SyntheticCompositionEvent;
      var normalizeKey = {
        Esc: "Escape",
        Spacebar: " ",
        Left: "ArrowLeft",
        Up: "ArrowUp",
        Right: "ArrowRight",
        Down: "ArrowDown",
        Del: "Delete",
        Win: "OS",
        Menu: "ContextMenu",
        Apps: "ContextMenu",
        Scroll: "ScrollLock",
        MozPrintableKey: "Unidentified"
      };
      var translateToKey = {
        "8": "Backspace",
        "9": "Tab",
        "12": "Clear",
        "13": "Enter",
        "16": "Shift",
        "17": "Control",
        "18": "Alt",
        "19": "Pause",
        "20": "CapsLock",
        "27": "Escape",
        "32": " ",
        "33": "PageUp",
        "34": "PageDown",
        "35": "End",
        "36": "Home",
        "37": "ArrowLeft",
        "38": "ArrowUp",
        "39": "ArrowRight",
        "40": "ArrowDown",
        "45": "Insert",
        "46": "Delete",
        "112": "F1",
        "113": "F2",
        "114": "F3",
        "115": "F4",
        "116": "F5",
        "117": "F6",
        "118": "F7",
        "119": "F8",
        "120": "F9",
        "121": "F10",
        "122": "F11",
        "123": "F12",
        "144": "NumLock",
        "145": "ScrollLock",
        "224": "Meta"
      };
      function getEventKey(nativeEvent) {
        if (nativeEvent.key) {
          var key2 = normalizeKey[nativeEvent.key] || nativeEvent.key;
          if (key2 !== "Unidentified") {
            return key2;
          }
        }
        if (nativeEvent.type === "keypress") {
          var charCode = getEventCharCode(nativeEvent);
          return charCode === 13 ? "Enter" : String.fromCharCode(charCode);
        }
        if (nativeEvent.type === "keydown" || nativeEvent.type === "keyup") {
          return translateToKey[nativeEvent.keyCode] || "Unidentified";
        }
        return "";
      }
      var modifierKeyToProp = {
        Alt: "altKey",
        Control: "ctrlKey",
        Meta: "metaKey",
        Shift: "shiftKey"
      };
      function modifierStateGetter(keyArg) {
        var syntheticEvent = this;
        var nativeEvent = syntheticEvent.nativeEvent;
        if (nativeEvent.getModifierState) {
          return nativeEvent.getModifierState(keyArg);
        }
        var keyProp = modifierKeyToProp[keyArg];
        return keyProp ? !!nativeEvent[keyProp] : false;
      }
      function getEventModifierState(nativeEvent) {
        return modifierStateGetter;
      }
      var KeyboardEventInterface = assign({}, UIEventInterface, {
        key: getEventKey,
        code: 0,
        location: 0,
        ctrlKey: 0,
        shiftKey: 0,
        altKey: 0,
        metaKey: 0,
        repeat: 0,
        locale: 0,
        getModifierState: getEventModifierState,
        // Legacy Interface
        charCode: function(event) {
          if (event.type === "keypress") {
            return getEventCharCode(event);
          }
          return 0;
        },
        keyCode: function(event) {
          if (event.type === "keydown" || event.type === "keyup") {
            return event.keyCode;
          }
          return 0;
        },
        which: function(event) {
          if (event.type === "keypress") {
            return getEventCharCode(event);
          }
          if (event.type === "keydown" || event.type === "keyup") {
            return event.keyCode;
          }
          return 0;
        }
      });
      var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
      var PointerEventInterface = assign({}, MouseEventInterface, {
        pointerId: 0,
        width: 0,
        height: 0,
        pressure: 0,
        tangentialPressure: 0,
        tiltX: 0,
        tiltY: 0,
        twist: 0,
        pointerType: 0,
        isPrimary: 0
      });
      var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
      var TouchEventInterface = assign({}, UIEventInterface, {
        touches: 0,
        targetTouches: 0,
        changedTouches: 0,
        altKey: 0,
        metaKey: 0,
        ctrlKey: 0,
        shiftKey: 0,
        getModifierState: getEventModifierState
      });
      var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
      var TransitionEventInterface = assign({}, EventInterface, {
        propertyName: 0,
        elapsedTime: 0,
        pseudoElement: 0
      });
      var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
      var WheelEventInterface = assign({}, MouseEventInterface, {
        deltaX: function(event) {
          return "deltaX" in event ? event.deltaX : (
            // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
            "wheelDeltaX" in event ? -event.wheelDeltaX : 0
          );
        },
        deltaY: function(event) {
          return "deltaY" in event ? event.deltaY : (
            // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
            "wheelDeltaY" in event ? -event.wheelDeltaY : (
              // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
              "wheelDelta" in event ? -event.wheelDelta : 0
            )
          );
        },
        deltaZ: 0,
        // Browsers without "deltaMode" is reporting in raw wheel delta where one
        // notch on the scroll is always +/- 120, roughly equivalent to pixels.
        // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
        // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
        deltaMode: 0
      });
      var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
      var END_KEYCODES = [9, 13, 27, 32];
      var START_KEYCODE = 229;
      var canUseCompositionEvent = canUseDOM && "CompositionEvent" in window;
      var documentMode = null;
      if (canUseDOM && "documentMode" in document) {
        documentMode = document.documentMode;
      }
      var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode;
      var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
      var SPACEBAR_CODE = 32;
      var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
      function registerEvents() {
        registerTwoPhaseEvent("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
        registerTwoPhaseEvent("onCompositionEnd", ["compositionend", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
        registerTwoPhaseEvent("onCompositionStart", ["compositionstart", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
        registerTwoPhaseEvent("onCompositionUpdate", ["compositionupdate", "focusout", "keydown", "keypress", "keyup", "mousedown"]);
      }
      var hasSpaceKeypress = false;
      function isKeypressCommand(nativeEvent) {
        return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
        !(nativeEvent.ctrlKey && nativeEvent.altKey);
      }
      function getCompositionEventType(domEventName) {
        switch (domEventName) {
          case "compositionstart":
            return "onCompositionStart";
          case "compositionend":
            return "onCompositionEnd";
          case "compositionupdate":
            return "onCompositionUpdate";
        }
      }
      function isFallbackCompositionStart(domEventName, nativeEvent) {
        return domEventName === "keydown" && nativeEvent.keyCode === START_KEYCODE;
      }
      function isFallbackCompositionEnd(domEventName, nativeEvent) {
        switch (domEventName) {
          case "keyup":
            return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
          case "keydown":
            return nativeEvent.keyCode !== START_KEYCODE;
          case "keypress":
          case "mousedown":
          case "focusout":
            return true;
          default:
            return false;
        }
      }
      function getDataFromCustomEvent(nativeEvent) {
        var detail = nativeEvent.detail;
        if (typeof detail === "object" && "data" in detail) {
          return detail.data;
        }
        return null;
      }
      function isUsingKoreanIME(nativeEvent) {
        return nativeEvent.locale === "ko";
      }
      var isComposing = false;
      function extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
        var eventType;
        var fallbackData;
        if (canUseCompositionEvent) {
          eventType = getCompositionEventType(domEventName);
        } else if (!isComposing) {
          if (isFallbackCompositionStart(domEventName, nativeEvent)) {
            eventType = "onCompositionStart";
          }
        } else if (isFallbackCompositionEnd(domEventName, nativeEvent)) {
          eventType = "onCompositionEnd";
        }
        if (!eventType) {
          return null;
        }
        if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
          if (!isComposing && eventType === "onCompositionStart") {
            isComposing = initialize(nativeEventTarget);
          } else if (eventType === "onCompositionEnd") {
            if (isComposing) {
              fallbackData = getData();
            }
          }
        }
        var listeners = accumulateTwoPhaseListeners(targetInst, eventType);
        if (listeners.length > 0) {
          var event = new SyntheticCompositionEvent(eventType, domEventName, null, nativeEvent, nativeEventTarget);
          dispatchQueue.push({
            event,
            listeners
          });
          if (fallbackData) {
            event.data = fallbackData;
          } else {
            var customData = getDataFromCustomEvent(nativeEvent);
            if (customData !== null) {
              event.data = customData;
            }
          }
        }
      }
      function getNativeBeforeInputChars(domEventName, nativeEvent) {
        switch (domEventName) {
          case "compositionend":
            return getDataFromCustomEvent(nativeEvent);
          case "keypress":
            var which = nativeEvent.which;
            if (which !== SPACEBAR_CODE) {
              return null;
            }
            hasSpaceKeypress = true;
            return SPACEBAR_CHAR;
          case "textInput":
            var chars2 = nativeEvent.data;
            if (chars2 === SPACEBAR_CHAR && hasSpaceKeypress) {
              return null;
            }
            return chars2;
          default:
            return null;
        }
      }
      function getFallbackBeforeInputChars(domEventName, nativeEvent) {
        if (isComposing) {
          if (domEventName === "compositionend" || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent)) {
            var chars2 = getData();
            reset();
            isComposing = false;
            return chars2;
          }
          return null;
        }
        switch (domEventName) {
          case "paste":
            return null;
          case "keypress":
            if (!isKeypressCommand(nativeEvent)) {
              if (nativeEvent.char && nativeEvent.char.length > 1) {
                return nativeEvent.char;
              } else if (nativeEvent.which) {
                return String.fromCharCode(nativeEvent.which);
              }
            }
            return null;
          case "compositionend":
            return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
          default:
            return null;
        }
      }
      function extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget) {
        var chars2;
        if (canUseTextInputEvent) {
          chars2 = getNativeBeforeInputChars(domEventName, nativeEvent);
        } else {
          chars2 = getFallbackBeforeInputChars(domEventName, nativeEvent);
        }
        if (!chars2) {
          return null;
        }
        var listeners = accumulateTwoPhaseListeners(targetInst, "onBeforeInput");
        if (listeners.length > 0) {
          var event = new SyntheticInputEvent("onBeforeInput", "beforeinput", null, nativeEvent, nativeEventTarget);
          dispatchQueue.push({
            event,
            listeners
          });
          event.data = chars2;
        }
      }
      function extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        extractCompositionEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
        extractBeforeInputEvent(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
      }
      var supportedInputTypes = {
        color: true,
        date: true,
        datetime: true,
        "datetime-local": true,
        email: true,
        month: true,
        number: true,
        password: true,
        range: true,
        search: true,
        tel: true,
        text: true,
        time: true,
        url: true,
        week: true
      };
      function isTextInputElement(elem) {
        var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
        if (nodeName === "input") {
          return !!supportedInputTypes[elem.type];
        }
        if (nodeName === "textarea") {
          return true;
        }
        return false;
      }
      /**
       * Checks if an event is supported in the current execution environment.
       *
       * NOTE: This will not work correctly for non-generic events such as `change`,
       * `reset`, `load`, `error`, and `select`.
       *
       * Borrows from Modernizr.
       *
       * @param {string} eventNameSuffix Event name, e.g. "click".
       * @return {boolean} True if the event is supported.
       * @internal
       * @license Modernizr 3.0.0pre (Custom Build) | MIT
       */
      function isEventSupported(eventNameSuffix) {
        if (!canUseDOM) {
          return false;
        }
        var eventName = "on" + eventNameSuffix;
        var isSupported2 = eventName in document;
        if (!isSupported2) {
          var element = document.createElement("div");
          element.setAttribute(eventName, "return;");
          isSupported2 = typeof element[eventName] === "function";
        }
        return isSupported2;
      }
      function registerEvents$1() {
        registerTwoPhaseEvent("onChange", ["change", "click", "focusin", "focusout", "input", "keydown", "keyup", "selectionchange"]);
      }
      function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
        enqueueStateRestore(target);
        var listeners = accumulateTwoPhaseListeners(inst, "onChange");
        if (listeners.length > 0) {
          var event = new SyntheticEvent("onChange", "change", null, nativeEvent, target);
          dispatchQueue.push({
            event,
            listeners
          });
        }
      }
      var activeElement = null;
      var activeElementInst = null;
      function shouldUseChangeEvent(elem) {
        var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
        return nodeName === "select" || nodeName === "input" && elem.type === "file";
      }
      function manualDispatchChangeEvent(nativeEvent) {
        var dispatchQueue = [];
        createAndAccumulateChangeEvent(dispatchQueue, activeElementInst, nativeEvent, getEventTarget(nativeEvent));
        batchedUpdates(runEventInBatch, dispatchQueue);
      }
      function runEventInBatch(dispatchQueue) {
        processDispatchQueue(dispatchQueue, 0);
      }
      function getInstIfValueChanged(targetInst) {
        var targetNode = getNodeFromInstance(targetInst);
        if (updateValueIfChanged(targetNode)) {
          return targetInst;
        }
      }
      function getTargetInstForChangeEvent(domEventName, targetInst) {
        if (domEventName === "change") {
          return targetInst;
        }
      }
      var isInputEventSupported = false;
      if (canUseDOM) {
        isInputEventSupported = isEventSupported("input") && (!document.documentMode || document.documentMode > 9);
      }
      function startWatchingForValueChange(target, targetInst) {
        activeElement = target;
        activeElementInst = targetInst;
        activeElement.attachEvent("onpropertychange", handlePropertyChange);
      }
      function stopWatchingForValueChange() {
        if (!activeElement) {
          return;
        }
        activeElement.detachEvent("onpropertychange", handlePropertyChange);
        activeElement = null;
        activeElementInst = null;
      }
      function handlePropertyChange(nativeEvent) {
        if (nativeEvent.propertyName !== "value") {
          return;
        }
        if (getInstIfValueChanged(activeElementInst)) {
          manualDispatchChangeEvent(nativeEvent);
        }
      }
      function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
        if (domEventName === "focusin") {
          stopWatchingForValueChange();
          startWatchingForValueChange(target, targetInst);
        } else if (domEventName === "focusout") {
          stopWatchingForValueChange();
        }
      }
      function getTargetInstForInputEventPolyfill(domEventName, targetInst) {
        if (domEventName === "selectionchange" || domEventName === "keyup" || domEventName === "keydown") {
          return getInstIfValueChanged(activeElementInst);
        }
      }
      function shouldUseClickEvent(elem) {
        var nodeName = elem.nodeName;
        return nodeName && nodeName.toLowerCase() === "input" && (elem.type === "checkbox" || elem.type === "radio");
      }
      function getTargetInstForClickEvent(domEventName, targetInst) {
        if (domEventName === "click") {
          return getInstIfValueChanged(targetInst);
        }
      }
      function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
        if (domEventName === "input" || domEventName === "change") {
          return getInstIfValueChanged(targetInst);
        }
      }
      function handleControlledInputBlur(node2) {
        var state = node2._wrapperState;
        if (!state || !state.controlled || node2.type !== "number") {
          return;
        }
        {
          setDefaultValue(node2, "number", node2.value);
        }
      }
      function extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
        var getTargetInstFunc, handleEventFunc;
        if (shouldUseChangeEvent(targetNode)) {
          getTargetInstFunc = getTargetInstForChangeEvent;
        } else if (isTextInputElement(targetNode)) {
          if (isInputEventSupported) {
            getTargetInstFunc = getTargetInstForInputOrChangeEvent;
          } else {
            getTargetInstFunc = getTargetInstForInputEventPolyfill;
            handleEventFunc = handleEventsForInputEventPolyfill;
          }
        } else if (shouldUseClickEvent(targetNode)) {
          getTargetInstFunc = getTargetInstForClickEvent;
        }
        if (getTargetInstFunc) {
          var inst = getTargetInstFunc(domEventName, targetInst);
          if (inst) {
            createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, nativeEventTarget);
            return;
          }
        }
        if (handleEventFunc) {
          handleEventFunc(domEventName, targetNode, targetInst);
        }
        if (domEventName === "focusout") {
          handleControlledInputBlur(targetNode);
        }
      }
      function registerEvents$2() {
        registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
        registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
        registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
        registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
      }
      function extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        var isOverEvent = domEventName === "mouseover" || domEventName === "pointerover";
        var isOutEvent = domEventName === "mouseout" || domEventName === "pointerout";
        if (isOverEvent && !isReplayingEvent(nativeEvent)) {
          var related = nativeEvent.relatedTarget || nativeEvent.fromElement;
          if (related) {
            if (getClosestInstanceFromNode(related) || isContainerMarkedAsRoot(related)) {
              return;
            }
          }
        }
        if (!isOutEvent && !isOverEvent) {
          return;
        }
        var win;
        if (nativeEventTarget.window === nativeEventTarget) {
          win = nativeEventTarget;
        } else {
          var doc = nativeEventTarget.ownerDocument;
          if (doc) {
            win = doc.defaultView || doc.parentWindow;
          } else {
            win = window;
          }
        }
        var from2;
        var to2;
        if (isOutEvent) {
          var _related = nativeEvent.relatedTarget || nativeEvent.toElement;
          from2 = targetInst;
          to2 = _related ? getClosestInstanceFromNode(_related) : null;
          if (to2 !== null) {
            var nearestMounted = getNearestMountedFiber(to2);
            if (to2 !== nearestMounted || to2.tag !== HostComponent && to2.tag !== HostText) {
              to2 = null;
            }
          }
        } else {
          from2 = null;
          to2 = targetInst;
        }
        if (from2 === to2) {
          return;
        }
        var SyntheticEventCtor = SyntheticMouseEvent;
        var leaveEventType = "onMouseLeave";
        var enterEventType = "onMouseEnter";
        var eventTypePrefix = "mouse";
        if (domEventName === "pointerout" || domEventName === "pointerover") {
          SyntheticEventCtor = SyntheticPointerEvent;
          leaveEventType = "onPointerLeave";
          enterEventType = "onPointerEnter";
          eventTypePrefix = "pointer";
        }
        var fromNode = from2 == null ? win : getNodeFromInstance(from2);
        var toNode = to2 == null ? win : getNodeFromInstance(to2);
        var leave = new SyntheticEventCtor(leaveEventType, eventTypePrefix + "leave", from2, nativeEvent, nativeEventTarget);
        leave.target = fromNode;
        leave.relatedTarget = toNode;
        var enter = null;
        var nativeTargetInst = getClosestInstanceFromNode(nativeEventTarget);
        if (nativeTargetInst === targetInst) {
          var enterEvent = new SyntheticEventCtor(enterEventType, eventTypePrefix + "enter", to2, nativeEvent, nativeEventTarget);
          enterEvent.target = toNode;
          enterEvent.relatedTarget = fromNode;
          enter = enterEvent;
        }
        accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leave, enter, from2, to2);
      }
      function is(x2, y2) {
        return x2 === y2 && (x2 !== 0 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
      }
      var objectIs = typeof Object.is === "function" ? Object.is : is;
      function shallowEqual(objA, objB) {
        if (objectIs(objA, objB)) {
          return true;
        }
        if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
          return false;
        }
        var keysA = Object.keys(objA);
        var keysB = Object.keys(objB);
        if (keysA.length !== keysB.length) {
          return false;
        }
        for (var i2 = 0; i2 < keysA.length; i2++) {
          var currentKey = keysA[i2];
          if (!hasOwnProperty.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey])) {
            return false;
          }
        }
        return true;
      }
      function getLeafNode(node2) {
        while (node2 && node2.firstChild) {
          node2 = node2.firstChild;
        }
        return node2;
      }
      function getSiblingNode(node2) {
        while (node2) {
          if (node2.nextSibling) {
            return node2.nextSibling;
          }
          node2 = node2.parentNode;
        }
      }
      function getNodeForCharacterOffset(root2, offset) {
        var node2 = getLeafNode(root2);
        var nodeStart = 0;
        var nodeEnd = 0;
        while (node2) {
          if (node2.nodeType === TEXT_NODE) {
            nodeEnd = nodeStart + node2.textContent.length;
            if (nodeStart <= offset && nodeEnd >= offset) {
              return {
                node: node2,
                offset: offset - nodeStart
              };
            }
            nodeStart = nodeEnd;
          }
          node2 = getLeafNode(getSiblingNode(node2));
        }
      }
      function getOffsets(outerNode) {
        var ownerDocument = outerNode.ownerDocument;
        var win = ownerDocument && ownerDocument.defaultView || window;
        var selection = win.getSelection && win.getSelection();
        if (!selection || selection.rangeCount === 0) {
          return null;
        }
        var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset;
        try {
          anchorNode.nodeType;
          focusNode.nodeType;
        } catch (e4) {
          return null;
        }
        return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
      }
      function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
        var length = 0;
        var start = -1;
        var end = -1;
        var indexWithinAnchor = 0;
        var indexWithinFocus = 0;
        var node2 = outerNode;
        var parentNode = null;
        outer: while (true) {
          var next = null;
          while (true) {
            if (node2 === anchorNode && (anchorOffset === 0 || node2.nodeType === TEXT_NODE)) {
              start = length + anchorOffset;
            }
            if (node2 === focusNode && (focusOffset === 0 || node2.nodeType === TEXT_NODE)) {
              end = length + focusOffset;
            }
            if (node2.nodeType === TEXT_NODE) {
              length += node2.nodeValue.length;
            }
            if ((next = node2.firstChild) === null) {
              break;
            }
            parentNode = node2;
            node2 = next;
          }
          while (true) {
            if (node2 === outerNode) {
              break outer;
            }
            if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
              start = length;
            }
            if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
              end = length;
            }
            if ((next = node2.nextSibling) !== null) {
              break;
            }
            node2 = parentNode;
            parentNode = node2.parentNode;
          }
          node2 = next;
        }
        if (start === -1 || end === -1) {
          return null;
        }
        return {
          start,
          end
        };
      }
      function setOffsets(node2, offsets) {
        var doc = node2.ownerDocument || document;
        var win = doc && doc.defaultView || window;
        if (!win.getSelection) {
          return;
        }
        var selection = win.getSelection();
        var length = node2.textContent.length;
        var start = Math.min(offsets.start, length);
        var end = offsets.end === void 0 ? start : Math.min(offsets.end, length);
        if (!selection.extend && start > end) {
          var temp = end;
          end = start;
          start = temp;
        }
        var startMarker = getNodeForCharacterOffset(node2, start);
        var endMarker = getNodeForCharacterOffset(node2, end);
        if (startMarker && endMarker) {
          if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
            return;
          }
          var range2 = doc.createRange();
          range2.setStart(startMarker.node, startMarker.offset);
          selection.removeAllRanges();
          if (start > end) {
            selection.addRange(range2);
            selection.extend(endMarker.node, endMarker.offset);
          } else {
            range2.setEnd(endMarker.node, endMarker.offset);
            selection.addRange(range2);
          }
        }
      }
      function isTextNode(node2) {
        return node2 && node2.nodeType === TEXT_NODE;
      }
      function containsNode(outerNode, innerNode) {
        if (!outerNode || !innerNode) {
          return false;
        } else if (outerNode === innerNode) {
          return true;
        } else if (isTextNode(outerNode)) {
          return false;
        } else if (isTextNode(innerNode)) {
          return containsNode(outerNode, innerNode.parentNode);
        } else if ("contains" in outerNode) {
          return outerNode.contains(innerNode);
        } else if (outerNode.compareDocumentPosition) {
          return !!(outerNode.compareDocumentPosition(innerNode) & 16);
        } else {
          return false;
        }
      }
      function isInDocument(node2) {
        return node2 && node2.ownerDocument && containsNode(node2.ownerDocument.documentElement, node2);
      }
      function isSameOriginFrame(iframe) {
        try {
          return typeof iframe.contentWindow.location.href === "string";
        } catch (err) {
          return false;
        }
      }
      function getActiveElementDeep() {
        var win = window;
        var element = getActiveElement();
        while (element instanceof win.HTMLIFrameElement) {
          if (isSameOriginFrame(element)) {
            win = element.contentWindow;
          } else {
            return element;
          }
          element = getActiveElement(win.document);
        }
        return element;
      }
      function hasSelectionCapabilities(elem) {
        var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
        return nodeName && (nodeName === "input" && (elem.type === "text" || elem.type === "search" || elem.type === "tel" || elem.type === "url" || elem.type === "password") || nodeName === "textarea" || elem.contentEditable === "true");
      }
      function getSelectionInformation() {
        var focusedElem = getActiveElementDeep();
        return {
          focusedElem,
          selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection2(focusedElem) : null
        };
      }
      function restoreSelection(priorSelectionInformation) {
        var curFocusedElem = getActiveElementDeep();
        var priorFocusedElem = priorSelectionInformation.focusedElem;
        var priorSelectionRange = priorSelectionInformation.selectionRange;
        if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
          if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
            setSelection(priorFocusedElem, priorSelectionRange);
          }
          var ancestors = [];
          var ancestor = priorFocusedElem;
          while (ancestor = ancestor.parentNode) {
            if (ancestor.nodeType === ELEMENT_NODE) {
              ancestors.push({
                element: ancestor,
                left: ancestor.scrollLeft,
                top: ancestor.scrollTop
              });
            }
          }
          if (typeof priorFocusedElem.focus === "function") {
            priorFocusedElem.focus();
          }
          for (var i2 = 0; i2 < ancestors.length; i2++) {
            var info = ancestors[i2];
            info.element.scrollLeft = info.left;
            info.element.scrollTop = info.top;
          }
        }
      }
      function getSelection2(input) {
        var selection;
        if ("selectionStart" in input) {
          selection = {
            start: input.selectionStart,
            end: input.selectionEnd
          };
        } else {
          selection = getOffsets(input);
        }
        return selection || {
          start: 0,
          end: 0
        };
      }
      function setSelection(input, offsets) {
        var start = offsets.start;
        var end = offsets.end;
        if (end === void 0) {
          end = start;
        }
        if ("selectionStart" in input) {
          input.selectionStart = start;
          input.selectionEnd = Math.min(end, input.value.length);
        } else {
          setOffsets(input, offsets);
        }
      }
      var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && document.documentMode <= 11;
      function registerEvents$3() {
        registerTwoPhaseEvent("onSelect", ["focusout", "contextmenu", "dragend", "focusin", "keydown", "keyup", "mousedown", "mouseup", "selectionchange"]);
      }
      var activeElement$1 = null;
      var activeElementInst$1 = null;
      var lastSelection = null;
      var mouseDown = false;
      function getSelection$1(node2) {
        if ("selectionStart" in node2 && hasSelectionCapabilities(node2)) {
          return {
            start: node2.selectionStart,
            end: node2.selectionEnd
          };
        } else {
          var win = node2.ownerDocument && node2.ownerDocument.defaultView || window;
          var selection = win.getSelection();
          return {
            anchorNode: selection.anchorNode,
            anchorOffset: selection.anchorOffset,
            focusNode: selection.focusNode,
            focusOffset: selection.focusOffset
          };
        }
      }
      function getEventTargetDocument(eventTarget) {
        return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
      }
      function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
        var doc = getEventTargetDocument(nativeEventTarget);
        if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
          return;
        }
        var currentSelection = getSelection$1(activeElement$1);
        if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
          lastSelection = currentSelection;
          var listeners = accumulateTwoPhaseListeners(activeElementInst$1, "onSelect");
          if (listeners.length > 0) {
            var event = new SyntheticEvent("onSelect", "select", null, nativeEvent, nativeEventTarget);
            dispatchQueue.push({
              event,
              listeners
            });
            event.target = activeElement$1;
          }
        }
      }
      function extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        var targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
        switch (domEventName) {
          // Track the input node that has focus.
          case "focusin":
            if (isTextInputElement(targetNode) || targetNode.contentEditable === "true") {
              activeElement$1 = targetNode;
              activeElementInst$1 = targetInst;
              lastSelection = null;
            }
            break;
          case "focusout":
            activeElement$1 = null;
            activeElementInst$1 = null;
            lastSelection = null;
            break;
          // Don't fire the event while the user is dragging. This matches the
          // semantics of the native select event.
          case "mousedown":
            mouseDown = true;
            break;
          case "contextmenu":
          case "mouseup":
          case "dragend":
            mouseDown = false;
            constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
            break;
          // Chrome and IE fire non-standard event when selection is changed (and
          // sometimes when it hasn't). IE's event fires out of order with respect
          // to key and input events on deletion, so we discard it.
          //
          // Firefox doesn't support selectionchange, so check selection status
          // after each key entry. The selection changes after keydown and before
          // keyup, but we check on keydown as well in the case of holding down a
          // key, when multiple keydown events are fired but only one keyup is.
          // This is also our approach for IE handling, for the reason above.
          case "selectionchange":
            if (skipSelectionChangeEvent) {
              break;
            }
          // falls through
          case "keydown":
          case "keyup":
            constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
        }
      }
      function makePrefixMap(styleProp, eventName) {
        var prefixes2 = {};
        prefixes2[styleProp.toLowerCase()] = eventName.toLowerCase();
        prefixes2["Webkit" + styleProp] = "webkit" + eventName;
        prefixes2["Moz" + styleProp] = "moz" + eventName;
        return prefixes2;
      }
      var vendorPrefixes = {
        animationend: makePrefixMap("Animation", "AnimationEnd"),
        animationiteration: makePrefixMap("Animation", "AnimationIteration"),
        animationstart: makePrefixMap("Animation", "AnimationStart"),
        transitionend: makePrefixMap("Transition", "TransitionEnd")
      };
      var prefixedEventNames = {};
      var style = {};
      if (canUseDOM) {
        style = document.createElement("div").style;
        if (!("AnimationEvent" in window)) {
          delete vendorPrefixes.animationend.animation;
          delete vendorPrefixes.animationiteration.animation;
          delete vendorPrefixes.animationstart.animation;
        }
        if (!("TransitionEvent" in window)) {
          delete vendorPrefixes.transitionend.transition;
        }
      }
      function getVendorPrefixedEventName(eventName) {
        if (prefixedEventNames[eventName]) {
          return prefixedEventNames[eventName];
        } else if (!vendorPrefixes[eventName]) {
          return eventName;
        }
        var prefixMap = vendorPrefixes[eventName];
        for (var styleProp in prefixMap) {
          if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
            return prefixedEventNames[eventName] = prefixMap[styleProp];
          }
        }
        return eventName;
      }
      var ANIMATION_END = getVendorPrefixedEventName("animationend");
      var ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration");
      var ANIMATION_START = getVendorPrefixedEventName("animationstart");
      var TRANSITION_END = getVendorPrefixedEventName("transitionend");
      var topLevelEventsToReactNames = /* @__PURE__ */ new Map();
      var simpleEventPluginEvents = ["abort", "auxClick", "cancel", "canPlay", "canPlayThrough", "click", "close", "contextMenu", "copy", "cut", "drag", "dragEnd", "dragEnter", "dragExit", "dragLeave", "dragOver", "dragStart", "drop", "durationChange", "emptied", "encrypted", "ended", "error", "gotPointerCapture", "input", "invalid", "keyDown", "keyPress", "keyUp", "load", "loadedData", "loadedMetadata", "loadStart", "lostPointerCapture", "mouseDown", "mouseMove", "mouseOut", "mouseOver", "mouseUp", "paste", "pause", "play", "playing", "pointerCancel", "pointerDown", "pointerMove", "pointerOut", "pointerOver", "pointerUp", "progress", "rateChange", "reset", "resize", "seeked", "seeking", "stalled", "submit", "suspend", "timeUpdate", "touchCancel", "touchEnd", "touchStart", "volumeChange", "scroll", "toggle", "touchMove", "waiting", "wheel"];
      function registerSimpleEvent(domEventName, reactName) {
        topLevelEventsToReactNames.set(domEventName, reactName);
        registerTwoPhaseEvent(reactName, [domEventName]);
      }
      function registerSimpleEvents() {
        for (var i2 = 0; i2 < simpleEventPluginEvents.length; i2++) {
          var eventName = simpleEventPluginEvents[i2];
          var domEventName = eventName.toLowerCase();
          var capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
          registerSimpleEvent(domEventName, "on" + capitalizedEvent);
        }
        registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
        registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
        registerSimpleEvent(ANIMATION_START, "onAnimationStart");
        registerSimpleEvent("dblclick", "onDoubleClick");
        registerSimpleEvent("focusin", "onFocus");
        registerSimpleEvent("focusout", "onBlur");
        registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
      }
      function extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        var reactName = topLevelEventsToReactNames.get(domEventName);
        if (reactName === void 0) {
          return;
        }
        var SyntheticEventCtor = SyntheticEvent;
        var reactEventType = domEventName;
        switch (domEventName) {
          case "keypress":
            if (getEventCharCode(nativeEvent) === 0) {
              return;
            }
          /* falls through */
          case "keydown":
          case "keyup":
            SyntheticEventCtor = SyntheticKeyboardEvent;
            break;
          case "focusin":
            reactEventType = "focus";
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "focusout":
            reactEventType = "blur";
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "beforeblur":
          case "afterblur":
            SyntheticEventCtor = SyntheticFocusEvent;
            break;
          case "click":
            if (nativeEvent.button === 2) {
              return;
            }
          /* falls through */
          case "auxclick":
          case "dblclick":
          case "mousedown":
          case "mousemove":
          case "mouseup":
          // TODO: Disabled elements should not respond to mouse events
          /* falls through */
          case "mouseout":
          case "mouseover":
          case "contextmenu":
            SyntheticEventCtor = SyntheticMouseEvent;
            break;
          case "drag":
          case "dragend":
          case "dragenter":
          case "dragexit":
          case "dragleave":
          case "dragover":
          case "dragstart":
          case "drop":
            SyntheticEventCtor = SyntheticDragEvent;
            break;
          case "touchcancel":
          case "touchend":
          case "touchmove":
          case "touchstart":
            SyntheticEventCtor = SyntheticTouchEvent;
            break;
          case ANIMATION_END:
          case ANIMATION_ITERATION:
          case ANIMATION_START:
            SyntheticEventCtor = SyntheticAnimationEvent;
            break;
          case TRANSITION_END:
            SyntheticEventCtor = SyntheticTransitionEvent;
            break;
          case "scroll":
            SyntheticEventCtor = SyntheticUIEvent;
            break;
          case "wheel":
            SyntheticEventCtor = SyntheticWheelEvent;
            break;
          case "copy":
          case "cut":
          case "paste":
            SyntheticEventCtor = SyntheticClipboardEvent;
            break;
          case "gotpointercapture":
          case "lostpointercapture":
          case "pointercancel":
          case "pointerdown":
          case "pointermove":
          case "pointerout":
          case "pointerover":
          case "pointerup":
            SyntheticEventCtor = SyntheticPointerEvent;
            break;
        }
        var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
        {
          var accumulateTargetOnly = !inCapturePhase && // TODO: ideally, we'd eventually add all events from
          // nonDelegatedEvents list in DOMPluginEventSystem.
          // Then we can remove this special list.
          // This is a breaking change that can wait until React 18.
          domEventName === "scroll";
          var _listeners = accumulateSinglePhaseListeners(targetInst, reactName, nativeEvent.type, inCapturePhase, accumulateTargetOnly);
          if (_listeners.length > 0) {
            var _event = new SyntheticEventCtor(reactName, reactEventType, null, nativeEvent, nativeEventTarget);
            dispatchQueue.push({
              event: _event,
              listeners: _listeners
            });
          }
        }
      }
      registerSimpleEvents();
      registerEvents$2();
      registerEvents$1();
      registerEvents$3();
      registerEvents();
      function extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, targetContainer) {
        extractEvents$4(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
        var shouldProcessPolyfillPlugins = (eventSystemFlags & SHOULD_NOT_PROCESS_POLYFILL_EVENT_PLUGINS) === 0;
        if (shouldProcessPolyfillPlugins) {
          extractEvents$2(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
          extractEvents$1(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
          extractEvents$3(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
          extractEvents(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget);
        }
      }
      var mediaEventTypes = ["abort", "canplay", "canplaythrough", "durationchange", "emptied", "encrypted", "ended", "error", "loadeddata", "loadedmetadata", "loadstart", "pause", "play", "playing", "progress", "ratechange", "resize", "seeked", "seeking", "stalled", "suspend", "timeupdate", "volumechange", "waiting"];
      var nonDelegatedEvents = new Set(["cancel", "close", "invalid", "load", "scroll", "toggle"].concat(mediaEventTypes));
      function executeDispatch(event, listener, currentTarget) {
        var type2 = event.type || "unknown-event";
        event.currentTarget = currentTarget;
        invokeGuardedCallbackAndCatchFirstError(type2, listener, void 0, event);
        event.currentTarget = null;
      }
      function processDispatchQueueItemsInOrder(event, dispatchListeners, inCapturePhase) {
        var previousInstance;
        if (inCapturePhase) {
          for (var i2 = dispatchListeners.length - 1; i2 >= 0; i2--) {
            var _dispatchListeners$i = dispatchListeners[i2], instance2 = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget, listener = _dispatchListeners$i.listener;
            if (instance2 !== previousInstance && event.isPropagationStopped()) {
              return;
            }
            executeDispatch(event, listener, currentTarget);
            previousInstance = instance2;
          }
        } else {
          for (var _i2 = 0; _i2 < dispatchListeners.length; _i2++) {
            var _dispatchListeners$_i = dispatchListeners[_i2], _instance = _dispatchListeners$_i.instance, _currentTarget = _dispatchListeners$_i.currentTarget, _listener = _dispatchListeners$_i.listener;
            if (_instance !== previousInstance && event.isPropagationStopped()) {
              return;
            }
            executeDispatch(event, _listener, _currentTarget);
            previousInstance = _instance;
          }
        }
      }
      function processDispatchQueue(dispatchQueue, eventSystemFlags) {
        var inCapturePhase = (eventSystemFlags & IS_CAPTURE_PHASE) !== 0;
        for (var i2 = 0; i2 < dispatchQueue.length; i2++) {
          var _dispatchQueue$i = dispatchQueue[i2], event = _dispatchQueue$i.event, listeners = _dispatchQueue$i.listeners;
          processDispatchQueueItemsInOrder(event, listeners, inCapturePhase);
        }
        rethrowCaughtError();
      }
      function dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
        var nativeEventTarget = getEventTarget(nativeEvent);
        var dispatchQueue = [];
        extractEvents$5(dispatchQueue, domEventName, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
        processDispatchQueue(dispatchQueue, eventSystemFlags);
      }
      function listenToNonDelegatedEvent(domEventName, targetElement) {
        {
          if (!nonDelegatedEvents.has(domEventName)) {
            error('Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.', domEventName);
          }
        }
        var isCapturePhaseListener = false;
        var listenerSet = getEventListenerSet(targetElement);
        var listenerSetKey = getListenerSetKey(domEventName);
        if (!listenerSet.has(listenerSetKey)) {
          addTrappedEventListener(targetElement, domEventName, IS_NON_DELEGATED, isCapturePhaseListener);
          listenerSet.add(listenerSetKey);
        }
      }
      function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
        {
          if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
            error('Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.', domEventName);
          }
        }
        var eventSystemFlags = 0;
        if (isCapturePhaseListener) {
          eventSystemFlags |= IS_CAPTURE_PHASE;
        }
        addTrappedEventListener(target, domEventName, eventSystemFlags, isCapturePhaseListener);
      }
      var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
      function listenToAllSupportedEvents(rootContainerElement) {
        if (!rootContainerElement[listeningMarker]) {
          rootContainerElement[listeningMarker] = true;
          allNativeEvents.forEach(function(domEventName) {
            if (domEventName !== "selectionchange") {
              if (!nonDelegatedEvents.has(domEventName)) {
                listenToNativeEvent(domEventName, false, rootContainerElement);
              }
              listenToNativeEvent(domEventName, true, rootContainerElement);
            }
          });
          var ownerDocument = rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
          if (ownerDocument !== null) {
            if (!ownerDocument[listeningMarker]) {
              ownerDocument[listeningMarker] = true;
              listenToNativeEvent("selectionchange", false, ownerDocument);
            }
          }
        }
      }
      function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener, isDeferredListenerForLegacyFBSupport) {
        var listener = createEventListenerWrapperWithPriority(targetContainer, domEventName, eventSystemFlags);
        var isPassiveListener = void 0;
        if (passiveBrowserEventsSupported) {
          if (domEventName === "touchstart" || domEventName === "touchmove" || domEventName === "wheel") {
            isPassiveListener = true;
          }
        }
        targetContainer = targetContainer;
        if (isCapturePhaseListener) {
          if (isPassiveListener !== void 0) {
            addEventCaptureListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
          } else {
            addEventCaptureListener(targetContainer, domEventName, listener);
          }
        } else {
          if (isPassiveListener !== void 0) {
            addEventBubbleListenerWithPassiveFlag(targetContainer, domEventName, listener, isPassiveListener);
          } else {
            addEventBubbleListener(targetContainer, domEventName, listener);
          }
        }
      }
      function isMatchingRootContainer(grandContainer, targetContainer) {
        return grandContainer === targetContainer || grandContainer.nodeType === COMMENT_NODE && grandContainer.parentNode === targetContainer;
      }
      function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer) {
        var ancestorInst = targetInst;
        if ((eventSystemFlags & IS_EVENT_HANDLE_NON_MANAGED_NODE) === 0 && (eventSystemFlags & IS_NON_DELEGATED) === 0) {
          var targetContainerNode = targetContainer;
          if (targetInst !== null) {
            var node2 = targetInst;
            mainLoop: while (true) {
              if (node2 === null) {
                return;
              }
              var nodeTag = node2.tag;
              if (nodeTag === HostRoot || nodeTag === HostPortal) {
                var container = node2.stateNode.containerInfo;
                if (isMatchingRootContainer(container, targetContainerNode)) {
                  break;
                }
                if (nodeTag === HostPortal) {
                  var grandNode = node2.return;
                  while (grandNode !== null) {
                    var grandTag = grandNode.tag;
                    if (grandTag === HostRoot || grandTag === HostPortal) {
                      var grandContainer = grandNode.stateNode.containerInfo;
                      if (isMatchingRootContainer(grandContainer, targetContainerNode)) {
                        return;
                      }
                    }
                    grandNode = grandNode.return;
                  }
                }
                while (container !== null) {
                  var parentNode = getClosestInstanceFromNode(container);
                  if (parentNode === null) {
                    return;
                  }
                  var parentTag = parentNode.tag;
                  if (parentTag === HostComponent || parentTag === HostText) {
                    node2 = ancestorInst = parentNode;
                    continue mainLoop;
                  }
                  container = container.parentNode;
                }
              }
              node2 = node2.return;
            }
          }
        }
        batchedUpdates(function() {
          return dispatchEventsForPlugins(domEventName, eventSystemFlags, nativeEvent, ancestorInst);
        });
      }
      function createDispatchListener(instance2, listener, currentTarget) {
        return {
          instance: instance2,
          listener,
          currentTarget
        };
      }
      function accumulateSinglePhaseListeners(targetFiber, reactName, nativeEventType, inCapturePhase, accumulateTargetOnly, nativeEvent) {
        var captureName = reactName !== null ? reactName + "Capture" : null;
        var reactEventName = inCapturePhase ? captureName : reactName;
        var listeners = [];
        var instance2 = targetFiber;
        var lastHostComponent = null;
        while (instance2 !== null) {
          var _instance2 = instance2, stateNode = _instance2.stateNode, tag = _instance2.tag;
          if (tag === HostComponent && stateNode !== null) {
            lastHostComponent = stateNode;
            if (reactEventName !== null) {
              var listener = getListener(instance2, reactEventName);
              if (listener != null) {
                listeners.push(createDispatchListener(instance2, listener, lastHostComponent));
              }
            }
          }
          if (accumulateTargetOnly) {
            break;
          }
          instance2 = instance2.return;
        }
        return listeners;
      }
      function accumulateTwoPhaseListeners(targetFiber, reactName) {
        var captureName = reactName + "Capture";
        var listeners = [];
        var instance2 = targetFiber;
        while (instance2 !== null) {
          var _instance3 = instance2, stateNode = _instance3.stateNode, tag = _instance3.tag;
          if (tag === HostComponent && stateNode !== null) {
            var currentTarget = stateNode;
            var captureListener = getListener(instance2, captureName);
            if (captureListener != null) {
              listeners.unshift(createDispatchListener(instance2, captureListener, currentTarget));
            }
            var bubbleListener = getListener(instance2, reactName);
            if (bubbleListener != null) {
              listeners.push(createDispatchListener(instance2, bubbleListener, currentTarget));
            }
          }
          instance2 = instance2.return;
        }
        return listeners;
      }
      function getParent(inst) {
        if (inst === null) {
          return null;
        }
        do {
          inst = inst.return;
        } while (inst && inst.tag !== HostComponent);
        if (inst) {
          return inst;
        }
        return null;
      }
      function getLowestCommonAncestor(instA, instB) {
        var nodeA = instA;
        var nodeB = instB;
        var depthA = 0;
        for (var tempA = nodeA; tempA; tempA = getParent(tempA)) {
          depthA++;
        }
        var depthB = 0;
        for (var tempB = nodeB; tempB; tempB = getParent(tempB)) {
          depthB++;
        }
        while (depthA - depthB > 0) {
          nodeA = getParent(nodeA);
          depthA--;
        }
        while (depthB - depthA > 0) {
          nodeB = getParent(nodeB);
          depthB--;
        }
        var depth = depthA;
        while (depth--) {
          if (nodeA === nodeB || nodeB !== null && nodeA === nodeB.alternate) {
            return nodeA;
          }
          nodeA = getParent(nodeA);
          nodeB = getParent(nodeB);
        }
        return null;
      }
      function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common2, inCapturePhase) {
        var registrationName = event._reactName;
        var listeners = [];
        var instance2 = target;
        while (instance2 !== null) {
          if (instance2 === common2) {
            break;
          }
          var _instance4 = instance2, alternate = _instance4.alternate, stateNode = _instance4.stateNode, tag = _instance4.tag;
          if (alternate !== null && alternate === common2) {
            break;
          }
          if (tag === HostComponent && stateNode !== null) {
            var currentTarget = stateNode;
            if (inCapturePhase) {
              var captureListener = getListener(instance2, registrationName);
              if (captureListener != null) {
                listeners.unshift(createDispatchListener(instance2, captureListener, currentTarget));
              }
            } else if (!inCapturePhase) {
              var bubbleListener = getListener(instance2, registrationName);
              if (bubbleListener != null) {
                listeners.push(createDispatchListener(instance2, bubbleListener, currentTarget));
              }
            }
          }
          instance2 = instance2.return;
        }
        if (listeners.length !== 0) {
          dispatchQueue.push({
            event,
            listeners
          });
        }
      }
      function accumulateEnterLeaveTwoPhaseListeners(dispatchQueue, leaveEvent, enterEvent, from2, to2) {
        var common2 = from2 && to2 ? getLowestCommonAncestor(from2, to2) : null;
        if (from2 !== null) {
          accumulateEnterLeaveListenersForEvent(dispatchQueue, leaveEvent, from2, common2, false);
        }
        if (to2 !== null && enterEvent !== null) {
          accumulateEnterLeaveListenersForEvent(dispatchQueue, enterEvent, to2, common2, true);
        }
      }
      function getListenerSetKey(domEventName, capture) {
        return domEventName + "__bubble";
      }
      var didWarnInvalidHydration = false;
      var DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML";
      var SUPPRESS_CONTENT_EDITABLE_WARNING = "suppressContentEditableWarning";
      var SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning";
      var AUTOFOCUS = "autoFocus";
      var CHILDREN = "children";
      var STYLE = "style";
      var HTML$1 = "__html";
      var warnedUnknownTags;
      var validatePropertiesInDevelopment;
      var warnForPropDifference;
      var warnForExtraAttributes;
      var warnForInvalidEventListener;
      var canDiffStyleForHydrationWarning;
      var normalizeHTML;
      {
        warnedUnknownTags = {
          // There are working polyfills for <dialog>. Let people use it.
          dialog: true,
          // Electron ships a custom <webview> tag to display external web content in
          // an isolated frame and process.
          // This tag is not present in non Electron environments such as JSDom which
          // is often used for testing purposes.
          // @see https://electronjs.org/docs/api/webview-tag
          webview: true
        };
        validatePropertiesInDevelopment = function(type2, props) {
          validateProperties(type2, props);
          validateProperties$1(type2, props);
          validateProperties$2(type2, props, {
            registrationNameDependencies,
            possibleRegistrationNames
          });
        };
        canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode;
        warnForPropDifference = function(propName, serverValue, clientValue) {
          if (didWarnInvalidHydration) {
            return;
          }
          var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
          var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
          if (normalizedServerValue === normalizedClientValue) {
            return;
          }
          didWarnInvalidHydration = true;
          error("Prop `%s` did not match. Server: %s Client: %s", propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
        };
        warnForExtraAttributes = function(attributeNames) {
          if (didWarnInvalidHydration) {
            return;
          }
          didWarnInvalidHydration = true;
          var names2 = [];
          attributeNames.forEach(function(name) {
            names2.push(name);
          });
          error("Extra attributes from the server: %s", names2);
        };
        warnForInvalidEventListener = function(registrationName, listener) {
          if (listener === false) {
            error("Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.", registrationName, registrationName, registrationName);
          } else {
            error("Expected `%s` listener to be a function, instead got a value of `%s` type.", registrationName, typeof listener);
          }
        };
        normalizeHTML = function(parent, html) {
          var testElement = parent.namespaceURI === HTML_NAMESPACE ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
          testElement.innerHTML = html;
          return testElement.innerHTML;
        };
      }
      var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
      var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
      function normalizeMarkupForTextOrAttribute(markup) {
        {
          checkHtmlStringCoercion(markup);
        }
        var markupString = typeof markup === "string" ? markup : "" + markup;
        return markupString.replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
      }
      function checkForUnmatchedText(serverText, clientText, isConcurrentMode, shouldWarnDev) {
        var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
        var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
        if (normalizedServerText === normalizedClientText) {
          return;
        }
        if (shouldWarnDev) {
          {
            if (!didWarnInvalidHydration) {
              didWarnInvalidHydration = true;
              error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
            }
          }
        }
        if (isConcurrentMode && enableClientRenderFallbackOnTextMismatch) {
          throw new Error("Text content does not match server-rendered HTML.");
        }
      }
      function getOwnerDocumentFromRootContainer(rootContainerElement) {
        return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
      }
      function noop2() {
      }
      function trapClickOnNonInteractiveElement(node2) {
        node2.onclick = noop2;
      }
      function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
        for (var propKey in nextProps) {
          if (!nextProps.hasOwnProperty(propKey)) {
            continue;
          }
          var nextProp = nextProps[propKey];
          if (propKey === STYLE) {
            {
              if (nextProp) {
                Object.freeze(nextProp);
              }
            }
            setValueForStyles(domElement, nextProp);
          } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
            var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
            if (nextHtml != null) {
              setInnerHTML(domElement, nextHtml);
            }
          } else if (propKey === CHILDREN) {
            if (typeof nextProp === "string") {
              var canSetTextContent = tag !== "textarea" || nextProp !== "";
              if (canSetTextContent) {
                setTextContent(domElement, nextProp);
              }
            } else if (typeof nextProp === "number") {
              setTextContent(domElement, "" + nextProp);
            }
          } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;
          else if (propKey === AUTOFOCUS) ;
          else if (registrationNameDependencies.hasOwnProperty(propKey)) {
            if (nextProp != null) {
              if (typeof nextProp !== "function") {
                warnForInvalidEventListener(propKey, nextProp);
              }
              if (propKey === "onScroll") {
                listenToNonDelegatedEvent("scroll", domElement);
              }
            }
          } else if (nextProp != null) {
            setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
          }
        }
      }
      function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
        for (var i2 = 0; i2 < updatePayload.length; i2 += 2) {
          var propKey = updatePayload[i2];
          var propValue = updatePayload[i2 + 1];
          if (propKey === STYLE) {
            setValueForStyles(domElement, propValue);
          } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
            setInnerHTML(domElement, propValue);
          } else if (propKey === CHILDREN) {
            setTextContent(domElement, propValue);
          } else {
            setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
          }
        }
      }
      function createElement(type2, props, rootContainerElement, parentNamespace) {
        var isCustomComponentTag;
        var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
        var domElement;
        var namespaceURI = parentNamespace;
        if (namespaceURI === HTML_NAMESPACE) {
          namespaceURI = getIntrinsicNamespace(type2);
        }
        if (namespaceURI === HTML_NAMESPACE) {
          {
            isCustomComponentTag = isCustomComponent(type2, props);
            if (!isCustomComponentTag && type2 !== type2.toLowerCase()) {
              error("<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.", type2);
            }
          }
          if (type2 === "script") {
            var div = ownerDocument.createElement("div");
            div.innerHTML = "<script><\/script>";
            var firstChild = div.firstChild;
            domElement = div.removeChild(firstChild);
          } else if (typeof props.is === "string") {
            domElement = ownerDocument.createElement(type2, {
              is: props.is
            });
          } else {
            domElement = ownerDocument.createElement(type2);
            if (type2 === "select") {
              var node2 = domElement;
              if (props.multiple) {
                node2.multiple = true;
              } else if (props.size) {
                node2.size = props.size;
              }
            }
          }
        } else {
          domElement = ownerDocument.createElementNS(namespaceURI, type2);
        }
        {
          if (namespaceURI === HTML_NAMESPACE) {
            if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === "[object HTMLUnknownElement]" && !hasOwnProperty.call(warnedUnknownTags, type2)) {
              warnedUnknownTags[type2] = true;
              error("The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.", type2);
            }
          }
        }
        return domElement;
      }
      function createTextNode(text, rootContainerElement) {
        return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
      }
      function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
        var isCustomComponentTag = isCustomComponent(tag, rawProps);
        {
          validatePropertiesInDevelopment(tag, rawProps);
        }
        var props;
        switch (tag) {
          case "dialog":
            listenToNonDelegatedEvent("cancel", domElement);
            listenToNonDelegatedEvent("close", domElement);
            props = rawProps;
            break;
          case "iframe":
          case "object":
          case "embed":
            listenToNonDelegatedEvent("load", domElement);
            props = rawProps;
            break;
          case "video":
          case "audio":
            for (var i2 = 0; i2 < mediaEventTypes.length; i2++) {
              listenToNonDelegatedEvent(mediaEventTypes[i2], domElement);
            }
            props = rawProps;
            break;
          case "source":
            listenToNonDelegatedEvent("error", domElement);
            props = rawProps;
            break;
          case "img":
          case "image":
          case "link":
            listenToNonDelegatedEvent("error", domElement);
            listenToNonDelegatedEvent("load", domElement);
            props = rawProps;
            break;
          case "details":
            listenToNonDelegatedEvent("toggle", domElement);
            props = rawProps;
            break;
          case "input":
            initWrapperState(domElement, rawProps);
            props = getHostProps(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
          case "option":
            validateProps(domElement, rawProps);
            props = rawProps;
            break;
          case "select":
            initWrapperState$1(domElement, rawProps);
            props = getHostProps$1(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
          case "textarea":
            initWrapperState$2(domElement, rawProps);
            props = getHostProps$2(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
          default:
            props = rawProps;
        }
        assertValidProps(tag, props);
        setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
        switch (tag) {
          case "input":
            track(domElement);
            postMountWrapper(domElement, rawProps, false);
            break;
          case "textarea":
            track(domElement);
            postMountWrapper$3(domElement);
            break;
          case "option":
            postMountWrapper$1(domElement, rawProps);
            break;
          case "select":
            postMountWrapper$2(domElement, rawProps);
            break;
          default:
            if (typeof props.onClick === "function") {
              trapClickOnNonInteractiveElement(domElement);
            }
            break;
        }
      }
      function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
        {
          validatePropertiesInDevelopment(tag, nextRawProps);
        }
        var updatePayload = null;
        var lastProps;
        var nextProps;
        switch (tag) {
          case "input":
            lastProps = getHostProps(domElement, lastRawProps);
            nextProps = getHostProps(domElement, nextRawProps);
            updatePayload = [];
            break;
          case "select":
            lastProps = getHostProps$1(domElement, lastRawProps);
            nextProps = getHostProps$1(domElement, nextRawProps);
            updatePayload = [];
            break;
          case "textarea":
            lastProps = getHostProps$2(domElement, lastRawProps);
            nextProps = getHostProps$2(domElement, nextRawProps);
            updatePayload = [];
            break;
          default:
            lastProps = lastRawProps;
            nextProps = nextRawProps;
            if (typeof lastProps.onClick !== "function" && typeof nextProps.onClick === "function") {
              trapClickOnNonInteractiveElement(domElement);
            }
            break;
        }
        assertValidProps(tag, nextProps);
        var propKey;
        var styleName;
        var styleUpdates = null;
        for (propKey in lastProps) {
          if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
            continue;
          }
          if (propKey === STYLE) {
            var lastStyle = lastProps[propKey];
            for (styleName in lastStyle) {
              if (lastStyle.hasOwnProperty(styleName)) {
                if (!styleUpdates) {
                  styleUpdates = {};
                }
                styleUpdates[styleName] = "";
              }
            }
          } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ;
          else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;
          else if (propKey === AUTOFOCUS) ;
          else if (registrationNameDependencies.hasOwnProperty(propKey)) {
            if (!updatePayload) {
              updatePayload = [];
            }
          } else {
            (updatePayload = updatePayload || []).push(propKey, null);
          }
        }
        for (propKey in nextProps) {
          var nextProp = nextProps[propKey];
          var lastProp = lastProps != null ? lastProps[propKey] : void 0;
          if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
            continue;
          }
          if (propKey === STYLE) {
            {
              if (nextProp) {
                Object.freeze(nextProp);
              }
            }
            if (lastProp) {
              for (styleName in lastProp) {
                if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
                  if (!styleUpdates) {
                    styleUpdates = {};
                  }
                  styleUpdates[styleName] = "";
                }
              }
              for (styleName in nextProp) {
                if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
                  if (!styleUpdates) {
                    styleUpdates = {};
                  }
                  styleUpdates[styleName] = nextProp[styleName];
                }
              }
            } else {
              if (!styleUpdates) {
                if (!updatePayload) {
                  updatePayload = [];
                }
                updatePayload.push(propKey, styleUpdates);
              }
              styleUpdates = nextProp;
            }
          } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
            var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
            var lastHtml = lastProp ? lastProp[HTML$1] : void 0;
            if (nextHtml != null) {
              if (lastHtml !== nextHtml) {
                (updatePayload = updatePayload || []).push(propKey, nextHtml);
              }
            }
          } else if (propKey === CHILDREN) {
            if (typeof nextProp === "string" || typeof nextProp === "number") {
              (updatePayload = updatePayload || []).push(propKey, "" + nextProp);
            }
          } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ;
          else if (registrationNameDependencies.hasOwnProperty(propKey)) {
            if (nextProp != null) {
              if (typeof nextProp !== "function") {
                warnForInvalidEventListener(propKey, nextProp);
              }
              if (propKey === "onScroll") {
                listenToNonDelegatedEvent("scroll", domElement);
              }
            }
            if (!updatePayload && lastProp !== nextProp) {
              updatePayload = [];
            }
          } else {
            (updatePayload = updatePayload || []).push(propKey, nextProp);
          }
        }
        if (styleUpdates) {
          {
            validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
          }
          (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
        }
        return updatePayload;
      }
      function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
        if (tag === "input" && nextRawProps.type === "radio" && nextRawProps.name != null) {
          updateChecked(domElement, nextRawProps);
        }
        var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
        var isCustomComponentTag = isCustomComponent(tag, nextRawProps);
        updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag);
        switch (tag) {
          case "input":
            updateWrapper(domElement, nextRawProps);
            break;
          case "textarea":
            updateWrapper$1(domElement, nextRawProps);
            break;
          case "select":
            postUpdateWrapper(domElement, nextRawProps);
            break;
        }
      }
      function getPossibleStandardName(propName) {
        {
          var lowerCasedName = propName.toLowerCase();
          if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
            return null;
          }
          return possibleStandardNames[lowerCasedName] || null;
        }
      }
      function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement, isConcurrentMode, shouldWarnDev) {
        var isCustomComponentTag;
        var extraAttributeNames;
        {
          isCustomComponentTag = isCustomComponent(tag, rawProps);
          validatePropertiesInDevelopment(tag, rawProps);
        }
        switch (tag) {
          case "dialog":
            listenToNonDelegatedEvent("cancel", domElement);
            listenToNonDelegatedEvent("close", domElement);
            break;
          case "iframe":
          case "object":
          case "embed":
            listenToNonDelegatedEvent("load", domElement);
            break;
          case "video":
          case "audio":
            for (var i2 = 0; i2 < mediaEventTypes.length; i2++) {
              listenToNonDelegatedEvent(mediaEventTypes[i2], domElement);
            }
            break;
          case "source":
            listenToNonDelegatedEvent("error", domElement);
            break;
          case "img":
          case "image":
          case "link":
            listenToNonDelegatedEvent("error", domElement);
            listenToNonDelegatedEvent("load", domElement);
            break;
          case "details":
            listenToNonDelegatedEvent("toggle", domElement);
            break;
          case "input":
            initWrapperState(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
          case "option":
            validateProps(domElement, rawProps);
            break;
          case "select":
            initWrapperState$1(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
          case "textarea":
            initWrapperState$2(domElement, rawProps);
            listenToNonDelegatedEvent("invalid", domElement);
            break;
        }
        assertValidProps(tag, rawProps);
        {
          extraAttributeNames = /* @__PURE__ */ new Set();
          var attributes = domElement.attributes;
          for (var _i2 = 0; _i2 < attributes.length; _i2++) {
            var name = attributes[_i2].name.toLowerCase();
            switch (name) {
              // Controlled attributes are not validated
              // TODO: Only ignore them on controlled tags.
              case "value":
                break;
              case "checked":
                break;
              case "selected":
                break;
              default:
                extraAttributeNames.add(attributes[_i2].name);
            }
          }
        }
        var updatePayload = null;
        for (var propKey in rawProps) {
          if (!rawProps.hasOwnProperty(propKey)) {
            continue;
          }
          var nextProp = rawProps[propKey];
          if (propKey === CHILDREN) {
            if (typeof nextProp === "string") {
              if (domElement.textContent !== nextProp) {
                if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
                  checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
                }
                updatePayload = [CHILDREN, nextProp];
              }
            } else if (typeof nextProp === "number") {
              if (domElement.textContent !== "" + nextProp) {
                if (rawProps[SUPPRESS_HYDRATION_WARNING] !== true) {
                  checkForUnmatchedText(domElement.textContent, nextProp, isConcurrentMode, shouldWarnDev);
                }
                updatePayload = [CHILDREN, "" + nextProp];
              }
            }
          } else if (registrationNameDependencies.hasOwnProperty(propKey)) {
            if (nextProp != null) {
              if (typeof nextProp !== "function") {
                warnForInvalidEventListener(propKey, nextProp);
              }
              if (propKey === "onScroll") {
                listenToNonDelegatedEvent("scroll", domElement);
              }
            }
          } else if (shouldWarnDev && true && // Convince Flow we've calculated it (it's DEV-only in this method.)
          typeof isCustomComponentTag === "boolean") {
            var serverValue = void 0;
            var propertyInfo = getPropertyInfo(propKey);
            if (rawProps[SUPPRESS_HYDRATION_WARNING] === true) ;
            else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
            // TODO: Only ignore them on controlled tags.
            propKey === "value" || propKey === "checked" || propKey === "selected") ;
            else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
              var serverHTML = domElement.innerHTML;
              var nextHtml = nextProp ? nextProp[HTML$1] : void 0;
              if (nextHtml != null) {
                var expectedHTML = normalizeHTML(domElement, nextHtml);
                if (expectedHTML !== serverHTML) {
                  warnForPropDifference(propKey, serverHTML, expectedHTML);
                }
              }
            } else if (propKey === STYLE) {
              extraAttributeNames.delete(propKey);
              if (canDiffStyleForHydrationWarning) {
                var expectedStyle = createDangerousStringForStyles(nextProp);
                serverValue = domElement.getAttribute("style");
                if (expectedStyle !== serverValue) {
                  warnForPropDifference(propKey, serverValue, expectedStyle);
                }
              }
            } else if (isCustomComponentTag && true) {
              extraAttributeNames.delete(propKey.toLowerCase());
              serverValue = getValueForAttribute(domElement, propKey, nextProp);
              if (nextProp !== serverValue) {
                warnForPropDifference(propKey, serverValue, nextProp);
              }
            } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
              var isMismatchDueToBadCasing = false;
              if (propertyInfo !== null) {
                extraAttributeNames.delete(propertyInfo.attributeName);
                serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
              } else {
                var ownNamespace = parentNamespace;
                if (ownNamespace === HTML_NAMESPACE) {
                  ownNamespace = getIntrinsicNamespace(tag);
                }
                if (ownNamespace === HTML_NAMESPACE) {
                  extraAttributeNames.delete(propKey.toLowerCase());
                } else {
                  var standardName = getPossibleStandardName(propKey);
                  if (standardName !== null && standardName !== propKey) {
                    isMismatchDueToBadCasing = true;
                    extraAttributeNames.delete(standardName);
                  }
                  extraAttributeNames.delete(propKey);
                }
                serverValue = getValueForAttribute(domElement, propKey, nextProp);
              }
              var dontWarnCustomElement = enableCustomElementPropertySupport;
              if (!dontWarnCustomElement && nextProp !== serverValue && !isMismatchDueToBadCasing) {
                warnForPropDifference(propKey, serverValue, nextProp);
              }
            }
          }
        }
        {
          if (shouldWarnDev) {
            if (
              // $FlowFixMe - Should be inferred as not undefined.
              extraAttributeNames.size > 0 && rawProps[SUPPRESS_HYDRATION_WARNING] !== true
            ) {
              warnForExtraAttributes(extraAttributeNames);
            }
          }
        }
        switch (tag) {
          case "input":
            track(domElement);
            postMountWrapper(domElement, rawProps, true);
            break;
          case "textarea":
            track(domElement);
            postMountWrapper$3(domElement);
            break;
          case "select":
          case "option":
            break;
          default:
            if (typeof rawProps.onClick === "function") {
              trapClickOnNonInteractiveElement(domElement);
            }
            break;
        }
        return updatePayload;
      }
      function diffHydratedText(textNode, text, isConcurrentMode) {
        var isDifferent = textNode.nodeValue !== text;
        return isDifferent;
      }
      function warnForDeletedHydratableElement(parentNode, child) {
        {
          if (didWarnInvalidHydration) {
            return;
          }
          didWarnInvalidHydration = true;
          error("Did not expect server HTML to contain a <%s> in <%s>.", child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
        }
      }
      function warnForDeletedHydratableText(parentNode, child) {
        {
          if (didWarnInvalidHydration) {
            return;
          }
          didWarnInvalidHydration = true;
          error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
        }
      }
      function warnForInsertedHydratedElement(parentNode, tag, props) {
        {
          if (didWarnInvalidHydration) {
            return;
          }
          didWarnInvalidHydration = true;
          error("Expected server HTML to contain a matching <%s> in <%s>.", tag, parentNode.nodeName.toLowerCase());
        }
      }
      function warnForInsertedHydratedText(parentNode, text) {
        {
          if (text === "") {
            return;
          }
          if (didWarnInvalidHydration) {
            return;
          }
          didWarnInvalidHydration = true;
          error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
        }
      }
      function restoreControlledState$3(domElement, tag, props) {
        switch (tag) {
          case "input":
            restoreControlledState(domElement, props);
            return;
          case "textarea":
            restoreControlledState$2(domElement, props);
            return;
          case "select":
            restoreControlledState$1(domElement, props);
            return;
        }
      }
      var validateDOMNesting = function() {
      };
      var updatedAncestorInfo = function() {
      };
      {
        var specialTags = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "menu", "menuitem", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp"];
        var inScopeTags = [
          "applet",
          "caption",
          "html",
          "table",
          "td",
          "th",
          "marquee",
          "object",
          "template",
          // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
          // TODO: Distinguish by namespace here -- for <title>, including it here
          // errs on the side of fewer warnings
          "foreignObject",
          "desc",
          "title"
        ];
        var buttonScopeTags = inScopeTags.concat(["button"]);
        var impliedEndTags = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"];
        var emptyAncestorInfo = {
          current: null,
          formTag: null,
          aTagInScope: null,
          buttonTagInScope: null,
          nobrTagInScope: null,
          pTagInButtonScope: null,
          listItemTagAutoclosing: null,
          dlItemTagAutoclosing: null
        };
        updatedAncestorInfo = function(oldInfo, tag) {
          var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
          var info = {
            tag
          };
          if (inScopeTags.indexOf(tag) !== -1) {
            ancestorInfo.aTagInScope = null;
            ancestorInfo.buttonTagInScope = null;
            ancestorInfo.nobrTagInScope = null;
          }
          if (buttonScopeTags.indexOf(tag) !== -1) {
            ancestorInfo.pTagInButtonScope = null;
          }
          if (specialTags.indexOf(tag) !== -1 && tag !== "address" && tag !== "div" && tag !== "p") {
            ancestorInfo.listItemTagAutoclosing = null;
            ancestorInfo.dlItemTagAutoclosing = null;
          }
          ancestorInfo.current = info;
          if (tag === "form") {
            ancestorInfo.formTag = info;
          }
          if (tag === "a") {
            ancestorInfo.aTagInScope = info;
          }
          if (tag === "button") {
            ancestorInfo.buttonTagInScope = info;
          }
          if (tag === "nobr") {
            ancestorInfo.nobrTagInScope = info;
          }
          if (tag === "p") {
            ancestorInfo.pTagInButtonScope = info;
          }
          if (tag === "li") {
            ancestorInfo.listItemTagAutoclosing = info;
          }
          if (tag === "dd" || tag === "dt") {
            ancestorInfo.dlItemTagAutoclosing = info;
          }
          return ancestorInfo;
        };
        var isTagValidWithParent = function(tag, parentTag) {
          switch (parentTag) {
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
            case "select":
              return tag === "option" || tag === "optgroup" || tag === "#text";
            case "optgroup":
              return tag === "option" || tag === "#text";
            // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
            // but
            case "option":
              return tag === "#text";
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
            // No special behavior since these rules fall back to "in body" mode for
            // all except special table nodes which cause bad parsing behavior anyway.
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
            case "tr":
              return tag === "th" || tag === "td" || tag === "style" || tag === "script" || tag === "template";
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
            case "tbody":
            case "thead":
            case "tfoot":
              return tag === "tr" || tag === "style" || tag === "script" || tag === "template";
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
            case "colgroup":
              return tag === "col" || tag === "template";
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
            case "table":
              return tag === "caption" || tag === "colgroup" || tag === "tbody" || tag === "tfoot" || tag === "thead" || tag === "style" || tag === "script" || tag === "template";
            // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
            case "head":
              return tag === "base" || tag === "basefont" || tag === "bgsound" || tag === "link" || tag === "meta" || tag === "title" || tag === "noscript" || tag === "noframes" || tag === "style" || tag === "script" || tag === "template";
            // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
            case "html":
              return tag === "head" || tag === "body" || tag === "frameset";
            case "frameset":
              return tag === "frame";
            case "#document":
              return tag === "html";
          }
          switch (tag) {
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
              return parentTag !== "h1" && parentTag !== "h2" && parentTag !== "h3" && parentTag !== "h4" && parentTag !== "h5" && parentTag !== "h6";
            case "rp":
            case "rt":
              return impliedEndTags.indexOf(parentTag) === -1;
            case "body":
            case "caption":
            case "col":
            case "colgroup":
            case "frameset":
            case "frame":
            case "head":
            case "html":
            case "tbody":
            case "td":
            case "tfoot":
            case "th":
            case "thead":
            case "tr":
              return parentTag == null;
          }
          return true;
        };
        var findInvalidAncestorForTag = function(tag, ancestorInfo) {
          switch (tag) {
            case "address":
            case "article":
            case "aside":
            case "blockquote":
            case "center":
            case "details":
            case "dialog":
            case "dir":
            case "div":
            case "dl":
            case "fieldset":
            case "figcaption":
            case "figure":
            case "footer":
            case "header":
            case "hgroup":
            case "main":
            case "menu":
            case "nav":
            case "ol":
            case "p":
            case "section":
            case "summary":
            case "ul":
            case "pre":
            case "listing":
            case "table":
            case "hr":
            case "xmp":
            case "h1":
            case "h2":
            case "h3":
            case "h4":
            case "h5":
            case "h6":
              return ancestorInfo.pTagInButtonScope;
            case "form":
              return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
            case "li":
              return ancestorInfo.listItemTagAutoclosing;
            case "dd":
            case "dt":
              return ancestorInfo.dlItemTagAutoclosing;
            case "button":
              return ancestorInfo.buttonTagInScope;
            case "a":
              return ancestorInfo.aTagInScope;
            case "nobr":
              return ancestorInfo.nobrTagInScope;
          }
          return null;
        };
        var didWarn$1 = {};
        validateDOMNesting = function(childTag, childText, ancestorInfo) {
          ancestorInfo = ancestorInfo || emptyAncestorInfo;
          var parentInfo = ancestorInfo.current;
          var parentTag = parentInfo && parentInfo.tag;
          if (childText != null) {
            if (childTag != null) {
              error("validateDOMNesting: when childText is passed, childTag should be null");
            }
            childTag = "#text";
          }
          var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
          var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
          var invalidParentOrAncestor = invalidParent || invalidAncestor;
          if (!invalidParentOrAncestor) {
            return;
          }
          var ancestorTag = invalidParentOrAncestor.tag;
          var warnKey = !!invalidParent + "|" + childTag + "|" + ancestorTag;
          if (didWarn$1[warnKey]) {
            return;
          }
          didWarn$1[warnKey] = true;
          var tagDisplayName = childTag;
          var whitespaceInfo = "";
          if (childTag === "#text") {
            if (/\S/.test(childText)) {
              tagDisplayName = "Text nodes";
            } else {
              tagDisplayName = "Whitespace text nodes";
              whitespaceInfo = " Make sure you don't have any extra whitespace between tags on each line of your source code.";
            }
          } else {
            tagDisplayName = "<" + childTag + ">";
          }
          if (invalidParent) {
            var info = "";
            if (ancestorTag === "table" && childTag === "tr") {
              info += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser.";
            }
            error("validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s", tagDisplayName, ancestorTag, whitespaceInfo, info);
          } else {
            error("validateDOMNesting(...): %s cannot appear as a descendant of <%s>.", tagDisplayName, ancestorTag);
          }
        };
      }
      var SUPPRESS_HYDRATION_WARNING$1 = "suppressHydrationWarning";
      var SUSPENSE_START_DATA = "$";
      var SUSPENSE_END_DATA = "/$";
      var SUSPENSE_PENDING_START_DATA = "$?";
      var SUSPENSE_FALLBACK_START_DATA = "$!";
      var STYLE$1 = "style";
      var eventsEnabled = null;
      var selectionInformation = null;
      function getRootHostContext(rootContainerInstance) {
        var type2;
        var namespace;
        var nodeType = rootContainerInstance.nodeType;
        switch (nodeType) {
          case DOCUMENT_NODE:
          case DOCUMENT_FRAGMENT_NODE: {
            type2 = nodeType === DOCUMENT_NODE ? "#document" : "#fragment";
            var root2 = rootContainerInstance.documentElement;
            namespace = root2 ? root2.namespaceURI : getChildNamespace(null, "");
            break;
          }
          default: {
            var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
            var ownNamespace = container.namespaceURI || null;
            type2 = container.tagName;
            namespace = getChildNamespace(ownNamespace, type2);
            break;
          }
        }
        {
          var validatedTag = type2.toLowerCase();
          var ancestorInfo = updatedAncestorInfo(null, validatedTag);
          return {
            namespace,
            ancestorInfo
          };
        }
      }
      function getChildHostContext(parentHostContext, type2, rootContainerInstance) {
        {
          var parentHostContextDev = parentHostContext;
          var namespace = getChildNamespace(parentHostContextDev.namespace, type2);
          var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type2);
          return {
            namespace,
            ancestorInfo
          };
        }
      }
      function getPublicInstance(instance2) {
        return instance2;
      }
      function prepareForCommit(containerInfo) {
        eventsEnabled = isEnabled();
        selectionInformation = getSelectionInformation();
        var activeInstance = null;
        setEnabled(false);
        return activeInstance;
      }
      function resetAfterCommit(containerInfo) {
        restoreSelection(selectionInformation);
        setEnabled(eventsEnabled);
        eventsEnabled = null;
        selectionInformation = null;
      }
      function createInstance(type2, props, rootContainerInstance, hostContext, internalInstanceHandle) {
        var parentNamespace;
        {
          var hostContextDev = hostContext;
          validateDOMNesting(type2, null, hostContextDev.ancestorInfo);
          if (typeof props.children === "string" || typeof props.children === "number") {
            var string = "" + props.children;
            var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type2);
            validateDOMNesting(null, string, ownAncestorInfo);
          }
          parentNamespace = hostContextDev.namespace;
        }
        var domElement = createElement(type2, props, rootContainerInstance, parentNamespace);
        precacheFiberNode(internalInstanceHandle, domElement);
        updateFiberProps(domElement, props);
        return domElement;
      }
      function appendInitialChild(parentInstance, child) {
        parentInstance.appendChild(child);
      }
      function finalizeInitialChildren(domElement, type2, props, rootContainerInstance, hostContext) {
        setInitialProperties(domElement, type2, props, rootContainerInstance);
        switch (type2) {
          case "button":
          case "input":
          case "select":
          case "textarea":
            return !!props.autoFocus;
          case "img":
            return true;
          default:
            return false;
        }
      }
      function prepareUpdate(domElement, type2, oldProps, newProps, rootContainerInstance, hostContext) {
        {
          var hostContextDev = hostContext;
          if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === "string" || typeof newProps.children === "number")) {
            var string = "" + newProps.children;
            var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type2);
            validateDOMNesting(null, string, ownAncestorInfo);
          }
        }
        return diffProperties(domElement, type2, oldProps, newProps);
      }
      function shouldSetTextContent(type2, props) {
        return type2 === "textarea" || type2 === "noscript" || typeof props.children === "string" || typeof props.children === "number" || typeof props.dangerouslySetInnerHTML === "object" && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
      }
      function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
        {
          var hostContextDev = hostContext;
          validateDOMNesting(null, text, hostContextDev.ancestorInfo);
        }
        var textNode = createTextNode(text, rootContainerInstance);
        precacheFiberNode(internalInstanceHandle, textNode);
        return textNode;
      }
      function getCurrentEventPriority() {
        var currentEvent = window.event;
        if (currentEvent === void 0) {
          return DefaultEventPriority;
        }
        return getEventPriority(currentEvent.type);
      }
      var scheduleTimeout = typeof setTimeout === "function" ? setTimeout : void 0;
      var cancelTimeout = typeof clearTimeout === "function" ? clearTimeout : void 0;
      var noTimeout = -1;
      var localPromise = typeof Promise === "function" ? Promise : void 0;
      var scheduleMicrotask = typeof queueMicrotask === "function" ? queueMicrotask : typeof localPromise !== "undefined" ? function(callback) {
        return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
      } : scheduleTimeout;
      function handleErrorInNextTick(error2) {
        setTimeout(function() {
          throw error2;
        });
      }
      function commitMount(domElement, type2, newProps, internalInstanceHandle) {
        switch (type2) {
          case "button":
          case "input":
          case "select":
          case "textarea":
            if (newProps.autoFocus) {
              domElement.focus();
            }
            return;
          case "img": {
            if (newProps.src) {
              domElement.src = newProps.src;
            }
            return;
          }
        }
      }
      function commitUpdate(domElement, updatePayload, type2, oldProps, newProps, internalInstanceHandle) {
        updateProperties(domElement, updatePayload, type2, oldProps, newProps);
        updateFiberProps(domElement, newProps);
      }
      function resetTextContent(domElement) {
        setTextContent(domElement, "");
      }
      function commitTextUpdate(textInstance, oldText, newText) {
        textInstance.nodeValue = newText;
      }
      function appendChild(parentInstance, child) {
        parentInstance.appendChild(child);
      }
      function appendChildToContainer(container, child) {
        var parentNode;
        if (container.nodeType === COMMENT_NODE) {
          parentNode = container.parentNode;
          parentNode.insertBefore(child, container);
        } else {
          parentNode = container;
          parentNode.appendChild(child);
        }
        var reactRootContainer = container._reactRootContainer;
        if ((reactRootContainer === null || reactRootContainer === void 0) && parentNode.onclick === null) {
          trapClickOnNonInteractiveElement(parentNode);
        }
      }
      function insertBefore(parentInstance, child, beforeChild) {
        parentInstance.insertBefore(child, beforeChild);
      }
      function insertInContainerBefore(container, child, beforeChild) {
        if (container.nodeType === COMMENT_NODE) {
          container.parentNode.insertBefore(child, beforeChild);
        } else {
          container.insertBefore(child, beforeChild);
        }
      }
      function removeChild(parentInstance, child) {
        parentInstance.removeChild(child);
      }
      function removeChildFromContainer(container, child) {
        if (container.nodeType === COMMENT_NODE) {
          container.parentNode.removeChild(child);
        } else {
          container.removeChild(child);
        }
      }
      function clearSuspenseBoundary(parentInstance, suspenseInstance) {
        var node2 = suspenseInstance;
        var depth = 0;
        do {
          var nextNode = node2.nextSibling;
          parentInstance.removeChild(node2);
          if (nextNode && nextNode.nodeType === COMMENT_NODE) {
            var data2 = nextNode.data;
            if (data2 === SUSPENSE_END_DATA) {
              if (depth === 0) {
                parentInstance.removeChild(nextNode);
                retryIfBlockedOn(suspenseInstance);
                return;
              } else {
                depth--;
              }
            } else if (data2 === SUSPENSE_START_DATA || data2 === SUSPENSE_PENDING_START_DATA || data2 === SUSPENSE_FALLBACK_START_DATA) {
              depth++;
            }
          }
          node2 = nextNode;
        } while (node2);
        retryIfBlockedOn(suspenseInstance);
      }
      function clearSuspenseBoundaryFromContainer(container, suspenseInstance) {
        if (container.nodeType === COMMENT_NODE) {
          clearSuspenseBoundary(container.parentNode, suspenseInstance);
        } else if (container.nodeType === ELEMENT_NODE) {
          clearSuspenseBoundary(container, suspenseInstance);
        }
        retryIfBlockedOn(container);
      }
      function hideInstance(instance2) {
        instance2 = instance2;
        var style2 = instance2.style;
        if (typeof style2.setProperty === "function") {
          style2.setProperty("display", "none", "important");
        } else {
          style2.display = "none";
        }
      }
      function hideTextInstance(textInstance) {
        textInstance.nodeValue = "";
      }
      function unhideInstance(instance2, props) {
        instance2 = instance2;
        var styleProp = props[STYLE$1];
        var display = styleProp !== void 0 && styleProp !== null && styleProp.hasOwnProperty("display") ? styleProp.display : null;
        instance2.style.display = dangerousStyleValue("display", display);
      }
      function unhideTextInstance(textInstance, text) {
        textInstance.nodeValue = text;
      }
      function clearContainer(container) {
        if (container.nodeType === ELEMENT_NODE) {
          container.textContent = "";
        } else if (container.nodeType === DOCUMENT_NODE) {
          if (container.documentElement) {
            container.removeChild(container.documentElement);
          }
        }
      }
      function canHydrateInstance(instance2, type2, props) {
        if (instance2.nodeType !== ELEMENT_NODE || type2.toLowerCase() !== instance2.nodeName.toLowerCase()) {
          return null;
        }
        return instance2;
      }
      function canHydrateTextInstance(instance2, text) {
        if (text === "" || instance2.nodeType !== TEXT_NODE) {
          return null;
        }
        return instance2;
      }
      function canHydrateSuspenseInstance(instance2) {
        if (instance2.nodeType !== COMMENT_NODE) {
          return null;
        }
        return instance2;
      }
      function isSuspenseInstancePending(instance2) {
        return instance2.data === SUSPENSE_PENDING_START_DATA;
      }
      function isSuspenseInstanceFallback(instance2) {
        return instance2.data === SUSPENSE_FALLBACK_START_DATA;
      }
      function getSuspenseInstanceFallbackErrorDetails(instance2) {
        var dataset = instance2.nextSibling && instance2.nextSibling.dataset;
        var digest, message, stack;
        if (dataset) {
          digest = dataset.dgst;
          {
            message = dataset.msg;
            stack = dataset.stck;
          }
        }
        {
          return {
            message,
            digest,
            stack
          };
        }
      }
      function registerSuspenseInstanceRetry(instance2, callback) {
        instance2._reactRetry = callback;
      }
      function getNextHydratable(node2) {
        for (; node2 != null; node2 = node2.nextSibling) {
          var nodeType = node2.nodeType;
          if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
            break;
          }
          if (nodeType === COMMENT_NODE) {
            var nodeData = node2.data;
            if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) {
              break;
            }
            if (nodeData === SUSPENSE_END_DATA) {
              return null;
            }
          }
        }
        return node2;
      }
      function getNextHydratableSibling(instance2) {
        return getNextHydratable(instance2.nextSibling);
      }
      function getFirstHydratableChild(parentInstance) {
        return getNextHydratable(parentInstance.firstChild);
      }
      function getFirstHydratableChildWithinContainer(parentContainer) {
        return getNextHydratable(parentContainer.firstChild);
      }
      function getFirstHydratableChildWithinSuspenseInstance(parentInstance) {
        return getNextHydratable(parentInstance.nextSibling);
      }
      function hydrateInstance(instance2, type2, props, rootContainerInstance, hostContext, internalInstanceHandle, shouldWarnDev) {
        precacheFiberNode(internalInstanceHandle, instance2);
        updateFiberProps(instance2, props);
        var parentNamespace;
        {
          var hostContextDev = hostContext;
          parentNamespace = hostContextDev.namespace;
        }
        var isConcurrentMode = (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
        return diffHydratedProperties(instance2, type2, props, parentNamespace, rootContainerInstance, isConcurrentMode, shouldWarnDev);
      }
      function hydrateTextInstance(textInstance, text, internalInstanceHandle, shouldWarnDev) {
        precacheFiberNode(internalInstanceHandle, textInstance);
        (internalInstanceHandle.mode & ConcurrentMode) !== NoMode;
        return diffHydratedText(textInstance, text);
      }
      function hydrateSuspenseInstance(suspenseInstance, internalInstanceHandle) {
        precacheFiberNode(internalInstanceHandle, suspenseInstance);
      }
      function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
        var node2 = suspenseInstance.nextSibling;
        var depth = 0;
        while (node2) {
          if (node2.nodeType === COMMENT_NODE) {
            var data2 = node2.data;
            if (data2 === SUSPENSE_END_DATA) {
              if (depth === 0) {
                return getNextHydratableSibling(node2);
              } else {
                depth--;
              }
            } else if (data2 === SUSPENSE_START_DATA || data2 === SUSPENSE_FALLBACK_START_DATA || data2 === SUSPENSE_PENDING_START_DATA) {
              depth++;
            }
          }
          node2 = node2.nextSibling;
        }
        return null;
      }
      function getParentSuspenseInstance(targetInstance) {
        var node2 = targetInstance.previousSibling;
        var depth = 0;
        while (node2) {
          if (node2.nodeType === COMMENT_NODE) {
            var data2 = node2.data;
            if (data2 === SUSPENSE_START_DATA || data2 === SUSPENSE_FALLBACK_START_DATA || data2 === SUSPENSE_PENDING_START_DATA) {
              if (depth === 0) {
                return node2;
              } else {
                depth--;
              }
            } else if (data2 === SUSPENSE_END_DATA) {
              depth++;
            }
          }
          node2 = node2.previousSibling;
        }
        return null;
      }
      function commitHydratedContainer(container) {
        retryIfBlockedOn(container);
      }
      function commitHydratedSuspenseInstance(suspenseInstance) {
        retryIfBlockedOn(suspenseInstance);
      }
      function shouldDeleteUnhydratedTailInstances(parentType) {
        return parentType !== "head" && parentType !== "body";
      }
      function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text, isConcurrentMode) {
        var shouldWarnDev = true;
        checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
      }
      function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text, isConcurrentMode) {
        if (parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
          var shouldWarnDev = true;
          checkForUnmatchedText(textInstance.nodeValue, text, isConcurrentMode, shouldWarnDev);
        }
      }
      function didNotHydrateInstanceWithinContainer(parentContainer, instance2) {
        {
          if (instance2.nodeType === ELEMENT_NODE) {
            warnForDeletedHydratableElement(parentContainer, instance2);
          } else if (instance2.nodeType === COMMENT_NODE) ;
          else {
            warnForDeletedHydratableText(parentContainer, instance2);
          }
        }
      }
      function didNotHydrateInstanceWithinSuspenseInstance(parentInstance, instance2) {
        {
          var parentNode = parentInstance.parentNode;
          if (parentNode !== null) {
            if (instance2.nodeType === ELEMENT_NODE) {
              warnForDeletedHydratableElement(parentNode, instance2);
            } else if (instance2.nodeType === COMMENT_NODE) ;
            else {
              warnForDeletedHydratableText(parentNode, instance2);
            }
          }
        }
      }
      function didNotHydrateInstance(parentType, parentProps, parentInstance, instance2, isConcurrentMode) {
        {
          if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
            if (instance2.nodeType === ELEMENT_NODE) {
              warnForDeletedHydratableElement(parentInstance, instance2);
            } else if (instance2.nodeType === COMMENT_NODE) ;
            else {
              warnForDeletedHydratableText(parentInstance, instance2);
            }
          }
        }
      }
      function didNotFindHydratableInstanceWithinContainer(parentContainer, type2, props) {
        {
          warnForInsertedHydratedElement(parentContainer, type2);
        }
      }
      function didNotFindHydratableTextInstanceWithinContainer(parentContainer, text) {
        {
          warnForInsertedHydratedText(parentContainer, text);
        }
      }
      function didNotFindHydratableInstanceWithinSuspenseInstance(parentInstance, type2, props) {
        {
          var parentNode = parentInstance.parentNode;
          if (parentNode !== null) warnForInsertedHydratedElement(parentNode, type2);
        }
      }
      function didNotFindHydratableTextInstanceWithinSuspenseInstance(parentInstance, text) {
        {
          var parentNode = parentInstance.parentNode;
          if (parentNode !== null) warnForInsertedHydratedText(parentNode, text);
        }
      }
      function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type2, props, isConcurrentMode) {
        {
          if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
            warnForInsertedHydratedElement(parentInstance, type2);
          }
        }
      }
      function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text, isConcurrentMode) {
        {
          if (isConcurrentMode || parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
            warnForInsertedHydratedText(parentInstance, text);
          }
        }
      }
      function errorHydratingContainer(parentContainer) {
        {
          error("An error occurred during hydration. The server HTML was replaced with client content in <%s>.", parentContainer.nodeName.toLowerCase());
        }
      }
      function preparePortalMount(portalInstance) {
        listenToAllSupportedEvents(portalInstance);
      }
      var randomKey = Math.random().toString(36).slice(2);
      var internalInstanceKey = "__reactFiber$" + randomKey;
      var internalPropsKey = "__reactProps$" + randomKey;
      var internalContainerInstanceKey = "__reactContainer$" + randomKey;
      var internalEventHandlersKey = "__reactEvents$" + randomKey;
      var internalEventHandlerListenersKey = "__reactListeners$" + randomKey;
      var internalEventHandlesSetKey = "__reactHandles$" + randomKey;
      function detachDeletedInstance(node2) {
        delete node2[internalInstanceKey];
        delete node2[internalPropsKey];
        delete node2[internalEventHandlersKey];
        delete node2[internalEventHandlerListenersKey];
        delete node2[internalEventHandlesSetKey];
      }
      function precacheFiberNode(hostInst, node2) {
        node2[internalInstanceKey] = hostInst;
      }
      function markContainerAsRoot(hostRoot, node2) {
        node2[internalContainerInstanceKey] = hostRoot;
      }
      function unmarkContainerAsRoot(node2) {
        node2[internalContainerInstanceKey] = null;
      }
      function isContainerMarkedAsRoot(node2) {
        return !!node2[internalContainerInstanceKey];
      }
      function getClosestInstanceFromNode(targetNode) {
        var targetInst = targetNode[internalInstanceKey];
        if (targetInst) {
          return targetInst;
        }
        var parentNode = targetNode.parentNode;
        while (parentNode) {
          targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
          if (targetInst) {
            var alternate = targetInst.alternate;
            if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
              var suspenseInstance = getParentSuspenseInstance(targetNode);
              while (suspenseInstance !== null) {
                var targetSuspenseInst = suspenseInstance[internalInstanceKey];
                if (targetSuspenseInst) {
                  return targetSuspenseInst;
                }
                suspenseInstance = getParentSuspenseInstance(suspenseInstance);
              }
            }
            return targetInst;
          }
          targetNode = parentNode;
          parentNode = targetNode.parentNode;
        }
        return null;
      }
      function getInstanceFromNode(node2) {
        var inst = node2[internalInstanceKey] || node2[internalContainerInstanceKey];
        if (inst) {
          if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
            return inst;
          } else {
            return null;
          }
        }
        return null;
      }
      function getNodeFromInstance(inst) {
        if (inst.tag === HostComponent || inst.tag === HostText) {
          return inst.stateNode;
        }
        throw new Error("getNodeFromInstance: Invalid argument.");
      }
      function getFiberCurrentPropsFromNode(node2) {
        return node2[internalPropsKey] || null;
      }
      function updateFiberProps(node2, props) {
        node2[internalPropsKey] = props;
      }
      function getEventListenerSet(node2) {
        var elementListenerSet = node2[internalEventHandlersKey];
        if (elementListenerSet === void 0) {
          elementListenerSet = node2[internalEventHandlersKey] = /* @__PURE__ */ new Set();
        }
        return elementListenerSet;
      }
      var loggedTypeFailures = {};
      var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame$1.setExtraStackFrame(null);
          }
        }
      }
      function checkPropTypes(typeSpecs, values, location, componentName, element) {
        {
          var has2 = Function.call.bind(hasOwnProperty);
          for (var typeSpecName in typeSpecs) {
            if (has2(typeSpecs, typeSpecName)) {
              var error$1 = void 0;
              try {
                if (typeof typeSpecs[typeSpecName] !== "function") {
                  var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                  err.name = "Invariant Violation";
                  throw err;
                }
                error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
              } catch (ex) {
                error$1 = ex;
              }
              if (error$1 && !(error$1 instanceof Error)) {
                setCurrentlyValidatingElement(element);
                error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
                setCurrentlyValidatingElement(null);
              }
              if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                loggedTypeFailures[error$1.message] = true;
                setCurrentlyValidatingElement(element);
                error("Failed %s type: %s", location, error$1.message);
                setCurrentlyValidatingElement(null);
              }
            }
          }
        }
      }
      var valueStack = [];
      var fiberStack;
      {
        fiberStack = [];
      }
      var index2 = -1;
      function createCursor(defaultValue) {
        return {
          current: defaultValue
        };
      }
      function pop(cursor, fiber) {
        if (index2 < 0) {
          {
            error("Unexpected pop.");
          }
          return;
        }
        {
          if (fiber !== fiberStack[index2]) {
            error("Unexpected Fiber popped.");
          }
        }
        cursor.current = valueStack[index2];
        valueStack[index2] = null;
        {
          fiberStack[index2] = null;
        }
        index2--;
      }
      function push(cursor, value, fiber) {
        index2++;
        valueStack[index2] = cursor.current;
        {
          fiberStack[index2] = fiber;
        }
        cursor.current = value;
      }
      var warnedAboutMissingGetChildContext;
      {
        warnedAboutMissingGetChildContext = {};
      }
      var emptyContextObject = {};
      {
        Object.freeze(emptyContextObject);
      }
      var contextStackCursor = createCursor(emptyContextObject);
      var didPerformWorkStackCursor = createCursor(false);
      var previousContext = emptyContextObject;
      function getUnmaskedContext(workInProgress2, Component, didPushOwnContextIfProvider) {
        {
          if (didPushOwnContextIfProvider && isContextProvider(Component)) {
            return previousContext;
          }
          return contextStackCursor.current;
        }
      }
      function cacheContext(workInProgress2, unmaskedContext, maskedContext) {
        {
          var instance2 = workInProgress2.stateNode;
          instance2.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
          instance2.__reactInternalMemoizedMaskedChildContext = maskedContext;
        }
      }
      function getMaskedContext(workInProgress2, unmaskedContext) {
        {
          var type2 = workInProgress2.type;
          var contextTypes = type2.contextTypes;
          if (!contextTypes) {
            return emptyContextObject;
          }
          var instance2 = workInProgress2.stateNode;
          if (instance2 && instance2.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
            return instance2.__reactInternalMemoizedMaskedChildContext;
          }
          var context = {};
          for (var key2 in contextTypes) {
            context[key2] = unmaskedContext[key2];
          }
          {
            var name = getComponentNameFromFiber(workInProgress2) || "Unknown";
            checkPropTypes(contextTypes, context, "context", name);
          }
          if (instance2) {
            cacheContext(workInProgress2, unmaskedContext, context);
          }
          return context;
        }
      }
      function hasContextChanged() {
        {
          return didPerformWorkStackCursor.current;
        }
      }
      function isContextProvider(type2) {
        {
          var childContextTypes = type2.childContextTypes;
          return childContextTypes !== null && childContextTypes !== void 0;
        }
      }
      function popContext(fiber) {
        {
          pop(didPerformWorkStackCursor, fiber);
          pop(contextStackCursor, fiber);
        }
      }
      function popTopLevelContextObject(fiber) {
        {
          pop(didPerformWorkStackCursor, fiber);
          pop(contextStackCursor, fiber);
        }
      }
      function pushTopLevelContextObject(fiber, context, didChange) {
        {
          if (contextStackCursor.current !== emptyContextObject) {
            throw new Error("Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.");
          }
          push(contextStackCursor, context, fiber);
          push(didPerformWorkStackCursor, didChange, fiber);
        }
      }
      function processChildContext(fiber, type2, parentContext) {
        {
          var instance2 = fiber.stateNode;
          var childContextTypes = type2.childContextTypes;
          if (typeof instance2.getChildContext !== "function") {
            {
              var componentName = getComponentNameFromFiber(fiber) || "Unknown";
              if (!warnedAboutMissingGetChildContext[componentName]) {
                warnedAboutMissingGetChildContext[componentName] = true;
                error("%s.childContextTypes is specified but there is no getChildContext() method on the instance. You can either define getChildContext() on %s or remove childContextTypes from it.", componentName, componentName);
              }
            }
            return parentContext;
          }
          var childContext = instance2.getChildContext();
          for (var contextKey in childContext) {
            if (!(contextKey in childContextTypes)) {
              throw new Error((getComponentNameFromFiber(fiber) || "Unknown") + '.getChildContext(): key "' + contextKey + '" is not defined in childContextTypes.');
            }
          }
          {
            var name = getComponentNameFromFiber(fiber) || "Unknown";
            checkPropTypes(childContextTypes, childContext, "child context", name);
          }
          return assign({}, parentContext, childContext);
        }
      }
      function pushContextProvider(workInProgress2) {
        {
          var instance2 = workInProgress2.stateNode;
          var memoizedMergedChildContext = instance2 && instance2.__reactInternalMemoizedMergedChildContext || emptyContextObject;
          previousContext = contextStackCursor.current;
          push(contextStackCursor, memoizedMergedChildContext, workInProgress2);
          push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress2);
          return true;
        }
      }
      function invalidateContextProvider(workInProgress2, type2, didChange) {
        {
          var instance2 = workInProgress2.stateNode;
          if (!instance2) {
            throw new Error("Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.");
          }
          if (didChange) {
            var mergedContext = processChildContext(workInProgress2, type2, previousContext);
            instance2.__reactInternalMemoizedMergedChildContext = mergedContext;
            pop(didPerformWorkStackCursor, workInProgress2);
            pop(contextStackCursor, workInProgress2);
            push(contextStackCursor, mergedContext, workInProgress2);
            push(didPerformWorkStackCursor, didChange, workInProgress2);
          } else {
            pop(didPerformWorkStackCursor, workInProgress2);
            push(didPerformWorkStackCursor, didChange, workInProgress2);
          }
        }
      }
      function findCurrentUnmaskedContext(fiber) {
        {
          if (!isFiberMounted(fiber) || fiber.tag !== ClassComponent) {
            throw new Error("Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.");
          }
          var node2 = fiber;
          do {
            switch (node2.tag) {
              case HostRoot:
                return node2.stateNode.context;
              case ClassComponent: {
                var Component = node2.type;
                if (isContextProvider(Component)) {
                  return node2.stateNode.__reactInternalMemoizedMergedChildContext;
                }
                break;
              }
            }
            node2 = node2.return;
          } while (node2 !== null);
          throw new Error("Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
      var LegacyRoot = 0;
      var ConcurrentRoot = 1;
      var syncQueue = null;
      var includesLegacySyncCallbacks = false;
      var isFlushingSyncQueue = false;
      function scheduleSyncCallback(callback) {
        if (syncQueue === null) {
          syncQueue = [callback];
        } else {
          syncQueue.push(callback);
        }
      }
      function scheduleLegacySyncCallback(callback) {
        includesLegacySyncCallbacks = true;
        scheduleSyncCallback(callback);
      }
      function flushSyncCallbacksOnlyInLegacyMode() {
        if (includesLegacySyncCallbacks) {
          flushSyncCallbacks();
        }
      }
      function flushSyncCallbacks() {
        if (!isFlushingSyncQueue && syncQueue !== null) {
          isFlushingSyncQueue = true;
          var i2 = 0;
          var previousUpdatePriority = getCurrentUpdatePriority();
          try {
            var isSync = true;
            var queue = syncQueue;
            setCurrentUpdatePriority(DiscreteEventPriority);
            for (; i2 < queue.length; i2++) {
              var callback = queue[i2];
              do {
                callback = callback(isSync);
              } while (callback !== null);
            }
            syncQueue = null;
            includesLegacySyncCallbacks = false;
          } catch (error2) {
            if (syncQueue !== null) {
              syncQueue = syncQueue.slice(i2 + 1);
            }
            scheduleCallback(ImmediatePriority, flushSyncCallbacks);
            throw error2;
          } finally {
            setCurrentUpdatePriority(previousUpdatePriority);
            isFlushingSyncQueue = false;
          }
        }
        return null;
      }
      var forkStack = [];
      var forkStackIndex = 0;
      var treeForkProvider = null;
      var treeForkCount = 0;
      var idStack = [];
      var idStackIndex = 0;
      var treeContextProvider = null;
      var treeContextId = 1;
      var treeContextOverflow = "";
      function isForkedChild(workInProgress2) {
        warnIfNotHydrating();
        return (workInProgress2.flags & Forked) !== NoFlags;
      }
      function getForksAtLevel(workInProgress2) {
        warnIfNotHydrating();
        return treeForkCount;
      }
      function getTreeId() {
        var overflow = treeContextOverflow;
        var idWithLeadingBit = treeContextId;
        var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit);
        return id.toString(32) + overflow;
      }
      function pushTreeFork(workInProgress2, totalChildren) {
        warnIfNotHydrating();
        forkStack[forkStackIndex++] = treeForkCount;
        forkStack[forkStackIndex++] = treeForkProvider;
        treeForkProvider = workInProgress2;
        treeForkCount = totalChildren;
      }
      function pushTreeId(workInProgress2, totalChildren, index22) {
        warnIfNotHydrating();
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextProvider = workInProgress2;
        var baseIdWithLeadingBit = treeContextId;
        var baseOverflow = treeContextOverflow;
        var baseLength = getBitLength(baseIdWithLeadingBit) - 1;
        var baseId = baseIdWithLeadingBit & ~(1 << baseLength);
        var slot = index22 + 1;
        var length = getBitLength(totalChildren) + baseLength;
        if (length > 30) {
          var numberOfOverflowBits = baseLength - baseLength % 5;
          var newOverflowBits = (1 << numberOfOverflowBits) - 1;
          var newOverflow = (baseId & newOverflowBits).toString(32);
          var restOfBaseId = baseId >> numberOfOverflowBits;
          var restOfBaseLength = baseLength - numberOfOverflowBits;
          var restOfLength = getBitLength(totalChildren) + restOfBaseLength;
          var restOfNewBits = slot << restOfBaseLength;
          var id = restOfNewBits | restOfBaseId;
          var overflow = newOverflow + baseOverflow;
          treeContextId = 1 << restOfLength | id;
          treeContextOverflow = overflow;
        } else {
          var newBits = slot << baseLength;
          var _id = newBits | baseId;
          var _overflow = baseOverflow;
          treeContextId = 1 << length | _id;
          treeContextOverflow = _overflow;
        }
      }
      function pushMaterializedTreeId(workInProgress2) {
        warnIfNotHydrating();
        var returnFiber = workInProgress2.return;
        if (returnFiber !== null) {
          var numberOfForks = 1;
          var slotIndex = 0;
          pushTreeFork(workInProgress2, numberOfForks);
          pushTreeId(workInProgress2, numberOfForks, slotIndex);
        }
      }
      function getBitLength(number) {
        return 32 - clz32(number);
      }
      function getLeadingBit(id) {
        return 1 << getBitLength(id) - 1;
      }
      function popTreeContext(workInProgress2) {
        while (workInProgress2 === treeForkProvider) {
          treeForkProvider = forkStack[--forkStackIndex];
          forkStack[forkStackIndex] = null;
          treeForkCount = forkStack[--forkStackIndex];
          forkStack[forkStackIndex] = null;
        }
        while (workInProgress2 === treeContextProvider) {
          treeContextProvider = idStack[--idStackIndex];
          idStack[idStackIndex] = null;
          treeContextOverflow = idStack[--idStackIndex];
          idStack[idStackIndex] = null;
          treeContextId = idStack[--idStackIndex];
          idStack[idStackIndex] = null;
        }
      }
      function getSuspendedTreeContext() {
        warnIfNotHydrating();
        if (treeContextProvider !== null) {
          return {
            id: treeContextId,
            overflow: treeContextOverflow
          };
        } else {
          return null;
        }
      }
      function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
        warnIfNotHydrating();
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextId = suspendedContext.id;
        treeContextOverflow = suspendedContext.overflow;
        treeContextProvider = workInProgress2;
      }
      function warnIfNotHydrating() {
        {
          if (!getIsHydrating()) {
            error("Expected to be hydrating. This is a bug in React. Please file an issue.");
          }
        }
      }
      var hydrationParentFiber = null;
      var nextHydratableInstance = null;
      var isHydrating = false;
      var didSuspendOrErrorDEV = false;
      var hydrationErrors = null;
      function warnIfHydrating() {
        {
          if (isHydrating) {
            error("We should not be hydrating here. This is a bug in React. Please file a bug.");
          }
        }
      }
      function markDidThrowWhileHydratingDEV() {
        {
          didSuspendOrErrorDEV = true;
        }
      }
      function didSuspendOrErrorWhileHydratingDEV() {
        {
          return didSuspendOrErrorDEV;
        }
      }
      function enterHydrationState(fiber) {
        var parentInstance = fiber.stateNode.containerInfo;
        nextHydratableInstance = getFirstHydratableChildWithinContainer(parentInstance);
        hydrationParentFiber = fiber;
        isHydrating = true;
        hydrationErrors = null;
        didSuspendOrErrorDEV = false;
        return true;
      }
      function reenterHydrationStateFromDehydratedSuspenseInstance(fiber, suspenseInstance, treeContext) {
        nextHydratableInstance = getFirstHydratableChildWithinSuspenseInstance(suspenseInstance);
        hydrationParentFiber = fiber;
        isHydrating = true;
        hydrationErrors = null;
        didSuspendOrErrorDEV = false;
        if (treeContext !== null) {
          restoreSuspendedTreeContext(fiber, treeContext);
        }
        return true;
      }
      function warnUnhydratedInstance(returnFiber, instance2) {
        {
          switch (returnFiber.tag) {
            case HostRoot: {
              didNotHydrateInstanceWithinContainer(returnFiber.stateNode.containerInfo, instance2);
              break;
            }
            case HostComponent: {
              var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
              didNotHydrateInstance(
                returnFiber.type,
                returnFiber.memoizedProps,
                returnFiber.stateNode,
                instance2,
                // TODO: Delete this argument when we remove the legacy root API.
                isConcurrentMode
              );
              break;
            }
            case SuspenseComponent: {
              var suspenseState = returnFiber.memoizedState;
              if (suspenseState.dehydrated !== null) didNotHydrateInstanceWithinSuspenseInstance(suspenseState.dehydrated, instance2);
              break;
            }
          }
        }
      }
      function deleteHydratableInstance(returnFiber, instance2) {
        warnUnhydratedInstance(returnFiber, instance2);
        var childToDelete = createFiberFromHostInstanceForDeletion();
        childToDelete.stateNode = instance2;
        childToDelete.return = returnFiber;
        var deletions = returnFiber.deletions;
        if (deletions === null) {
          returnFiber.deletions = [childToDelete];
          returnFiber.flags |= ChildDeletion;
        } else {
          deletions.push(childToDelete);
        }
      }
      function warnNonhydratedInstance(returnFiber, fiber) {
        {
          if (didSuspendOrErrorDEV) {
            return;
          }
          switch (returnFiber.tag) {
            case HostRoot: {
              var parentContainer = returnFiber.stateNode.containerInfo;
              switch (fiber.tag) {
                case HostComponent:
                  var type2 = fiber.type;
                  fiber.pendingProps;
                  didNotFindHydratableInstanceWithinContainer(parentContainer, type2);
                  break;
                case HostText:
                  var text = fiber.pendingProps;
                  didNotFindHydratableTextInstanceWithinContainer(parentContainer, text);
                  break;
              }
              break;
            }
            case HostComponent: {
              var parentType = returnFiber.type;
              var parentProps = returnFiber.memoizedProps;
              var parentInstance = returnFiber.stateNode;
              switch (fiber.tag) {
                case HostComponent: {
                  var _type = fiber.type;
                  var _props = fiber.pendingProps;
                  var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                  didNotFindHydratableInstance(
                    parentType,
                    parentProps,
                    parentInstance,
                    _type,
                    _props,
                    // TODO: Delete this argument when we remove the legacy root API.
                    isConcurrentMode
                  );
                  break;
                }
                case HostText: {
                  var _text = fiber.pendingProps;
                  var _isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                  didNotFindHydratableTextInstance(
                    parentType,
                    parentProps,
                    parentInstance,
                    _text,
                    // TODO: Delete this argument when we remove the legacy root API.
                    _isConcurrentMode
                  );
                  break;
                }
              }
              break;
            }
            case SuspenseComponent: {
              var suspenseState = returnFiber.memoizedState;
              var _parentInstance = suspenseState.dehydrated;
              if (_parentInstance !== null) switch (fiber.tag) {
                case HostComponent:
                  var _type2 = fiber.type;
                  fiber.pendingProps;
                  didNotFindHydratableInstanceWithinSuspenseInstance(_parentInstance, _type2);
                  break;
                case HostText:
                  var _text2 = fiber.pendingProps;
                  didNotFindHydratableTextInstanceWithinSuspenseInstance(_parentInstance, _text2);
                  break;
              }
              break;
            }
            default:
              return;
          }
        }
      }
      function insertNonHydratedInstance(returnFiber, fiber) {
        fiber.flags = fiber.flags & -4097 | Placement;
        warnNonhydratedInstance(returnFiber, fiber);
      }
      function tryHydrate(fiber, nextInstance) {
        switch (fiber.tag) {
          case HostComponent: {
            var type2 = fiber.type;
            fiber.pendingProps;
            var instance2 = canHydrateInstance(nextInstance, type2);
            if (instance2 !== null) {
              fiber.stateNode = instance2;
              hydrationParentFiber = fiber;
              nextHydratableInstance = getFirstHydratableChild(instance2);
              return true;
            }
            return false;
          }
          case HostText: {
            var text = fiber.pendingProps;
            var textInstance = canHydrateTextInstance(nextInstance, text);
            if (textInstance !== null) {
              fiber.stateNode = textInstance;
              hydrationParentFiber = fiber;
              nextHydratableInstance = null;
              return true;
            }
            return false;
          }
          case SuspenseComponent: {
            var suspenseInstance = canHydrateSuspenseInstance(nextInstance);
            if (suspenseInstance !== null) {
              var suspenseState = {
                dehydrated: suspenseInstance,
                treeContext: getSuspendedTreeContext(),
                retryLane: OffscreenLane
              };
              fiber.memoizedState = suspenseState;
              var dehydratedFragment = createFiberFromDehydratedFragment(suspenseInstance);
              dehydratedFragment.return = fiber;
              fiber.child = dehydratedFragment;
              hydrationParentFiber = fiber;
              nextHydratableInstance = null;
              return true;
            }
            return false;
          }
          default:
            return false;
        }
      }
      function shouldClientRenderOnMismatch(fiber) {
        return (fiber.mode & ConcurrentMode) !== NoMode && (fiber.flags & DidCapture) === NoFlags;
      }
      function throwOnHydrationMismatch(fiber) {
        throw new Error("Hydration failed because the initial UI does not match what was rendered on the server.");
      }
      function tryToClaimNextHydratableInstance(fiber) {
        if (!isHydrating) {
          return;
        }
        var nextInstance = nextHydratableInstance;
        if (!nextInstance) {
          if (shouldClientRenderOnMismatch(fiber)) {
            warnNonhydratedInstance(hydrationParentFiber, fiber);
            throwOnHydrationMismatch();
          }
          insertNonHydratedInstance(hydrationParentFiber, fiber);
          isHydrating = false;
          hydrationParentFiber = fiber;
          return;
        }
        var firstAttemptedInstance = nextInstance;
        if (!tryHydrate(fiber, nextInstance)) {
          if (shouldClientRenderOnMismatch(fiber)) {
            warnNonhydratedInstance(hydrationParentFiber, fiber);
            throwOnHydrationMismatch();
          }
          nextInstance = getNextHydratableSibling(firstAttemptedInstance);
          var prevHydrationParentFiber = hydrationParentFiber;
          if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
            insertNonHydratedInstance(hydrationParentFiber, fiber);
            isHydrating = false;
            hydrationParentFiber = fiber;
            return;
          }
          deleteHydratableInstance(prevHydrationParentFiber, firstAttemptedInstance);
        }
      }
      function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
        var instance2 = fiber.stateNode;
        var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV;
        var updatePayload = hydrateInstance(instance2, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev);
        fiber.updateQueue = updatePayload;
        if (updatePayload !== null) {
          return true;
        }
        return false;
      }
      function prepareToHydrateHostTextInstance(fiber) {
        var textInstance = fiber.stateNode;
        var textContent = fiber.memoizedProps;
        var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
        if (shouldUpdate) {
          var returnFiber = hydrationParentFiber;
          if (returnFiber !== null) {
            switch (returnFiber.tag) {
              case HostRoot: {
                var parentContainer = returnFiber.stateNode.containerInfo;
                var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode;
                didNotMatchHydratedContainerTextInstance(
                  parentContainer,
                  textInstance,
                  textContent,
                  // TODO: Delete this argument when we remove the legacy root API.
                  isConcurrentMode
                );
                break;
              }
              case HostComponent: {
                var parentType = returnFiber.type;
                var parentProps = returnFiber.memoizedProps;
                var parentInstance = returnFiber.stateNode;
                var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode;
                didNotMatchHydratedTextInstance(
                  parentType,
                  parentProps,
                  parentInstance,
                  textInstance,
                  textContent,
                  // TODO: Delete this argument when we remove the legacy root API.
                  _isConcurrentMode2
                );
                break;
              }
            }
          }
        }
        return shouldUpdate;
      }
      function prepareToHydrateHostSuspenseInstance(fiber) {
        var suspenseState = fiber.memoizedState;
        var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
        if (!suspenseInstance) {
          throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
        }
        hydrateSuspenseInstance(suspenseInstance, fiber);
      }
      function skipPastDehydratedSuspenseInstance(fiber) {
        var suspenseState = fiber.memoizedState;
        var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
        if (!suspenseInstance) {
          throw new Error("Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.");
        }
        return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
      }
      function popToNextHostParent(fiber) {
        var parent = fiber.return;
        while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
          parent = parent.return;
        }
        hydrationParentFiber = parent;
      }
      function popHydrationState(fiber) {
        if (fiber !== hydrationParentFiber) {
          return false;
        }
        if (!isHydrating) {
          popToNextHostParent(fiber);
          isHydrating = true;
          return false;
        }
        if (fiber.tag !== HostRoot && (fiber.tag !== HostComponent || shouldDeleteUnhydratedTailInstances(fiber.type) && !shouldSetTextContent(fiber.type, fiber.memoizedProps))) {
          var nextInstance = nextHydratableInstance;
          if (nextInstance) {
            if (shouldClientRenderOnMismatch(fiber)) {
              warnIfUnhydratedTailNodes(fiber);
              throwOnHydrationMismatch();
            } else {
              while (nextInstance) {
                deleteHydratableInstance(fiber, nextInstance);
                nextInstance = getNextHydratableSibling(nextInstance);
              }
            }
          }
        }
        popToNextHostParent(fiber);
        if (fiber.tag === SuspenseComponent) {
          nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
        } else {
          nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
        }
        return true;
      }
      function hasUnhydratedTailNodes() {
        return isHydrating && nextHydratableInstance !== null;
      }
      function warnIfUnhydratedTailNodes(fiber) {
        var nextInstance = nextHydratableInstance;
        while (nextInstance) {
          warnUnhydratedInstance(fiber, nextInstance);
          nextInstance = getNextHydratableSibling(nextInstance);
        }
      }
      function resetHydrationState() {
        hydrationParentFiber = null;
        nextHydratableInstance = null;
        isHydrating = false;
        didSuspendOrErrorDEV = false;
      }
      function upgradeHydrationErrorsToRecoverable() {
        if (hydrationErrors !== null) {
          queueRecoverableErrors(hydrationErrors);
          hydrationErrors = null;
        }
      }
      function getIsHydrating() {
        return isHydrating;
      }
      function queueHydrationError(error2) {
        if (hydrationErrors === null) {
          hydrationErrors = [error2];
        } else {
          hydrationErrors.push(error2);
        }
      }
      var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
      var NoTransition = null;
      function requestCurrentTransition() {
        return ReactCurrentBatchConfig$1.transition;
      }
      var ReactStrictModeWarnings = {
        recordUnsafeLifecycleWarnings: function(fiber, instance2) {
        },
        flushPendingUnsafeLifecycleWarnings: function() {
        },
        recordLegacyContextWarning: function(fiber, instance2) {
        },
        flushLegacyContextWarning: function() {
        },
        discardPendingWarnings: function() {
        }
      };
      {
        var findStrictRoot = function(fiber) {
          var maybeStrictRoot = null;
          var node2 = fiber;
          while (node2 !== null) {
            if (node2.mode & StrictLegacyMode) {
              maybeStrictRoot = node2;
            }
            node2 = node2.return;
          }
          return maybeStrictRoot;
        };
        var setToSortedString = function(set2) {
          var array = [];
          set2.forEach(function(value) {
            array.push(value);
          });
          return array.sort().join(", ");
        };
        var pendingComponentWillMountWarnings = [];
        var pendingUNSAFE_ComponentWillMountWarnings = [];
        var pendingComponentWillReceivePropsWarnings = [];
        var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
        var pendingComponentWillUpdateWarnings = [];
        var pendingUNSAFE_ComponentWillUpdateWarnings = [];
        var didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
        ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance2) {
          if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
            return;
          }
          if (typeof instance2.componentWillMount === "function" && // Don't warn about react-lifecycles-compat polyfilled components.
          instance2.componentWillMount.__suppressDeprecationWarning !== true) {
            pendingComponentWillMountWarnings.push(fiber);
          }
          if (fiber.mode & StrictLegacyMode && typeof instance2.UNSAFE_componentWillMount === "function") {
            pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
          }
          if (typeof instance2.componentWillReceiveProps === "function" && instance2.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
            pendingComponentWillReceivePropsWarnings.push(fiber);
          }
          if (fiber.mode & StrictLegacyMode && typeof instance2.UNSAFE_componentWillReceiveProps === "function") {
            pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
          }
          if (typeof instance2.componentWillUpdate === "function" && instance2.componentWillUpdate.__suppressDeprecationWarning !== true) {
            pendingComponentWillUpdateWarnings.push(fiber);
          }
          if (fiber.mode & StrictLegacyMode && typeof instance2.UNSAFE_componentWillUpdate === "function") {
            pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
          }
        };
        ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
          var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
          if (pendingComponentWillMountWarnings.length > 0) {
            pendingComponentWillMountWarnings.forEach(function(fiber) {
              componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingComponentWillMountWarnings = [];
          }
          var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
          if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
            pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
              UNSAFE_componentWillMountUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingUNSAFE_ComponentWillMountWarnings = [];
          }
          var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
          if (pendingComponentWillReceivePropsWarnings.length > 0) {
            pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
              componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingComponentWillReceivePropsWarnings = [];
          }
          var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
          if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
            pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function(fiber) {
              UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
          }
          var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
          if (pendingComponentWillUpdateWarnings.length > 0) {
            pendingComponentWillUpdateWarnings.forEach(function(fiber) {
              componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingComponentWillUpdateWarnings = [];
          }
          var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
          if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
            pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
              UNSAFE_componentWillUpdateUniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutUnsafeLifecycles.add(fiber.type);
            });
            pendingUNSAFE_ComponentWillUpdateWarnings = [];
          }
          if (UNSAFE_componentWillMountUniqueNames.size > 0) {
            var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
            error("Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s", sortedNames);
          }
          if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
            var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
            error("Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n\nPlease update the following components: %s", _sortedNames);
          }
          if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
            var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
            error("Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s", _sortedNames2);
          }
          if (componentWillMountUniqueNames.size > 0) {
            var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
            warn("componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames3);
          }
          if (componentWillReceivePropsUniqueNames.size > 0) {
            var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
            warn("componentWillReceiveProps has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames4);
          }
          if (componentWillUpdateUniqueNames.size > 0) {
            var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
            warn("componentWillUpdate has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s", _sortedNames5);
          }
        };
        var pendingLegacyContextWarning = /* @__PURE__ */ new Map();
        var didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
        ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance2) {
          var strictRoot = findStrictRoot(fiber);
          if (strictRoot === null) {
            error("Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue.");
            return;
          }
          if (didWarnAboutLegacyContext.has(fiber.type)) {
            return;
          }
          var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
          if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance2 !== null && typeof instance2.getChildContext === "function") {
            if (warningsForRoot === void 0) {
              warningsForRoot = [];
              pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
            }
            warningsForRoot.push(fiber);
          }
        };
        ReactStrictModeWarnings.flushLegacyContextWarning = function() {
          pendingLegacyContextWarning.forEach(function(fiberArray, strictRoot) {
            if (fiberArray.length === 0) {
              return;
            }
            var firstFiber = fiberArray[0];
            var uniqueNames = /* @__PURE__ */ new Set();
            fiberArray.forEach(function(fiber) {
              uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutLegacyContext.add(fiber.type);
            });
            var sortedNames = setToSortedString(uniqueNames);
            try {
              setCurrentFiber(firstFiber);
              error("Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", sortedNames);
            } finally {
              resetCurrentFiber();
            }
          });
        };
        ReactStrictModeWarnings.discardPendingWarnings = function() {
          pendingComponentWillMountWarnings = [];
          pendingUNSAFE_ComponentWillMountWarnings = [];
          pendingComponentWillReceivePropsWarnings = [];
          pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
          pendingComponentWillUpdateWarnings = [];
          pendingUNSAFE_ComponentWillUpdateWarnings = [];
          pendingLegacyContextWarning = /* @__PURE__ */ new Map();
        };
      }
      var didWarnAboutMaps;
      var didWarnAboutGenerators;
      var didWarnAboutStringRefs;
      var ownerHasKeyUseWarning;
      var ownerHasFunctionTypeWarning;
      var warnForMissingKey = function(child, returnFiber) {
      };
      {
        didWarnAboutMaps = false;
        didWarnAboutGenerators = false;
        didWarnAboutStringRefs = {};
        ownerHasKeyUseWarning = {};
        ownerHasFunctionTypeWarning = {};
        warnForMissingKey = function(child, returnFiber) {
          if (child === null || typeof child !== "object") {
            return;
          }
          if (!child._store || child._store.validated || child.key != null) {
            return;
          }
          if (typeof child._store !== "object") {
            throw new Error("React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.");
          }
          child._store.validated = true;
          var componentName = getComponentNameFromFiber(returnFiber) || "Component";
          if (ownerHasKeyUseWarning[componentName]) {
            return;
          }
          ownerHasKeyUseWarning[componentName] = true;
          error('Each child in a list should have a unique "key" prop. See https://reactjs.org/link/warning-keys for more information.');
        };
      }
      function isReactClass(type2) {
        return type2.prototype && type2.prototype.isReactComponent;
      }
      function coerceRef(returnFiber, current2, element) {
        var mixedRef = element.ref;
        if (mixedRef !== null && typeof mixedRef !== "function" && typeof mixedRef !== "object") {
          {
            if ((returnFiber.mode & StrictLegacyMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
            // because these cannot be automatically converted to an arrow function
            // using a codemod. Therefore, we don't have to warn about string refs again.
            !(element._owner && element._self && element._owner.stateNode !== element._self) && // Will already throw with "Function components cannot have string refs"
            !(element._owner && element._owner.tag !== ClassComponent) && // Will already warn with "Function components cannot be given refs"
            !(typeof element.type === "function" && !isReactClass(element.type)) && // Will already throw with "Element ref was specified as a string (someStringRef) but no owner was set"
            element._owner) {
              var componentName = getComponentNameFromFiber(returnFiber) || "Component";
              if (!didWarnAboutStringRefs[componentName]) {
                {
                  error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, mixedRef);
                }
                didWarnAboutStringRefs[componentName] = true;
              }
            }
          }
          if (element._owner) {
            var owner = element._owner;
            var inst;
            if (owner) {
              var ownerFiber = owner;
              if (ownerFiber.tag !== ClassComponent) {
                throw new Error("Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref");
              }
              inst = ownerFiber.stateNode;
            }
            if (!inst) {
              throw new Error("Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue.");
            }
            var resolvedInst = inst;
            {
              checkPropStringCoercion(mixedRef, "ref");
            }
            var stringRef = "" + mixedRef;
            if (current2 !== null && current2.ref !== null && typeof current2.ref === "function" && current2.ref._stringRef === stringRef) {
              return current2.ref;
            }
            var ref2 = function(value) {
              var refs = resolvedInst.refs;
              if (value === null) {
                delete refs[stringRef];
              } else {
                refs[stringRef] = value;
              }
            };
            ref2._stringRef = stringRef;
            return ref2;
          } else {
            if (typeof mixedRef !== "string") {
              throw new Error("Expected ref to be a function, a string, an object returned by React.createRef(), or null.");
            }
            if (!element._owner) {
              throw new Error("Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://reactjs.org/link/refs-must-have-owner for more information.");
            }
          }
        }
        return mixedRef;
      }
      function throwOnInvalidObjectType(returnFiber, newChild) {
        var childString = Object.prototype.toString.call(newChild);
        throw new Error("Objects are not valid as a React child (found: " + (childString === "[object Object]" ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : childString) + "). If you meant to render a collection of children, use an array instead.");
      }
      function warnOnFunctionType(returnFiber) {
        {
          var componentName = getComponentNameFromFiber(returnFiber) || "Component";
          if (ownerHasFunctionTypeWarning[componentName]) {
            return;
          }
          ownerHasFunctionTypeWarning[componentName] = true;
          error("Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.");
        }
      }
      function resolveLazy(lazyType2) {
        var payload = lazyType2._payload;
        var init2 = lazyType2._init;
        return init2(payload);
      }
      function ChildReconciler(shouldTrackSideEffects) {
        function deleteChild(returnFiber, childToDelete) {
          if (!shouldTrackSideEffects) {
            return;
          }
          var deletions = returnFiber.deletions;
          if (deletions === null) {
            returnFiber.deletions = [childToDelete];
            returnFiber.flags |= ChildDeletion;
          } else {
            deletions.push(childToDelete);
          }
        }
        function deleteRemainingChildren(returnFiber, currentFirstChild) {
          if (!shouldTrackSideEffects) {
            return null;
          }
          var childToDelete = currentFirstChild;
          while (childToDelete !== null) {
            deleteChild(returnFiber, childToDelete);
            childToDelete = childToDelete.sibling;
          }
          return null;
        }
        function mapRemainingChildren(returnFiber, currentFirstChild) {
          var existingChildren = /* @__PURE__ */ new Map();
          var existingChild = currentFirstChild;
          while (existingChild !== null) {
            if (existingChild.key !== null) {
              existingChildren.set(existingChild.key, existingChild);
            } else {
              existingChildren.set(existingChild.index, existingChild);
            }
            existingChild = existingChild.sibling;
          }
          return existingChildren;
        }
        function useFiber(fiber, pendingProps) {
          var clone2 = createWorkInProgress(fiber, pendingProps);
          clone2.index = 0;
          clone2.sibling = null;
          return clone2;
        }
        function placeChild(newFiber, lastPlacedIndex, newIndex) {
          newFiber.index = newIndex;
          if (!shouldTrackSideEffects) {
            newFiber.flags |= Forked;
            return lastPlacedIndex;
          }
          var current2 = newFiber.alternate;
          if (current2 !== null) {
            var oldIndex = current2.index;
            if (oldIndex < lastPlacedIndex) {
              newFiber.flags |= Placement;
              return lastPlacedIndex;
            } else {
              return oldIndex;
            }
          } else {
            newFiber.flags |= Placement;
            return lastPlacedIndex;
          }
        }
        function placeSingleChild(newFiber) {
          if (shouldTrackSideEffects && newFiber.alternate === null) {
            newFiber.flags |= Placement;
          }
          return newFiber;
        }
        function updateTextNode(returnFiber, current2, textContent, lanes) {
          if (current2 === null || current2.tag !== HostText) {
            var created = createFiberFromText(textContent, returnFiber.mode, lanes);
            created.return = returnFiber;
            return created;
          } else {
            var existing = useFiber(current2, textContent);
            existing.return = returnFiber;
            return existing;
          }
        }
        function updateElement(returnFiber, current2, element, lanes) {
          var elementType = element.type;
          if (elementType === REACT_FRAGMENT_TYPE) {
            return updateFragment2(returnFiber, current2, element.props.children, lanes, element.key);
          }
          if (current2 !== null) {
            if (current2.elementType === elementType || // Keep this check inline so it only runs on the false path:
            isCompatibleFamilyForHotReloading(current2, element) || // Lazy types should reconcile their resolved type.
            // We need to do this after the Hot Reloading check above,
            // because hot reloading has different semantics than prod because
            // it doesn't resuspend. So we can't let the call below suspend.
            typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type) {
              var existing = useFiber(current2, element.props);
              existing.ref = coerceRef(returnFiber, current2, element);
              existing.return = returnFiber;
              {
                existing._debugSource = element._source;
                existing._debugOwner = element._owner;
              }
              return existing;
            }
          }
          var created = createFiberFromElement(element, returnFiber.mode, lanes);
          created.ref = coerceRef(returnFiber, current2, element);
          created.return = returnFiber;
          return created;
        }
        function updatePortal(returnFiber, current2, portal, lanes) {
          if (current2 === null || current2.tag !== HostPortal || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation) {
            var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
            created.return = returnFiber;
            return created;
          } else {
            var existing = useFiber(current2, portal.children || []);
            existing.return = returnFiber;
            return existing;
          }
        }
        function updateFragment2(returnFiber, current2, fragment, lanes, key2) {
          if (current2 === null || current2.tag !== Fragment) {
            var created = createFiberFromFragment(fragment, returnFiber.mode, lanes, key2);
            created.return = returnFiber;
            return created;
          } else {
            var existing = useFiber(current2, fragment);
            existing.return = returnFiber;
            return existing;
          }
        }
        function createChild(returnFiber, newChild, lanes) {
          if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
            var created = createFiberFromText("" + newChild, returnFiber.mode, lanes);
            created.return = returnFiber;
            return created;
          }
          if (typeof newChild === "object" && newChild !== null) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE: {
                var _created = createFiberFromElement(newChild, returnFiber.mode, lanes);
                _created.ref = coerceRef(returnFiber, null, newChild);
                _created.return = returnFiber;
                return _created;
              }
              case REACT_PORTAL_TYPE: {
                var _created2 = createFiberFromPortal(newChild, returnFiber.mode, lanes);
                _created2.return = returnFiber;
                return _created2;
              }
              case REACT_LAZY_TYPE: {
                var payload = newChild._payload;
                var init2 = newChild._init;
                return createChild(returnFiber, init2(payload), lanes);
              }
            }
            if (isArray2(newChild) || getIteratorFn(newChild)) {
              var _created3 = createFiberFromFragment(newChild, returnFiber.mode, lanes, null);
              _created3.return = returnFiber;
              return _created3;
            }
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          {
            if (typeof newChild === "function") {
              warnOnFunctionType(returnFiber);
            }
          }
          return null;
        }
        function updateSlot(returnFiber, oldFiber, newChild, lanes) {
          var key2 = oldFiber !== null ? oldFiber.key : null;
          if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
            if (key2 !== null) {
              return null;
            }
            return updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
          }
          if (typeof newChild === "object" && newChild !== null) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE: {
                if (newChild.key === key2) {
                  return updateElement(returnFiber, oldFiber, newChild, lanes);
                } else {
                  return null;
                }
              }
              case REACT_PORTAL_TYPE: {
                if (newChild.key === key2) {
                  return updatePortal(returnFiber, oldFiber, newChild, lanes);
                } else {
                  return null;
                }
              }
              case REACT_LAZY_TYPE: {
                var payload = newChild._payload;
                var init2 = newChild._init;
                return updateSlot(returnFiber, oldFiber, init2(payload), lanes);
              }
            }
            if (isArray2(newChild) || getIteratorFn(newChild)) {
              if (key2 !== null) {
                return null;
              }
              return updateFragment2(returnFiber, oldFiber, newChild, lanes, null);
            }
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          {
            if (typeof newChild === "function") {
              warnOnFunctionType(returnFiber);
            }
          }
          return null;
        }
        function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
          if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
            var matchedFiber = existingChildren.get(newIdx) || null;
            return updateTextNode(returnFiber, matchedFiber, "" + newChild, lanes);
          }
          if (typeof newChild === "object" && newChild !== null) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE: {
                var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
                return updateElement(returnFiber, _matchedFiber, newChild, lanes);
              }
              case REACT_PORTAL_TYPE: {
                var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
                return updatePortal(returnFiber, _matchedFiber2, newChild, lanes);
              }
              case REACT_LAZY_TYPE:
                var payload = newChild._payload;
                var init2 = newChild._init;
                return updateFromMap(existingChildren, returnFiber, newIdx, init2(payload), lanes);
            }
            if (isArray2(newChild) || getIteratorFn(newChild)) {
              var _matchedFiber3 = existingChildren.get(newIdx) || null;
              return updateFragment2(returnFiber, _matchedFiber3, newChild, lanes, null);
            }
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          {
            if (typeof newChild === "function") {
              warnOnFunctionType(returnFiber);
            }
          }
          return null;
        }
        function warnOnInvalidKey(child, knownKeys, returnFiber) {
          {
            if (typeof child !== "object" || child === null) {
              return knownKeys;
            }
            switch (child.$$typeof) {
              case REACT_ELEMENT_TYPE:
              case REACT_PORTAL_TYPE:
                warnForMissingKey(child, returnFiber);
                var key2 = child.key;
                if (typeof key2 !== "string") {
                  break;
                }
                if (knownKeys === null) {
                  knownKeys = /* @__PURE__ */ new Set();
                  knownKeys.add(key2);
                  break;
                }
                if (!knownKeys.has(key2)) {
                  knownKeys.add(key2);
                  break;
                }
                error("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.", key2);
                break;
              case REACT_LAZY_TYPE:
                var payload = child._payload;
                var init2 = child._init;
                warnOnInvalidKey(init2(payload), knownKeys, returnFiber);
                break;
            }
          }
          return knownKeys;
        }
        function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
          {
            var knownKeys = null;
            for (var i2 = 0; i2 < newChildren.length; i2++) {
              var child = newChildren[i2];
              knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
            }
          }
          var resultingFirstChild = null;
          var previousNewFiber = null;
          var oldFiber = currentFirstChild;
          var lastPlacedIndex = 0;
          var newIdx = 0;
          var nextOldFiber = null;
          for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
            if (oldFiber.index > newIdx) {
              nextOldFiber = oldFiber;
              oldFiber = null;
            } else {
              nextOldFiber = oldFiber.sibling;
            }
            var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], lanes);
            if (newFiber === null) {
              if (oldFiber === null) {
                oldFiber = nextOldFiber;
              }
              break;
            }
            if (shouldTrackSideEffects) {
              if (oldFiber && newFiber.alternate === null) {
                deleteChild(returnFiber, oldFiber);
              }
            }
            lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
            if (previousNewFiber === null) {
              resultingFirstChild = newFiber;
            } else {
              previousNewFiber.sibling = newFiber;
            }
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (newIdx === newChildren.length) {
            deleteRemainingChildren(returnFiber, oldFiber);
            if (getIsHydrating()) {
              var numberOfForks = newIdx;
              pushTreeFork(returnFiber, numberOfForks);
            }
            return resultingFirstChild;
          }
          if (oldFiber === null) {
            for (; newIdx < newChildren.length; newIdx++) {
              var _newFiber = createChild(returnFiber, newChildren[newIdx], lanes);
              if (_newFiber === null) {
                continue;
              }
              lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = _newFiber;
              } else {
                previousNewFiber.sibling = _newFiber;
              }
              previousNewFiber = _newFiber;
            }
            if (getIsHydrating()) {
              var _numberOfForks = newIdx;
              pushTreeFork(returnFiber, _numberOfForks);
            }
            return resultingFirstChild;
          }
          var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
          for (; newIdx < newChildren.length; newIdx++) {
            var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], lanes);
            if (_newFiber2 !== null) {
              if (shouldTrackSideEffects) {
                if (_newFiber2.alternate !== null) {
                  existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
                }
              }
              lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = _newFiber2;
              } else {
                previousNewFiber.sibling = _newFiber2;
              }
              previousNewFiber = _newFiber2;
            }
          }
          if (shouldTrackSideEffects) {
            existingChildren.forEach(function(child2) {
              return deleteChild(returnFiber, child2);
            });
          }
          if (getIsHydrating()) {
            var _numberOfForks2 = newIdx;
            pushTreeFork(returnFiber, _numberOfForks2);
          }
          return resultingFirstChild;
        }
        function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, lanes) {
          var iteratorFn = getIteratorFn(newChildrenIterable);
          if (typeof iteratorFn !== "function") {
            throw new Error("An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.");
          }
          {
            if (typeof Symbol === "function" && // $FlowFixMe Flow doesn't know about toStringTag
            newChildrenIterable[Symbol.toStringTag] === "Generator") {
              if (!didWarnAboutGenerators) {
                error("Using Generators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. Keep in mind you might need to polyfill these features for older browsers.");
              }
              didWarnAboutGenerators = true;
            }
            if (newChildrenIterable.entries === iteratorFn) {
              if (!didWarnAboutMaps) {
                error("Using Maps as children is not supported. Use an array of keyed ReactElements instead.");
              }
              didWarnAboutMaps = true;
            }
            var _newChildren = iteratorFn.call(newChildrenIterable);
            if (_newChildren) {
              var knownKeys = null;
              var _step = _newChildren.next();
              for (; !_step.done; _step = _newChildren.next()) {
                var child = _step.value;
                knownKeys = warnOnInvalidKey(child, knownKeys, returnFiber);
              }
            }
          }
          var newChildren = iteratorFn.call(newChildrenIterable);
          if (newChildren == null) {
            throw new Error("An iterable object provided no iterator.");
          }
          var resultingFirstChild = null;
          var previousNewFiber = null;
          var oldFiber = currentFirstChild;
          var lastPlacedIndex = 0;
          var newIdx = 0;
          var nextOldFiber = null;
          var step = newChildren.next();
          for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
            if (oldFiber.index > newIdx) {
              nextOldFiber = oldFiber;
              oldFiber = null;
            } else {
              nextOldFiber = oldFiber.sibling;
            }
            var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
            if (newFiber === null) {
              if (oldFiber === null) {
                oldFiber = nextOldFiber;
              }
              break;
            }
            if (shouldTrackSideEffects) {
              if (oldFiber && newFiber.alternate === null) {
                deleteChild(returnFiber, oldFiber);
              }
            }
            lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
            if (previousNewFiber === null) {
              resultingFirstChild = newFiber;
            } else {
              previousNewFiber.sibling = newFiber;
            }
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (step.done) {
            deleteRemainingChildren(returnFiber, oldFiber);
            if (getIsHydrating()) {
              var numberOfForks = newIdx;
              pushTreeFork(returnFiber, numberOfForks);
            }
            return resultingFirstChild;
          }
          if (oldFiber === null) {
            for (; !step.done; newIdx++, step = newChildren.next()) {
              var _newFiber3 = createChild(returnFiber, step.value, lanes);
              if (_newFiber3 === null) {
                continue;
              }
              lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = _newFiber3;
              } else {
                previousNewFiber.sibling = _newFiber3;
              }
              previousNewFiber = _newFiber3;
            }
            if (getIsHydrating()) {
              var _numberOfForks3 = newIdx;
              pushTreeFork(returnFiber, _numberOfForks3);
            }
            return resultingFirstChild;
          }
          var existingChildren = mapRemainingChildren(returnFiber, oldFiber);
          for (; !step.done; newIdx++, step = newChildren.next()) {
            var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, lanes);
            if (_newFiber4 !== null) {
              if (shouldTrackSideEffects) {
                if (_newFiber4.alternate !== null) {
                  existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
                }
              }
              lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
              if (previousNewFiber === null) {
                resultingFirstChild = _newFiber4;
              } else {
                previousNewFiber.sibling = _newFiber4;
              }
              previousNewFiber = _newFiber4;
            }
          }
          if (shouldTrackSideEffects) {
            existingChildren.forEach(function(child2) {
              return deleteChild(returnFiber, child2);
            });
          }
          if (getIsHydrating()) {
            var _numberOfForks4 = newIdx;
            pushTreeFork(returnFiber, _numberOfForks4);
          }
          return resultingFirstChild;
        }
        function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, lanes) {
          if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
            deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
            var existing = useFiber(currentFirstChild, textContent);
            existing.return = returnFiber;
            return existing;
          }
          deleteRemainingChildren(returnFiber, currentFirstChild);
          var created = createFiberFromText(textContent, returnFiber.mode, lanes);
          created.return = returnFiber;
          return created;
        }
        function reconcileSingleElement(returnFiber, currentFirstChild, element, lanes) {
          var key2 = element.key;
          var child = currentFirstChild;
          while (child !== null) {
            if (child.key === key2) {
              var elementType = element.type;
              if (elementType === REACT_FRAGMENT_TYPE) {
                if (child.tag === Fragment) {
                  deleteRemainingChildren(returnFiber, child.sibling);
                  var existing = useFiber(child, element.props.children);
                  existing.return = returnFiber;
                  {
                    existing._debugSource = element._source;
                    existing._debugOwner = element._owner;
                  }
                  return existing;
                }
              } else {
                if (child.elementType === elementType || // Keep this check inline so it only runs on the false path:
                isCompatibleFamilyForHotReloading(child, element) || // Lazy types should reconcile their resolved type.
                // We need to do this after the Hot Reloading check above,
                // because hot reloading has different semantics than prod because
                // it doesn't resuspend. So we can't let the call below suspend.
                typeof elementType === "object" && elementType !== null && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === child.type) {
                  deleteRemainingChildren(returnFiber, child.sibling);
                  var _existing = useFiber(child, element.props);
                  _existing.ref = coerceRef(returnFiber, child, element);
                  _existing.return = returnFiber;
                  {
                    _existing._debugSource = element._source;
                    _existing._debugOwner = element._owner;
                  }
                  return _existing;
                }
              }
              deleteRemainingChildren(returnFiber, child);
              break;
            } else {
              deleteChild(returnFiber, child);
            }
            child = child.sibling;
          }
          if (element.type === REACT_FRAGMENT_TYPE) {
            var created = createFiberFromFragment(element.props.children, returnFiber.mode, lanes, element.key);
            created.return = returnFiber;
            return created;
          } else {
            var _created4 = createFiberFromElement(element, returnFiber.mode, lanes);
            _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
            _created4.return = returnFiber;
            return _created4;
          }
        }
        function reconcileSinglePortal(returnFiber, currentFirstChild, portal, lanes) {
          var key2 = portal.key;
          var child = currentFirstChild;
          while (child !== null) {
            if (child.key === key2) {
              if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
                deleteRemainingChildren(returnFiber, child.sibling);
                var existing = useFiber(child, portal.children || []);
                existing.return = returnFiber;
                return existing;
              } else {
                deleteRemainingChildren(returnFiber, child);
                break;
              }
            } else {
              deleteChild(returnFiber, child);
            }
            child = child.sibling;
          }
          var created = createFiberFromPortal(portal, returnFiber.mode, lanes);
          created.return = returnFiber;
          return created;
        }
        function reconcileChildFibers2(returnFiber, currentFirstChild, newChild, lanes) {
          var isUnkeyedTopLevelFragment = typeof newChild === "object" && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
          if (isUnkeyedTopLevelFragment) {
            newChild = newChild.props.children;
          }
          if (typeof newChild === "object" && newChild !== null) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, lanes));
              case REACT_PORTAL_TYPE:
                return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, lanes));
              case REACT_LAZY_TYPE:
                var payload = newChild._payload;
                var init2 = newChild._init;
                return reconcileChildFibers2(returnFiber, currentFirstChild, init2(payload), lanes);
            }
            if (isArray2(newChild)) {
              return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, lanes);
            }
            if (getIteratorFn(newChild)) {
              return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, lanes);
            }
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          if (typeof newChild === "string" && newChild !== "" || typeof newChild === "number") {
            return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, "" + newChild, lanes));
          }
          {
            if (typeof newChild === "function") {
              warnOnFunctionType(returnFiber);
            }
          }
          return deleteRemainingChildren(returnFiber, currentFirstChild);
        }
        return reconcileChildFibers2;
      }
      var reconcileChildFibers = ChildReconciler(true);
      var mountChildFibers = ChildReconciler(false);
      function cloneChildFibers(current2, workInProgress2) {
        if (current2 !== null && workInProgress2.child !== current2.child) {
          throw new Error("Resuming work not yet implemented.");
        }
        if (workInProgress2.child === null) {
          return;
        }
        var currentChild = workInProgress2.child;
        var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
        workInProgress2.child = newChild;
        newChild.return = workInProgress2;
        while (currentChild.sibling !== null) {
          currentChild = currentChild.sibling;
          newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
          newChild.return = workInProgress2;
        }
        newChild.sibling = null;
      }
      function resetChildFibers(workInProgress2, lanes) {
        var child = workInProgress2.child;
        while (child !== null) {
          resetWorkInProgress(child, lanes);
          child = child.sibling;
        }
      }
      var valueCursor = createCursor(null);
      var rendererSigil;
      {
        rendererSigil = {};
      }
      var currentlyRenderingFiber = null;
      var lastContextDependency = null;
      var lastFullyObservedContext = null;
      var isDisallowedContextReadInDEV = false;
      function resetContextDependencies() {
        currentlyRenderingFiber = null;
        lastContextDependency = null;
        lastFullyObservedContext = null;
        {
          isDisallowedContextReadInDEV = false;
        }
      }
      function enterDisallowedContextReadInDEV() {
        {
          isDisallowedContextReadInDEV = true;
        }
      }
      function exitDisallowedContextReadInDEV() {
        {
          isDisallowedContextReadInDEV = false;
        }
      }
      function pushProvider(providerFiber, context, nextValue) {
        {
          push(valueCursor, context._currentValue, providerFiber);
          context._currentValue = nextValue;
          {
            if (context._currentRenderer !== void 0 && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
              error("Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.");
            }
            context._currentRenderer = rendererSigil;
          }
        }
      }
      function popProvider(context, providerFiber) {
        var currentValue = valueCursor.current;
        pop(valueCursor, providerFiber);
        {
          {
            context._currentValue = currentValue;
          }
        }
      }
      function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
        var node2 = parent;
        while (node2 !== null) {
          var alternate = node2.alternate;
          if (!isSubsetOfLanes(node2.childLanes, renderLanes2)) {
            node2.childLanes = mergeLanes(node2.childLanes, renderLanes2);
            if (alternate !== null) {
              alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
            }
          } else if (alternate !== null && !isSubsetOfLanes(alternate.childLanes, renderLanes2)) {
            alternate.childLanes = mergeLanes(alternate.childLanes, renderLanes2);
          }
          if (node2 === propagationRoot) {
            break;
          }
          node2 = node2.return;
        }
        {
          if (node2 !== propagationRoot) {
            error("Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
      }
      function propagateContextChange(workInProgress2, context, renderLanes2) {
        {
          propagateContextChange_eager(workInProgress2, context, renderLanes2);
        }
      }
      function propagateContextChange_eager(workInProgress2, context, renderLanes2) {
        var fiber = workInProgress2.child;
        if (fiber !== null) {
          fiber.return = workInProgress2;
        }
        while (fiber !== null) {
          var nextFiber = void 0;
          var list = fiber.dependencies;
          if (list !== null) {
            nextFiber = fiber.child;
            var dependency = list.firstContext;
            while (dependency !== null) {
              if (dependency.context === context) {
                if (fiber.tag === ClassComponent) {
                  var lane = pickArbitraryLane(renderLanes2);
                  var update = createUpdate(NoTimestamp, lane);
                  update.tag = ForceUpdate;
                  var updateQueue = fiber.updateQueue;
                  if (updateQueue === null) ;
                  else {
                    var sharedQueue = updateQueue.shared;
                    var pending = sharedQueue.pending;
                    if (pending === null) {
                      update.next = update;
                    } else {
                      update.next = pending.next;
                      pending.next = update;
                    }
                    sharedQueue.pending = update;
                  }
                }
                fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
                var alternate = fiber.alternate;
                if (alternate !== null) {
                  alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
                }
                scheduleContextWorkOnParentPath(fiber.return, renderLanes2, workInProgress2);
                list.lanes = mergeLanes(list.lanes, renderLanes2);
                break;
              }
              dependency = dependency.next;
            }
          } else if (fiber.tag === ContextProvider) {
            nextFiber = fiber.type === workInProgress2.type ? null : fiber.child;
          } else if (fiber.tag === DehydratedFragment) {
            var parentSuspense = fiber.return;
            if (parentSuspense === null) {
              throw new Error("We just came from a parent so we must have had a parent. This is a bug in React.");
            }
            parentSuspense.lanes = mergeLanes(parentSuspense.lanes, renderLanes2);
            var _alternate = parentSuspense.alternate;
            if (_alternate !== null) {
              _alternate.lanes = mergeLanes(_alternate.lanes, renderLanes2);
            }
            scheduleContextWorkOnParentPath(parentSuspense, renderLanes2, workInProgress2);
            nextFiber = fiber.sibling;
          } else {
            nextFiber = fiber.child;
          }
          if (nextFiber !== null) {
            nextFiber.return = fiber;
          } else {
            nextFiber = fiber;
            while (nextFiber !== null) {
              if (nextFiber === workInProgress2) {
                nextFiber = null;
                break;
              }
              var sibling = nextFiber.sibling;
              if (sibling !== null) {
                sibling.return = nextFiber.return;
                nextFiber = sibling;
                break;
              }
              nextFiber = nextFiber.return;
            }
          }
          fiber = nextFiber;
        }
      }
      function prepareToReadContext(workInProgress2, renderLanes2) {
        currentlyRenderingFiber = workInProgress2;
        lastContextDependency = null;
        lastFullyObservedContext = null;
        var dependencies2 = workInProgress2.dependencies;
        if (dependencies2 !== null) {
          {
            var firstContext = dependencies2.firstContext;
            if (firstContext !== null) {
              if (includesSomeLane(dependencies2.lanes, renderLanes2)) {
                markWorkInProgressReceivedUpdate();
              }
              dependencies2.firstContext = null;
            }
          }
        }
      }
      function readContext(context) {
        {
          if (isDisallowedContextReadInDEV) {
            error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
          }
        }
        var value = context._currentValue;
        if (lastFullyObservedContext === context) ;
        else {
          var contextItem = {
            context,
            memoizedValue: value,
            next: null
          };
          if (lastContextDependency === null) {
            if (currentlyRenderingFiber === null) {
              throw new Error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
            }
            lastContextDependency = contextItem;
            currentlyRenderingFiber.dependencies = {
              lanes: NoLanes,
              firstContext: contextItem
            };
          } else {
            lastContextDependency = lastContextDependency.next = contextItem;
          }
        }
        return value;
      }
      var concurrentQueues = null;
      function pushConcurrentUpdateQueue(queue) {
        if (concurrentQueues === null) {
          concurrentQueues = [queue];
        } else {
          concurrentQueues.push(queue);
        }
      }
      function finishQueueingConcurrentUpdates() {
        if (concurrentQueues !== null) {
          for (var i2 = 0; i2 < concurrentQueues.length; i2++) {
            var queue = concurrentQueues[i2];
            var lastInterleavedUpdate = queue.interleaved;
            if (lastInterleavedUpdate !== null) {
              queue.interleaved = null;
              var firstInterleavedUpdate = lastInterleavedUpdate.next;
              var lastPendingUpdate = queue.pending;
              if (lastPendingUpdate !== null) {
                var firstPendingUpdate = lastPendingUpdate.next;
                lastPendingUpdate.next = firstInterleavedUpdate;
                lastInterleavedUpdate.next = firstPendingUpdate;
              }
              queue.pending = lastInterleavedUpdate;
            }
          }
          concurrentQueues = null;
        }
      }
      function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
        var interleaved = queue.interleaved;
        if (interleaved === null) {
          update.next = update;
          pushConcurrentUpdateQueue(queue);
        } else {
          update.next = interleaved.next;
          interleaved.next = update;
        }
        queue.interleaved = update;
        return markUpdateLaneFromFiberToRoot(fiber, lane);
      }
      function enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane) {
        var interleaved = queue.interleaved;
        if (interleaved === null) {
          update.next = update;
          pushConcurrentUpdateQueue(queue);
        } else {
          update.next = interleaved.next;
          interleaved.next = update;
        }
        queue.interleaved = update;
      }
      function enqueueConcurrentClassUpdate(fiber, queue, update, lane) {
        var interleaved = queue.interleaved;
        if (interleaved === null) {
          update.next = update;
          pushConcurrentUpdateQueue(queue);
        } else {
          update.next = interleaved.next;
          interleaved.next = update;
        }
        queue.interleaved = update;
        return markUpdateLaneFromFiberToRoot(fiber, lane);
      }
      function enqueueConcurrentRenderForLane(fiber, lane) {
        return markUpdateLaneFromFiberToRoot(fiber, lane);
      }
      var unsafe_markUpdateLaneFromFiberToRoot = markUpdateLaneFromFiberToRoot;
      function markUpdateLaneFromFiberToRoot(sourceFiber, lane) {
        sourceFiber.lanes = mergeLanes(sourceFiber.lanes, lane);
        var alternate = sourceFiber.alternate;
        if (alternate !== null) {
          alternate.lanes = mergeLanes(alternate.lanes, lane);
        }
        {
          if (alternate === null && (sourceFiber.flags & (Placement | Hydrating)) !== NoFlags) {
            warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
          }
        }
        var node2 = sourceFiber;
        var parent = sourceFiber.return;
        while (parent !== null) {
          parent.childLanes = mergeLanes(parent.childLanes, lane);
          alternate = parent.alternate;
          if (alternate !== null) {
            alternate.childLanes = mergeLanes(alternate.childLanes, lane);
          } else {
            {
              if ((parent.flags & (Placement | Hydrating)) !== NoFlags) {
                warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
              }
            }
          }
          node2 = parent;
          parent = parent.return;
        }
        if (node2.tag === HostRoot) {
          var root2 = node2.stateNode;
          return root2;
        } else {
          return null;
        }
      }
      var UpdateState = 0;
      var ReplaceState = 1;
      var ForceUpdate = 2;
      var CaptureUpdate = 3;
      var hasForceUpdate = false;
      var didWarnUpdateInsideUpdate;
      var currentlyProcessingQueue;
      {
        didWarnUpdateInsideUpdate = false;
        currentlyProcessingQueue = null;
      }
      function initializeUpdateQueue(fiber) {
        var queue = {
          baseState: fiber.memoizedState,
          firstBaseUpdate: null,
          lastBaseUpdate: null,
          shared: {
            pending: null,
            interleaved: null,
            lanes: NoLanes
          },
          effects: null
        };
        fiber.updateQueue = queue;
      }
      function cloneUpdateQueue(current2, workInProgress2) {
        var queue = workInProgress2.updateQueue;
        var currentQueue = current2.updateQueue;
        if (queue === currentQueue) {
          var clone2 = {
            baseState: currentQueue.baseState,
            firstBaseUpdate: currentQueue.firstBaseUpdate,
            lastBaseUpdate: currentQueue.lastBaseUpdate,
            shared: currentQueue.shared,
            effects: currentQueue.effects
          };
          workInProgress2.updateQueue = clone2;
        }
      }
      function createUpdate(eventTime, lane) {
        var update = {
          eventTime,
          lane,
          tag: UpdateState,
          payload: null,
          callback: null,
          next: null
        };
        return update;
      }
      function enqueueUpdate(fiber, update, lane) {
        var updateQueue = fiber.updateQueue;
        if (updateQueue === null) {
          return null;
        }
        var sharedQueue = updateQueue.shared;
        {
          if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
            error("An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.");
            didWarnUpdateInsideUpdate = true;
          }
        }
        if (isUnsafeClassRenderPhaseUpdate()) {
          var pending = sharedQueue.pending;
          if (pending === null) {
            update.next = update;
          } else {
            update.next = pending.next;
            pending.next = update;
          }
          sharedQueue.pending = update;
          return unsafe_markUpdateLaneFromFiberToRoot(fiber, lane);
        } else {
          return enqueueConcurrentClassUpdate(fiber, sharedQueue, update, lane);
        }
      }
      function entangleTransitions(root2, fiber, lane) {
        var updateQueue = fiber.updateQueue;
        if (updateQueue === null) {
          return;
        }
        var sharedQueue = updateQueue.shared;
        if (isTransitionLane(lane)) {
          var queueLanes = sharedQueue.lanes;
          queueLanes = intersectLanes(queueLanes, root2.pendingLanes);
          var newQueueLanes = mergeLanes(queueLanes, lane);
          sharedQueue.lanes = newQueueLanes;
          markRootEntangled(root2, newQueueLanes);
        }
      }
      function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
        var queue = workInProgress2.updateQueue;
        var current2 = workInProgress2.alternate;
        if (current2 !== null) {
          var currentQueue = current2.updateQueue;
          if (queue === currentQueue) {
            var newFirst = null;
            var newLast = null;
            var firstBaseUpdate = queue.firstBaseUpdate;
            if (firstBaseUpdate !== null) {
              var update = firstBaseUpdate;
              do {
                var clone2 = {
                  eventTime: update.eventTime,
                  lane: update.lane,
                  tag: update.tag,
                  payload: update.payload,
                  callback: update.callback,
                  next: null
                };
                if (newLast === null) {
                  newFirst = newLast = clone2;
                } else {
                  newLast.next = clone2;
                  newLast = clone2;
                }
                update = update.next;
              } while (update !== null);
              if (newLast === null) {
                newFirst = newLast = capturedUpdate;
              } else {
                newLast.next = capturedUpdate;
                newLast = capturedUpdate;
              }
            } else {
              newFirst = newLast = capturedUpdate;
            }
            queue = {
              baseState: currentQueue.baseState,
              firstBaseUpdate: newFirst,
              lastBaseUpdate: newLast,
              shared: currentQueue.shared,
              effects: currentQueue.effects
            };
            workInProgress2.updateQueue = queue;
            return;
          }
        }
        var lastBaseUpdate = queue.lastBaseUpdate;
        if (lastBaseUpdate === null) {
          queue.firstBaseUpdate = capturedUpdate;
        } else {
          lastBaseUpdate.next = capturedUpdate;
        }
        queue.lastBaseUpdate = capturedUpdate;
      }
      function getStateFromUpdate(workInProgress2, queue, update, prevState, nextProps, instance2) {
        switch (update.tag) {
          case ReplaceState: {
            var payload = update.payload;
            if (typeof payload === "function") {
              {
                enterDisallowedContextReadInDEV();
              }
              var nextState = payload.call(instance2, prevState, nextProps);
              {
                if (workInProgress2.mode & StrictLegacyMode) {
                  setIsStrictModeForDevtools(true);
                  try {
                    payload.call(instance2, prevState, nextProps);
                  } finally {
                    setIsStrictModeForDevtools(false);
                  }
                }
                exitDisallowedContextReadInDEV();
              }
              return nextState;
            }
            return payload;
          }
          case CaptureUpdate: {
            workInProgress2.flags = workInProgress2.flags & -65537 | DidCapture;
          }
          // Intentional fallthrough
          case UpdateState: {
            var _payload = update.payload;
            var partialState;
            if (typeof _payload === "function") {
              {
                enterDisallowedContextReadInDEV();
              }
              partialState = _payload.call(instance2, prevState, nextProps);
              {
                if (workInProgress2.mode & StrictLegacyMode) {
                  setIsStrictModeForDevtools(true);
                  try {
                    _payload.call(instance2, prevState, nextProps);
                  } finally {
                    setIsStrictModeForDevtools(false);
                  }
                }
                exitDisallowedContextReadInDEV();
              }
            } else {
              partialState = _payload;
            }
            if (partialState === null || partialState === void 0) {
              return prevState;
            }
            return assign({}, prevState, partialState);
          }
          case ForceUpdate: {
            hasForceUpdate = true;
            return prevState;
          }
        }
        return prevState;
      }
      function processUpdateQueue(workInProgress2, props, instance2, renderLanes2) {
        var queue = workInProgress2.updateQueue;
        hasForceUpdate = false;
        {
          currentlyProcessingQueue = queue.shared;
        }
        var firstBaseUpdate = queue.firstBaseUpdate;
        var lastBaseUpdate = queue.lastBaseUpdate;
        var pendingQueue = queue.shared.pending;
        if (pendingQueue !== null) {
          queue.shared.pending = null;
          var lastPendingUpdate = pendingQueue;
          var firstPendingUpdate = lastPendingUpdate.next;
          lastPendingUpdate.next = null;
          if (lastBaseUpdate === null) {
            firstBaseUpdate = firstPendingUpdate;
          } else {
            lastBaseUpdate.next = firstPendingUpdate;
          }
          lastBaseUpdate = lastPendingUpdate;
          var current2 = workInProgress2.alternate;
          if (current2 !== null) {
            var currentQueue = current2.updateQueue;
            var currentLastBaseUpdate = currentQueue.lastBaseUpdate;
            if (currentLastBaseUpdate !== lastBaseUpdate) {
              if (currentLastBaseUpdate === null) {
                currentQueue.firstBaseUpdate = firstPendingUpdate;
              } else {
                currentLastBaseUpdate.next = firstPendingUpdate;
              }
              currentQueue.lastBaseUpdate = lastPendingUpdate;
            }
          }
        }
        if (firstBaseUpdate !== null) {
          var newState = queue.baseState;
          var newLanes = NoLanes;
          var newBaseState = null;
          var newFirstBaseUpdate = null;
          var newLastBaseUpdate = null;
          var update = firstBaseUpdate;
          do {
            var updateLane = update.lane;
            var updateEventTime = update.eventTime;
            if (!isSubsetOfLanes(renderLanes2, updateLane)) {
              var clone2 = {
                eventTime: updateEventTime,
                lane: updateLane,
                tag: update.tag,
                payload: update.payload,
                callback: update.callback,
                next: null
              };
              if (newLastBaseUpdate === null) {
                newFirstBaseUpdate = newLastBaseUpdate = clone2;
                newBaseState = newState;
              } else {
                newLastBaseUpdate = newLastBaseUpdate.next = clone2;
              }
              newLanes = mergeLanes(newLanes, updateLane);
            } else {
              if (newLastBaseUpdate !== null) {
                var _clone = {
                  eventTime: updateEventTime,
                  // This update is going to be committed so we never want uncommit
                  // it. Using NoLane works because 0 is a subset of all bitmasks, so
                  // this will never be skipped by the check above.
                  lane: NoLane,
                  tag: update.tag,
                  payload: update.payload,
                  callback: update.callback,
                  next: null
                };
                newLastBaseUpdate = newLastBaseUpdate.next = _clone;
              }
              newState = getStateFromUpdate(workInProgress2, queue, update, newState, props, instance2);
              var callback = update.callback;
              if (callback !== null && // If the update was already committed, we should not queue its
              // callback again.
              update.lane !== NoLane) {
                workInProgress2.flags |= Callback;
                var effects = queue.effects;
                if (effects === null) {
                  queue.effects = [update];
                } else {
                  effects.push(update);
                }
              }
            }
            update = update.next;
            if (update === null) {
              pendingQueue = queue.shared.pending;
              if (pendingQueue === null) {
                break;
              } else {
                var _lastPendingUpdate = pendingQueue;
                var _firstPendingUpdate = _lastPendingUpdate.next;
                _lastPendingUpdate.next = null;
                update = _firstPendingUpdate;
                queue.lastBaseUpdate = _lastPendingUpdate;
                queue.shared.pending = null;
              }
            }
          } while (true);
          if (newLastBaseUpdate === null) {
            newBaseState = newState;
          }
          queue.baseState = newBaseState;
          queue.firstBaseUpdate = newFirstBaseUpdate;
          queue.lastBaseUpdate = newLastBaseUpdate;
          var lastInterleaved = queue.shared.interleaved;
          if (lastInterleaved !== null) {
            var interleaved = lastInterleaved;
            do {
              newLanes = mergeLanes(newLanes, interleaved.lane);
              interleaved = interleaved.next;
            } while (interleaved !== lastInterleaved);
          } else if (firstBaseUpdate === null) {
            queue.shared.lanes = NoLanes;
          }
          markSkippedUpdateLanes(newLanes);
          workInProgress2.lanes = newLanes;
          workInProgress2.memoizedState = newState;
        }
        {
          currentlyProcessingQueue = null;
        }
      }
      function callCallback(callback, context) {
        if (typeof callback !== "function") {
          throw new Error("Invalid argument passed as callback. Expected a function. Instead " + ("received: " + callback));
        }
        callback.call(context);
      }
      function resetHasForceUpdateBeforeProcessing() {
        hasForceUpdate = false;
      }
      function checkHasForceUpdateAfterProcessing() {
        return hasForceUpdate;
      }
      function commitUpdateQueue(finishedWork, finishedQueue, instance2) {
        var effects = finishedQueue.effects;
        finishedQueue.effects = null;
        if (effects !== null) {
          for (var i2 = 0; i2 < effects.length; i2++) {
            var effect = effects[i2];
            var callback = effect.callback;
            if (callback !== null) {
              effect.callback = null;
              callCallback(callback, instance2);
            }
          }
        }
      }
      var NO_CONTEXT = {};
      var contextStackCursor$1 = createCursor(NO_CONTEXT);
      var contextFiberStackCursor = createCursor(NO_CONTEXT);
      var rootInstanceStackCursor = createCursor(NO_CONTEXT);
      function requiredContext(c2) {
        if (c2 === NO_CONTEXT) {
          throw new Error("Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.");
        }
        return c2;
      }
      function getRootHostContainer() {
        var rootInstance = requiredContext(rootInstanceStackCursor.current);
        return rootInstance;
      }
      function pushHostContainer(fiber, nextRootInstance) {
        push(rootInstanceStackCursor, nextRootInstance, fiber);
        push(contextFiberStackCursor, fiber, fiber);
        push(contextStackCursor$1, NO_CONTEXT, fiber);
        var nextRootContext = getRootHostContext(nextRootInstance);
        pop(contextStackCursor$1, fiber);
        push(contextStackCursor$1, nextRootContext, fiber);
      }
      function popHostContainer(fiber) {
        pop(contextStackCursor$1, fiber);
        pop(contextFiberStackCursor, fiber);
        pop(rootInstanceStackCursor, fiber);
      }
      function getHostContext() {
        var context = requiredContext(contextStackCursor$1.current);
        return context;
      }
      function pushHostContext(fiber) {
        requiredContext(rootInstanceStackCursor.current);
        var context = requiredContext(contextStackCursor$1.current);
        var nextContext = getChildHostContext(context, fiber.type);
        if (context === nextContext) {
          return;
        }
        push(contextFiberStackCursor, fiber, fiber);
        push(contextStackCursor$1, nextContext, fiber);
      }
      function popHostContext(fiber) {
        if (contextFiberStackCursor.current !== fiber) {
          return;
        }
        pop(contextStackCursor$1, fiber);
        pop(contextFiberStackCursor, fiber);
      }
      var DefaultSuspenseContext = 0;
      var SubtreeSuspenseContextMask = 1;
      var InvisibleParentSuspenseContext = 1;
      var ForceSuspenseFallback = 2;
      var suspenseStackCursor = createCursor(DefaultSuspenseContext);
      function hasSuspenseContext(parentContext, flag) {
        return (parentContext & flag) !== 0;
      }
      function setDefaultShallowSuspenseContext(parentContext) {
        return parentContext & SubtreeSuspenseContextMask;
      }
      function setShallowSuspenseContext(parentContext, shallowContext) {
        return parentContext & SubtreeSuspenseContextMask | shallowContext;
      }
      function addSubtreeSuspenseContext(parentContext, subtreeContext) {
        return parentContext | subtreeContext;
      }
      function pushSuspenseContext(fiber, newContext) {
        push(suspenseStackCursor, newContext, fiber);
      }
      function popSuspenseContext(fiber) {
        pop(suspenseStackCursor, fiber);
      }
      function shouldCaptureSuspense(workInProgress2, hasInvisibleParent) {
        var nextState = workInProgress2.memoizedState;
        if (nextState !== null) {
          if (nextState.dehydrated !== null) {
            return true;
          }
          return false;
        }
        workInProgress2.memoizedProps;
        {
          return true;
        }
      }
      function findFirstSuspended(row) {
        var node2 = row;
        while (node2 !== null) {
          if (node2.tag === SuspenseComponent) {
            var state = node2.memoizedState;
            if (state !== null) {
              var dehydrated = state.dehydrated;
              if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
                return node2;
              }
            }
          } else if (node2.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
          // keep track of whether it suspended or not.
          node2.memoizedProps.revealOrder !== void 0) {
            var didSuspend = (node2.flags & DidCapture) !== NoFlags;
            if (didSuspend) {
              return node2;
            }
          } else if (node2.child !== null) {
            node2.child.return = node2;
            node2 = node2.child;
            continue;
          }
          if (node2 === row) {
            return null;
          }
          while (node2.sibling === null) {
            if (node2.return === null || node2.return === row) {
              return null;
            }
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
        return null;
      }
      var NoFlags$1 = (
        /*   */
        0
      );
      var HasEffect = (
        /* */
        1
      );
      var Insertion = (
        /*  */
        2
      );
      var Layout = (
        /*    */
        4
      );
      var Passive$1 = (
        /*   */
        8
      );
      var workInProgressSources = [];
      function resetWorkInProgressVersions() {
        for (var i2 = 0; i2 < workInProgressSources.length; i2++) {
          var mutableSource = workInProgressSources[i2];
          {
            mutableSource._workInProgressVersionPrimary = null;
          }
        }
        workInProgressSources.length = 0;
      }
      function registerMutableSourceForHydration(root2, mutableSource) {
        var getVersion = mutableSource._getVersion;
        var version2 = getVersion(mutableSource._source);
        if (root2.mutableSourceEagerHydrationData == null) {
          root2.mutableSourceEagerHydrationData = [mutableSource, version2];
        } else {
          root2.mutableSourceEagerHydrationData.push(mutableSource, version2);
        }
      }
      var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentBatchConfig$2 = ReactSharedInternals.ReactCurrentBatchConfig;
      var didWarnAboutMismatchedHooksForComponent;
      var didWarnUncachedGetSnapshot;
      {
        didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
      }
      var renderLanes = NoLanes;
      var currentlyRenderingFiber$1 = null;
      var currentHook = null;
      var workInProgressHook = null;
      var didScheduleRenderPhaseUpdate = false;
      var didScheduleRenderPhaseUpdateDuringThisPass = false;
      var localIdCounter = 0;
      var globalClientIdCounter = 0;
      var RE_RENDER_LIMIT = 25;
      var currentHookNameInDev = null;
      var hookTypesDev = null;
      var hookTypesUpdateIndexDev = -1;
      var ignorePreviousDependencies = false;
      function mountHookTypesDev() {
        {
          var hookName = currentHookNameInDev;
          if (hookTypesDev === null) {
            hookTypesDev = [hookName];
          } else {
            hookTypesDev.push(hookName);
          }
        }
      }
      function updateHookTypesDev() {
        {
          var hookName = currentHookNameInDev;
          if (hookTypesDev !== null) {
            hookTypesUpdateIndexDev++;
            if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
              warnOnHookMismatchInDev(hookName);
            }
          }
        }
      }
      function checkDepsAreArrayDev(deps) {
        {
          if (deps !== void 0 && deps !== null && !isArray2(deps)) {
            error("%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.", currentHookNameInDev, typeof deps);
          }
        }
      }
      function warnOnHookMismatchInDev(currentHookName) {
        {
          var componentName = getComponentNameFromFiber(currentlyRenderingFiber$1);
          if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
            didWarnAboutMismatchedHooksForComponent.add(componentName);
            if (hookTypesDev !== null) {
              var table = "";
              var secondColumnStart = 30;
              for (var i2 = 0; i2 <= hookTypesUpdateIndexDev; i2++) {
                var oldHookName = hookTypesDev[i2];
                var newHookName = i2 === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
                var row = i2 + 1 + ". " + oldHookName;
                while (row.length < secondColumnStart) {
                  row += " ";
                }
                row += newHookName + "\n";
                table += row;
              }
              error("React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", componentName, table);
            }
          }
        }
      }
      function throwInvalidHookError() {
        throw new Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
      }
      function areHookInputsEqual(nextDeps, prevDeps) {
        {
          if (ignorePreviousDependencies) {
            return false;
          }
        }
        if (prevDeps === null) {
          {
            error("%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.", currentHookNameInDev);
          }
          return false;
        }
        {
          if (nextDeps.length !== prevDeps.length) {
            error("The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s", currentHookNameInDev, "[" + prevDeps.join(", ") + "]", "[" + nextDeps.join(", ") + "]");
          }
        }
        for (var i2 = 0; i2 < prevDeps.length && i2 < nextDeps.length; i2++) {
          if (objectIs(nextDeps[i2], prevDeps[i2])) {
            continue;
          }
          return false;
        }
        return true;
      }
      function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
        renderLanes = nextRenderLanes;
        currentlyRenderingFiber$1 = workInProgress2;
        {
          hookTypesDev = current2 !== null ? current2._debugHookTypes : null;
          hookTypesUpdateIndexDev = -1;
          ignorePreviousDependencies = current2 !== null && current2.type !== workInProgress2.type;
        }
        workInProgress2.memoizedState = null;
        workInProgress2.updateQueue = null;
        workInProgress2.lanes = NoLanes;
        {
          if (current2 !== null && current2.memoizedState !== null) {
            ReactCurrentDispatcher$1.current = HooksDispatcherOnUpdateInDEV;
          } else if (hookTypesDev !== null) {
            ReactCurrentDispatcher$1.current = HooksDispatcherOnMountWithHookTypesInDEV;
          } else {
            ReactCurrentDispatcher$1.current = HooksDispatcherOnMountInDEV;
          }
        }
        var children = Component(props, secondArg);
        if (didScheduleRenderPhaseUpdateDuringThisPass) {
          var numberOfReRenders = 0;
          do {
            didScheduleRenderPhaseUpdateDuringThisPass = false;
            localIdCounter = 0;
            if (numberOfReRenders >= RE_RENDER_LIMIT) {
              throw new Error("Too many re-renders. React limits the number of renders to prevent an infinite loop.");
            }
            numberOfReRenders += 1;
            {
              ignorePreviousDependencies = false;
            }
            currentHook = null;
            workInProgressHook = null;
            workInProgress2.updateQueue = null;
            {
              hookTypesUpdateIndexDev = -1;
            }
            ReactCurrentDispatcher$1.current = HooksDispatcherOnRerenderInDEV;
            children = Component(props, secondArg);
          } while (didScheduleRenderPhaseUpdateDuringThisPass);
        }
        ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
        {
          workInProgress2._debugHookTypes = hookTypesDev;
        }
        var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
        renderLanes = NoLanes;
        currentlyRenderingFiber$1 = null;
        currentHook = null;
        workInProgressHook = null;
        {
          currentHookNameInDev = null;
          hookTypesDev = null;
          hookTypesUpdateIndexDev = -1;
          if (current2 !== null && (current2.flags & StaticMask) !== (workInProgress2.flags & StaticMask) && // Disable this warning in legacy mode, because legacy Suspense is weird
          // and creates false positives. To make this work in legacy mode, we'd
          // need to mark fibers that commit in an incomplete state, somehow. For
          // now I'll disable the warning that most of the bugs that would trigger
          // it are either exclusive to concurrent mode or exist in both.
          (current2.mode & ConcurrentMode) !== NoMode) {
            error("Internal React error: Expected static flag was missing. Please notify the React team.");
          }
        }
        didScheduleRenderPhaseUpdate = false;
        if (didRenderTooFewHooks) {
          throw new Error("Rendered fewer hooks than expected. This may be caused by an accidental early return statement.");
        }
        return children;
      }
      function checkDidRenderIdHook() {
        var didRenderIdHook = localIdCounter !== 0;
        localIdCounter = 0;
        return didRenderIdHook;
      }
      function bailoutHooks(current2, workInProgress2, lanes) {
        workInProgress2.updateQueue = current2.updateQueue;
        if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
          workInProgress2.flags &= -50333701;
        } else {
          workInProgress2.flags &= -2053;
        }
        current2.lanes = removeLanes(current2.lanes, lanes);
      }
      function resetHooksAfterThrow() {
        ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
        if (didScheduleRenderPhaseUpdate) {
          var hook = currentlyRenderingFiber$1.memoizedState;
          while (hook !== null) {
            var queue = hook.queue;
            if (queue !== null) {
              queue.pending = null;
            }
            hook = hook.next;
          }
          didScheduleRenderPhaseUpdate = false;
        }
        renderLanes = NoLanes;
        currentlyRenderingFiber$1 = null;
        currentHook = null;
        workInProgressHook = null;
        {
          hookTypesDev = null;
          hookTypesUpdateIndexDev = -1;
          currentHookNameInDev = null;
          isUpdatingOpaqueValueInRenderPhase = false;
        }
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        localIdCounter = 0;
      }
      function mountWorkInProgressHook() {
        var hook = {
          memoizedState: null,
          baseState: null,
          baseQueue: null,
          queue: null,
          next: null
        };
        if (workInProgressHook === null) {
          currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
        } else {
          workInProgressHook = workInProgressHook.next = hook;
        }
        return workInProgressHook;
      }
      function updateWorkInProgressHook() {
        var nextCurrentHook;
        if (currentHook === null) {
          var current2 = currentlyRenderingFiber$1.alternate;
          if (current2 !== null) {
            nextCurrentHook = current2.memoizedState;
          } else {
            nextCurrentHook = null;
          }
        } else {
          nextCurrentHook = currentHook.next;
        }
        var nextWorkInProgressHook;
        if (workInProgressHook === null) {
          nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
        } else {
          nextWorkInProgressHook = workInProgressHook.next;
        }
        if (nextWorkInProgressHook !== null) {
          workInProgressHook = nextWorkInProgressHook;
          nextWorkInProgressHook = workInProgressHook.next;
          currentHook = nextCurrentHook;
        } else {
          if (nextCurrentHook === null) {
            throw new Error("Rendered more hooks than during the previous render.");
          }
          currentHook = nextCurrentHook;
          var newHook = {
            memoizedState: currentHook.memoizedState,
            baseState: currentHook.baseState,
            baseQueue: currentHook.baseQueue,
            queue: currentHook.queue,
            next: null
          };
          if (workInProgressHook === null) {
            currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
          } else {
            workInProgressHook = workInProgressHook.next = newHook;
          }
        }
        return workInProgressHook;
      }
      function createFunctionComponentUpdateQueue() {
        return {
          lastEffect: null,
          stores: null
        };
      }
      function basicStateReducer(state, action) {
        return typeof action === "function" ? action(state) : action;
      }
      function mountReducer(reducer, initialArg, init2) {
        var hook = mountWorkInProgressHook();
        var initialState;
        if (init2 !== void 0) {
          initialState = init2(initialArg);
        } else {
          initialState = initialArg;
        }
        hook.memoizedState = hook.baseState = initialState;
        var queue = {
          pending: null,
          interleaved: null,
          lanes: NoLanes,
          dispatch: null,
          lastRenderedReducer: reducer,
          lastRenderedState: initialState
        };
        hook.queue = queue;
        var dispatch = queue.dispatch = dispatchReducerAction.bind(null, currentlyRenderingFiber$1, queue);
        return [hook.memoizedState, dispatch];
      }
      function updateReducer(reducer, initialArg, init2) {
        var hook = updateWorkInProgressHook();
        var queue = hook.queue;
        if (queue === null) {
          throw new Error("Should have a queue. This is likely a bug in React. Please file an issue.");
        }
        queue.lastRenderedReducer = reducer;
        var current2 = currentHook;
        var baseQueue = current2.baseQueue;
        var pendingQueue = queue.pending;
        if (pendingQueue !== null) {
          if (baseQueue !== null) {
            var baseFirst = baseQueue.next;
            var pendingFirst = pendingQueue.next;
            baseQueue.next = pendingFirst;
            pendingQueue.next = baseFirst;
          }
          {
            if (current2.baseQueue !== baseQueue) {
              error("Internal error: Expected work-in-progress queue to be a clone. This is a bug in React.");
            }
          }
          current2.baseQueue = baseQueue = pendingQueue;
          queue.pending = null;
        }
        if (baseQueue !== null) {
          var first = baseQueue.next;
          var newState = current2.baseState;
          var newBaseState = null;
          var newBaseQueueFirst = null;
          var newBaseQueueLast = null;
          var update = first;
          do {
            var updateLane = update.lane;
            if (!isSubsetOfLanes(renderLanes, updateLane)) {
              var clone2 = {
                lane: updateLane,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              };
              if (newBaseQueueLast === null) {
                newBaseQueueFirst = newBaseQueueLast = clone2;
                newBaseState = newState;
              } else {
                newBaseQueueLast = newBaseQueueLast.next = clone2;
              }
              currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, updateLane);
              markSkippedUpdateLanes(updateLane);
            } else {
              if (newBaseQueueLast !== null) {
                var _clone = {
                  // This update is going to be committed so we never want uncommit
                  // it. Using NoLane works because 0 is a subset of all bitmasks, so
                  // this will never be skipped by the check above.
                  lane: NoLane,
                  action: update.action,
                  hasEagerState: update.hasEagerState,
                  eagerState: update.eagerState,
                  next: null
                };
                newBaseQueueLast = newBaseQueueLast.next = _clone;
              }
              if (update.hasEagerState) {
                newState = update.eagerState;
              } else {
                var action = update.action;
                newState = reducer(newState, action);
              }
            }
            update = update.next;
          } while (update !== null && update !== first);
          if (newBaseQueueLast === null) {
            newBaseState = newState;
          } else {
            newBaseQueueLast.next = newBaseQueueFirst;
          }
          if (!objectIs(newState, hook.memoizedState)) {
            markWorkInProgressReceivedUpdate();
          }
          hook.memoizedState = newState;
          hook.baseState = newBaseState;
          hook.baseQueue = newBaseQueueLast;
          queue.lastRenderedState = newState;
        }
        var lastInterleaved = queue.interleaved;
        if (lastInterleaved !== null) {
          var interleaved = lastInterleaved;
          do {
            var interleavedLane = interleaved.lane;
            currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, interleavedLane);
            markSkippedUpdateLanes(interleavedLane);
            interleaved = interleaved.next;
          } while (interleaved !== lastInterleaved);
        } else if (baseQueue === null) {
          queue.lanes = NoLanes;
        }
        var dispatch = queue.dispatch;
        return [hook.memoizedState, dispatch];
      }
      function rerenderReducer(reducer, initialArg, init2) {
        var hook = updateWorkInProgressHook();
        var queue = hook.queue;
        if (queue === null) {
          throw new Error("Should have a queue. This is likely a bug in React. Please file an issue.");
        }
        queue.lastRenderedReducer = reducer;
        var dispatch = queue.dispatch;
        var lastRenderPhaseUpdate = queue.pending;
        var newState = hook.memoizedState;
        if (lastRenderPhaseUpdate !== null) {
          queue.pending = null;
          var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
          var update = firstRenderPhaseUpdate;
          do {
            var action = update.action;
            newState = reducer(newState, action);
            update = update.next;
          } while (update !== firstRenderPhaseUpdate);
          if (!objectIs(newState, hook.memoizedState)) {
            markWorkInProgressReceivedUpdate();
          }
          hook.memoizedState = newState;
          if (hook.baseQueue === null) {
            hook.baseState = newState;
          }
          queue.lastRenderedState = newState;
        }
        return [newState, dispatch];
      }
      function mountMutableSource(source, getSnapshot, subscribe) {
        {
          return void 0;
        }
      }
      function updateMutableSource(source, getSnapshot, subscribe) {
        {
          return void 0;
        }
      }
      function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber$1;
        var hook = mountWorkInProgressHook();
        var nextSnapshot;
        var isHydrating2 = getIsHydrating();
        if (isHydrating2) {
          if (getServerSnapshot === void 0) {
            throw new Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");
          }
          nextSnapshot = getServerSnapshot();
          {
            if (!didWarnUncachedGetSnapshot) {
              if (nextSnapshot !== getServerSnapshot()) {
                error("The result of getServerSnapshot should be cached to avoid an infinite loop");
                didWarnUncachedGetSnapshot = true;
              }
            }
          }
        } else {
          nextSnapshot = getSnapshot();
          {
            if (!didWarnUncachedGetSnapshot) {
              var cachedSnapshot = getSnapshot();
              if (!objectIs(nextSnapshot, cachedSnapshot)) {
                error("The result of getSnapshot should be cached to avoid an infinite loop");
                didWarnUncachedGetSnapshot = true;
              }
            }
          }
          var root2 = getWorkInProgressRoot();
          if (root2 === null) {
            throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
          }
          if (!includesBlockingLane(root2, renderLanes)) {
            pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
          }
        }
        hook.memoizedState = nextSnapshot;
        var inst = {
          value: nextSnapshot,
          getSnapshot
        };
        hook.queue = inst;
        mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
        fiber.flags |= Passive;
        pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null);
        return nextSnapshot;
      }
      function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber$1;
        var hook = updateWorkInProgressHook();
        var nextSnapshot = getSnapshot();
        {
          if (!didWarnUncachedGetSnapshot) {
            var cachedSnapshot = getSnapshot();
            if (!objectIs(nextSnapshot, cachedSnapshot)) {
              error("The result of getSnapshot should be cached to avoid an infinite loop");
              didWarnUncachedGetSnapshot = true;
            }
          }
        }
        var prevSnapshot = hook.memoizedState;
        var snapshotChanged = !objectIs(prevSnapshot, nextSnapshot);
        if (snapshotChanged) {
          hook.memoizedState = nextSnapshot;
          markWorkInProgressReceivedUpdate();
        }
        var inst = hook.queue;
        updateEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]);
        if (inst.getSnapshot !== getSnapshot || snapshotChanged || // Check if the susbcribe function changed. We can save some memory by
        // checking whether we scheduled a subscription effect above.
        workInProgressHook !== null && workInProgressHook.memoizedState.tag & HasEffect) {
          fiber.flags |= Passive;
          pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), void 0, null);
          var root2 = getWorkInProgressRoot();
          if (root2 === null) {
            throw new Error("Expected a work-in-progress root. This is a bug in React. Please file an issue.");
          }
          if (!includesBlockingLane(root2, renderLanes)) {
            pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
          }
        }
        return nextSnapshot;
      }
      function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
        fiber.flags |= StoreConsistency;
        var check = {
          getSnapshot,
          value: renderedSnapshot
        };
        var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
        if (componentUpdateQueue === null) {
          componentUpdateQueue = createFunctionComponentUpdateQueue();
          currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
          componentUpdateQueue.stores = [check];
        } else {
          var stores = componentUpdateQueue.stores;
          if (stores === null) {
            componentUpdateQueue.stores = [check];
          } else {
            stores.push(check);
          }
        }
      }
      function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
        inst.value = nextSnapshot;
        inst.getSnapshot = getSnapshot;
        if (checkIfSnapshotChanged(inst)) {
          forceStoreRerender(fiber);
        }
      }
      function subscribeToStore(fiber, inst, subscribe) {
        var handleStoreChange = function() {
          if (checkIfSnapshotChanged(inst)) {
            forceStoreRerender(fiber);
          }
        };
        return subscribe(handleStoreChange);
      }
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        var prevValue = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(prevValue, nextValue);
        } catch (error2) {
          return true;
        }
      }
      function forceStoreRerender(fiber) {
        var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
        if (root2 !== null) {
          scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
        }
      }
      function mountState(initialState) {
        var hook = mountWorkInProgressHook();
        if (typeof initialState === "function") {
          initialState = initialState();
        }
        hook.memoizedState = hook.baseState = initialState;
        var queue = {
          pending: null,
          interleaved: null,
          lanes: NoLanes,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialState
        };
        hook.queue = queue;
        var dispatch = queue.dispatch = dispatchSetState.bind(null, currentlyRenderingFiber$1, queue);
        return [hook.memoizedState, dispatch];
      }
      function updateState(initialState) {
        return updateReducer(basicStateReducer);
      }
      function rerenderState(initialState) {
        return rerenderReducer(basicStateReducer);
      }
      function pushEffect(tag, create2, destroy, deps) {
        var effect = {
          tag,
          create: create2,
          destroy,
          deps,
          // Circular
          next: null
        };
        var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
        if (componentUpdateQueue === null) {
          componentUpdateQueue = createFunctionComponentUpdateQueue();
          currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
          componentUpdateQueue.lastEffect = effect.next = effect;
        } else {
          var lastEffect = componentUpdateQueue.lastEffect;
          if (lastEffect === null) {
            componentUpdateQueue.lastEffect = effect.next = effect;
          } else {
            var firstEffect = lastEffect.next;
            lastEffect.next = effect;
            effect.next = firstEffect;
            componentUpdateQueue.lastEffect = effect;
          }
        }
        return effect;
      }
      function mountRef(initialValue) {
        var hook = mountWorkInProgressHook();
        {
          var _ref2 = {
            current: initialValue
          };
          hook.memoizedState = _ref2;
          return _ref2;
        }
      }
      function updateRef(initialValue) {
        var hook = updateWorkInProgressHook();
        return hook.memoizedState;
      }
      function mountEffectImpl(fiberFlags, hookFlags, create2, deps) {
        var hook = mountWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        currentlyRenderingFiber$1.flags |= fiberFlags;
        hook.memoizedState = pushEffect(HasEffect | hookFlags, create2, void 0, nextDeps);
      }
      function updateEffectImpl(fiberFlags, hookFlags, create2, deps) {
        var hook = updateWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        var destroy = void 0;
        if (currentHook !== null) {
          var prevEffect = currentHook.memoizedState;
          destroy = prevEffect.destroy;
          if (nextDeps !== null) {
            var prevDeps = prevEffect.deps;
            if (areHookInputsEqual(nextDeps, prevDeps)) {
              hook.memoizedState = pushEffect(hookFlags, create2, destroy, nextDeps);
              return;
            }
          }
        }
        currentlyRenderingFiber$1.flags |= fiberFlags;
        hook.memoizedState = pushEffect(HasEffect | hookFlags, create2, destroy, nextDeps);
      }
      function mountEffect(create2, deps) {
        if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
          return mountEffectImpl(MountPassiveDev | Passive | PassiveStatic, Passive$1, create2, deps);
        } else {
          return mountEffectImpl(Passive | PassiveStatic, Passive$1, create2, deps);
        }
      }
      function updateEffect(create2, deps) {
        return updateEffectImpl(Passive, Passive$1, create2, deps);
      }
      function mountInsertionEffect(create2, deps) {
        return mountEffectImpl(Update, Insertion, create2, deps);
      }
      function updateInsertionEffect(create2, deps) {
        return updateEffectImpl(Update, Insertion, create2, deps);
      }
      function mountLayoutEffect(create2, deps) {
        var fiberFlags = Update;
        {
          fiberFlags |= LayoutStatic;
        }
        if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
          fiberFlags |= MountLayoutDev;
        }
        return mountEffectImpl(fiberFlags, Layout, create2, deps);
      }
      function updateLayoutEffect(create2, deps) {
        return updateEffectImpl(Update, Layout, create2, deps);
      }
      function imperativeHandleEffect(create2, ref2) {
        if (typeof ref2 === "function") {
          var refCallback = ref2;
          var _inst = create2();
          refCallback(_inst);
          return function() {
            refCallback(null);
          };
        } else if (ref2 !== null && ref2 !== void 0) {
          var refObject = ref2;
          {
            if (!refObject.hasOwnProperty("current")) {
              error("Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.", "an object with keys {" + Object.keys(refObject).join(", ") + "}");
            }
          }
          var _inst2 = create2();
          refObject.current = _inst2;
          return function() {
            refObject.current = null;
          };
        }
      }
      function mountImperativeHandle(ref2, create2, deps) {
        {
          if (typeof create2 !== "function") {
            error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create2 !== null ? typeof create2 : "null");
          }
        }
        var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref2]) : null;
        var fiberFlags = Update;
        {
          fiberFlags |= LayoutStatic;
        }
        if ((currentlyRenderingFiber$1.mode & StrictEffectsMode) !== NoMode) {
          fiberFlags |= MountLayoutDev;
        }
        return mountEffectImpl(fiberFlags, Layout, imperativeHandleEffect.bind(null, create2, ref2), effectDeps);
      }
      function updateImperativeHandle(ref2, create2, deps) {
        {
          if (typeof create2 !== "function") {
            error("Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.", create2 !== null ? typeof create2 : "null");
          }
        }
        var effectDeps = deps !== null && deps !== void 0 ? deps.concat([ref2]) : null;
        return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create2, ref2), effectDeps);
      }
      function mountDebugValue(value, formatterFn) {
      }
      var updateDebugValue = mountDebugValue;
      function mountCallback(callback, deps) {
        var hook = mountWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        hook.memoizedState = [callback, nextDeps];
        return callback;
      }
      function updateCallback(callback, deps) {
        var hook = updateWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        var prevState = hook.memoizedState;
        if (prevState !== null) {
          if (nextDeps !== null) {
            var prevDeps = prevState[1];
            if (areHookInputsEqual(nextDeps, prevDeps)) {
              return prevState[0];
            }
          }
        }
        hook.memoizedState = [callback, nextDeps];
        return callback;
      }
      function mountMemo(nextCreate, deps) {
        var hook = mountWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        var nextValue = nextCreate();
        hook.memoizedState = [nextValue, nextDeps];
        return nextValue;
      }
      function updateMemo(nextCreate, deps) {
        var hook = updateWorkInProgressHook();
        var nextDeps = deps === void 0 ? null : deps;
        var prevState = hook.memoizedState;
        if (prevState !== null) {
          if (nextDeps !== null) {
            var prevDeps = prevState[1];
            if (areHookInputsEqual(nextDeps, prevDeps)) {
              return prevState[0];
            }
          }
        }
        var nextValue = nextCreate();
        hook.memoizedState = [nextValue, nextDeps];
        return nextValue;
      }
      function mountDeferredValue(value) {
        var hook = mountWorkInProgressHook();
        hook.memoizedState = value;
        return value;
      }
      function updateDeferredValue(value) {
        var hook = updateWorkInProgressHook();
        var resolvedCurrentHook = currentHook;
        var prevValue = resolvedCurrentHook.memoizedState;
        return updateDeferredValueImpl(hook, prevValue, value);
      }
      function rerenderDeferredValue(value) {
        var hook = updateWorkInProgressHook();
        if (currentHook === null) {
          hook.memoizedState = value;
          return value;
        } else {
          var prevValue = currentHook.memoizedState;
          return updateDeferredValueImpl(hook, prevValue, value);
        }
      }
      function updateDeferredValueImpl(hook, prevValue, value) {
        var shouldDeferValue = !includesOnlyNonUrgentLanes(renderLanes);
        if (shouldDeferValue) {
          if (!objectIs(value, prevValue)) {
            var deferredLane = claimNextTransitionLane();
            currentlyRenderingFiber$1.lanes = mergeLanes(currentlyRenderingFiber$1.lanes, deferredLane);
            markSkippedUpdateLanes(deferredLane);
            hook.baseState = true;
          }
          return prevValue;
        } else {
          if (hook.baseState) {
            hook.baseState = false;
            markWorkInProgressReceivedUpdate();
          }
          hook.memoizedState = value;
          return value;
        }
      }
      function startTransition(setPending, callback, options22) {
        var previousPriority = getCurrentUpdatePriority();
        setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority));
        setPending(true);
        var prevTransition = ReactCurrentBatchConfig$2.transition;
        ReactCurrentBatchConfig$2.transition = {};
        var currentTransition = ReactCurrentBatchConfig$2.transition;
        {
          ReactCurrentBatchConfig$2.transition._updatedFibers = /* @__PURE__ */ new Set();
        }
        try {
          setPending(false);
          callback();
        } finally {
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig$2.transition = prevTransition;
          {
            if (prevTransition === null && currentTransition._updatedFibers) {
              var updatedFibersCount = currentTransition._updatedFibers.size;
              if (updatedFibersCount > 10) {
                warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.");
              }
              currentTransition._updatedFibers.clear();
            }
          }
        }
      }
      function mountTransition() {
        var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1];
        var start = startTransition.bind(null, setPending);
        var hook = mountWorkInProgressHook();
        hook.memoizedState = start;
        return [isPending, start];
      }
      function updateTransition() {
        var _updateState = updateState(), isPending = _updateState[0];
        var hook = updateWorkInProgressHook();
        var start = hook.memoizedState;
        return [isPending, start];
      }
      function rerenderTransition() {
        var _rerenderState = rerenderState(), isPending = _rerenderState[0];
        var hook = updateWorkInProgressHook();
        var start = hook.memoizedState;
        return [isPending, start];
      }
      var isUpdatingOpaqueValueInRenderPhase = false;
      function getIsUpdatingOpaqueValueInRenderPhaseInDEV() {
        {
          return isUpdatingOpaqueValueInRenderPhase;
        }
      }
      function mountId() {
        var hook = mountWorkInProgressHook();
        var root2 = getWorkInProgressRoot();
        var identifierPrefix = root2.identifierPrefix;
        var id;
        if (getIsHydrating()) {
          var treeId = getTreeId();
          id = ":" + identifierPrefix + "R" + treeId;
          var localId = localIdCounter++;
          if (localId > 0) {
            id += "H" + localId.toString(32);
          }
          id += ":";
        } else {
          var globalClientId = globalClientIdCounter++;
          id = ":" + identifierPrefix + "r" + globalClientId.toString(32) + ":";
        }
        hook.memoizedState = id;
        return id;
      }
      function updateId() {
        var hook = updateWorkInProgressHook();
        var id = hook.memoizedState;
        return id;
      }
      function dispatchReducerAction(fiber, queue, action) {
        {
          if (typeof arguments[3] === "function") {
            error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
          }
        }
        var lane = requestUpdateLane(fiber);
        var update = {
          lane,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) {
          enqueueRenderPhaseUpdate(queue, update);
        } else {
          var root2 = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
          if (root2 !== null) {
            var eventTime = requestEventTime();
            scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
            entangleTransitionUpdate(root2, queue, lane);
          }
        }
        markUpdateInDevTools(fiber, lane);
      }
      function dispatchSetState(fiber, queue, action) {
        {
          if (typeof arguments[3] === "function") {
            error("State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().");
          }
        }
        var lane = requestUpdateLane(fiber);
        var update = {
          lane,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) {
          enqueueRenderPhaseUpdate(queue, update);
        } else {
          var alternate = fiber.alternate;
          if (fiber.lanes === NoLanes && (alternate === null || alternate.lanes === NoLanes)) {
            var lastRenderedReducer = queue.lastRenderedReducer;
            if (lastRenderedReducer !== null) {
              var prevDispatcher;
              {
                prevDispatcher = ReactCurrentDispatcher$1.current;
                ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
              }
              try {
                var currentState = queue.lastRenderedState;
                var eagerState = lastRenderedReducer(currentState, action);
                update.hasEagerState = true;
                update.eagerState = eagerState;
                if (objectIs(eagerState, currentState)) {
                  enqueueConcurrentHookUpdateAndEagerlyBailout(fiber, queue, update, lane);
                  return;
                }
              } catch (error2) {
              } finally {
                {
                  ReactCurrentDispatcher$1.current = prevDispatcher;
                }
              }
            }
          }
          var root2 = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
          if (root2 !== null) {
            var eventTime = requestEventTime();
            scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
            entangleTransitionUpdate(root2, queue, lane);
          }
        }
        markUpdateInDevTools(fiber, lane);
      }
      function isRenderPhaseUpdate(fiber) {
        var alternate = fiber.alternate;
        return fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1;
      }
      function enqueueRenderPhaseUpdate(queue, update) {
        didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
        var pending = queue.pending;
        if (pending === null) {
          update.next = update;
        } else {
          update.next = pending.next;
          pending.next = update;
        }
        queue.pending = update;
      }
      function entangleTransitionUpdate(root2, queue, lane) {
        if (isTransitionLane(lane)) {
          var queueLanes = queue.lanes;
          queueLanes = intersectLanes(queueLanes, root2.pendingLanes);
          var newQueueLanes = mergeLanes(queueLanes, lane);
          queue.lanes = newQueueLanes;
          markRootEntangled(root2, newQueueLanes);
        }
      }
      function markUpdateInDevTools(fiber, lane, action) {
        {
          markStateUpdateScheduled(fiber, lane);
        }
      }
      var ContextOnlyDispatcher = {
        readContext,
        useCallback: throwInvalidHookError,
        useContext: throwInvalidHookError,
        useEffect: throwInvalidHookError,
        useImperativeHandle: throwInvalidHookError,
        useInsertionEffect: throwInvalidHookError,
        useLayoutEffect: throwInvalidHookError,
        useMemo: throwInvalidHookError,
        useReducer: throwInvalidHookError,
        useRef: throwInvalidHookError,
        useState: throwInvalidHookError,
        useDebugValue: throwInvalidHookError,
        useDeferredValue: throwInvalidHookError,
        useTransition: throwInvalidHookError,
        useMutableSource: throwInvalidHookError,
        useSyncExternalStore: throwInvalidHookError,
        useId: throwInvalidHookError,
        unstable_isNewReconciler: enableNewReconciler
      };
      var HooksDispatcherOnMountInDEV = null;
      var HooksDispatcherOnMountWithHookTypesInDEV = null;
      var HooksDispatcherOnUpdateInDEV = null;
      var HooksDispatcherOnRerenderInDEV = null;
      var InvalidNestedHooksDispatcherOnMountInDEV = null;
      var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
      var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
      {
        var warnInvalidContextAccess = function() {
          error("Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().");
        };
        var warnInvalidHookAccess = function() {
          error("Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks");
        };
        HooksDispatcherOnMountInDEV = {
          readContext: function(context) {
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            return mountCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            mountHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            return mountEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            return mountImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            return mountInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            return mountLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            mountHookTypesDev();
            checkDepsAreArrayDev(deps);
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            mountHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            mountHookTypesDev();
            return mountRef(initialValue);
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            mountHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            mountHookTypesDev();
            return mountDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            mountHookTypesDev();
            return mountDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            mountHookTypesDev();
            return mountTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            mountHookTypesDev();
            return mountMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            mountHookTypesDev();
            return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            mountHookTypesDev();
            return mountId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        HooksDispatcherOnMountWithHookTypesInDEV = {
          readContext: function(context) {
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            updateHookTypesDev();
            return mountCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            updateHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            updateHookTypesDev();
            return mountEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            updateHookTypesDev();
            return mountImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            updateHookTypesDev();
            return mountInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            updateHookTypesDev();
            return mountLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            updateHookTypesDev();
            return mountRef(initialValue);
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            updateHookTypesDev();
            return mountDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            updateHookTypesDev();
            return mountDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            updateHookTypesDev();
            return mountTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            updateHookTypesDev();
            return mountMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            updateHookTypesDev();
            return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            updateHookTypesDev();
            return mountId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        HooksDispatcherOnUpdateInDEV = {
          readContext: function(context) {
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            updateHookTypesDev();
            return updateCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            updateHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            updateHookTypesDev();
            return updateEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            updateHookTypesDev();
            return updateImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            updateHookTypesDev();
            return updateInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            updateHookTypesDev();
            return updateLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            updateHookTypesDev();
            return updateRef();
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            updateHookTypesDev();
            return updateDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            updateHookTypesDev();
            return updateDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            updateHookTypesDev();
            return updateTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            updateHookTypesDev();
            return updateMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            updateHookTypesDev();
            return updateSyncExternalStore(subscribe, getSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            updateHookTypesDev();
            return updateId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        HooksDispatcherOnRerenderInDEV = {
          readContext: function(context) {
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            updateHookTypesDev();
            return updateCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            updateHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            updateHookTypesDev();
            return updateEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            updateHookTypesDev();
            return updateImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            updateHookTypesDev();
            return updateInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            updateHookTypesDev();
            return updateLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
            try {
              return updateMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
            try {
              return rerenderReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            updateHookTypesDev();
            return updateRef();
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
            try {
              return rerenderState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            updateHookTypesDev();
            return updateDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            updateHookTypesDev();
            return rerenderDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            updateHookTypesDev();
            return rerenderTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            updateHookTypesDev();
            return updateMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            updateHookTypesDev();
            return updateSyncExternalStore(subscribe, getSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            updateHookTypesDev();
            return updateId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        InvalidNestedHooksDispatcherOnMountInDEV = {
          readContext: function(context) {
            warnInvalidContextAccess();
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            warnInvalidHookAccess();
            mountHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            warnInvalidHookAccess();
            mountHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountRef(initialValue);
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            warnInvalidHookAccess();
            mountHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnMountInDEV;
            try {
              return mountState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            warnInvalidHookAccess();
            mountHookTypesDev();
            return mountId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        InvalidNestedHooksDispatcherOnUpdateInDEV = {
          readContext: function(context) {
            warnInvalidContextAccess();
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateRef();
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateSyncExternalStore(subscribe, getSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
        InvalidNestedHooksDispatcherOnRerenderInDEV = {
          readContext: function(context) {
            warnInvalidContextAccess();
            return readContext(context);
          },
          useCallback: function(callback, deps) {
            currentHookNameInDev = "useCallback";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateCallback(callback, deps);
          },
          useContext: function(context) {
            currentHookNameInDev = "useContext";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return readContext(context);
          },
          useEffect: function(create2, deps) {
            currentHookNameInDev = "useEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateEffect(create2, deps);
          },
          useImperativeHandle: function(ref2, create2, deps) {
            currentHookNameInDev = "useImperativeHandle";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateImperativeHandle(ref2, create2, deps);
          },
          useInsertionEffect: function(create2, deps) {
            currentHookNameInDev = "useInsertionEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateInsertionEffect(create2, deps);
          },
          useLayoutEffect: function(create2, deps) {
            currentHookNameInDev = "useLayoutEffect";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateLayoutEffect(create2, deps);
          },
          useMemo: function(create2, deps) {
            currentHookNameInDev = "useMemo";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return updateMemo(create2, deps);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useReducer: function(reducer, initialArg, init2) {
            currentHookNameInDev = "useReducer";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return rerenderReducer(reducer, initialArg, init2);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useRef: function(initialValue) {
            currentHookNameInDev = "useRef";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateRef();
          },
          useState: function(initialState) {
            currentHookNameInDev = "useState";
            warnInvalidHookAccess();
            updateHookTypesDev();
            var prevDispatcher = ReactCurrentDispatcher$1.current;
            ReactCurrentDispatcher$1.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              return rerenderState(initialState);
            } finally {
              ReactCurrentDispatcher$1.current = prevDispatcher;
            }
          },
          useDebugValue: function(value, formatterFn) {
            currentHookNameInDev = "useDebugValue";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateDebugValue();
          },
          useDeferredValue: function(value) {
            currentHookNameInDev = "useDeferredValue";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return rerenderDeferredValue(value);
          },
          useTransition: function() {
            currentHookNameInDev = "useTransition";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return rerenderTransition();
          },
          useMutableSource: function(source, getSnapshot, subscribe) {
            currentHookNameInDev = "useMutableSource";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateMutableSource();
          },
          useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
            currentHookNameInDev = "useSyncExternalStore";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateSyncExternalStore(subscribe, getSnapshot);
          },
          useId: function() {
            currentHookNameInDev = "useId";
            warnInvalidHookAccess();
            updateHookTypesDev();
            return updateId();
          },
          unstable_isNewReconciler: enableNewReconciler
        };
      }
      var now$1 = Scheduler.unstable_now;
      var commitTime = 0;
      var layoutEffectStartTime = -1;
      var profilerStartTime = -1;
      var passiveEffectStartTime = -1;
      var currentUpdateIsNested = false;
      var nestedUpdateScheduled = false;
      function isCurrentUpdateNested() {
        return currentUpdateIsNested;
      }
      function markNestedUpdateScheduled() {
        {
          nestedUpdateScheduled = true;
        }
      }
      function resetNestedUpdateFlag() {
        {
          currentUpdateIsNested = false;
          nestedUpdateScheduled = false;
        }
      }
      function syncNestedUpdateFlag() {
        {
          currentUpdateIsNested = nestedUpdateScheduled;
          nestedUpdateScheduled = false;
        }
      }
      function getCommitTime() {
        return commitTime;
      }
      function recordCommitTime() {
        commitTime = now$1();
      }
      function startProfilerTimer(fiber) {
        profilerStartTime = now$1();
        if (fiber.actualStartTime < 0) {
          fiber.actualStartTime = now$1();
        }
      }
      function stopProfilerTimerIfRunning(fiber) {
        profilerStartTime = -1;
      }
      function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
        if (profilerStartTime >= 0) {
          var elapsedTime = now$1() - profilerStartTime;
          fiber.actualDuration += elapsedTime;
          if (overrideBaseTime) {
            fiber.selfBaseDuration = elapsedTime;
          }
          profilerStartTime = -1;
        }
      }
      function recordLayoutEffectDuration(fiber) {
        if (layoutEffectStartTime >= 0) {
          var elapsedTime = now$1() - layoutEffectStartTime;
          layoutEffectStartTime = -1;
          var parentFiber = fiber.return;
          while (parentFiber !== null) {
            switch (parentFiber.tag) {
              case HostRoot:
                var root2 = parentFiber.stateNode;
                root2.effectDuration += elapsedTime;
                return;
              case Profiler:
                var parentStateNode = parentFiber.stateNode;
                parentStateNode.effectDuration += elapsedTime;
                return;
            }
            parentFiber = parentFiber.return;
          }
        }
      }
      function recordPassiveEffectDuration(fiber) {
        if (passiveEffectStartTime >= 0) {
          var elapsedTime = now$1() - passiveEffectStartTime;
          passiveEffectStartTime = -1;
          var parentFiber = fiber.return;
          while (parentFiber !== null) {
            switch (parentFiber.tag) {
              case HostRoot:
                var root2 = parentFiber.stateNode;
                if (root2 !== null) {
                  root2.passiveEffectDuration += elapsedTime;
                }
                return;
              case Profiler:
                var parentStateNode = parentFiber.stateNode;
                if (parentStateNode !== null) {
                  parentStateNode.passiveEffectDuration += elapsedTime;
                }
                return;
            }
            parentFiber = parentFiber.return;
          }
        }
      }
      function startLayoutEffectTimer() {
        layoutEffectStartTime = now$1();
      }
      function startPassiveEffectTimer() {
        passiveEffectStartTime = now$1();
      }
      function transferActualDuration(fiber) {
        var child = fiber.child;
        while (child) {
          fiber.actualDuration += child.actualDuration;
          child = child.sibling;
        }
      }
      function resolveDefaultProps(Component, baseProps) {
        if (Component && Component.defaultProps) {
          var props = assign({}, baseProps);
          var defaultProps = Component.defaultProps;
          for (var propName in defaultProps) {
            if (props[propName] === void 0) {
              props[propName] = defaultProps[propName];
            }
          }
          return props;
        }
        return baseProps;
      }
      var fakeInternalInstance = {};
      var didWarnAboutStateAssignmentForComponent;
      var didWarnAboutUninitializedState;
      var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
      var didWarnAboutLegacyLifecyclesAndDerivedState;
      var didWarnAboutUndefinedDerivedState;
      var warnOnUndefinedDerivedState;
      var warnOnInvalidCallback;
      var didWarnAboutDirectlyAssigningPropsToState;
      var didWarnAboutContextTypeAndContextTypes;
      var didWarnAboutInvalidateContextType;
      var didWarnAboutLegacyContext$1;
      {
        didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
        didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
        didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
        didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
        didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
        didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
        didWarnAboutContextTypeAndContextTypes = /* @__PURE__ */ new Set();
        didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
        didWarnAboutLegacyContext$1 = /* @__PURE__ */ new Set();
        var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
        warnOnInvalidCallback = function(callback, callerName) {
          if (callback === null || typeof callback === "function") {
            return;
          }
          var key2 = callerName + "_" + callback;
          if (!didWarnOnInvalidCallback.has(key2)) {
            didWarnOnInvalidCallback.add(key2);
            error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
          }
        };
        warnOnUndefinedDerivedState = function(type2, partialState) {
          if (partialState === void 0) {
            var componentName = getComponentNameFromType(type2) || "Component";
            if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
              didWarnAboutUndefinedDerivedState.add(componentName);
              error("%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.", componentName);
            }
          }
        };
        Object.defineProperty(fakeInternalInstance, "_processChildContext", {
          enumerable: false,
          value: function() {
            throw new Error("_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).");
          }
        });
        Object.freeze(fakeInternalInstance);
      }
      function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
        var prevState = workInProgress2.memoizedState;
        var partialState = getDerivedStateFromProps(nextProps, prevState);
        {
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              partialState = getDerivedStateFromProps(nextProps, prevState);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          warnOnUndefinedDerivedState(ctor, partialState);
        }
        var memoizedState = partialState === null || partialState === void 0 ? prevState : assign({}, prevState, partialState);
        workInProgress2.memoizedState = memoizedState;
        if (workInProgress2.lanes === NoLanes) {
          var updateQueue = workInProgress2.updateQueue;
          updateQueue.baseState = memoizedState;
        }
      }
      var classComponentUpdater = {
        isMounted,
        enqueueSetState: function(inst, payload, callback) {
          var fiber = get2(inst);
          var eventTime = requestEventTime();
          var lane = requestUpdateLane(fiber);
          var update = createUpdate(eventTime, lane);
          update.payload = payload;
          if (callback !== void 0 && callback !== null) {
            {
              warnOnInvalidCallback(callback, "setState");
            }
            update.callback = callback;
          }
          var root2 = enqueueUpdate(fiber, update, lane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
            entangleTransitions(root2, fiber, lane);
          }
          {
            markStateUpdateScheduled(fiber, lane);
          }
        },
        enqueueReplaceState: function(inst, payload, callback) {
          var fiber = get2(inst);
          var eventTime = requestEventTime();
          var lane = requestUpdateLane(fiber);
          var update = createUpdate(eventTime, lane);
          update.tag = ReplaceState;
          update.payload = payload;
          if (callback !== void 0 && callback !== null) {
            {
              warnOnInvalidCallback(callback, "replaceState");
            }
            update.callback = callback;
          }
          var root2 = enqueueUpdate(fiber, update, lane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
            entangleTransitions(root2, fiber, lane);
          }
          {
            markStateUpdateScheduled(fiber, lane);
          }
        },
        enqueueForceUpdate: function(inst, callback) {
          var fiber = get2(inst);
          var eventTime = requestEventTime();
          var lane = requestUpdateLane(fiber);
          var update = createUpdate(eventTime, lane);
          update.tag = ForceUpdate;
          if (callback !== void 0 && callback !== null) {
            {
              warnOnInvalidCallback(callback, "forceUpdate");
            }
            update.callback = callback;
          }
          var root2 = enqueueUpdate(fiber, update, lane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
            entangleTransitions(root2, fiber, lane);
          }
          {
            markForceUpdateScheduled(fiber, lane);
          }
        }
      };
      function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
        var instance2 = workInProgress2.stateNode;
        if (typeof instance2.shouldComponentUpdate === "function") {
          var shouldUpdate = instance2.shouldComponentUpdate(newProps, newState, nextContext);
          {
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                shouldUpdate = instance2.shouldComponentUpdate(newProps, newState, nextContext);
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            if (shouldUpdate === void 0) {
              error("%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.", getComponentNameFromType(ctor) || "Component");
            }
          }
          return shouldUpdate;
        }
        if (ctor.prototype && ctor.prototype.isPureReactComponent) {
          return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
        }
        return true;
      }
      function checkClassInstance(workInProgress2, ctor, newProps) {
        var instance2 = workInProgress2.stateNode;
        {
          var name = getComponentNameFromType(ctor) || "Component";
          var renderPresent = instance2.render;
          if (!renderPresent) {
            if (ctor.prototype && typeof ctor.prototype.render === "function") {
              error("%s(...): No `render` method found on the returned component instance: did you accidentally return an object from the constructor?", name);
            } else {
              error("%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`.", name);
            }
          }
          if (instance2.getInitialState && !instance2.getInitialState.isReactClassApproved && !instance2.state) {
            error("getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?", name);
          }
          if (instance2.getDefaultProps && !instance2.getDefaultProps.isReactClassApproved) {
            error("getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.", name);
          }
          if (instance2.propTypes) {
            error("propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.", name);
          }
          if (instance2.contextType) {
            error("contextType was defined as an instance property on %s. Use a static property to define contextType instead.", name);
          }
          {
            if (ctor.childContextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
            // this one.
            (workInProgress2.mode & StrictLegacyMode) === NoMode) {
              didWarnAboutLegacyContext$1.add(ctor);
              error("%s uses the legacy childContextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() instead\n\n.Learn more about this warning here: https://reactjs.org/link/legacy-context", name);
            }
            if (ctor.contextTypes && !didWarnAboutLegacyContext$1.has(ctor) && // Strict Mode has its own warning for legacy context, so we can skip
            // this one.
            (workInProgress2.mode & StrictLegacyMode) === NoMode) {
              didWarnAboutLegacyContext$1.add(ctor);
              error("%s uses the legacy contextTypes API which is no longer supported and will be removed in the next major release. Use React.createContext() with static contextType instead.\n\nLearn more about this warning here: https://reactjs.org/link/legacy-context", name);
            }
            if (instance2.contextTypes) {
              error("contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.", name);
            }
            if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
              didWarnAboutContextTypeAndContextTypes.add(ctor);
              error("%s declares both contextTypes and contextType static properties. The legacy contextTypes property will be ignored.", name);
            }
          }
          if (typeof instance2.componentShouldUpdate === "function") {
            error("%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.", name);
          }
          if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance2.shouldComponentUpdate !== "undefined") {
            error("%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.", getComponentNameFromType(ctor) || "A pure component");
          }
          if (typeof instance2.componentDidUnmount === "function") {
            error("%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?", name);
          }
          if (typeof instance2.componentDidReceiveProps === "function") {
            error("%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().", name);
          }
          if (typeof instance2.componentWillRecieveProps === "function") {
            error("%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?", name);
          }
          if (typeof instance2.UNSAFE_componentWillRecieveProps === "function") {
            error("%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?", name);
          }
          var hasMutatedProps = instance2.props !== newProps;
          if (instance2.props !== void 0 && hasMutatedProps) {
            error("%s(...): When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.", name, name);
          }
          if (instance2.defaultProps) {
            error("Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.", name, name);
          }
          if (typeof instance2.getSnapshotBeforeUpdate === "function" && typeof instance2.componentDidUpdate !== "function" && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
            didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
            error("%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.", getComponentNameFromType(ctor));
          }
          if (typeof instance2.getDerivedStateFromProps === "function") {
            error("%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
          }
          if (typeof instance2.getDerivedStateFromError === "function") {
            error("%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.", name);
          }
          if (typeof ctor.getSnapshotBeforeUpdate === "function") {
            error("%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.", name);
          }
          var _state = instance2.state;
          if (_state && (typeof _state !== "object" || isArray2(_state))) {
            error("%s.state: must be set to an object or null", name);
          }
          if (typeof instance2.getChildContext === "function" && typeof ctor.childContextTypes !== "object") {
            error("%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().", name);
          }
        }
      }
      function adoptClassInstance(workInProgress2, instance2) {
        instance2.updater = classComponentUpdater;
        workInProgress2.stateNode = instance2;
        set(instance2, workInProgress2);
        {
          instance2._reactInternalInstance = fakeInternalInstance;
        }
      }
      function constructClassInstance(workInProgress2, ctor, props) {
        var isLegacyContextConsumer = false;
        var unmaskedContext = emptyContextObject;
        var context = emptyContextObject;
        var contextType = ctor.contextType;
        {
          if ("contextType" in ctor) {
            var isValid2 = (
              // Allow null for conditional declaration
              contextType === null || contextType !== void 0 && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === void 0
            );
            if (!isValid2 && !didWarnAboutInvalidateContextType.has(ctor)) {
              didWarnAboutInvalidateContextType.add(ctor);
              var addendum = "";
              if (contextType === void 0) {
                addendum = " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file.";
              } else if (typeof contextType !== "object") {
                addendum = " However, it is set to a " + typeof contextType + ".";
              } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
                addendum = " Did you accidentally pass the Context.Provider instead?";
              } else if (contextType._context !== void 0) {
                addendum = " Did you accidentally pass the Context.Consumer instead?";
              } else {
                addendum = " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}.";
              }
              error("%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s", getComponentNameFromType(ctor) || "Component", addendum);
            }
          }
        }
        if (typeof contextType === "object" && contextType !== null) {
          context = readContext(contextType);
        } else {
          unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
          var contextTypes = ctor.contextTypes;
          isLegacyContextConsumer = contextTypes !== null && contextTypes !== void 0;
          context = isLegacyContextConsumer ? getMaskedContext(workInProgress2, unmaskedContext) : emptyContextObject;
        }
        var instance2 = new ctor(props, context);
        {
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              instance2 = new ctor(props, context);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        }
        var state = workInProgress2.memoizedState = instance2.state !== null && instance2.state !== void 0 ? instance2.state : null;
        adoptClassInstance(workInProgress2, instance2);
        {
          if (typeof ctor.getDerivedStateFromProps === "function" && state === null) {
            var componentName = getComponentNameFromType(ctor) || "Component";
            if (!didWarnAboutUninitializedState.has(componentName)) {
              didWarnAboutUninitializedState.add(componentName);
              error("`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.", componentName, instance2.state === null ? "null" : "undefined", componentName);
            }
          }
          if (typeof ctor.getDerivedStateFromProps === "function" || typeof instance2.getSnapshotBeforeUpdate === "function") {
            var foundWillMountName = null;
            var foundWillReceivePropsName = null;
            var foundWillUpdateName = null;
            if (typeof instance2.componentWillMount === "function" && instance2.componentWillMount.__suppressDeprecationWarning !== true) {
              foundWillMountName = "componentWillMount";
            } else if (typeof instance2.UNSAFE_componentWillMount === "function") {
              foundWillMountName = "UNSAFE_componentWillMount";
            }
            if (typeof instance2.componentWillReceiveProps === "function" && instance2.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
              foundWillReceivePropsName = "componentWillReceiveProps";
            } else if (typeof instance2.UNSAFE_componentWillReceiveProps === "function") {
              foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps";
            }
            if (typeof instance2.componentWillUpdate === "function" && instance2.componentWillUpdate.__suppressDeprecationWarning !== true) {
              foundWillUpdateName = "componentWillUpdate";
            } else if (typeof instance2.UNSAFE_componentWillUpdate === "function") {
              foundWillUpdateName = "UNSAFE_componentWillUpdate";
            }
            if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
              var _componentName = getComponentNameFromType(ctor) || "Component";
              var newApiName = typeof ctor.getDerivedStateFromProps === "function" ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
              if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
                didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
                error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://reactjs.org/link/unsafe-component-lifecycles", _componentName, newApiName, foundWillMountName !== null ? "\n  " + foundWillMountName : "", foundWillReceivePropsName !== null ? "\n  " + foundWillReceivePropsName : "", foundWillUpdateName !== null ? "\n  " + foundWillUpdateName : "");
              }
            }
          }
        }
        if (isLegacyContextConsumer) {
          cacheContext(workInProgress2, unmaskedContext, context);
        }
        return instance2;
      }
      function callComponentWillMount(workInProgress2, instance2) {
        var oldState = instance2.state;
        if (typeof instance2.componentWillMount === "function") {
          instance2.componentWillMount();
        }
        if (typeof instance2.UNSAFE_componentWillMount === "function") {
          instance2.UNSAFE_componentWillMount();
        }
        if (oldState !== instance2.state) {
          {
            error("%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", getComponentNameFromFiber(workInProgress2) || "Component");
          }
          classComponentUpdater.enqueueReplaceState(instance2, instance2.state, null);
        }
      }
      function callComponentWillReceiveProps(workInProgress2, instance2, newProps, nextContext) {
        var oldState = instance2.state;
        if (typeof instance2.componentWillReceiveProps === "function") {
          instance2.componentWillReceiveProps(newProps, nextContext);
        }
        if (typeof instance2.UNSAFE_componentWillReceiveProps === "function") {
          instance2.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        }
        if (instance2.state !== oldState) {
          {
            var componentName = getComponentNameFromFiber(workInProgress2) || "Component";
            if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
              didWarnAboutStateAssignmentForComponent.add(componentName);
              error("%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.", componentName);
            }
          }
          classComponentUpdater.enqueueReplaceState(instance2, instance2.state, null);
        }
      }
      function mountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
        {
          checkClassInstance(workInProgress2, ctor, newProps);
        }
        var instance2 = workInProgress2.stateNode;
        instance2.props = newProps;
        instance2.state = workInProgress2.memoizedState;
        instance2.refs = {};
        initializeUpdateQueue(workInProgress2);
        var contextType = ctor.contextType;
        if (typeof contextType === "object" && contextType !== null) {
          instance2.context = readContext(contextType);
        } else {
          var unmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
          instance2.context = getMaskedContext(workInProgress2, unmaskedContext);
        }
        {
          if (instance2.state === newProps) {
            var componentName = getComponentNameFromType(ctor) || "Component";
            if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
              didWarnAboutDirectlyAssigningPropsToState.add(componentName);
              error("%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.", componentName);
            }
          }
          if (workInProgress2.mode & StrictLegacyMode) {
            ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, instance2);
          }
          {
            ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress2, instance2);
          }
        }
        instance2.state = workInProgress2.memoizedState;
        var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
        if (typeof getDerivedStateFromProps === "function") {
          applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
          instance2.state = workInProgress2.memoizedState;
        }
        if (typeof ctor.getDerivedStateFromProps !== "function" && typeof instance2.getSnapshotBeforeUpdate !== "function" && (typeof instance2.UNSAFE_componentWillMount === "function" || typeof instance2.componentWillMount === "function")) {
          callComponentWillMount(workInProgress2, instance2);
          processUpdateQueue(workInProgress2, newProps, instance2, renderLanes2);
          instance2.state = workInProgress2.memoizedState;
        }
        if (typeof instance2.componentDidMount === "function") {
          var fiberFlags = Update;
          {
            fiberFlags |= LayoutStatic;
          }
          if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
            fiberFlags |= MountLayoutDev;
          }
          workInProgress2.flags |= fiberFlags;
        }
      }
      function resumeMountClassInstance(workInProgress2, ctor, newProps, renderLanes2) {
        var instance2 = workInProgress2.stateNode;
        var oldProps = workInProgress2.memoizedProps;
        instance2.props = oldProps;
        var oldContext = instance2.context;
        var contextType = ctor.contextType;
        var nextContext = emptyContextObject;
        if (typeof contextType === "object" && contextType !== null) {
          nextContext = readContext(contextType);
        } else {
          var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
          nextContext = getMaskedContext(workInProgress2, nextLegacyUnmaskedContext);
        }
        var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
        var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance2.getSnapshotBeforeUpdate === "function";
        if (!hasNewLifecycles && (typeof instance2.UNSAFE_componentWillReceiveProps === "function" || typeof instance2.componentWillReceiveProps === "function")) {
          if (oldProps !== newProps || oldContext !== nextContext) {
            callComponentWillReceiveProps(workInProgress2, instance2, newProps, nextContext);
          }
        }
        resetHasForceUpdateBeforeProcessing();
        var oldState = workInProgress2.memoizedState;
        var newState = instance2.state = oldState;
        processUpdateQueue(workInProgress2, newProps, instance2, renderLanes2);
        newState = workInProgress2.memoizedState;
        if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
          if (typeof instance2.componentDidMount === "function") {
            var fiberFlags = Update;
            {
              fiberFlags |= LayoutStatic;
            }
            if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
              fiberFlags |= MountLayoutDev;
            }
            workInProgress2.flags |= fiberFlags;
          }
          return false;
        }
        if (typeof getDerivedStateFromProps === "function") {
          applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
          newState = workInProgress2.memoizedState;
        }
        var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext);
        if (shouldUpdate) {
          if (!hasNewLifecycles && (typeof instance2.UNSAFE_componentWillMount === "function" || typeof instance2.componentWillMount === "function")) {
            if (typeof instance2.componentWillMount === "function") {
              instance2.componentWillMount();
            }
            if (typeof instance2.UNSAFE_componentWillMount === "function") {
              instance2.UNSAFE_componentWillMount();
            }
          }
          if (typeof instance2.componentDidMount === "function") {
            var _fiberFlags = Update;
            {
              _fiberFlags |= LayoutStatic;
            }
            if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
              _fiberFlags |= MountLayoutDev;
            }
            workInProgress2.flags |= _fiberFlags;
          }
        } else {
          if (typeof instance2.componentDidMount === "function") {
            var _fiberFlags2 = Update;
            {
              _fiberFlags2 |= LayoutStatic;
            }
            if ((workInProgress2.mode & StrictEffectsMode) !== NoMode) {
              _fiberFlags2 |= MountLayoutDev;
            }
            workInProgress2.flags |= _fiberFlags2;
          }
          workInProgress2.memoizedProps = newProps;
          workInProgress2.memoizedState = newState;
        }
        instance2.props = newProps;
        instance2.state = newState;
        instance2.context = nextContext;
        return shouldUpdate;
      }
      function updateClassInstance(current2, workInProgress2, ctor, newProps, renderLanes2) {
        var instance2 = workInProgress2.stateNode;
        cloneUpdateQueue(current2, workInProgress2);
        var unresolvedOldProps = workInProgress2.memoizedProps;
        var oldProps = workInProgress2.type === workInProgress2.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress2.type, unresolvedOldProps);
        instance2.props = oldProps;
        var unresolvedNewProps = workInProgress2.pendingProps;
        var oldContext = instance2.context;
        var contextType = ctor.contextType;
        var nextContext = emptyContextObject;
        if (typeof contextType === "object" && contextType !== null) {
          nextContext = readContext(contextType);
        } else {
          var nextUnmaskedContext = getUnmaskedContext(workInProgress2, ctor, true);
          nextContext = getMaskedContext(workInProgress2, nextUnmaskedContext);
        }
        var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
        var hasNewLifecycles = typeof getDerivedStateFromProps === "function" || typeof instance2.getSnapshotBeforeUpdate === "function";
        if (!hasNewLifecycles && (typeof instance2.UNSAFE_componentWillReceiveProps === "function" || typeof instance2.componentWillReceiveProps === "function")) {
          if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) {
            callComponentWillReceiveProps(workInProgress2, instance2, newProps, nextContext);
          }
        }
        resetHasForceUpdateBeforeProcessing();
        var oldState = workInProgress2.memoizedState;
        var newState = instance2.state = oldState;
        processUpdateQueue(workInProgress2, newProps, instance2, renderLanes2);
        newState = workInProgress2.memoizedState;
        if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && true) {
          if (typeof instance2.componentDidUpdate === "function") {
            if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
              workInProgress2.flags |= Update;
            }
          }
          if (typeof instance2.getSnapshotBeforeUpdate === "function") {
            if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
              workInProgress2.flags |= Snapshot;
            }
          }
          return false;
        }
        if (typeof getDerivedStateFromProps === "function") {
          applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, newProps);
          newState = workInProgress2.memoizedState;
        }
        var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) || // TODO: In some cases, we'll end up checking if context has changed twice,
        // both before and after `shouldComponentUpdate` has been called. Not ideal,
        // but I'm loath to refactor this function. This only happens for memoized
        // components so it's not that common.
        enableLazyContextPropagation;
        if (shouldUpdate) {
          if (!hasNewLifecycles && (typeof instance2.UNSAFE_componentWillUpdate === "function" || typeof instance2.componentWillUpdate === "function")) {
            if (typeof instance2.componentWillUpdate === "function") {
              instance2.componentWillUpdate(newProps, newState, nextContext);
            }
            if (typeof instance2.UNSAFE_componentWillUpdate === "function") {
              instance2.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
            }
          }
          if (typeof instance2.componentDidUpdate === "function") {
            workInProgress2.flags |= Update;
          }
          if (typeof instance2.getSnapshotBeforeUpdate === "function") {
            workInProgress2.flags |= Snapshot;
          }
        } else {
          if (typeof instance2.componentDidUpdate === "function") {
            if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
              workInProgress2.flags |= Update;
            }
          }
          if (typeof instance2.getSnapshotBeforeUpdate === "function") {
            if (unresolvedOldProps !== current2.memoizedProps || oldState !== current2.memoizedState) {
              workInProgress2.flags |= Snapshot;
            }
          }
          workInProgress2.memoizedProps = newProps;
          workInProgress2.memoizedState = newState;
        }
        instance2.props = newProps;
        instance2.state = newState;
        instance2.context = nextContext;
        return shouldUpdate;
      }
      function createCapturedValueAtFiber(value, source) {
        return {
          value,
          source,
          stack: getStackByFiberInDevAndProd(source),
          digest: null
        };
      }
      function createCapturedValue(value, digest, stack) {
        return {
          value,
          source: null,
          stack: stack != null ? stack : null,
          digest: digest != null ? digest : null
        };
      }
      function showErrorDialog(boundary, errorInfo) {
        return true;
      }
      function logCapturedError(boundary, errorInfo) {
        try {
          var logError = showErrorDialog(boundary, errorInfo);
          if (logError === false) {
            return;
          }
          var error2 = errorInfo.value;
          if (true) {
            var source = errorInfo.source;
            var stack = errorInfo.stack;
            var componentStack = stack !== null ? stack : "";
            if (error2 != null && error2._suppressLogging) {
              if (boundary.tag === ClassComponent) {
                return;
              }
              console["error"](error2);
            }
            var componentName = source ? getComponentNameFromFiber(source) : null;
            var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : "The above error occurred in one of your React components:";
            var errorBoundaryMessage;
            if (boundary.tag === HostRoot) {
              errorBoundaryMessage = "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://reactjs.org/link/error-boundaries to learn more about error boundaries.";
            } else {
              var errorBoundaryName = getComponentNameFromFiber(boundary) || "Anonymous";
              errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
            }
            var combinedMessage = componentNameMessage + "\n" + componentStack + "\n\n" + ("" + errorBoundaryMessage);
            console["error"](combinedMessage);
          }
        } catch (e4) {
          setTimeout(function() {
            throw e4;
          });
        }
      }
      var PossiblyWeakMap$1 = typeof WeakMap === "function" ? WeakMap : Map;
      function createRootErrorUpdate(fiber, errorInfo, lane) {
        var update = createUpdate(NoTimestamp, lane);
        update.tag = CaptureUpdate;
        update.payload = {
          element: null
        };
        var error2 = errorInfo.value;
        update.callback = function() {
          onUncaughtError(error2);
          logCapturedError(fiber, errorInfo);
        };
        return update;
      }
      function createClassErrorUpdate(fiber, errorInfo, lane) {
        var update = createUpdate(NoTimestamp, lane);
        update.tag = CaptureUpdate;
        var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
        if (typeof getDerivedStateFromError === "function") {
          var error$1 = errorInfo.value;
          update.payload = function() {
            return getDerivedStateFromError(error$1);
          };
          update.callback = function() {
            {
              markFailedErrorBoundaryForHotReloading(fiber);
            }
            logCapturedError(fiber, errorInfo);
          };
        }
        var inst = fiber.stateNode;
        if (inst !== null && typeof inst.componentDidCatch === "function") {
          update.callback = function callback() {
            {
              markFailedErrorBoundaryForHotReloading(fiber);
            }
            logCapturedError(fiber, errorInfo);
            if (typeof getDerivedStateFromError !== "function") {
              markLegacyErrorBoundaryAsFailed(this);
            }
            var error$12 = errorInfo.value;
            var stack = errorInfo.stack;
            this.componentDidCatch(error$12, {
              componentStack: stack !== null ? stack : ""
            });
            {
              if (typeof getDerivedStateFromError !== "function") {
                if (!includesSomeLane(fiber.lanes, SyncLane)) {
                  error("%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.", getComponentNameFromFiber(fiber) || "Unknown");
                }
              }
            }
          };
        }
        return update;
      }
      function attachPingListener(root2, wakeable, lanes) {
        var pingCache = root2.pingCache;
        var threadIDs;
        if (pingCache === null) {
          pingCache = root2.pingCache = new PossiblyWeakMap$1();
          threadIDs = /* @__PURE__ */ new Set();
          pingCache.set(wakeable, threadIDs);
        } else {
          threadIDs = pingCache.get(wakeable);
          if (threadIDs === void 0) {
            threadIDs = /* @__PURE__ */ new Set();
            pingCache.set(wakeable, threadIDs);
          }
        }
        if (!threadIDs.has(lanes)) {
          threadIDs.add(lanes);
          var ping = pingSuspendedRoot.bind(null, root2, wakeable, lanes);
          {
            if (isDevToolsPresent) {
              restorePendingUpdaters(root2, lanes);
            }
          }
          wakeable.then(ping, ping);
        }
      }
      function attachRetryListener(suspenseBoundary, root2, wakeable, lanes) {
        var wakeables = suspenseBoundary.updateQueue;
        if (wakeables === null) {
          var updateQueue = /* @__PURE__ */ new Set();
          updateQueue.add(wakeable);
          suspenseBoundary.updateQueue = updateQueue;
        } else {
          wakeables.add(wakeable);
        }
      }
      function resetSuspendedComponent(sourceFiber, rootRenderLanes) {
        var tag = sourceFiber.tag;
        if ((sourceFiber.mode & ConcurrentMode) === NoMode && (tag === FunctionComponent || tag === ForwardRef || tag === SimpleMemoComponent)) {
          var currentSource = sourceFiber.alternate;
          if (currentSource) {
            sourceFiber.updateQueue = currentSource.updateQueue;
            sourceFiber.memoizedState = currentSource.memoizedState;
            sourceFiber.lanes = currentSource.lanes;
          } else {
            sourceFiber.updateQueue = null;
            sourceFiber.memoizedState = null;
          }
        }
      }
      function getNearestSuspenseBoundaryToCapture(returnFiber) {
        var node2 = returnFiber;
        do {
          if (node2.tag === SuspenseComponent && shouldCaptureSuspense(node2)) {
            return node2;
          }
          node2 = node2.return;
        } while (node2 !== null);
        return null;
      }
      function markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes) {
        if ((suspenseBoundary.mode & ConcurrentMode) === NoMode) {
          if (suspenseBoundary === returnFiber) {
            suspenseBoundary.flags |= ShouldCapture;
          } else {
            suspenseBoundary.flags |= DidCapture;
            sourceFiber.flags |= ForceUpdateForLegacySuspense;
            sourceFiber.flags &= -52805;
            if (sourceFiber.tag === ClassComponent) {
              var currentSourceFiber = sourceFiber.alternate;
              if (currentSourceFiber === null) {
                sourceFiber.tag = IncompleteClassComponent;
              } else {
                var update = createUpdate(NoTimestamp, SyncLane);
                update.tag = ForceUpdate;
                enqueueUpdate(sourceFiber, update, SyncLane);
              }
            }
            sourceFiber.lanes = mergeLanes(sourceFiber.lanes, SyncLane);
          }
          return suspenseBoundary;
        }
        suspenseBoundary.flags |= ShouldCapture;
        suspenseBoundary.lanes = rootRenderLanes;
        return suspenseBoundary;
      }
      function throwException(root2, returnFiber, sourceFiber, value, rootRenderLanes) {
        sourceFiber.flags |= Incomplete;
        {
          if (isDevToolsPresent) {
            restorePendingUpdaters(root2, rootRenderLanes);
          }
        }
        if (value !== null && typeof value === "object" && typeof value.then === "function") {
          var wakeable = value;
          resetSuspendedComponent(sourceFiber);
          {
            if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
              markDidThrowWhileHydratingDEV();
            }
          }
          var suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
          if (suspenseBoundary !== null) {
            suspenseBoundary.flags &= -257;
            markSuspenseBoundaryShouldCapture(suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes);
            if (suspenseBoundary.mode & ConcurrentMode) {
              attachPingListener(root2, wakeable, rootRenderLanes);
            }
            attachRetryListener(suspenseBoundary, root2, wakeable);
            return;
          } else {
            if (!includesSyncLane(rootRenderLanes)) {
              attachPingListener(root2, wakeable, rootRenderLanes);
              renderDidSuspendDelayIfPossible();
              return;
            }
            var uncaughtSuspenseError = new Error("A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.");
            value = uncaughtSuspenseError;
          }
        } else {
          if (getIsHydrating() && sourceFiber.mode & ConcurrentMode) {
            markDidThrowWhileHydratingDEV();
            var _suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);
            if (_suspenseBoundary !== null) {
              if ((_suspenseBoundary.flags & ShouldCapture) === NoFlags) {
                _suspenseBoundary.flags |= ForceClientRender;
              }
              markSuspenseBoundaryShouldCapture(_suspenseBoundary, returnFiber, sourceFiber, root2, rootRenderLanes);
              queueHydrationError(createCapturedValueAtFiber(value, sourceFiber));
              return;
            }
          }
        }
        value = createCapturedValueAtFiber(value, sourceFiber);
        renderDidError(value);
        var workInProgress2 = returnFiber;
        do {
          switch (workInProgress2.tag) {
            case HostRoot: {
              var _errorInfo = value;
              workInProgress2.flags |= ShouldCapture;
              var lane = pickArbitraryLane(rootRenderLanes);
              workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane);
              var update = createRootErrorUpdate(workInProgress2, _errorInfo, lane);
              enqueueCapturedUpdate(workInProgress2, update);
              return;
            }
            case ClassComponent:
              var errorInfo = value;
              var ctor = workInProgress2.type;
              var instance2 = workInProgress2.stateNode;
              if ((workInProgress2.flags & DidCapture) === NoFlags && (typeof ctor.getDerivedStateFromError === "function" || instance2 !== null && typeof instance2.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance2))) {
                workInProgress2.flags |= ShouldCapture;
                var _lane = pickArbitraryLane(rootRenderLanes);
                workInProgress2.lanes = mergeLanes(workInProgress2.lanes, _lane);
                var _update = createClassErrorUpdate(workInProgress2, errorInfo, _lane);
                enqueueCapturedUpdate(workInProgress2, _update);
                return;
              }
              break;
          }
          workInProgress2 = workInProgress2.return;
        } while (workInProgress2 !== null);
      }
      function getSuspendedCache() {
        {
          return null;
        }
      }
      var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
      var didReceiveUpdate = false;
      var didWarnAboutBadClass;
      var didWarnAboutModulePatternComponent;
      var didWarnAboutContextTypeOnFunctionComponent;
      var didWarnAboutGetDerivedStateOnFunctionComponent;
      var didWarnAboutFunctionRefs;
      var didWarnAboutReassigningProps;
      var didWarnAboutRevealOrder;
      var didWarnAboutTailOptions;
      var didWarnAboutDefaultPropsOnFunctionComponent;
      {
        didWarnAboutBadClass = {};
        didWarnAboutModulePatternComponent = {};
        didWarnAboutContextTypeOnFunctionComponent = {};
        didWarnAboutGetDerivedStateOnFunctionComponent = {};
        didWarnAboutFunctionRefs = {};
        didWarnAboutReassigningProps = false;
        didWarnAboutRevealOrder = {};
        didWarnAboutTailOptions = {};
        didWarnAboutDefaultPropsOnFunctionComponent = {};
      }
      function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
        if (current2 === null) {
          workInProgress2.child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
        } else {
          workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, nextChildren, renderLanes2);
        }
      }
      function forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2) {
        workInProgress2.child = reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
      }
      function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
        {
          if (workInProgress2.type !== workInProgress2.elementType) {
            var innerPropTypes = Component.propTypes;
            if (innerPropTypes) {
              checkPropTypes(
                innerPropTypes,
                nextProps,
                // Resolved props
                "prop",
                getComponentNameFromType(Component)
              );
            }
          }
        }
        var render2 = Component.render;
        var ref2 = workInProgress2.ref;
        var nextChildren;
        var hasId;
        prepareToReadContext(workInProgress2, renderLanes2);
        {
          markComponentRenderStarted(workInProgress2);
        }
        {
          ReactCurrentOwner$1.current = workInProgress2;
          setIsRendering(true);
          nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref2, renderLanes2);
          hasId = checkDidRenderIdHook();
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              nextChildren = renderWithHooks(current2, workInProgress2, render2, nextProps, ref2, renderLanes2);
              hasId = checkDidRenderIdHook();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          setIsRendering(false);
        }
        {
          markComponentRenderStopped();
        }
        if (current2 !== null && !didReceiveUpdate) {
          bailoutHooks(current2, workInProgress2, renderLanes2);
          return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        if (getIsHydrating() && hasId) {
          pushMaterializedTreeId(workInProgress2);
        }
        workInProgress2.flags |= PerformedWork;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (current2 === null) {
          var type2 = Component.type;
          if (isSimpleFunctionComponent(type2) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
          Component.defaultProps === void 0) {
            var resolvedType = type2;
            {
              resolvedType = resolveFunctionForHotReloading(type2);
            }
            workInProgress2.tag = SimpleMemoComponent;
            workInProgress2.type = resolvedType;
            {
              validateFunctionComponentInDev(workInProgress2, type2);
            }
            return updateSimpleMemoComponent(current2, workInProgress2, resolvedType, nextProps, renderLanes2);
          }
          {
            var innerPropTypes = type2.propTypes;
            if (innerPropTypes) {
              checkPropTypes(
                innerPropTypes,
                nextProps,
                // Resolved props
                "prop",
                getComponentNameFromType(type2)
              );
            }
            if (Component.defaultProps !== void 0) {
              var componentName = getComponentNameFromType(type2) || "Unknown";
              if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
                error("%s: Support for defaultProps will be removed from memo components in a future major release. Use JavaScript default parameters instead.", componentName);
                didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
              }
            }
          }
          var child = createFiberFromTypeAndProps(Component.type, null, nextProps, workInProgress2, workInProgress2.mode, renderLanes2);
          child.ref = workInProgress2.ref;
          child.return = workInProgress2;
          workInProgress2.child = child;
          return child;
        }
        {
          var _type = Component.type;
          var _innerPropTypes = _type.propTypes;
          if (_innerPropTypes) {
            checkPropTypes(
              _innerPropTypes,
              nextProps,
              // Resolved props
              "prop",
              getComponentNameFromType(_type)
            );
          }
        }
        var currentChild = current2.child;
        var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2);
        if (!hasScheduledUpdateOrContext) {
          var prevProps = currentChild.memoizedProps;
          var compare = Component.compare;
          compare = compare !== null ? compare : shallowEqual;
          if (compare(prevProps, nextProps) && current2.ref === workInProgress2.ref) {
            return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
          }
        }
        workInProgress2.flags |= PerformedWork;
        var newChild = createWorkInProgress(currentChild, nextProps);
        newChild.ref = workInProgress2.ref;
        newChild.return = workInProgress2;
        workInProgress2.child = newChild;
        return newChild;
      }
      function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        {
          if (workInProgress2.type !== workInProgress2.elementType) {
            var outerMemoType = workInProgress2.elementType;
            if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
              var lazyComponent = outerMemoType;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                outerMemoType = init2(payload);
              } catch (x2) {
                outerMemoType = null;
              }
              var outerPropTypes = outerMemoType && outerMemoType.propTypes;
              if (outerPropTypes) {
                checkPropTypes(
                  outerPropTypes,
                  nextProps,
                  // Resolved (SimpleMemoComponent has no defaultProps)
                  "prop",
                  getComponentNameFromType(outerMemoType)
                );
              }
            }
          }
        }
        if (current2 !== null) {
          var prevProps = current2.memoizedProps;
          if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && // Prevent bailout if the implementation changed due to hot reload.
          workInProgress2.type === current2.type) {
            didReceiveUpdate = false;
            workInProgress2.pendingProps = nextProps = prevProps;
            if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
              workInProgress2.lanes = current2.lanes;
              return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
            } else if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
              didReceiveUpdate = true;
            }
          }
        }
        return updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2);
      }
      function updateOffscreenComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps;
        var nextChildren = nextProps.children;
        var prevState = current2 !== null ? current2.memoizedState : null;
        if (nextProps.mode === "hidden" || enableLegacyHidden) {
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            var nextState = {
              baseLanes: NoLanes,
              cachePool: null,
              transitions: null
            };
            workInProgress2.memoizedState = nextState;
            pushRenderLanes(workInProgress2, renderLanes2);
          } else if (!includesSomeLane(renderLanes2, OffscreenLane)) {
            var spawnedCachePool = null;
            var nextBaseLanes;
            if (prevState !== null) {
              var prevBaseLanes = prevState.baseLanes;
              nextBaseLanes = mergeLanes(prevBaseLanes, renderLanes2);
            } else {
              nextBaseLanes = renderLanes2;
            }
            workInProgress2.lanes = workInProgress2.childLanes = laneToLanes(OffscreenLane);
            var _nextState = {
              baseLanes: nextBaseLanes,
              cachePool: spawnedCachePool,
              transitions: null
            };
            workInProgress2.memoizedState = _nextState;
            workInProgress2.updateQueue = null;
            pushRenderLanes(workInProgress2, nextBaseLanes);
            return null;
          } else {
            var _nextState2 = {
              baseLanes: NoLanes,
              cachePool: null,
              transitions: null
            };
            workInProgress2.memoizedState = _nextState2;
            var subtreeRenderLanes2 = prevState !== null ? prevState.baseLanes : renderLanes2;
            pushRenderLanes(workInProgress2, subtreeRenderLanes2);
          }
        } else {
          var _subtreeRenderLanes;
          if (prevState !== null) {
            _subtreeRenderLanes = mergeLanes(prevState.baseLanes, renderLanes2);
            workInProgress2.memoizedState = null;
          } else {
            _subtreeRenderLanes = renderLanes2;
          }
          pushRenderLanes(workInProgress2, _subtreeRenderLanes);
        }
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateFragment(current2, workInProgress2, renderLanes2) {
        var nextChildren = workInProgress2.pendingProps;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateMode(current2, workInProgress2, renderLanes2) {
        var nextChildren = workInProgress2.pendingProps.children;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateProfiler(current2, workInProgress2, renderLanes2) {
        {
          workInProgress2.flags |= Update;
          {
            var stateNode = workInProgress2.stateNode;
            stateNode.effectDuration = 0;
            stateNode.passiveEffectDuration = 0;
          }
        }
        var nextProps = workInProgress2.pendingProps;
        var nextChildren = nextProps.children;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function markRef(current2, workInProgress2) {
        var ref2 = workInProgress2.ref;
        if (current2 === null && ref2 !== null || current2 !== null && current2.ref !== ref2) {
          workInProgress2.flags |= Ref;
          {
            workInProgress2.flags |= RefStatic;
          }
        }
      }
      function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        {
          if (workInProgress2.type !== workInProgress2.elementType) {
            var innerPropTypes = Component.propTypes;
            if (innerPropTypes) {
              checkPropTypes(
                innerPropTypes,
                nextProps,
                // Resolved props
                "prop",
                getComponentNameFromType(Component)
              );
            }
          }
        }
        var context;
        {
          var unmaskedContext = getUnmaskedContext(workInProgress2, Component, true);
          context = getMaskedContext(workInProgress2, unmaskedContext);
        }
        var nextChildren;
        var hasId;
        prepareToReadContext(workInProgress2, renderLanes2);
        {
          markComponentRenderStarted(workInProgress2);
        }
        {
          ReactCurrentOwner$1.current = workInProgress2;
          setIsRendering(true);
          nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2);
          hasId = checkDidRenderIdHook();
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              nextChildren = renderWithHooks(current2, workInProgress2, Component, nextProps, context, renderLanes2);
              hasId = checkDidRenderIdHook();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          setIsRendering(false);
        }
        {
          markComponentRenderStopped();
        }
        if (current2 !== null && !didReceiveUpdate) {
          bailoutHooks(current2, workInProgress2, renderLanes2);
          return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        if (getIsHydrating() && hasId) {
          pushMaterializedTreeId(workInProgress2);
        }
        workInProgress2.flags |= PerformedWork;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        {
          switch (shouldError(workInProgress2)) {
            case false: {
              var _instance = workInProgress2.stateNode;
              var ctor = workInProgress2.type;
              var tempInstance = new ctor(workInProgress2.memoizedProps, _instance.context);
              var state = tempInstance.state;
              _instance.updater.enqueueSetState(_instance, state, null);
              break;
            }
            case true: {
              workInProgress2.flags |= DidCapture;
              workInProgress2.flags |= ShouldCapture;
              var error$1 = new Error("Simulated error coming from DevTools");
              var lane = pickArbitraryLane(renderLanes2);
              workInProgress2.lanes = mergeLanes(workInProgress2.lanes, lane);
              var update = createClassErrorUpdate(workInProgress2, createCapturedValueAtFiber(error$1, workInProgress2), lane);
              enqueueCapturedUpdate(workInProgress2, update);
              break;
            }
          }
          if (workInProgress2.type !== workInProgress2.elementType) {
            var innerPropTypes = Component.propTypes;
            if (innerPropTypes) {
              checkPropTypes(
                innerPropTypes,
                nextProps,
                // Resolved props
                "prop",
                getComponentNameFromType(Component)
              );
            }
          }
        }
        var hasContext;
        if (isContextProvider(Component)) {
          hasContext = true;
          pushContextProvider(workInProgress2);
        } else {
          hasContext = false;
        }
        prepareToReadContext(workInProgress2, renderLanes2);
        var instance2 = workInProgress2.stateNode;
        var shouldUpdate;
        if (instance2 === null) {
          resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2);
          constructClassInstance(workInProgress2, Component, nextProps);
          mountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
          shouldUpdate = true;
        } else if (current2 === null) {
          shouldUpdate = resumeMountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
        } else {
          shouldUpdate = updateClassInstance(current2, workInProgress2, Component, nextProps, renderLanes2);
        }
        var nextUnitOfWork = finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2);
        {
          var inst = workInProgress2.stateNode;
          if (shouldUpdate && inst.props !== nextProps) {
            if (!didWarnAboutReassigningProps) {
              error("It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.", getComponentNameFromFiber(workInProgress2) || "a component");
            }
            didWarnAboutReassigningProps = true;
          }
        }
        return nextUnitOfWork;
      }
      function finishClassComponent(current2, workInProgress2, Component, shouldUpdate, hasContext, renderLanes2) {
        markRef(current2, workInProgress2);
        var didCaptureError = (workInProgress2.flags & DidCapture) !== NoFlags;
        if (!shouldUpdate && !didCaptureError) {
          if (hasContext) {
            invalidateContextProvider(workInProgress2, Component, false);
          }
          return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        var instance2 = workInProgress2.stateNode;
        ReactCurrentOwner$1.current = workInProgress2;
        var nextChildren;
        if (didCaptureError && typeof Component.getDerivedStateFromError !== "function") {
          nextChildren = null;
          {
            stopProfilerTimerIfRunning();
          }
        } else {
          {
            markComponentRenderStarted(workInProgress2);
          }
          {
            setIsRendering(true);
            nextChildren = instance2.render();
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                instance2.render();
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
            setIsRendering(false);
          }
          {
            markComponentRenderStopped();
          }
        }
        workInProgress2.flags |= PerformedWork;
        if (current2 !== null && didCaptureError) {
          forceUnmountCurrentAndReconcile(current2, workInProgress2, nextChildren, renderLanes2);
        } else {
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        }
        workInProgress2.memoizedState = instance2.state;
        if (hasContext) {
          invalidateContextProvider(workInProgress2, Component, true);
        }
        return workInProgress2.child;
      }
      function pushHostRootContext(workInProgress2) {
        var root2 = workInProgress2.stateNode;
        if (root2.pendingContext) {
          pushTopLevelContextObject(workInProgress2, root2.pendingContext, root2.pendingContext !== root2.context);
        } else if (root2.context) {
          pushTopLevelContextObject(workInProgress2, root2.context, false);
        }
        pushHostContainer(workInProgress2, root2.containerInfo);
      }
      function updateHostRoot(current2, workInProgress2, renderLanes2) {
        pushHostRootContext(workInProgress2);
        if (current2 === null) {
          throw new Error("Should have a current fiber. This is a bug in React.");
        }
        var nextProps = workInProgress2.pendingProps;
        var prevState = workInProgress2.memoizedState;
        var prevChildren = prevState.element;
        cloneUpdateQueue(current2, workInProgress2);
        processUpdateQueue(workInProgress2, nextProps, null, renderLanes2);
        var nextState = workInProgress2.memoizedState;
        workInProgress2.stateNode;
        var nextChildren = nextState.element;
        if (prevState.isDehydrated) {
          var overrideState = {
            element: nextChildren,
            isDehydrated: false,
            cache: nextState.cache,
            pendingSuspenseBoundaries: nextState.pendingSuspenseBoundaries,
            transitions: nextState.transitions
          };
          var updateQueue = workInProgress2.updateQueue;
          updateQueue.baseState = overrideState;
          workInProgress2.memoizedState = overrideState;
          if (workInProgress2.flags & ForceClientRender) {
            var recoverableError = createCapturedValueAtFiber(new Error("There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering."), workInProgress2);
            return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError);
          } else if (nextChildren !== prevChildren) {
            var _recoverableError = createCapturedValueAtFiber(new Error("This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."), workInProgress2);
            return mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, _recoverableError);
          } else {
            enterHydrationState(workInProgress2);
            var child = mountChildFibers(workInProgress2, null, nextChildren, renderLanes2);
            workInProgress2.child = child;
            var node2 = child;
            while (node2) {
              node2.flags = node2.flags & -3 | Hydrating;
              node2 = node2.sibling;
            }
          }
        } else {
          resetHydrationState();
          if (nextChildren === prevChildren) {
            return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
          }
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        }
        return workInProgress2.child;
      }
      function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2, recoverableError) {
        resetHydrationState();
        queueHydrationError(recoverableError);
        workInProgress2.flags |= ForceClientRender;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateHostComponent(current2, workInProgress2, renderLanes2) {
        pushHostContext(workInProgress2);
        if (current2 === null) {
          tryToClaimNextHydratableInstance(workInProgress2);
        }
        var type2 = workInProgress2.type;
        var nextProps = workInProgress2.pendingProps;
        var prevProps = current2 !== null ? current2.memoizedProps : null;
        var nextChildren = nextProps.children;
        var isDirectTextChild = shouldSetTextContent(type2, nextProps);
        if (isDirectTextChild) {
          nextChildren = null;
        } else if (prevProps !== null && shouldSetTextContent(type2, prevProps)) {
          workInProgress2.flags |= ContentReset;
        }
        markRef(current2, workInProgress2);
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function updateHostText(current2, workInProgress2) {
        if (current2 === null) {
          tryToClaimNextHydratableInstance(workInProgress2);
        }
        return null;
      }
      function mountLazyComponent(_current, workInProgress2, elementType, renderLanes2) {
        resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
        var props = workInProgress2.pendingProps;
        var lazyComponent = elementType;
        var payload = lazyComponent._payload;
        var init2 = lazyComponent._init;
        var Component = init2(payload);
        workInProgress2.type = Component;
        var resolvedTag = workInProgress2.tag = resolveLazyComponentTag(Component);
        var resolvedProps = resolveDefaultProps(Component, props);
        var child;
        switch (resolvedTag) {
          case FunctionComponent: {
            {
              validateFunctionComponentInDev(workInProgress2, Component);
              workInProgress2.type = Component = resolveFunctionForHotReloading(Component);
            }
            child = updateFunctionComponent(null, workInProgress2, Component, resolvedProps, renderLanes2);
            return child;
          }
          case ClassComponent: {
            {
              workInProgress2.type = Component = resolveClassForHotReloading(Component);
            }
            child = updateClassComponent(null, workInProgress2, Component, resolvedProps, renderLanes2);
            return child;
          }
          case ForwardRef: {
            {
              workInProgress2.type = Component = resolveForwardRefForHotReloading(Component);
            }
            child = updateForwardRef(null, workInProgress2, Component, resolvedProps, renderLanes2);
            return child;
          }
          case MemoComponent: {
            {
              if (workInProgress2.type !== workInProgress2.elementType) {
                var outerPropTypes = Component.propTypes;
                if (outerPropTypes) {
                  checkPropTypes(
                    outerPropTypes,
                    resolvedProps,
                    // Resolved for outer only
                    "prop",
                    getComponentNameFromType(Component)
                  );
                }
              }
            }
            child = updateMemoComponent(
              null,
              workInProgress2,
              Component,
              resolveDefaultProps(Component.type, resolvedProps),
              // The inner type can have defaults too
              renderLanes2
            );
            return child;
          }
        }
        var hint = "";
        {
          if (Component !== null && typeof Component === "object" && Component.$$typeof === REACT_LAZY_TYPE) {
            hint = " Did you wrap a component in React.lazy() more than once?";
          }
        }
        throw new Error("Element type is invalid. Received a promise that resolves to: " + Component + ". " + ("Lazy element type must resolve to a class or function." + hint));
      }
      function mountIncompleteClassComponent(_current, workInProgress2, Component, nextProps, renderLanes2) {
        resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
        workInProgress2.tag = ClassComponent;
        var hasContext;
        if (isContextProvider(Component)) {
          hasContext = true;
          pushContextProvider(workInProgress2);
        } else {
          hasContext = false;
        }
        prepareToReadContext(workInProgress2, renderLanes2);
        constructClassInstance(workInProgress2, Component, nextProps);
        mountClassInstance(workInProgress2, Component, nextProps, renderLanes2);
        return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2);
      }
      function mountIndeterminateComponent(_current, workInProgress2, Component, renderLanes2) {
        resetSuspendedCurrentOnMountInLegacyMode(_current, workInProgress2);
        var props = workInProgress2.pendingProps;
        var context;
        {
          var unmaskedContext = getUnmaskedContext(workInProgress2, Component, false);
          context = getMaskedContext(workInProgress2, unmaskedContext);
        }
        prepareToReadContext(workInProgress2, renderLanes2);
        var value;
        var hasId;
        {
          markComponentRenderStarted(workInProgress2);
        }
        {
          if (Component.prototype && typeof Component.prototype.render === "function") {
            var componentName = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutBadClass[componentName]) {
              error("The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.", componentName, componentName);
              didWarnAboutBadClass[componentName] = true;
            }
          }
          if (workInProgress2.mode & StrictLegacyMode) {
            ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress2, null);
          }
          setIsRendering(true);
          ReactCurrentOwner$1.current = workInProgress2;
          value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2);
          hasId = checkDidRenderIdHook();
          setIsRendering(false);
        }
        {
          markComponentRenderStopped();
        }
        workInProgress2.flags |= PerformedWork;
        {
          if (typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0) {
            var _componentName = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutModulePatternComponent[_componentName]) {
              error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName, _componentName, _componentName);
              didWarnAboutModulePatternComponent[_componentName] = true;
            }
          }
        }
        if (
          // Run these checks in production only if the flag is off.
          // Eventually we'll delete this branch altogether.
          typeof value === "object" && value !== null && typeof value.render === "function" && value.$$typeof === void 0
        ) {
          {
            var _componentName2 = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutModulePatternComponent[_componentName2]) {
              error("The <%s /> component appears to be a function component that returns a class instance. Change %s to a class that extends React.Component instead. If you can't use a class try assigning the prototype on the function as a workaround. `%s.prototype = React.Component.prototype`. Don't use an arrow function since it cannot be called with `new` by React.", _componentName2, _componentName2, _componentName2);
              didWarnAboutModulePatternComponent[_componentName2] = true;
            }
          }
          workInProgress2.tag = ClassComponent;
          workInProgress2.memoizedState = null;
          workInProgress2.updateQueue = null;
          var hasContext = false;
          if (isContextProvider(Component)) {
            hasContext = true;
            pushContextProvider(workInProgress2);
          } else {
            hasContext = false;
          }
          workInProgress2.memoizedState = value.state !== null && value.state !== void 0 ? value.state : null;
          initializeUpdateQueue(workInProgress2);
          adoptClassInstance(workInProgress2, value);
          mountClassInstance(workInProgress2, Component, props, renderLanes2);
          return finishClassComponent(null, workInProgress2, Component, true, hasContext, renderLanes2);
        } else {
          workInProgress2.tag = FunctionComponent;
          {
            if (workInProgress2.mode & StrictLegacyMode) {
              setIsStrictModeForDevtools(true);
              try {
                value = renderWithHooks(null, workInProgress2, Component, props, context, renderLanes2);
                hasId = checkDidRenderIdHook();
              } finally {
                setIsStrictModeForDevtools(false);
              }
            }
          }
          if (getIsHydrating() && hasId) {
            pushMaterializedTreeId(workInProgress2);
          }
          reconcileChildren(null, workInProgress2, value, renderLanes2);
          {
            validateFunctionComponentInDev(workInProgress2, Component);
          }
          return workInProgress2.child;
        }
      }
      function validateFunctionComponentInDev(workInProgress2, Component) {
        {
          if (Component) {
            if (Component.childContextTypes) {
              error("%s(...): childContextTypes cannot be defined on a function component.", Component.displayName || Component.name || "Component");
            }
          }
          if (workInProgress2.ref !== null) {
            var info = "";
            var ownerName = getCurrentFiberOwnerNameInDevOrNull();
            if (ownerName) {
              info += "\n\nCheck the render method of `" + ownerName + "`.";
            }
            var warningKey = ownerName || "";
            var debugSource = workInProgress2._debugSource;
            if (debugSource) {
              warningKey = debugSource.fileName + ":" + debugSource.lineNumber;
            }
            if (!didWarnAboutFunctionRefs[warningKey]) {
              didWarnAboutFunctionRefs[warningKey] = true;
              error("Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?%s", info);
            }
          }
          if (Component.defaultProps !== void 0) {
            var componentName = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) {
              error("%s: Support for defaultProps will be removed from function components in a future major release. Use JavaScript default parameters instead.", componentName);
              didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true;
            }
          }
          if (typeof Component.getDerivedStateFromProps === "function") {
            var _componentName3 = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) {
              error("%s: Function components do not support getDerivedStateFromProps.", _componentName3);
              didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true;
            }
          }
          if (typeof Component.contextType === "object" && Component.contextType !== null) {
            var _componentName4 = getComponentNameFromType(Component) || "Unknown";
            if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) {
              error("%s: Function components do not support contextType.", _componentName4);
              didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true;
            }
          }
        }
      }
      var SUSPENDED_MARKER = {
        dehydrated: null,
        treeContext: null,
        retryLane: NoLane
      };
      function mountSuspenseOffscreenState(renderLanes2) {
        return {
          baseLanes: renderLanes2,
          cachePool: getSuspendedCache(),
          transitions: null
        };
      }
      function updateSuspenseOffscreenState(prevOffscreenState, renderLanes2) {
        var cachePool = null;
        return {
          baseLanes: mergeLanes(prevOffscreenState.baseLanes, renderLanes2),
          cachePool,
          transitions: prevOffscreenState.transitions
        };
      }
      function shouldRemainOnFallback(suspenseContext, current2, workInProgress2, renderLanes2) {
        if (current2 !== null) {
          var suspenseState = current2.memoizedState;
          if (suspenseState === null) {
            return false;
          }
        }
        return hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
      }
      function getRemainingWorkInPrimaryTree(current2, renderLanes2) {
        return removeLanes(current2.childLanes, renderLanes2);
      }
      function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps;
        {
          if (shouldSuspend2(workInProgress2)) {
            workInProgress2.flags |= DidCapture;
          }
        }
        var suspenseContext = suspenseStackCursor.current;
        var showFallback = false;
        var didSuspend = (workInProgress2.flags & DidCapture) !== NoFlags;
        if (didSuspend || shouldRemainOnFallback(suspenseContext, current2)) {
          showFallback = true;
          workInProgress2.flags &= -129;
        } else {
          if (current2 === null || current2.memoizedState !== null) {
            {
              suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
            }
          }
        }
        suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
        pushSuspenseContext(workInProgress2, suspenseContext);
        if (current2 === null) {
          tryToClaimNextHydratableInstance(workInProgress2);
          var suspenseState = workInProgress2.memoizedState;
          if (suspenseState !== null) {
            var dehydrated = suspenseState.dehydrated;
            if (dehydrated !== null) {
              return mountDehydratedSuspenseComponent(workInProgress2, dehydrated);
            }
          }
          var nextPrimaryChildren = nextProps.children;
          var nextFallbackChildren = nextProps.fallback;
          if (showFallback) {
            var fallbackFragment = mountSuspenseFallbackChildren(workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
            var primaryChildFragment = workInProgress2.child;
            primaryChildFragment.memoizedState = mountSuspenseOffscreenState(renderLanes2);
            workInProgress2.memoizedState = SUSPENDED_MARKER;
            return fallbackFragment;
          } else {
            return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren);
          }
        } else {
          var prevState = current2.memoizedState;
          if (prevState !== null) {
            var _dehydrated = prevState.dehydrated;
            if (_dehydrated !== null) {
              return updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, _dehydrated, prevState, renderLanes2);
            }
          }
          if (showFallback) {
            var _nextFallbackChildren = nextProps.fallback;
            var _nextPrimaryChildren = nextProps.children;
            var fallbackChildFragment = updateSuspenseFallbackChildren(current2, workInProgress2, _nextPrimaryChildren, _nextFallbackChildren, renderLanes2);
            var _primaryChildFragment2 = workInProgress2.child;
            var prevOffscreenState = current2.child.memoizedState;
            _primaryChildFragment2.memoizedState = prevOffscreenState === null ? mountSuspenseOffscreenState(renderLanes2) : updateSuspenseOffscreenState(prevOffscreenState, renderLanes2);
            _primaryChildFragment2.childLanes = getRemainingWorkInPrimaryTree(current2, renderLanes2);
            workInProgress2.memoizedState = SUSPENDED_MARKER;
            return fallbackChildFragment;
          } else {
            var _nextPrimaryChildren2 = nextProps.children;
            var _primaryChildFragment3 = updateSuspensePrimaryChildren(current2, workInProgress2, _nextPrimaryChildren2, renderLanes2);
            workInProgress2.memoizedState = null;
            return _primaryChildFragment3;
          }
        }
      }
      function mountSuspensePrimaryChildren(workInProgress2, primaryChildren, renderLanes2) {
        var mode = workInProgress2.mode;
        var primaryChildProps = {
          mode: "visible",
          children: primaryChildren
        };
        var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
        primaryChildFragment.return = workInProgress2;
        workInProgress2.child = primaryChildFragment;
        return primaryChildFragment;
      }
      function mountSuspenseFallbackChildren(workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
        var mode = workInProgress2.mode;
        var progressedPrimaryFragment = workInProgress2.child;
        var primaryChildProps = {
          mode: "hidden",
          children: primaryChildren
        };
        var primaryChildFragment;
        var fallbackChildFragment;
        if ((mode & ConcurrentMode) === NoMode && progressedPrimaryFragment !== null) {
          primaryChildFragment = progressedPrimaryFragment;
          primaryChildFragment.childLanes = NoLanes;
          primaryChildFragment.pendingProps = primaryChildProps;
          if (workInProgress2.mode & ProfileMode) {
            primaryChildFragment.actualDuration = 0;
            primaryChildFragment.actualStartTime = -1;
            primaryChildFragment.selfBaseDuration = 0;
            primaryChildFragment.treeBaseDuration = 0;
          }
          fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
        } else {
          primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, mode);
          fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
        }
        primaryChildFragment.return = workInProgress2;
        fallbackChildFragment.return = workInProgress2;
        primaryChildFragment.sibling = fallbackChildFragment;
        workInProgress2.child = primaryChildFragment;
        return fallbackChildFragment;
      }
      function mountWorkInProgressOffscreenFiber(offscreenProps, mode, renderLanes2) {
        return createFiberFromOffscreen(offscreenProps, mode, NoLanes, null);
      }
      function updateWorkInProgressOffscreenFiber(current2, offscreenProps) {
        return createWorkInProgress(current2, offscreenProps);
      }
      function updateSuspensePrimaryChildren(current2, workInProgress2, primaryChildren, renderLanes2) {
        var currentPrimaryChildFragment = current2.child;
        var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
        var primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, {
          mode: "visible",
          children: primaryChildren
        });
        if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
          primaryChildFragment.lanes = renderLanes2;
        }
        primaryChildFragment.return = workInProgress2;
        primaryChildFragment.sibling = null;
        if (currentFallbackChildFragment !== null) {
          var deletions = workInProgress2.deletions;
          if (deletions === null) {
            workInProgress2.deletions = [currentFallbackChildFragment];
            workInProgress2.flags |= ChildDeletion;
          } else {
            deletions.push(currentFallbackChildFragment);
          }
        }
        workInProgress2.child = primaryChildFragment;
        return primaryChildFragment;
      }
      function updateSuspenseFallbackChildren(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
        var mode = workInProgress2.mode;
        var currentPrimaryChildFragment = current2.child;
        var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
        var primaryChildProps = {
          mode: "hidden",
          children: primaryChildren
        };
        var primaryChildFragment;
        if (
          // In legacy mode, we commit the primary tree as if it successfully
          // completed, even though it's in an inconsistent state.
          (mode & ConcurrentMode) === NoMode && // Make sure we're on the second pass, i.e. the primary child fragment was
          // already cloned. In legacy mode, the only case where this isn't true is
          // when DevTools forces us to display a fallback; we skip the first render
          // pass entirely and go straight to rendering the fallback. (In Concurrent
          // Mode, SuspenseList can also trigger this scenario, but this is a legacy-
          // only codepath.)
          workInProgress2.child !== currentPrimaryChildFragment
        ) {
          var progressedPrimaryFragment = workInProgress2.child;
          primaryChildFragment = progressedPrimaryFragment;
          primaryChildFragment.childLanes = NoLanes;
          primaryChildFragment.pendingProps = primaryChildProps;
          if (workInProgress2.mode & ProfileMode) {
            primaryChildFragment.actualDuration = 0;
            primaryChildFragment.actualStartTime = -1;
            primaryChildFragment.selfBaseDuration = currentPrimaryChildFragment.selfBaseDuration;
            primaryChildFragment.treeBaseDuration = currentPrimaryChildFragment.treeBaseDuration;
          }
          workInProgress2.deletions = null;
        } else {
          primaryChildFragment = updateWorkInProgressOffscreenFiber(currentPrimaryChildFragment, primaryChildProps);
          primaryChildFragment.subtreeFlags = currentPrimaryChildFragment.subtreeFlags & StaticMask;
        }
        var fallbackChildFragment;
        if (currentFallbackChildFragment !== null) {
          fallbackChildFragment = createWorkInProgress(currentFallbackChildFragment, fallbackChildren);
        } else {
          fallbackChildFragment = createFiberFromFragment(fallbackChildren, mode, renderLanes2, null);
          fallbackChildFragment.flags |= Placement;
        }
        fallbackChildFragment.return = workInProgress2;
        primaryChildFragment.return = workInProgress2;
        primaryChildFragment.sibling = fallbackChildFragment;
        workInProgress2.child = primaryChildFragment;
        return fallbackChildFragment;
      }
      function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, recoverableError) {
        if (recoverableError !== null) {
          queueHydrationError(recoverableError);
        }
        reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        var nextProps = workInProgress2.pendingProps;
        var primaryChildren = nextProps.children;
        var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren);
        primaryChildFragment.flags |= Placement;
        workInProgress2.memoizedState = null;
        return primaryChildFragment;
      }
      function mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, primaryChildren, fallbackChildren, renderLanes2) {
        var fiberMode = workInProgress2.mode;
        var primaryChildProps = {
          mode: "visible",
          children: primaryChildren
        };
        var primaryChildFragment = mountWorkInProgressOffscreenFiber(primaryChildProps, fiberMode);
        var fallbackChildFragment = createFiberFromFragment(fallbackChildren, fiberMode, renderLanes2, null);
        fallbackChildFragment.flags |= Placement;
        primaryChildFragment.return = workInProgress2;
        fallbackChildFragment.return = workInProgress2;
        primaryChildFragment.sibling = fallbackChildFragment;
        workInProgress2.child = primaryChildFragment;
        if ((workInProgress2.mode & ConcurrentMode) !== NoMode) {
          reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        }
        return fallbackChildFragment;
      }
      function mountDehydratedSuspenseComponent(workInProgress2, suspenseInstance, renderLanes2) {
        if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
          {
            error("Cannot hydrate Suspense in legacy mode. Switch from ReactDOM.hydrate(element, container) to ReactDOMClient.hydrateRoot(container, <App />).render(element) or remove the Suspense components from the server rendered components.");
          }
          workInProgress2.lanes = laneToLanes(SyncLane);
        } else if (isSuspenseInstanceFallback(suspenseInstance)) {
          workInProgress2.lanes = laneToLanes(DefaultHydrationLane);
        } else {
          workInProgress2.lanes = laneToLanes(OffscreenLane);
        }
        return null;
      }
      function updateDehydratedSuspenseComponent(current2, workInProgress2, didSuspend, nextProps, suspenseInstance, suspenseState, renderLanes2) {
        if (!didSuspend) {
          warnIfHydrating();
          if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
            return retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2,
              // TODO: When we delete legacy mode, we should make this error argument
              // required — every concurrent mode path that causes hydration to
              // de-opt to client rendering should have an error message.
              null
            );
          }
          if (isSuspenseInstanceFallback(suspenseInstance)) {
            var digest, message, stack;
            {
              var _getSuspenseInstanceF = getSuspenseInstanceFallbackErrorDetails(suspenseInstance);
              digest = _getSuspenseInstanceF.digest;
              message = _getSuspenseInstanceF.message;
              stack = _getSuspenseInstanceF.stack;
            }
            var error2;
            if (message) {
              error2 = new Error(message);
            } else {
              error2 = new Error("The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering.");
            }
            var capturedValue = createCapturedValue(error2, digest, stack);
            return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, capturedValue);
          }
          var hasContextChanged2 = includesSomeLane(renderLanes2, current2.childLanes);
          if (didReceiveUpdate || hasContextChanged2) {
            var root2 = getWorkInProgressRoot();
            if (root2 !== null) {
              var attemptHydrationAtLane = getBumpedLaneForHydration(root2, renderLanes2);
              if (attemptHydrationAtLane !== NoLane && attemptHydrationAtLane !== suspenseState.retryLane) {
                suspenseState.retryLane = attemptHydrationAtLane;
                var eventTime = NoTimestamp;
                enqueueConcurrentRenderForLane(current2, attemptHydrationAtLane);
                scheduleUpdateOnFiber(root2, current2, attemptHydrationAtLane, eventTime);
              }
            }
            renderDidSuspendDelayIfPossible();
            var _capturedValue = createCapturedValue(new Error("This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch to client rendering. The usual way to fix this is to wrap the original update in startTransition."));
            return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue);
          } else if (isSuspenseInstancePending(suspenseInstance)) {
            workInProgress2.flags |= DidCapture;
            workInProgress2.child = current2.child;
            var retry = retryDehydratedSuspenseBoundary.bind(null, current2);
            registerSuspenseInstanceRetry(suspenseInstance, retry);
            return null;
          } else {
            reenterHydrationStateFromDehydratedSuspenseInstance(workInProgress2, suspenseInstance, suspenseState.treeContext);
            var primaryChildren = nextProps.children;
            var primaryChildFragment = mountSuspensePrimaryChildren(workInProgress2, primaryChildren);
            primaryChildFragment.flags |= Hydrating;
            return primaryChildFragment;
          }
        } else {
          if (workInProgress2.flags & ForceClientRender) {
            workInProgress2.flags &= -257;
            var _capturedValue2 = createCapturedValue(new Error("There was an error while hydrating this Suspense boundary. Switched to client rendering."));
            return retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2, _capturedValue2);
          } else if (workInProgress2.memoizedState !== null) {
            workInProgress2.child = current2.child;
            workInProgress2.flags |= DidCapture;
            return null;
          } else {
            var nextPrimaryChildren = nextProps.children;
            var nextFallbackChildren = nextProps.fallback;
            var fallbackChildFragment = mountSuspenseFallbackAfterRetryWithoutHydrating(current2, workInProgress2, nextPrimaryChildren, nextFallbackChildren, renderLanes2);
            var _primaryChildFragment4 = workInProgress2.child;
            _primaryChildFragment4.memoizedState = mountSuspenseOffscreenState(renderLanes2);
            workInProgress2.memoizedState = SUSPENDED_MARKER;
            return fallbackChildFragment;
          }
        }
      }
      function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
        fiber.lanes = mergeLanes(fiber.lanes, renderLanes2);
        var alternate = fiber.alternate;
        if (alternate !== null) {
          alternate.lanes = mergeLanes(alternate.lanes, renderLanes2);
        }
        scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
      }
      function propagateSuspenseContextChange(workInProgress2, firstChild, renderLanes2) {
        var node2 = firstChild;
        while (node2 !== null) {
          if (node2.tag === SuspenseComponent) {
            var state = node2.memoizedState;
            if (state !== null) {
              scheduleSuspenseWorkOnFiber(node2, renderLanes2, workInProgress2);
            }
          } else if (node2.tag === SuspenseListComponent) {
            scheduleSuspenseWorkOnFiber(node2, renderLanes2, workInProgress2);
          } else if (node2.child !== null) {
            node2.child.return = node2;
            node2 = node2.child;
            continue;
          }
          if (node2 === workInProgress2) {
            return;
          }
          while (node2.sibling === null) {
            if (node2.return === null || node2.return === workInProgress2) {
              return;
            }
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
      }
      function findLastContentRow(firstChild) {
        var row = firstChild;
        var lastContentRow = null;
        while (row !== null) {
          var currentRow = row.alternate;
          if (currentRow !== null && findFirstSuspended(currentRow) === null) {
            lastContentRow = row;
          }
          row = row.sibling;
        }
        return lastContentRow;
      }
      function validateRevealOrder(revealOrder) {
        {
          if (revealOrder !== void 0 && revealOrder !== "forwards" && revealOrder !== "backwards" && revealOrder !== "together" && !didWarnAboutRevealOrder[revealOrder]) {
            didWarnAboutRevealOrder[revealOrder] = true;
            if (typeof revealOrder === "string") {
              switch (revealOrder.toLowerCase()) {
                case "together":
                case "forwards":
                case "backwards": {
                  error('"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
                  break;
                }
                case "forward":
                case "backward": {
                  error('"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
                  break;
                }
                default:
                  error('"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
                  break;
              }
            } else {
              error('%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "together", "forwards" or "backwards"?', revealOrder);
            }
          }
        }
      }
      function validateTailOptions(tailMode, revealOrder) {
        {
          if (tailMode !== void 0 && !didWarnAboutTailOptions[tailMode]) {
            if (tailMode !== "collapsed" && tailMode !== "hidden") {
              didWarnAboutTailOptions[tailMode] = true;
              error('"%s" is not a supported value for tail on <SuspenseList />. Did you mean "collapsed" or "hidden"?', tailMode);
            } else if (revealOrder !== "forwards" && revealOrder !== "backwards") {
              didWarnAboutTailOptions[tailMode] = true;
              error('<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?', tailMode);
            }
          }
        }
      }
      function validateSuspenseListNestedChild(childSlot, index22) {
        {
          var isAnArray = isArray2(childSlot);
          var isIterable = !isAnArray && typeof getIteratorFn(childSlot) === "function";
          if (isAnArray || isIterable) {
            var type2 = isAnArray ? "array" : "iterable";
            error("A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>", type2, index22, type2);
            return false;
          }
        }
        return true;
      }
      function validateSuspenseListChildren(children, revealOrder) {
        {
          if ((revealOrder === "forwards" || revealOrder === "backwards") && children !== void 0 && children !== null && children !== false) {
            if (isArray2(children)) {
              for (var i2 = 0; i2 < children.length; i2++) {
                if (!validateSuspenseListNestedChild(children[i2], i2)) {
                  return;
                }
              }
            } else {
              var iteratorFn = getIteratorFn(children);
              if (typeof iteratorFn === "function") {
                var childrenIterator = iteratorFn.call(children);
                if (childrenIterator) {
                  var step = childrenIterator.next();
                  var _i2 = 0;
                  for (; !step.done; step = childrenIterator.next()) {
                    if (!validateSuspenseListNestedChild(step.value, _i2)) {
                      return;
                    }
                    _i2++;
                  }
                }
              } else {
                error('A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?', revealOrder);
              }
            }
          }
        }
      }
      function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode) {
        var renderState = workInProgress2.memoizedState;
        if (renderState === null) {
          workInProgress2.memoizedState = {
            isBackwards,
            rendering: null,
            renderingStartTime: 0,
            last: lastContentRow,
            tail,
            tailMode
          };
        } else {
          renderState.isBackwards = isBackwards;
          renderState.rendering = null;
          renderState.renderingStartTime = 0;
          renderState.last = lastContentRow;
          renderState.tail = tail;
          renderState.tailMode = tailMode;
        }
      }
      function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps;
        var revealOrder = nextProps.revealOrder;
        var tailMode = nextProps.tail;
        var newChildren = nextProps.children;
        validateRevealOrder(revealOrder);
        validateTailOptions(tailMode, revealOrder);
        validateSuspenseListChildren(newChildren, revealOrder);
        reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
        var suspenseContext = suspenseStackCursor.current;
        var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
        if (shouldForceFallback) {
          suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
          workInProgress2.flags |= DidCapture;
        } else {
          var didSuspendBefore = current2 !== null && (current2.flags & DidCapture) !== NoFlags;
          if (didSuspendBefore) {
            propagateSuspenseContextChange(workInProgress2, workInProgress2.child, renderLanes2);
          }
          suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
        }
        pushSuspenseContext(workInProgress2, suspenseContext);
        if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
          workInProgress2.memoizedState = null;
        } else {
          switch (revealOrder) {
            case "forwards": {
              var lastContentRow = findLastContentRow(workInProgress2.child);
              var tail;
              if (lastContentRow === null) {
                tail = workInProgress2.child;
                workInProgress2.child = null;
              } else {
                tail = lastContentRow.sibling;
                lastContentRow.sibling = null;
              }
              initSuspenseListRenderState(
                workInProgress2,
                false,
                // isBackwards
                tail,
                lastContentRow,
                tailMode
              );
              break;
            }
            case "backwards": {
              var _tail = null;
              var row = workInProgress2.child;
              workInProgress2.child = null;
              while (row !== null) {
                var currentRow = row.alternate;
                if (currentRow !== null && findFirstSuspended(currentRow) === null) {
                  workInProgress2.child = row;
                  break;
                }
                var nextRow = row.sibling;
                row.sibling = _tail;
                _tail = row;
                row = nextRow;
              }
              initSuspenseListRenderState(
                workInProgress2,
                true,
                // isBackwards
                _tail,
                null,
                // last
                tailMode
              );
              break;
            }
            case "together": {
              initSuspenseListRenderState(
                workInProgress2,
                false,
                // isBackwards
                null,
                // tail
                null,
                // last
                void 0
              );
              break;
            }
            default: {
              workInProgress2.memoizedState = null;
            }
          }
        }
        return workInProgress2.child;
      }
      function updatePortalComponent(current2, workInProgress2, renderLanes2) {
        pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
        var nextChildren = workInProgress2.pendingProps;
        if (current2 === null) {
          workInProgress2.child = reconcileChildFibers(workInProgress2, null, nextChildren, renderLanes2);
        } else {
          reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        }
        return workInProgress2.child;
      }
      var hasWarnedAboutUsingNoValuePropOnContextProvider = false;
      function updateContextProvider(current2, workInProgress2, renderLanes2) {
        var providerType = workInProgress2.type;
        var context = providerType._context;
        var newProps = workInProgress2.pendingProps;
        var oldProps = workInProgress2.memoizedProps;
        var newValue = newProps.value;
        {
          if (!("value" in newProps)) {
            if (!hasWarnedAboutUsingNoValuePropOnContextProvider) {
              hasWarnedAboutUsingNoValuePropOnContextProvider = true;
              error("The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?");
            }
          }
          var providerPropTypes = workInProgress2.type.propTypes;
          if (providerPropTypes) {
            checkPropTypes(providerPropTypes, newProps, "prop", "Context.Provider");
          }
        }
        pushProvider(workInProgress2, context, newValue);
        {
          if (oldProps !== null) {
            var oldValue = oldProps.value;
            if (objectIs(oldValue, newValue)) {
              if (oldProps.children === newProps.children && !hasContextChanged()) {
                return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
              }
            } else {
              propagateContextChange(workInProgress2, context, renderLanes2);
            }
          }
        }
        var newChildren = newProps.children;
        reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
        return workInProgress2.child;
      }
      var hasWarnedAboutUsingContextAsConsumer = false;
      function updateContextConsumer(current2, workInProgress2, renderLanes2) {
        var context = workInProgress2.type;
        {
          if (context._context === void 0) {
            if (context !== context.Consumer) {
              if (!hasWarnedAboutUsingContextAsConsumer) {
                hasWarnedAboutUsingContextAsConsumer = true;
                error("Rendering <Context> directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?");
              }
            }
          } else {
            context = context._context;
          }
        }
        var newProps = workInProgress2.pendingProps;
        var render2 = newProps.children;
        {
          if (typeof render2 !== "function") {
            error("A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.");
          }
        }
        prepareToReadContext(workInProgress2, renderLanes2);
        var newValue = readContext(context);
        {
          markComponentRenderStarted(workInProgress2);
        }
        var newChildren;
        {
          ReactCurrentOwner$1.current = workInProgress2;
          setIsRendering(true);
          newChildren = render2(newValue);
          setIsRendering(false);
        }
        {
          markComponentRenderStopped();
        }
        workInProgress2.flags |= PerformedWork;
        reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
        return workInProgress2.child;
      }
      function markWorkInProgressReceivedUpdate() {
        didReceiveUpdate = true;
      }
      function resetSuspendedCurrentOnMountInLegacyMode(current2, workInProgress2) {
        if ((workInProgress2.mode & ConcurrentMode) === NoMode) {
          if (current2 !== null) {
            current2.alternate = null;
            workInProgress2.alternate = null;
            workInProgress2.flags |= Placement;
          }
        }
      }
      function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
        if (current2 !== null) {
          workInProgress2.dependencies = current2.dependencies;
        }
        {
          stopProfilerTimerIfRunning();
        }
        markSkippedUpdateLanes(workInProgress2.lanes);
        if (!includesSomeLane(renderLanes2, workInProgress2.childLanes)) {
          {
            return null;
          }
        }
        cloneChildFibers(current2, workInProgress2);
        return workInProgress2.child;
      }
      function remountFiber(current2, oldWorkInProgress, newWorkInProgress) {
        {
          var returnFiber = oldWorkInProgress.return;
          if (returnFiber === null) {
            throw new Error("Cannot swap the root fiber.");
          }
          current2.alternate = null;
          oldWorkInProgress.alternate = null;
          newWorkInProgress.index = oldWorkInProgress.index;
          newWorkInProgress.sibling = oldWorkInProgress.sibling;
          newWorkInProgress.return = oldWorkInProgress.return;
          newWorkInProgress.ref = oldWorkInProgress.ref;
          if (oldWorkInProgress === returnFiber.child) {
            returnFiber.child = newWorkInProgress;
          } else {
            var prevSibling = returnFiber.child;
            if (prevSibling === null) {
              throw new Error("Expected parent to have a child.");
            }
            while (prevSibling.sibling !== oldWorkInProgress) {
              prevSibling = prevSibling.sibling;
              if (prevSibling === null) {
                throw new Error("Expected to find the previous sibling.");
              }
            }
            prevSibling.sibling = newWorkInProgress;
          }
          var deletions = returnFiber.deletions;
          if (deletions === null) {
            returnFiber.deletions = [current2];
            returnFiber.flags |= ChildDeletion;
          } else {
            deletions.push(current2);
          }
          newWorkInProgress.flags |= Placement;
          return newWorkInProgress;
        }
      }
      function checkScheduledUpdateOrContext(current2, renderLanes2) {
        var updateLanes = current2.lanes;
        if (includesSomeLane(updateLanes, renderLanes2)) {
          return true;
        }
        return false;
      }
      function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
        switch (workInProgress2.tag) {
          case HostRoot:
            pushHostRootContext(workInProgress2);
            workInProgress2.stateNode;
            resetHydrationState();
            break;
          case HostComponent:
            pushHostContext(workInProgress2);
            break;
          case ClassComponent: {
            var Component = workInProgress2.type;
            if (isContextProvider(Component)) {
              pushContextProvider(workInProgress2);
            }
            break;
          }
          case HostPortal:
            pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
            break;
          case ContextProvider: {
            var newValue = workInProgress2.memoizedProps.value;
            var context = workInProgress2.type._context;
            pushProvider(workInProgress2, context, newValue);
            break;
          }
          case Profiler:
            {
              var hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
              if (hasChildWork) {
                workInProgress2.flags |= Update;
              }
              {
                var stateNode = workInProgress2.stateNode;
                stateNode.effectDuration = 0;
                stateNode.passiveEffectDuration = 0;
              }
            }
            break;
          case SuspenseComponent: {
            var state = workInProgress2.memoizedState;
            if (state !== null) {
              if (state.dehydrated !== null) {
                pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
                workInProgress2.flags |= DidCapture;
                return null;
              }
              var primaryChildFragment = workInProgress2.child;
              var primaryChildLanes = primaryChildFragment.childLanes;
              if (includesSomeLane(renderLanes2, primaryChildLanes)) {
                return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
              } else {
                pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
                var child = bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
                if (child !== null) {
                  return child.sibling;
                } else {
                  return null;
                }
              }
            } else {
              pushSuspenseContext(workInProgress2, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
            }
            break;
          }
          case SuspenseListComponent: {
            var didSuspendBefore = (current2.flags & DidCapture) !== NoFlags;
            var _hasChildWork = includesSomeLane(renderLanes2, workInProgress2.childLanes);
            if (didSuspendBefore) {
              if (_hasChildWork) {
                return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
              }
              workInProgress2.flags |= DidCapture;
            }
            var renderState = workInProgress2.memoizedState;
            if (renderState !== null) {
              renderState.rendering = null;
              renderState.tail = null;
              renderState.lastEffect = null;
            }
            pushSuspenseContext(workInProgress2, suspenseStackCursor.current);
            if (_hasChildWork) {
              break;
            } else {
              return null;
            }
          }
          case OffscreenComponent:
          case LegacyHiddenComponent: {
            workInProgress2.lanes = NoLanes;
            return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
          }
        }
        return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      }
      function beginWork(current2, workInProgress2, renderLanes2) {
        {
          if (workInProgress2._debugNeedsRemount && current2 !== null) {
            return remountFiber(current2, workInProgress2, createFiberFromTypeAndProps(workInProgress2.type, workInProgress2.key, workInProgress2.pendingProps, workInProgress2._debugOwner || null, workInProgress2.mode, workInProgress2.lanes));
          }
        }
        if (current2 !== null) {
          var oldProps = current2.memoizedProps;
          var newProps = workInProgress2.pendingProps;
          if (oldProps !== newProps || hasContextChanged() || // Force a re-render if the implementation changed due to hot reload:
          workInProgress2.type !== current2.type) {
            didReceiveUpdate = true;
          } else {
            var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current2, renderLanes2);
            if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there
            // may not be work scheduled on `current`, so we check for this flag.
            (workInProgress2.flags & DidCapture) === NoFlags) {
              didReceiveUpdate = false;
              return attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2);
            }
            if ((current2.flags & ForceUpdateForLegacySuspense) !== NoFlags) {
              didReceiveUpdate = true;
            } else {
              didReceiveUpdate = false;
            }
          }
        } else {
          didReceiveUpdate = false;
          if (getIsHydrating() && isForkedChild(workInProgress2)) {
            var slotIndex = workInProgress2.index;
            var numberOfForks = getForksAtLevel();
            pushTreeId(workInProgress2, numberOfForks, slotIndex);
          }
        }
        workInProgress2.lanes = NoLanes;
        switch (workInProgress2.tag) {
          case IndeterminateComponent: {
            return mountIndeterminateComponent(current2, workInProgress2, workInProgress2.type, renderLanes2);
          }
          case LazyComponent: {
            var elementType = workInProgress2.elementType;
            return mountLazyComponent(current2, workInProgress2, elementType, renderLanes2);
          }
          case FunctionComponent: {
            var Component = workInProgress2.type;
            var unresolvedProps = workInProgress2.pendingProps;
            var resolvedProps = workInProgress2.elementType === Component ? unresolvedProps : resolveDefaultProps(Component, unresolvedProps);
            return updateFunctionComponent(current2, workInProgress2, Component, resolvedProps, renderLanes2);
          }
          case ClassComponent: {
            var _Component = workInProgress2.type;
            var _unresolvedProps = workInProgress2.pendingProps;
            var _resolvedProps = workInProgress2.elementType === _Component ? _unresolvedProps : resolveDefaultProps(_Component, _unresolvedProps);
            return updateClassComponent(current2, workInProgress2, _Component, _resolvedProps, renderLanes2);
          }
          case HostRoot:
            return updateHostRoot(current2, workInProgress2, renderLanes2);
          case HostComponent:
            return updateHostComponent(current2, workInProgress2, renderLanes2);
          case HostText:
            return updateHostText(current2, workInProgress2);
          case SuspenseComponent:
            return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
          case HostPortal:
            return updatePortalComponent(current2, workInProgress2, renderLanes2);
          case ForwardRef: {
            var type2 = workInProgress2.type;
            var _unresolvedProps2 = workInProgress2.pendingProps;
            var _resolvedProps2 = workInProgress2.elementType === type2 ? _unresolvedProps2 : resolveDefaultProps(type2, _unresolvedProps2);
            return updateForwardRef(current2, workInProgress2, type2, _resolvedProps2, renderLanes2);
          }
          case Fragment:
            return updateFragment(current2, workInProgress2, renderLanes2);
          case Mode2:
            return updateMode(current2, workInProgress2, renderLanes2);
          case Profiler:
            return updateProfiler(current2, workInProgress2, renderLanes2);
          case ContextProvider:
            return updateContextProvider(current2, workInProgress2, renderLanes2);
          case ContextConsumer:
            return updateContextConsumer(current2, workInProgress2, renderLanes2);
          case MemoComponent: {
            var _type2 = workInProgress2.type;
            var _unresolvedProps3 = workInProgress2.pendingProps;
            var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
            {
              if (workInProgress2.type !== workInProgress2.elementType) {
                var outerPropTypes = _type2.propTypes;
                if (outerPropTypes) {
                  checkPropTypes(
                    outerPropTypes,
                    _resolvedProps3,
                    // Resolved for outer only
                    "prop",
                    getComponentNameFromType(_type2)
                  );
                }
              }
            }
            _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
            return updateMemoComponent(current2, workInProgress2, _type2, _resolvedProps3, renderLanes2);
          }
          case SimpleMemoComponent: {
            return updateSimpleMemoComponent(current2, workInProgress2, workInProgress2.type, workInProgress2.pendingProps, renderLanes2);
          }
          case IncompleteClassComponent: {
            var _Component2 = workInProgress2.type;
            var _unresolvedProps4 = workInProgress2.pendingProps;
            var _resolvedProps4 = workInProgress2.elementType === _Component2 ? _unresolvedProps4 : resolveDefaultProps(_Component2, _unresolvedProps4);
            return mountIncompleteClassComponent(current2, workInProgress2, _Component2, _resolvedProps4, renderLanes2);
          }
          case SuspenseListComponent: {
            return updateSuspenseListComponent(current2, workInProgress2, renderLanes2);
          }
          case ScopeComponent: {
            break;
          }
          case OffscreenComponent: {
            return updateOffscreenComponent(current2, workInProgress2, renderLanes2);
          }
        }
        throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
      }
      function markUpdate(workInProgress2) {
        workInProgress2.flags |= Update;
      }
      function markRef$1(workInProgress2) {
        workInProgress2.flags |= Ref;
        {
          workInProgress2.flags |= RefStatic;
        }
      }
      var appendAllChildren;
      var updateHostContainer;
      var updateHostComponent$1;
      var updateHostText$1;
      {
        appendAllChildren = function(parent, workInProgress2, needsVisibilityToggle, isHidden) {
          var node2 = workInProgress2.child;
          while (node2 !== null) {
            if (node2.tag === HostComponent || node2.tag === HostText) {
              appendInitialChild(parent, node2.stateNode);
            } else if (node2.tag === HostPortal) ;
            else if (node2.child !== null) {
              node2.child.return = node2;
              node2 = node2.child;
              continue;
            }
            if (node2 === workInProgress2) {
              return;
            }
            while (node2.sibling === null) {
              if (node2.return === null || node2.return === workInProgress2) {
                return;
              }
              node2 = node2.return;
            }
            node2.sibling.return = node2.return;
            node2 = node2.sibling;
          }
        };
        updateHostContainer = function(current2, workInProgress2) {
        };
        updateHostComponent$1 = function(current2, workInProgress2, type2, newProps, rootContainerInstance) {
          var oldProps = current2.memoizedProps;
          if (oldProps === newProps) {
            return;
          }
          var instance2 = workInProgress2.stateNode;
          var currentHostContext = getHostContext();
          var updatePayload = prepareUpdate(instance2, type2, oldProps, newProps, rootContainerInstance, currentHostContext);
          workInProgress2.updateQueue = updatePayload;
          if (updatePayload) {
            markUpdate(workInProgress2);
          }
        };
        updateHostText$1 = function(current2, workInProgress2, oldText, newText) {
          if (oldText !== newText) {
            markUpdate(workInProgress2);
          }
        };
      }
      function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
        if (getIsHydrating()) {
          return;
        }
        switch (renderState.tailMode) {
          case "hidden": {
            var tailNode = renderState.tail;
            var lastTailNode = null;
            while (tailNode !== null) {
              if (tailNode.alternate !== null) {
                lastTailNode = tailNode;
              }
              tailNode = tailNode.sibling;
            }
            if (lastTailNode === null) {
              renderState.tail = null;
            } else {
              lastTailNode.sibling = null;
            }
            break;
          }
          case "collapsed": {
            var _tailNode = renderState.tail;
            var _lastTailNode = null;
            while (_tailNode !== null) {
              if (_tailNode.alternate !== null) {
                _lastTailNode = _tailNode;
              }
              _tailNode = _tailNode.sibling;
            }
            if (_lastTailNode === null) {
              if (!hasRenderedATailFallback && renderState.tail !== null) {
                renderState.tail.sibling = null;
              } else {
                renderState.tail = null;
              }
            } else {
              _lastTailNode.sibling = null;
            }
            break;
          }
        }
      }
      function bubbleProperties(completedWork) {
        var didBailout = completedWork.alternate !== null && completedWork.alternate.child === completedWork.child;
        var newChildLanes = NoLanes;
        var subtreeFlags = NoFlags;
        if (!didBailout) {
          if ((completedWork.mode & ProfileMode) !== NoMode) {
            var actualDuration = completedWork.actualDuration;
            var treeBaseDuration = completedWork.selfBaseDuration;
            var child = completedWork.child;
            while (child !== null) {
              newChildLanes = mergeLanes(newChildLanes, mergeLanes(child.lanes, child.childLanes));
              subtreeFlags |= child.subtreeFlags;
              subtreeFlags |= child.flags;
              actualDuration += child.actualDuration;
              treeBaseDuration += child.treeBaseDuration;
              child = child.sibling;
            }
            completedWork.actualDuration = actualDuration;
            completedWork.treeBaseDuration = treeBaseDuration;
          } else {
            var _child = completedWork.child;
            while (_child !== null) {
              newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child.lanes, _child.childLanes));
              subtreeFlags |= _child.subtreeFlags;
              subtreeFlags |= _child.flags;
              _child.return = completedWork;
              _child = _child.sibling;
            }
          }
          completedWork.subtreeFlags |= subtreeFlags;
        } else {
          if ((completedWork.mode & ProfileMode) !== NoMode) {
            var _treeBaseDuration = completedWork.selfBaseDuration;
            var _child2 = completedWork.child;
            while (_child2 !== null) {
              newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child2.lanes, _child2.childLanes));
              subtreeFlags |= _child2.subtreeFlags & StaticMask;
              subtreeFlags |= _child2.flags & StaticMask;
              _treeBaseDuration += _child2.treeBaseDuration;
              _child2 = _child2.sibling;
            }
            completedWork.treeBaseDuration = _treeBaseDuration;
          } else {
            var _child3 = completedWork.child;
            while (_child3 !== null) {
              newChildLanes = mergeLanes(newChildLanes, mergeLanes(_child3.lanes, _child3.childLanes));
              subtreeFlags |= _child3.subtreeFlags & StaticMask;
              subtreeFlags |= _child3.flags & StaticMask;
              _child3.return = completedWork;
              _child3 = _child3.sibling;
            }
          }
          completedWork.subtreeFlags |= subtreeFlags;
        }
        completedWork.childLanes = newChildLanes;
        return didBailout;
      }
      function completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState) {
        if (hasUnhydratedTailNodes() && (workInProgress2.mode & ConcurrentMode) !== NoMode && (workInProgress2.flags & DidCapture) === NoFlags) {
          warnIfUnhydratedTailNodes(workInProgress2);
          resetHydrationState();
          workInProgress2.flags |= ForceClientRender | Incomplete | ShouldCapture;
          return false;
        }
        var wasHydrated = popHydrationState(workInProgress2);
        if (nextState !== null && nextState.dehydrated !== null) {
          if (current2 === null) {
            if (!wasHydrated) {
              throw new Error("A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React.");
            }
            prepareToHydrateHostSuspenseInstance(workInProgress2);
            bubbleProperties(workInProgress2);
            {
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                var isTimedOutSuspense = nextState !== null;
                if (isTimedOutSuspense) {
                  var primaryChildFragment = workInProgress2.child;
                  if (primaryChildFragment !== null) {
                    workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
                  }
                }
              }
            }
            return false;
          } else {
            resetHydrationState();
            if ((workInProgress2.flags & DidCapture) === NoFlags) {
              workInProgress2.memoizedState = null;
            }
            workInProgress2.flags |= Update;
            bubbleProperties(workInProgress2);
            {
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                var _isTimedOutSuspense = nextState !== null;
                if (_isTimedOutSuspense) {
                  var _primaryChildFragment = workInProgress2.child;
                  if (_primaryChildFragment !== null) {
                    workInProgress2.treeBaseDuration -= _primaryChildFragment.treeBaseDuration;
                  }
                }
              }
            }
            return false;
          }
        } else {
          upgradeHydrationErrorsToRecoverable();
          return true;
        }
      }
      function completeWork(current2, workInProgress2, renderLanes2) {
        var newProps = workInProgress2.pendingProps;
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case IndeterminateComponent:
          case LazyComponent:
          case SimpleMemoComponent:
          case FunctionComponent:
          case ForwardRef:
          case Fragment:
          case Mode2:
          case Profiler:
          case ContextConsumer:
          case MemoComponent:
            bubbleProperties(workInProgress2);
            return null;
          case ClassComponent: {
            var Component = workInProgress2.type;
            if (isContextProvider(Component)) {
              popContext(workInProgress2);
            }
            bubbleProperties(workInProgress2);
            return null;
          }
          case HostRoot: {
            var fiberRoot = workInProgress2.stateNode;
            popHostContainer(workInProgress2);
            popTopLevelContextObject(workInProgress2);
            resetWorkInProgressVersions();
            if (fiberRoot.pendingContext) {
              fiberRoot.context = fiberRoot.pendingContext;
              fiberRoot.pendingContext = null;
            }
            if (current2 === null || current2.child === null) {
              var wasHydrated = popHydrationState(workInProgress2);
              if (wasHydrated) {
                markUpdate(workInProgress2);
              } else {
                if (current2 !== null) {
                  var prevState = current2.memoizedState;
                  if (
                    // Check if this is a client root
                    !prevState.isDehydrated || // Check if we reverted to client rendering (e.g. due to an error)
                    (workInProgress2.flags & ForceClientRender) !== NoFlags
                  ) {
                    workInProgress2.flags |= Snapshot;
                    upgradeHydrationErrorsToRecoverable();
                  }
                }
              }
            }
            updateHostContainer(current2, workInProgress2);
            bubbleProperties(workInProgress2);
            return null;
          }
          case HostComponent: {
            popHostContext(workInProgress2);
            var rootContainerInstance = getRootHostContainer();
            var type2 = workInProgress2.type;
            if (current2 !== null && workInProgress2.stateNode != null) {
              updateHostComponent$1(current2, workInProgress2, type2, newProps, rootContainerInstance);
              if (current2.ref !== workInProgress2.ref) {
                markRef$1(workInProgress2);
              }
            } else {
              if (!newProps) {
                if (workInProgress2.stateNode === null) {
                  throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                }
                bubbleProperties(workInProgress2);
                return null;
              }
              var currentHostContext = getHostContext();
              var _wasHydrated = popHydrationState(workInProgress2);
              if (_wasHydrated) {
                if (prepareToHydrateHostInstance(workInProgress2, rootContainerInstance, currentHostContext)) {
                  markUpdate(workInProgress2);
                }
              } else {
                var instance2 = createInstance(type2, newProps, rootContainerInstance, currentHostContext, workInProgress2);
                appendAllChildren(instance2, workInProgress2, false, false);
                workInProgress2.stateNode = instance2;
                if (finalizeInitialChildren(instance2, type2, newProps, rootContainerInstance)) {
                  markUpdate(workInProgress2);
                }
              }
              if (workInProgress2.ref !== null) {
                markRef$1(workInProgress2);
              }
            }
            bubbleProperties(workInProgress2);
            return null;
          }
          case HostText: {
            var newText = newProps;
            if (current2 && workInProgress2.stateNode != null) {
              var oldText = current2.memoizedProps;
              updateHostText$1(current2, workInProgress2, oldText, newText);
            } else {
              if (typeof newText !== "string") {
                if (workInProgress2.stateNode === null) {
                  throw new Error("We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.");
                }
              }
              var _rootContainerInstance = getRootHostContainer();
              var _currentHostContext = getHostContext();
              var _wasHydrated2 = popHydrationState(workInProgress2);
              if (_wasHydrated2) {
                if (prepareToHydrateHostTextInstance(workInProgress2)) {
                  markUpdate(workInProgress2);
                }
              } else {
                workInProgress2.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress2);
              }
            }
            bubbleProperties(workInProgress2);
            return null;
          }
          case SuspenseComponent: {
            popSuspenseContext(workInProgress2);
            var nextState = workInProgress2.memoizedState;
            if (current2 === null || current2.memoizedState !== null && current2.memoizedState.dehydrated !== null) {
              var fallthroughToNormalSuspensePath = completeDehydratedSuspenseBoundary(current2, workInProgress2, nextState);
              if (!fallthroughToNormalSuspensePath) {
                if (workInProgress2.flags & ShouldCapture) {
                  return workInProgress2;
                } else {
                  return null;
                }
              }
            }
            if ((workInProgress2.flags & DidCapture) !== NoFlags) {
              workInProgress2.lanes = renderLanes2;
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                transferActualDuration(workInProgress2);
              }
              return workInProgress2;
            }
            var nextDidTimeout = nextState !== null;
            var prevDidTimeout = current2 !== null && current2.memoizedState !== null;
            if (nextDidTimeout !== prevDidTimeout) {
              if (nextDidTimeout) {
                var _offscreenFiber2 = workInProgress2.child;
                _offscreenFiber2.flags |= Visibility;
                if ((workInProgress2.mode & ConcurrentMode) !== NoMode) {
                  var hasInvisibleChildContext = current2 === null && (workInProgress2.memoizedProps.unstable_avoidThisFallback !== true || true);
                  if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
                    renderDidSuspend();
                  } else {
                    renderDidSuspendDelayIfPossible();
                  }
                }
              }
            }
            var wakeables = workInProgress2.updateQueue;
            if (wakeables !== null) {
              workInProgress2.flags |= Update;
            }
            bubbleProperties(workInProgress2);
            {
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                if (nextDidTimeout) {
                  var primaryChildFragment = workInProgress2.child;
                  if (primaryChildFragment !== null) {
                    workInProgress2.treeBaseDuration -= primaryChildFragment.treeBaseDuration;
                  }
                }
              }
            }
            return null;
          }
          case HostPortal:
            popHostContainer(workInProgress2);
            updateHostContainer(current2, workInProgress2);
            if (current2 === null) {
              preparePortalMount(workInProgress2.stateNode.containerInfo);
            }
            bubbleProperties(workInProgress2);
            return null;
          case ContextProvider:
            var context = workInProgress2.type._context;
            popProvider(context, workInProgress2);
            bubbleProperties(workInProgress2);
            return null;
          case IncompleteClassComponent: {
            var _Component = workInProgress2.type;
            if (isContextProvider(_Component)) {
              popContext(workInProgress2);
            }
            bubbleProperties(workInProgress2);
            return null;
          }
          case SuspenseListComponent: {
            popSuspenseContext(workInProgress2);
            var renderState = workInProgress2.memoizedState;
            if (renderState === null) {
              bubbleProperties(workInProgress2);
              return null;
            }
            var didSuspendAlready = (workInProgress2.flags & DidCapture) !== NoFlags;
            var renderedTail = renderState.rendering;
            if (renderedTail === null) {
              if (!didSuspendAlready) {
                var cannotBeSuspended = renderHasNotSuspendedYet() && (current2 === null || (current2.flags & DidCapture) === NoFlags);
                if (!cannotBeSuspended) {
                  var row = workInProgress2.child;
                  while (row !== null) {
                    var suspended = findFirstSuspended(row);
                    if (suspended !== null) {
                      didSuspendAlready = true;
                      workInProgress2.flags |= DidCapture;
                      cutOffTailIfNeeded(renderState, false);
                      var newThenables = suspended.updateQueue;
                      if (newThenables !== null) {
                        workInProgress2.updateQueue = newThenables;
                        workInProgress2.flags |= Update;
                      }
                      workInProgress2.subtreeFlags = NoFlags;
                      resetChildFibers(workInProgress2, renderLanes2);
                      pushSuspenseContext(workInProgress2, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
                      return workInProgress2.child;
                    }
                    row = row.sibling;
                  }
                }
                if (renderState.tail !== null && now() > getRenderTargetTime()) {
                  workInProgress2.flags |= DidCapture;
                  didSuspendAlready = true;
                  cutOffTailIfNeeded(renderState, false);
                  workInProgress2.lanes = SomeRetryLane;
                }
              } else {
                cutOffTailIfNeeded(renderState, false);
              }
            } else {
              if (!didSuspendAlready) {
                var _suspended = findFirstSuspended(renderedTail);
                if (_suspended !== null) {
                  workInProgress2.flags |= DidCapture;
                  didSuspendAlready = true;
                  var _newThenables = _suspended.updateQueue;
                  if (_newThenables !== null) {
                    workInProgress2.updateQueue = _newThenables;
                    workInProgress2.flags |= Update;
                  }
                  cutOffTailIfNeeded(renderState, true);
                  if (renderState.tail === null && renderState.tailMode === "hidden" && !renderedTail.alternate && !getIsHydrating()) {
                    bubbleProperties(workInProgress2);
                    return null;
                  }
                } else if (
                  // The time it took to render last row is greater than the remaining
                  // time we have to render. So rendering one more row would likely
                  // exceed it.
                  now() * 2 - renderState.renderingStartTime > getRenderTargetTime() && renderLanes2 !== OffscreenLane
                ) {
                  workInProgress2.flags |= DidCapture;
                  didSuspendAlready = true;
                  cutOffTailIfNeeded(renderState, false);
                  workInProgress2.lanes = SomeRetryLane;
                }
              }
              if (renderState.isBackwards) {
                renderedTail.sibling = workInProgress2.child;
                workInProgress2.child = renderedTail;
              } else {
                var previousSibling = renderState.last;
                if (previousSibling !== null) {
                  previousSibling.sibling = renderedTail;
                } else {
                  workInProgress2.child = renderedTail;
                }
                renderState.last = renderedTail;
              }
            }
            if (renderState.tail !== null) {
              var next = renderState.tail;
              renderState.rendering = next;
              renderState.tail = next.sibling;
              renderState.renderingStartTime = now();
              next.sibling = null;
              var suspenseContext = suspenseStackCursor.current;
              if (didSuspendAlready) {
                suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
              } else {
                suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
              }
              pushSuspenseContext(workInProgress2, suspenseContext);
              return next;
            }
            bubbleProperties(workInProgress2);
            return null;
          }
          case ScopeComponent: {
            break;
          }
          case OffscreenComponent:
          case LegacyHiddenComponent: {
            popRenderLanes(workInProgress2);
            var _nextState = workInProgress2.memoizedState;
            var nextIsHidden = _nextState !== null;
            if (current2 !== null) {
              var _prevState = current2.memoizedState;
              var prevIsHidden = _prevState !== null;
              if (prevIsHidden !== nextIsHidden && // LegacyHidden doesn't do any hiding — it only pre-renders.
              true) {
                workInProgress2.flags |= Visibility;
              }
            }
            if (!nextIsHidden || (workInProgress2.mode & ConcurrentMode) === NoMode) {
              bubbleProperties(workInProgress2);
            } else {
              if (includesSomeLane(subtreeRenderLanes, OffscreenLane)) {
                bubbleProperties(workInProgress2);
                {
                  if (workInProgress2.subtreeFlags & (Placement | Update)) {
                    workInProgress2.flags |= Visibility;
                  }
                }
              }
            }
            return null;
          }
          case CacheComponent: {
            return null;
          }
          case TracingMarkerComponent: {
            return null;
          }
        }
        throw new Error("Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue.");
      }
      function unwindWork(current2, workInProgress2, renderLanes2) {
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case ClassComponent: {
            var Component = workInProgress2.type;
            if (isContextProvider(Component)) {
              popContext(workInProgress2);
            }
            var flags = workInProgress2.flags;
            if (flags & ShouldCapture) {
              workInProgress2.flags = flags & -65537 | DidCapture;
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                transferActualDuration(workInProgress2);
              }
              return workInProgress2;
            }
            return null;
          }
          case HostRoot: {
            workInProgress2.stateNode;
            popHostContainer(workInProgress2);
            popTopLevelContextObject(workInProgress2);
            resetWorkInProgressVersions();
            var _flags = workInProgress2.flags;
            if ((_flags & ShouldCapture) !== NoFlags && (_flags & DidCapture) === NoFlags) {
              workInProgress2.flags = _flags & -65537 | DidCapture;
              return workInProgress2;
            }
            return null;
          }
          case HostComponent: {
            popHostContext(workInProgress2);
            return null;
          }
          case SuspenseComponent: {
            popSuspenseContext(workInProgress2);
            var suspenseState = workInProgress2.memoizedState;
            if (suspenseState !== null && suspenseState.dehydrated !== null) {
              if (workInProgress2.alternate === null) {
                throw new Error("Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue.");
              }
              resetHydrationState();
            }
            var _flags2 = workInProgress2.flags;
            if (_flags2 & ShouldCapture) {
              workInProgress2.flags = _flags2 & -65537 | DidCapture;
              if ((workInProgress2.mode & ProfileMode) !== NoMode) {
                transferActualDuration(workInProgress2);
              }
              return workInProgress2;
            }
            return null;
          }
          case SuspenseListComponent: {
            popSuspenseContext(workInProgress2);
            return null;
          }
          case HostPortal:
            popHostContainer(workInProgress2);
            return null;
          case ContextProvider:
            var context = workInProgress2.type._context;
            popProvider(context, workInProgress2);
            return null;
          case OffscreenComponent:
          case LegacyHiddenComponent:
            popRenderLanes(workInProgress2);
            return null;
          case CacheComponent:
            return null;
          default:
            return null;
        }
      }
      function unwindInterruptedWork(current2, interruptedWork, renderLanes2) {
        popTreeContext(interruptedWork);
        switch (interruptedWork.tag) {
          case ClassComponent: {
            var childContextTypes = interruptedWork.type.childContextTypes;
            if (childContextTypes !== null && childContextTypes !== void 0) {
              popContext(interruptedWork);
            }
            break;
          }
          case HostRoot: {
            interruptedWork.stateNode;
            popHostContainer(interruptedWork);
            popTopLevelContextObject(interruptedWork);
            resetWorkInProgressVersions();
            break;
          }
          case HostComponent: {
            popHostContext(interruptedWork);
            break;
          }
          case HostPortal:
            popHostContainer(interruptedWork);
            break;
          case SuspenseComponent:
            popSuspenseContext(interruptedWork);
            break;
          case SuspenseListComponent:
            popSuspenseContext(interruptedWork);
            break;
          case ContextProvider:
            var context = interruptedWork.type._context;
            popProvider(context, interruptedWork);
            break;
          case OffscreenComponent:
          case LegacyHiddenComponent:
            popRenderLanes(interruptedWork);
            break;
        }
      }
      var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
      {
        didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
      }
      var offscreenSubtreeIsHidden = false;
      var offscreenSubtreeWasHidden = false;
      var PossiblyWeakSet = typeof WeakSet === "function" ? WeakSet : Set;
      var nextEffect = null;
      var inProgressLanes = null;
      var inProgressRoot = null;
      function reportUncaughtErrorInDEV(error2) {
        {
          invokeGuardedCallback(null, function() {
            throw error2;
          });
          clearCaughtError();
        }
      }
      var callComponentWillUnmountWithTimer = function(current2, instance2) {
        instance2.props = current2.memoizedProps;
        instance2.state = current2.memoizedState;
        if (current2.mode & ProfileMode) {
          try {
            startLayoutEffectTimer();
            instance2.componentWillUnmount();
          } finally {
            recordLayoutEffectDuration(current2);
          }
        } else {
          instance2.componentWillUnmount();
        }
      };
      function safelyCallCommitHookLayoutEffectListMount(current2, nearestMountedAncestor) {
        try {
          commitHookEffectListMount(Layout, current2);
        } catch (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance2) {
        try {
          callComponentWillUnmountWithTimer(current2, instance2);
        } catch (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      function safelyCallComponentDidMount(current2, nearestMountedAncestor, instance2) {
        try {
          instance2.componentDidMount();
        } catch (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      function safelyAttachRef(current2, nearestMountedAncestor) {
        try {
          commitAttachRef(current2);
        } catch (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      function safelyDetachRef(current2, nearestMountedAncestor) {
        var ref2 = current2.ref;
        if (ref2 !== null) {
          if (typeof ref2 === "function") {
            var retVal;
            try {
              if (enableProfilerTimer && enableProfilerCommitHooks && current2.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  retVal = ref2(null);
                } finally {
                  recordLayoutEffectDuration(current2);
                }
              } else {
                retVal = ref2(null);
              }
            } catch (error2) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error2);
            }
            {
              if (typeof retVal === "function") {
                error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(current2));
              }
            }
          } else {
            ref2.current = null;
          }
        }
      }
      function safelyCallDestroy(current2, nearestMountedAncestor, destroy) {
        try {
          destroy();
        } catch (error2) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error2);
        }
      }
      var shouldFireAfterActiveInstanceBlur = false;
      function commitBeforeMutationEffects(root2, firstChild) {
        prepareForCommit(root2.containerInfo);
        nextEffect = firstChild;
        commitBeforeMutationEffects_begin();
        var shouldFire = shouldFireAfterActiveInstanceBlur;
        shouldFireAfterActiveInstanceBlur = false;
        return shouldFire;
      }
      function commitBeforeMutationEffects_begin() {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var child = fiber.child;
          if ((fiber.subtreeFlags & BeforeMutationMask) !== NoFlags && child !== null) {
            child.return = fiber;
            nextEffect = child;
          } else {
            commitBeforeMutationEffects_complete();
          }
        }
      }
      function commitBeforeMutationEffects_complete() {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          setCurrentFiber(fiber);
          try {
            commitBeforeMutationEffectsOnFiber(fiber);
          } catch (error2) {
            captureCommitPhaseError(fiber, fiber.return, error2);
          }
          resetCurrentFiber();
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function commitBeforeMutationEffectsOnFiber(finishedWork) {
        var current2 = finishedWork.alternate;
        var flags = finishedWork.flags;
        if ((flags & Snapshot) !== NoFlags) {
          setCurrentFiber(finishedWork);
          switch (finishedWork.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              break;
            }
            case ClassComponent: {
              if (current2 !== null) {
                var prevProps = current2.memoizedProps;
                var prevState = current2.memoizedState;
                var instance2 = finishedWork.stateNode;
                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance2.props !== finishedWork.memoizedProps) {
                      error("Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                    }
                    if (instance2.state !== finishedWork.memoizedState) {
                      error("Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                    }
                  }
                }
                var snapshot = instance2.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
                {
                  var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
                  if (snapshot === void 0 && !didWarnSet.has(finishedWork.type)) {
                    didWarnSet.add(finishedWork.type);
                    error("%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.", getComponentNameFromFiber(finishedWork));
                  }
                }
                instance2.__reactInternalSnapshotBeforeUpdate = snapshot;
              }
              break;
            }
            case HostRoot: {
              {
                var root2 = finishedWork.stateNode;
                clearContainer(root2.containerInfo);
              }
              break;
            }
            case HostComponent:
            case HostText:
            case HostPortal:
            case IncompleteClassComponent:
              break;
            default: {
              throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          resetCurrentFiber();
        }
      }
      function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
        var updateQueue = finishedWork.updateQueue;
        var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
        if (lastEffect !== null) {
          var firstEffect = lastEffect.next;
          var effect = firstEffect;
          do {
            if ((effect.tag & flags) === flags) {
              var destroy = effect.destroy;
              effect.destroy = void 0;
              if (destroy !== void 0) {
                {
                  if ((flags & Passive$1) !== NoFlags$1) {
                    markComponentPassiveEffectUnmountStarted(finishedWork);
                  } else if ((flags & Layout) !== NoFlags$1) {
                    markComponentLayoutEffectUnmountStarted(finishedWork);
                  }
                }
                {
                  if ((flags & Insertion) !== NoFlags$1) {
                    setIsRunningInsertionEffect(true);
                  }
                }
                safelyCallDestroy(finishedWork, nearestMountedAncestor, destroy);
                {
                  if ((flags & Insertion) !== NoFlags$1) {
                    setIsRunningInsertionEffect(false);
                  }
                }
                {
                  if ((flags & Passive$1) !== NoFlags$1) {
                    markComponentPassiveEffectUnmountStopped();
                  } else if ((flags & Layout) !== NoFlags$1) {
                    markComponentLayoutEffectUnmountStopped();
                  }
                }
              }
            }
            effect = effect.next;
          } while (effect !== firstEffect);
        }
      }
      function commitHookEffectListMount(flags, finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
        if (lastEffect !== null) {
          var firstEffect = lastEffect.next;
          var effect = firstEffect;
          do {
            if ((effect.tag & flags) === flags) {
              {
                if ((flags & Passive$1) !== NoFlags$1) {
                  markComponentPassiveEffectMountStarted(finishedWork);
                } else if ((flags & Layout) !== NoFlags$1) {
                  markComponentLayoutEffectMountStarted(finishedWork);
                }
              }
              var create2 = effect.create;
              {
                if ((flags & Insertion) !== NoFlags$1) {
                  setIsRunningInsertionEffect(true);
                }
              }
              effect.destroy = create2();
              {
                if ((flags & Insertion) !== NoFlags$1) {
                  setIsRunningInsertionEffect(false);
                }
              }
              {
                if ((flags & Passive$1) !== NoFlags$1) {
                  markComponentPassiveEffectMountStopped();
                } else if ((flags & Layout) !== NoFlags$1) {
                  markComponentLayoutEffectMountStopped();
                }
              }
              {
                var destroy = effect.destroy;
                if (destroy !== void 0 && typeof destroy !== "function") {
                  var hookName = void 0;
                  if ((effect.tag & Layout) !== NoFlags) {
                    hookName = "useLayoutEffect";
                  } else if ((effect.tag & Insertion) !== NoFlags) {
                    hookName = "useInsertionEffect";
                  } else {
                    hookName = "useEffect";
                  }
                  var addendum = void 0;
                  if (destroy === null) {
                    addendum = " You returned null. If your effect does not require clean up, return undefined (or nothing).";
                  } else if (typeof destroy.then === "function") {
                    addendum = "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://reactjs.org/link/hooks-data-fetching";
                  } else {
                    addendum = " You returned: " + destroy;
                  }
                  error("%s must not return anything besides a function, which is used for clean-up.%s", hookName, addendum);
                }
              }
            }
            effect = effect.next;
          } while (effect !== firstEffect);
        }
      }
      function commitPassiveEffectDurations(finishedRoot, finishedWork) {
        {
          if ((finishedWork.flags & Update) !== NoFlags) {
            switch (finishedWork.tag) {
              case Profiler: {
                var passiveEffectDuration = finishedWork.stateNode.passiveEffectDuration;
                var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onPostCommit = _finishedWork$memoize.onPostCommit;
                var commitTime2 = getCommitTime();
                var phase = finishedWork.alternate === null ? "mount" : "update";
                {
                  if (isCurrentUpdateNested()) {
                    phase = "nested-update";
                  }
                }
                if (typeof onPostCommit === "function") {
                  onPostCommit(id, phase, passiveEffectDuration, commitTime2);
                }
                var parentFiber = finishedWork.return;
                outer: while (parentFiber !== null) {
                  switch (parentFiber.tag) {
                    case HostRoot:
                      var root2 = parentFiber.stateNode;
                      root2.passiveEffectDuration += passiveEffectDuration;
                      break outer;
                    case Profiler:
                      var parentStateNode = parentFiber.stateNode;
                      parentStateNode.passiveEffectDuration += passiveEffectDuration;
                      break outer;
                  }
                  parentFiber = parentFiber.return;
                }
                break;
              }
            }
          }
        }
      }
      function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork, committedLanes) {
        if ((finishedWork.flags & LayoutMask) !== NoFlags) {
          switch (finishedWork.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              if (!offscreenSubtreeWasHidden) {
                if (finishedWork.mode & ProfileMode) {
                  try {
                    startLayoutEffectTimer();
                    commitHookEffectListMount(Layout | HasEffect, finishedWork);
                  } finally {
                    recordLayoutEffectDuration(finishedWork);
                  }
                } else {
                  commitHookEffectListMount(Layout | HasEffect, finishedWork);
                }
              }
              break;
            }
            case ClassComponent: {
              var instance2 = finishedWork.stateNode;
              if (finishedWork.flags & Update) {
                if (!offscreenSubtreeWasHidden) {
                  if (current2 === null) {
                    {
                      if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                        if (instance2.props !== finishedWork.memoizedProps) {
                          error("Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                        }
                        if (instance2.state !== finishedWork.memoizedState) {
                          error("Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                        }
                      }
                    }
                    if (finishedWork.mode & ProfileMode) {
                      try {
                        startLayoutEffectTimer();
                        instance2.componentDidMount();
                      } finally {
                        recordLayoutEffectDuration(finishedWork);
                      }
                    } else {
                      instance2.componentDidMount();
                    }
                  } else {
                    var prevProps = finishedWork.elementType === finishedWork.type ? current2.memoizedProps : resolveDefaultProps(finishedWork.type, current2.memoizedProps);
                    var prevState = current2.memoizedState;
                    {
                      if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                        if (instance2.props !== finishedWork.memoizedProps) {
                          error("Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                        }
                        if (instance2.state !== finishedWork.memoizedState) {
                          error("Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                        }
                      }
                    }
                    if (finishedWork.mode & ProfileMode) {
                      try {
                        startLayoutEffectTimer();
                        instance2.componentDidUpdate(prevProps, prevState, instance2.__reactInternalSnapshotBeforeUpdate);
                      } finally {
                        recordLayoutEffectDuration(finishedWork);
                      }
                    } else {
                      instance2.componentDidUpdate(prevProps, prevState, instance2.__reactInternalSnapshotBeforeUpdate);
                    }
                  }
                }
              }
              var updateQueue = finishedWork.updateQueue;
              if (updateQueue !== null) {
                {
                  if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
                    if (instance2.props !== finishedWork.memoizedProps) {
                      error("Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                    }
                    if (instance2.state !== finishedWork.memoizedState) {
                      error("Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.", getComponentNameFromFiber(finishedWork) || "instance");
                    }
                  }
                }
                commitUpdateQueue(finishedWork, updateQueue, instance2);
              }
              break;
            }
            case HostRoot: {
              var _updateQueue = finishedWork.updateQueue;
              if (_updateQueue !== null) {
                var _instance = null;
                if (finishedWork.child !== null) {
                  switch (finishedWork.child.tag) {
                    case HostComponent:
                      _instance = getPublicInstance(finishedWork.child.stateNode);
                      break;
                    case ClassComponent:
                      _instance = finishedWork.child.stateNode;
                      break;
                  }
                }
                commitUpdateQueue(finishedWork, _updateQueue, _instance);
              }
              break;
            }
            case HostComponent: {
              var _instance2 = finishedWork.stateNode;
              if (current2 === null && finishedWork.flags & Update) {
                var type2 = finishedWork.type;
                var props = finishedWork.memoizedProps;
                commitMount(_instance2, type2, props);
              }
              break;
            }
            case HostText: {
              break;
            }
            case HostPortal: {
              break;
            }
            case Profiler: {
              {
                var _finishedWork$memoize2 = finishedWork.memoizedProps, onCommit = _finishedWork$memoize2.onCommit, onRender = _finishedWork$memoize2.onRender;
                var effectDuration = finishedWork.stateNode.effectDuration;
                var commitTime2 = getCommitTime();
                var phase = current2 === null ? "mount" : "update";
                {
                  if (isCurrentUpdateNested()) {
                    phase = "nested-update";
                  }
                }
                if (typeof onRender === "function") {
                  onRender(finishedWork.memoizedProps.id, phase, finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, commitTime2);
                }
                {
                  if (typeof onCommit === "function") {
                    onCommit(finishedWork.memoizedProps.id, phase, effectDuration, commitTime2);
                  }
                  enqueuePendingPassiveProfilerEffect(finishedWork);
                  var parentFiber = finishedWork.return;
                  outer: while (parentFiber !== null) {
                    switch (parentFiber.tag) {
                      case HostRoot:
                        var root2 = parentFiber.stateNode;
                        root2.effectDuration += effectDuration;
                        break outer;
                      case Profiler:
                        var parentStateNode = parentFiber.stateNode;
                        parentStateNode.effectDuration += effectDuration;
                        break outer;
                    }
                    parentFiber = parentFiber.return;
                  }
                }
              }
              break;
            }
            case SuspenseComponent: {
              commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
              break;
            }
            case SuspenseListComponent:
            case IncompleteClassComponent:
            case ScopeComponent:
            case OffscreenComponent:
            case LegacyHiddenComponent:
            case TracingMarkerComponent: {
              break;
            }
            default:
              throw new Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.");
          }
        }
        if (!offscreenSubtreeWasHidden) {
          {
            if (finishedWork.flags & Ref) {
              commitAttachRef(finishedWork);
            }
          }
        }
      }
      function reappearLayoutEffectsOnFiber(node2) {
        switch (node2.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent: {
            if (node2.mode & ProfileMode) {
              try {
                startLayoutEffectTimer();
                safelyCallCommitHookLayoutEffectListMount(node2, node2.return);
              } finally {
                recordLayoutEffectDuration(node2);
              }
            } else {
              safelyCallCommitHookLayoutEffectListMount(node2, node2.return);
            }
            break;
          }
          case ClassComponent: {
            var instance2 = node2.stateNode;
            if (typeof instance2.componentDidMount === "function") {
              safelyCallComponentDidMount(node2, node2.return, instance2);
            }
            safelyAttachRef(node2, node2.return);
            break;
          }
          case HostComponent: {
            safelyAttachRef(node2, node2.return);
            break;
          }
        }
      }
      function hideOrUnhideAllChildren(finishedWork, isHidden) {
        var hostSubtreeRoot = null;
        {
          var node2 = finishedWork;
          while (true) {
            if (node2.tag === HostComponent) {
              if (hostSubtreeRoot === null) {
                hostSubtreeRoot = node2;
                try {
                  var instance2 = node2.stateNode;
                  if (isHidden) {
                    hideInstance(instance2);
                  } else {
                    unhideInstance(node2.stateNode, node2.memoizedProps);
                  }
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
            } else if (node2.tag === HostText) {
              if (hostSubtreeRoot === null) {
                try {
                  var _instance3 = node2.stateNode;
                  if (isHidden) {
                    hideTextInstance(_instance3);
                  } else {
                    unhideTextInstance(_instance3, node2.memoizedProps);
                  }
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
            } else if ((node2.tag === OffscreenComponent || node2.tag === LegacyHiddenComponent) && node2.memoizedState !== null && node2 !== finishedWork) ;
            else if (node2.child !== null) {
              node2.child.return = node2;
              node2 = node2.child;
              continue;
            }
            if (node2 === finishedWork) {
              return;
            }
            while (node2.sibling === null) {
              if (node2.return === null || node2.return === finishedWork) {
                return;
              }
              if (hostSubtreeRoot === node2) {
                hostSubtreeRoot = null;
              }
              node2 = node2.return;
            }
            if (hostSubtreeRoot === node2) {
              hostSubtreeRoot = null;
            }
            node2.sibling.return = node2.return;
            node2 = node2.sibling;
          }
        }
      }
      function commitAttachRef(finishedWork) {
        var ref2 = finishedWork.ref;
        if (ref2 !== null) {
          var instance2 = finishedWork.stateNode;
          var instanceToUse;
          switch (finishedWork.tag) {
            case HostComponent:
              instanceToUse = getPublicInstance(instance2);
              break;
            default:
              instanceToUse = instance2;
          }
          if (typeof ref2 === "function") {
            var retVal;
            if (finishedWork.mode & ProfileMode) {
              try {
                startLayoutEffectTimer();
                retVal = ref2(instanceToUse);
              } finally {
                recordLayoutEffectDuration(finishedWork);
              }
            } else {
              retVal = ref2(instanceToUse);
            }
            {
              if (typeof retVal === "function") {
                error("Unexpected return value from a callback ref in %s. A callback ref should not return a function.", getComponentNameFromFiber(finishedWork));
              }
            }
          } else {
            {
              if (!ref2.hasOwnProperty("current")) {
                error("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentNameFromFiber(finishedWork));
              }
            }
            ref2.current = instanceToUse;
          }
        }
      }
      function detachFiberMutation(fiber) {
        var alternate = fiber.alternate;
        if (alternate !== null) {
          alternate.return = null;
        }
        fiber.return = null;
      }
      function detachFiberAfterEffects(fiber) {
        var alternate = fiber.alternate;
        if (alternate !== null) {
          fiber.alternate = null;
          detachFiberAfterEffects(alternate);
        }
        {
          fiber.child = null;
          fiber.deletions = null;
          fiber.sibling = null;
          if (fiber.tag === HostComponent) {
            var hostInstance = fiber.stateNode;
            if (hostInstance !== null) {
              detachDeletedInstance(hostInstance);
            }
          }
          fiber.stateNode = null;
          {
            fiber._debugOwner = null;
          }
          {
            fiber.return = null;
            fiber.dependencies = null;
            fiber.memoizedProps = null;
            fiber.memoizedState = null;
            fiber.pendingProps = null;
            fiber.stateNode = null;
            fiber.updateQueue = null;
          }
        }
      }
      function getHostParentFiber(fiber) {
        var parent = fiber.return;
        while (parent !== null) {
          if (isHostParent(parent)) {
            return parent;
          }
          parent = parent.return;
        }
        throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
      }
      function isHostParent(fiber) {
        return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
      }
      function getHostSibling(fiber) {
        var node2 = fiber;
        siblings: while (true) {
          while (node2.sibling === null) {
            if (node2.return === null || isHostParent(node2.return)) {
              return null;
            }
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
          while (node2.tag !== HostComponent && node2.tag !== HostText && node2.tag !== DehydratedFragment) {
            if (node2.flags & Placement) {
              continue siblings;
            }
            if (node2.child === null || node2.tag === HostPortal) {
              continue siblings;
            } else {
              node2.child.return = node2;
              node2 = node2.child;
            }
          }
          if (!(node2.flags & Placement)) {
            return node2.stateNode;
          }
        }
      }
      function commitPlacement(finishedWork) {
        var parentFiber = getHostParentFiber(finishedWork);
        switch (parentFiber.tag) {
          case HostComponent: {
            var parent = parentFiber.stateNode;
            if (parentFiber.flags & ContentReset) {
              resetTextContent(parent);
              parentFiber.flags &= -33;
            }
            var before = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(finishedWork, before, parent);
            break;
          }
          case HostRoot:
          case HostPortal: {
            var _parent = parentFiber.stateNode.containerInfo;
            var _before = getHostSibling(finishedWork);
            insertOrAppendPlacementNodeIntoContainer(finishedWork, _before, _parent);
            break;
          }
          // eslint-disable-next-line-no-fallthrough
          default:
            throw new Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.");
        }
      }
      function insertOrAppendPlacementNodeIntoContainer(node2, before, parent) {
        var tag = node2.tag;
        var isHost = tag === HostComponent || tag === HostText;
        if (isHost) {
          var stateNode = node2.stateNode;
          if (before) {
            insertInContainerBefore(parent, stateNode, before);
          } else {
            appendChildToContainer(parent, stateNode);
          }
        } else if (tag === HostPortal) ;
        else {
          var child = node2.child;
          if (child !== null) {
            insertOrAppendPlacementNodeIntoContainer(child, before, parent);
            var sibling = child.sibling;
            while (sibling !== null) {
              insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
              sibling = sibling.sibling;
            }
          }
        }
      }
      function insertOrAppendPlacementNode(node2, before, parent) {
        var tag = node2.tag;
        var isHost = tag === HostComponent || tag === HostText;
        if (isHost) {
          var stateNode = node2.stateNode;
          if (before) {
            insertBefore(parent, stateNode, before);
          } else {
            appendChild(parent, stateNode);
          }
        } else if (tag === HostPortal) ;
        else {
          var child = node2.child;
          if (child !== null) {
            insertOrAppendPlacementNode(child, before, parent);
            var sibling = child.sibling;
            while (sibling !== null) {
              insertOrAppendPlacementNode(sibling, before, parent);
              sibling = sibling.sibling;
            }
          }
        }
      }
      var hostParent = null;
      var hostParentIsContainer = false;
      function commitDeletionEffects(root2, returnFiber, deletedFiber) {
        {
          var parent = returnFiber;
          findParent: while (parent !== null) {
            switch (parent.tag) {
              case HostComponent: {
                hostParent = parent.stateNode;
                hostParentIsContainer = false;
                break findParent;
              }
              case HostRoot: {
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break findParent;
              }
              case HostPortal: {
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break findParent;
              }
            }
            parent = parent.return;
          }
          if (hostParent === null) {
            throw new Error("Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.");
          }
          commitDeletionEffectsOnFiber(root2, returnFiber, deletedFiber);
          hostParent = null;
          hostParentIsContainer = false;
        }
        detachFiberMutation(deletedFiber);
      }
      function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
        var child = parent.child;
        while (child !== null) {
          commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, child);
          child = child.sibling;
        }
      }
      function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
        onCommitUnmount(deletedFiber);
        switch (deletedFiber.tag) {
          case HostComponent: {
            if (!offscreenSubtreeWasHidden) {
              safelyDetachRef(deletedFiber, nearestMountedAncestor);
            }
          }
          // eslint-disable-next-line-no-fallthrough
          case HostText: {
            {
              var prevHostParent = hostParent;
              var prevHostParentIsContainer = hostParentIsContainer;
              hostParent = null;
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              hostParent = prevHostParent;
              hostParentIsContainer = prevHostParentIsContainer;
              if (hostParent !== null) {
                if (hostParentIsContainer) {
                  removeChildFromContainer(hostParent, deletedFiber.stateNode);
                } else {
                  removeChild(hostParent, deletedFiber.stateNode);
                }
              }
            }
            return;
          }
          case DehydratedFragment: {
            {
              if (hostParent !== null) {
                if (hostParentIsContainer) {
                  clearSuspenseBoundaryFromContainer(hostParent, deletedFiber.stateNode);
                } else {
                  clearSuspenseBoundary(hostParent, deletedFiber.stateNode);
                }
              }
            }
            return;
          }
          case HostPortal: {
            {
              var _prevHostParent = hostParent;
              var _prevHostParentIsContainer = hostParentIsContainer;
              hostParent = deletedFiber.stateNode.containerInfo;
              hostParentIsContainer = true;
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              hostParent = _prevHostParent;
              hostParentIsContainer = _prevHostParentIsContainer;
            }
            return;
          }
          case FunctionComponent:
          case ForwardRef:
          case MemoComponent:
          case SimpleMemoComponent: {
            if (!offscreenSubtreeWasHidden) {
              var updateQueue = deletedFiber.updateQueue;
              if (updateQueue !== null) {
                var lastEffect = updateQueue.lastEffect;
                if (lastEffect !== null) {
                  var firstEffect = lastEffect.next;
                  var effect = firstEffect;
                  do {
                    var _effect = effect, destroy = _effect.destroy, tag = _effect.tag;
                    if (destroy !== void 0) {
                      if ((tag & Insertion) !== NoFlags$1) {
                        safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                      } else if ((tag & Layout) !== NoFlags$1) {
                        {
                          markComponentLayoutEffectUnmountStarted(deletedFiber);
                        }
                        if (deletedFiber.mode & ProfileMode) {
                          startLayoutEffectTimer();
                          safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                          recordLayoutEffectDuration(deletedFiber);
                        } else {
                          safelyCallDestroy(deletedFiber, nearestMountedAncestor, destroy);
                        }
                        {
                          markComponentLayoutEffectUnmountStopped();
                        }
                      }
                    }
                    effect = effect.next;
                  } while (effect !== firstEffect);
                }
              }
            }
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            return;
          }
          case ClassComponent: {
            if (!offscreenSubtreeWasHidden) {
              safelyDetachRef(deletedFiber, nearestMountedAncestor);
              var instance2 = deletedFiber.stateNode;
              if (typeof instance2.componentWillUnmount === "function") {
                safelyCallComponentWillUnmount(deletedFiber, nearestMountedAncestor, instance2);
              }
            }
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            return;
          }
          case ScopeComponent: {
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            return;
          }
          case OffscreenComponent: {
            if (
              // TODO: Remove this dead flag
              deletedFiber.mode & ConcurrentMode
            ) {
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || deletedFiber.memoizedState !== null;
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            } else {
              recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            }
            break;
          }
          default: {
            recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, deletedFiber);
            return;
          }
        }
      }
      function commitSuspenseCallback(finishedWork) {
        finishedWork.memoizedState;
      }
      function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
        var newState = finishedWork.memoizedState;
        if (newState === null) {
          var current2 = finishedWork.alternate;
          if (current2 !== null) {
            var prevState = current2.memoizedState;
            if (prevState !== null) {
              var suspenseInstance = prevState.dehydrated;
              if (suspenseInstance !== null) {
                commitHydratedSuspenseInstance(suspenseInstance);
              }
            }
          }
        }
      }
      function attachSuspenseRetryListeners(finishedWork) {
        var wakeables = finishedWork.updateQueue;
        if (wakeables !== null) {
          finishedWork.updateQueue = null;
          var retryCache = finishedWork.stateNode;
          if (retryCache === null) {
            retryCache = finishedWork.stateNode = new PossiblyWeakSet();
          }
          wakeables.forEach(function(wakeable) {
            var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
            if (!retryCache.has(wakeable)) {
              retryCache.add(wakeable);
              {
                if (isDevToolsPresent) {
                  if (inProgressLanes !== null && inProgressRoot !== null) {
                    restorePendingUpdaters(inProgressRoot, inProgressLanes);
                  } else {
                    throw Error("Expected finished root and lanes to be set. This is a bug in React.");
                  }
                }
              }
              wakeable.then(retry, retry);
            }
          });
        }
      }
      function commitMutationEffects(root2, finishedWork, committedLanes) {
        inProgressLanes = committedLanes;
        inProgressRoot = root2;
        setCurrentFiber(finishedWork);
        commitMutationEffectsOnFiber(finishedWork, root2);
        setCurrentFiber(finishedWork);
        inProgressLanes = null;
        inProgressRoot = null;
      }
      function recursivelyTraverseMutationEffects(root2, parentFiber, lanes) {
        var deletions = parentFiber.deletions;
        if (deletions !== null) {
          for (var i2 = 0; i2 < deletions.length; i2++) {
            var childToDelete = deletions[i2];
            try {
              commitDeletionEffects(root2, parentFiber, childToDelete);
            } catch (error2) {
              captureCommitPhaseError(childToDelete, parentFiber, error2);
            }
          }
        }
        var prevDebugFiber = getCurrentFiber();
        if (parentFiber.subtreeFlags & MutationMask) {
          var child = parentFiber.child;
          while (child !== null) {
            setCurrentFiber(child);
            commitMutationEffectsOnFiber(child, root2);
            child = child.sibling;
          }
        }
        setCurrentFiber(prevDebugFiber);
      }
      function commitMutationEffectsOnFiber(finishedWork, root2, lanes) {
        var current2 = finishedWork.alternate;
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case FunctionComponent:
          case ForwardRef:
          case MemoComponent:
          case SimpleMemoComponent: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Update) {
              try {
                commitHookEffectListUnmount(Insertion | HasEffect, finishedWork, finishedWork.return);
                commitHookEffectListMount(Insertion | HasEffect, finishedWork);
              } catch (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
              if (finishedWork.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
                recordLayoutEffectDuration(finishedWork);
              } else {
                try {
                  commitHookEffectListUnmount(Layout | HasEffect, finishedWork, finishedWork.return);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
            }
            return;
          }
          case ClassComponent: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Ref) {
              if (current2 !== null) {
                safelyDetachRef(current2, current2.return);
              }
            }
            return;
          }
          case HostComponent: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Ref) {
              if (current2 !== null) {
                safelyDetachRef(current2, current2.return);
              }
            }
            {
              if (finishedWork.flags & ContentReset) {
                var instance2 = finishedWork.stateNode;
                try {
                  resetTextContent(instance2);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
              if (flags & Update) {
                var _instance4 = finishedWork.stateNode;
                if (_instance4 != null) {
                  var newProps = finishedWork.memoizedProps;
                  var oldProps = current2 !== null ? current2.memoizedProps : newProps;
                  var type2 = finishedWork.type;
                  var updatePayload = finishedWork.updateQueue;
                  finishedWork.updateQueue = null;
                  if (updatePayload !== null) {
                    try {
                      commitUpdate(_instance4, updatePayload, type2, oldProps, newProps, finishedWork);
                    } catch (error2) {
                      captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                    }
                  }
                }
              }
            }
            return;
          }
          case HostText: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Update) {
              {
                if (finishedWork.stateNode === null) {
                  throw new Error("This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.");
                }
                var textInstance = finishedWork.stateNode;
                var newText = finishedWork.memoizedProps;
                var oldText = current2 !== null ? current2.memoizedProps : newText;
                try {
                  commitTextUpdate(textInstance, oldText, newText);
                } catch (error2) {
                  captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                }
              }
            }
            return;
          }
          case HostRoot: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Update) {
              {
                if (current2 !== null) {
                  var prevRootState = current2.memoizedState;
                  if (prevRootState.isDehydrated) {
                    try {
                      commitHydratedContainer(root2.containerInfo);
                    } catch (error2) {
                      captureCommitPhaseError(finishedWork, finishedWork.return, error2);
                    }
                  }
                }
              }
            }
            return;
          }
          case HostPortal: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            return;
          }
          case SuspenseComponent: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            var offscreenFiber = finishedWork.child;
            if (offscreenFiber.flags & Visibility) {
              var offscreenInstance = offscreenFiber.stateNode;
              var newState = offscreenFiber.memoizedState;
              var isHidden = newState !== null;
              offscreenInstance.isHidden = isHidden;
              if (isHidden) {
                var wasHidden = offscreenFiber.alternate !== null && offscreenFiber.alternate.memoizedState !== null;
                if (!wasHidden) {
                  markCommitTimeOfFallback();
                }
              }
            }
            if (flags & Update) {
              try {
                commitSuspenseCallback(finishedWork);
              } catch (error2) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error2);
              }
              attachSuspenseRetryListeners(finishedWork);
            }
            return;
          }
          case OffscreenComponent: {
            var _wasHidden = current2 !== null && current2.memoizedState !== null;
            if (
              // TODO: Remove this dead flag
              finishedWork.mode & ConcurrentMode
            ) {
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || _wasHidden;
              recursivelyTraverseMutationEffects(root2, finishedWork);
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            } else {
              recursivelyTraverseMutationEffects(root2, finishedWork);
            }
            commitReconciliationEffects(finishedWork);
            if (flags & Visibility) {
              var _offscreenInstance = finishedWork.stateNode;
              var _newState = finishedWork.memoizedState;
              var _isHidden = _newState !== null;
              var offscreenBoundary = finishedWork;
              _offscreenInstance.isHidden = _isHidden;
              {
                if (_isHidden) {
                  if (!_wasHidden) {
                    if ((offscreenBoundary.mode & ConcurrentMode) !== NoMode) {
                      nextEffect = offscreenBoundary;
                      var offscreenChild = offscreenBoundary.child;
                      while (offscreenChild !== null) {
                        nextEffect = offscreenChild;
                        disappearLayoutEffects_begin(offscreenChild);
                        offscreenChild = offscreenChild.sibling;
                      }
                    }
                  }
                }
              }
              {
                hideOrUnhideAllChildren(offscreenBoundary, _isHidden);
              }
            }
            return;
          }
          case SuspenseListComponent: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & Update) {
              attachSuspenseRetryListeners(finishedWork);
            }
            return;
          }
          case ScopeComponent: {
            return;
          }
          default: {
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            return;
          }
        }
      }
      function commitReconciliationEffects(finishedWork) {
        var flags = finishedWork.flags;
        if (flags & Placement) {
          try {
            commitPlacement(finishedWork);
          } catch (error2) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error2);
          }
          finishedWork.flags &= -3;
        }
        if (flags & Hydrating) {
          finishedWork.flags &= -4097;
        }
      }
      function commitLayoutEffects(finishedWork, root2, committedLanes) {
        inProgressLanes = committedLanes;
        inProgressRoot = root2;
        nextEffect = finishedWork;
        commitLayoutEffects_begin(finishedWork, root2, committedLanes);
        inProgressLanes = null;
        inProgressRoot = null;
      }
      function commitLayoutEffects_begin(subtreeRoot, root2, committedLanes) {
        var isModernRoot = (subtreeRoot.mode & ConcurrentMode) !== NoMode;
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var firstChild = fiber.child;
          if (fiber.tag === OffscreenComponent && isModernRoot) {
            var isHidden = fiber.memoizedState !== null;
            var newOffscreenSubtreeIsHidden = isHidden || offscreenSubtreeIsHidden;
            if (newOffscreenSubtreeIsHidden) {
              commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes);
              continue;
            } else {
              var current2 = fiber.alternate;
              var wasHidden = current2 !== null && current2.memoizedState !== null;
              var newOffscreenSubtreeWasHidden = wasHidden || offscreenSubtreeWasHidden;
              var prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = newOffscreenSubtreeIsHidden;
              offscreenSubtreeWasHidden = newOffscreenSubtreeWasHidden;
              if (offscreenSubtreeWasHidden && !prevOffscreenSubtreeWasHidden) {
                nextEffect = fiber;
                reappearLayoutEffects_begin(fiber);
              }
              var child = firstChild;
              while (child !== null) {
                nextEffect = child;
                commitLayoutEffects_begin(
                  child,
                  // New root; bubble back up to here and stop.
                  root2,
                  committedLanes
                );
                child = child.sibling;
              }
              nextEffect = fiber;
              offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
              commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes);
              continue;
            }
          }
          if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
            firstChild.return = fiber;
            nextEffect = firstChild;
          } else {
            commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes);
          }
        }
      }
      function commitLayoutMountEffects_complete(subtreeRoot, root2, committedLanes) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          if ((fiber.flags & LayoutMask) !== NoFlags) {
            var current2 = fiber.alternate;
            setCurrentFiber(fiber);
            try {
              commitLayoutEffectOnFiber(root2, current2, fiber, committedLanes);
            } catch (error2) {
              captureCommitPhaseError(fiber, fiber.return, error2);
            }
            resetCurrentFiber();
          }
          if (fiber === subtreeRoot) {
            nextEffect = null;
            return;
          }
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function disappearLayoutEffects_begin(subtreeRoot) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var firstChild = fiber.child;
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case MemoComponent:
            case SimpleMemoComponent: {
              if (fiber.mode & ProfileMode) {
                try {
                  startLayoutEffectTimer();
                  commitHookEffectListUnmount(Layout, fiber, fiber.return);
                } finally {
                  recordLayoutEffectDuration(fiber);
                }
              } else {
                commitHookEffectListUnmount(Layout, fiber, fiber.return);
              }
              break;
            }
            case ClassComponent: {
              safelyDetachRef(fiber, fiber.return);
              var instance2 = fiber.stateNode;
              if (typeof instance2.componentWillUnmount === "function") {
                safelyCallComponentWillUnmount(fiber, fiber.return, instance2);
              }
              break;
            }
            case HostComponent: {
              safelyDetachRef(fiber, fiber.return);
              break;
            }
            case OffscreenComponent: {
              var isHidden = fiber.memoizedState !== null;
              if (isHidden) {
                disappearLayoutEffects_complete(subtreeRoot);
                continue;
              }
              break;
            }
          }
          if (firstChild !== null) {
            firstChild.return = fiber;
            nextEffect = firstChild;
          } else {
            disappearLayoutEffects_complete(subtreeRoot);
          }
        }
      }
      function disappearLayoutEffects_complete(subtreeRoot) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          if (fiber === subtreeRoot) {
            nextEffect = null;
            return;
          }
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function reappearLayoutEffects_begin(subtreeRoot) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var firstChild = fiber.child;
          if (fiber.tag === OffscreenComponent) {
            var isHidden = fiber.memoizedState !== null;
            if (isHidden) {
              reappearLayoutEffects_complete(subtreeRoot);
              continue;
            }
          }
          if (firstChild !== null) {
            firstChild.return = fiber;
            nextEffect = firstChild;
          } else {
            reappearLayoutEffects_complete(subtreeRoot);
          }
        }
      }
      function reappearLayoutEffects_complete(subtreeRoot) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          setCurrentFiber(fiber);
          try {
            reappearLayoutEffectsOnFiber(fiber);
          } catch (error2) {
            captureCommitPhaseError(fiber, fiber.return, error2);
          }
          resetCurrentFiber();
          if (fiber === subtreeRoot) {
            nextEffect = null;
            return;
          }
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function commitPassiveMountEffects(root2, finishedWork, committedLanes, committedTransitions) {
        nextEffect = finishedWork;
        commitPassiveMountEffects_begin(finishedWork, root2, committedLanes, committedTransitions);
      }
      function commitPassiveMountEffects_begin(subtreeRoot, root2, committedLanes, committedTransitions) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var firstChild = fiber.child;
          if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && firstChild !== null) {
            firstChild.return = fiber;
            nextEffect = firstChild;
          } else {
            commitPassiveMountEffects_complete(subtreeRoot, root2, committedLanes, committedTransitions);
          }
        }
      }
      function commitPassiveMountEffects_complete(subtreeRoot, root2, committedLanes, committedTransitions) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          if ((fiber.flags & Passive) !== NoFlags) {
            setCurrentFiber(fiber);
            try {
              commitPassiveMountOnFiber(root2, fiber, committedLanes, committedTransitions);
            } catch (error2) {
              captureCommitPhaseError(fiber, fiber.return, error2);
            }
            resetCurrentFiber();
          }
          if (fiber === subtreeRoot) {
            nextEffect = null;
            return;
          }
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
        switch (finishedWork.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent: {
            if (finishedWork.mode & ProfileMode) {
              startPassiveEffectTimer();
              try {
                commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
              } finally {
                recordPassiveEffectDuration(finishedWork);
              }
            } else {
              commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
            }
            break;
          }
        }
      }
      function commitPassiveUnmountEffects(firstChild) {
        nextEffect = firstChild;
        commitPassiveUnmountEffects_begin();
      }
      function commitPassiveUnmountEffects_begin() {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var child = fiber.child;
          if ((nextEffect.flags & ChildDeletion) !== NoFlags) {
            var deletions = fiber.deletions;
            if (deletions !== null) {
              for (var i2 = 0; i2 < deletions.length; i2++) {
                var fiberToDelete = deletions[i2];
                nextEffect = fiberToDelete;
                commitPassiveUnmountEffectsInsideOfDeletedTree_begin(fiberToDelete, fiber);
              }
              {
                var previousFiber = fiber.alternate;
                if (previousFiber !== null) {
                  var detachedChild = previousFiber.child;
                  if (detachedChild !== null) {
                    previousFiber.child = null;
                    do {
                      var detachedSibling = detachedChild.sibling;
                      detachedChild.sibling = null;
                      detachedChild = detachedSibling;
                    } while (detachedChild !== null);
                  }
                }
              }
              nextEffect = fiber;
            }
          }
          if ((fiber.subtreeFlags & PassiveMask) !== NoFlags && child !== null) {
            child.return = fiber;
            nextEffect = child;
          } else {
            commitPassiveUnmountEffects_complete();
          }
        }
      }
      function commitPassiveUnmountEffects_complete() {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          if ((fiber.flags & Passive) !== NoFlags) {
            setCurrentFiber(fiber);
            commitPassiveUnmountOnFiber(fiber);
            resetCurrentFiber();
          }
          var sibling = fiber.sibling;
          if (sibling !== null) {
            sibling.return = fiber.return;
            nextEffect = sibling;
            return;
          }
          nextEffect = fiber.return;
        }
      }
      function commitPassiveUnmountOnFiber(finishedWork) {
        switch (finishedWork.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent: {
            if (finishedWork.mode & ProfileMode) {
              startPassiveEffectTimer();
              commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
              recordPassiveEffectDuration(finishedWork);
            } else {
              commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork, finishedWork.return);
            }
            break;
          }
        }
      }
      function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          setCurrentFiber(fiber);
          commitPassiveUnmountInsideDeletedTreeOnFiber(fiber, nearestMountedAncestor);
          resetCurrentFiber();
          var child = fiber.child;
          if (child !== null) {
            child.return = fiber;
            nextEffect = child;
          } else {
            commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot);
          }
        }
      }
      function commitPassiveUnmountEffectsInsideOfDeletedTree_complete(deletedSubtreeRoot) {
        while (nextEffect !== null) {
          var fiber = nextEffect;
          var sibling = fiber.sibling;
          var returnFiber = fiber.return;
          {
            detachFiberAfterEffects(fiber);
            if (fiber === deletedSubtreeRoot) {
              nextEffect = null;
              return;
            }
          }
          if (sibling !== null) {
            sibling.return = returnFiber;
            nextEffect = sibling;
            return;
          }
          nextEffect = returnFiber;
        }
      }
      function commitPassiveUnmountInsideDeletedTreeOnFiber(current2, nearestMountedAncestor) {
        switch (current2.tag) {
          case FunctionComponent:
          case ForwardRef:
          case SimpleMemoComponent: {
            if (current2.mode & ProfileMode) {
              startPassiveEffectTimer();
              commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor);
              recordPassiveEffectDuration(current2);
            } else {
              commitHookEffectListUnmount(Passive$1, current2, nearestMountedAncestor);
            }
            break;
          }
        }
      }
      function invokeLayoutEffectMountInDEV(fiber) {
        {
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              try {
                commitHookEffectListMount(Layout | HasEffect, fiber);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              break;
            }
            case ClassComponent: {
              var instance2 = fiber.stateNode;
              try {
                instance2.componentDidMount();
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              break;
            }
          }
        }
      }
      function invokePassiveEffectMountInDEV(fiber) {
        {
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              try {
                commitHookEffectListMount(Passive$1 | HasEffect, fiber);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              break;
            }
          }
        }
      }
      function invokeLayoutEffectUnmountInDEV(fiber) {
        {
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              try {
                commitHookEffectListUnmount(Layout | HasEffect, fiber, fiber.return);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
              break;
            }
            case ClassComponent: {
              var instance2 = fiber.stateNode;
              if (typeof instance2.componentWillUnmount === "function") {
                safelyCallComponentWillUnmount(fiber, fiber.return, instance2);
              }
              break;
            }
          }
        }
      }
      function invokePassiveEffectUnmountInDEV(fiber) {
        {
          switch (fiber.tag) {
            case FunctionComponent:
            case ForwardRef:
            case SimpleMemoComponent: {
              try {
                commitHookEffectListUnmount(Passive$1 | HasEffect, fiber, fiber.return);
              } catch (error2) {
                captureCommitPhaseError(fiber, fiber.return, error2);
              }
            }
          }
        }
      }
      if (typeof Symbol === "function" && Symbol.for) {
        var symbolFor = Symbol.for;
        symbolFor("selector.component");
        symbolFor("selector.has_pseudo_class");
        symbolFor("selector.role");
        symbolFor("selector.test_id");
        symbolFor("selector.text");
      }
      var commitHooks = [];
      function onCommitRoot$1() {
        {
          commitHooks.forEach(function(commitHook) {
            return commitHook();
          });
        }
      }
      var ReactCurrentActQueue = ReactSharedInternals.ReactCurrentActQueue;
      function isLegacyActEnvironment(fiber) {
        {
          var isReactActEnvironmentGlobal = (
            // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
            typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0
          );
          var jestIsDefined = typeof jest !== "undefined";
          return jestIsDefined && isReactActEnvironmentGlobal !== false;
        }
      }
      function isConcurrentActEnvironment() {
        {
          var isReactActEnvironmentGlobal = (
            // $FlowExpectedError – Flow doesn't know about IS_REACT_ACT_ENVIRONMENT global
            typeof IS_REACT_ACT_ENVIRONMENT !== "undefined" ? IS_REACT_ACT_ENVIRONMENT : void 0
          );
          if (!isReactActEnvironmentGlobal && ReactCurrentActQueue.current !== null) {
            error("The current testing environment is not configured to support act(...)");
          }
          return isReactActEnvironmentGlobal;
        }
      }
      var ceil = Math.ceil;
      var ReactCurrentDispatcher$2 = ReactSharedInternals.ReactCurrentDispatcher, ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner, ReactCurrentBatchConfig$3 = ReactSharedInternals.ReactCurrentBatchConfig, ReactCurrentActQueue$1 = ReactSharedInternals.ReactCurrentActQueue;
      var NoContext = (
        /*             */
        0
      );
      var BatchedContext = (
        /*               */
        1
      );
      var RenderContext = (
        /*                */
        2
      );
      var CommitContext = (
        /*                */
        4
      );
      var RootInProgress = 0;
      var RootFatalErrored = 1;
      var RootErrored = 2;
      var RootSuspended = 3;
      var RootSuspendedWithDelay = 4;
      var RootCompleted = 5;
      var RootDidNotComplete = 6;
      var executionContext = NoContext;
      var workInProgressRoot = null;
      var workInProgress = null;
      var workInProgressRootRenderLanes = NoLanes;
      var subtreeRenderLanes = NoLanes;
      var subtreeRenderLanesCursor = createCursor(NoLanes);
      var workInProgressRootExitStatus = RootInProgress;
      var workInProgressRootFatalError = null;
      var workInProgressRootSkippedLanes = NoLanes;
      var workInProgressRootInterleavedUpdatedLanes = NoLanes;
      var workInProgressRootPingedLanes = NoLanes;
      var workInProgressRootConcurrentErrors = null;
      var workInProgressRootRecoverableErrors = null;
      var globalMostRecentFallbackTime = 0;
      var FALLBACK_THROTTLE_MS = 500;
      var workInProgressRootRenderTargetTime = Infinity;
      var RENDER_TIMEOUT_MS = 500;
      var workInProgressTransitions = null;
      function resetRenderTimer() {
        workInProgressRootRenderTargetTime = now() + RENDER_TIMEOUT_MS;
      }
      function getRenderTargetTime() {
        return workInProgressRootRenderTargetTime;
      }
      var hasUncaughtError = false;
      var firstUncaughtError = null;
      var legacyErrorBoundariesThatAlreadyFailed = null;
      var rootDoesHavePassiveEffects = false;
      var rootWithPendingPassiveEffects = null;
      var pendingPassiveEffectsLanes = NoLanes;
      var pendingPassiveProfilerEffects = [];
      var pendingPassiveTransitions = null;
      var NESTED_UPDATE_LIMIT = 50;
      var nestedUpdateCount = 0;
      var rootWithNestedUpdates = null;
      var isFlushingPassiveEffects = false;
      var didScheduleUpdateDuringPassiveEffects = false;
      var NESTED_PASSIVE_UPDATE_LIMIT = 50;
      var nestedPassiveUpdateCount = 0;
      var rootWithPassiveNestedUpdates = null;
      var currentEventTime = NoTimestamp;
      var currentEventTransitionLane = NoLanes;
      var isRunningInsertionEffect = false;
      function getWorkInProgressRoot() {
        return workInProgressRoot;
      }
      function requestEventTime() {
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
          return now();
        }
        if (currentEventTime !== NoTimestamp) {
          return currentEventTime;
        }
        currentEventTime = now();
        return currentEventTime;
      }
      function requestUpdateLane(fiber) {
        var mode = fiber.mode;
        if ((mode & ConcurrentMode) === NoMode) {
          return SyncLane;
        } else if ((executionContext & RenderContext) !== NoContext && workInProgressRootRenderLanes !== NoLanes) {
          return pickArbitraryLane(workInProgressRootRenderLanes);
        }
        var isTransition = requestCurrentTransition() !== NoTransition;
        if (isTransition) {
          if (ReactCurrentBatchConfig$3.transition !== null) {
            var transition = ReactCurrentBatchConfig$3.transition;
            if (!transition._updatedFibers) {
              transition._updatedFibers = /* @__PURE__ */ new Set();
            }
            transition._updatedFibers.add(fiber);
          }
          if (currentEventTransitionLane === NoLane) {
            currentEventTransitionLane = claimNextTransitionLane();
          }
          return currentEventTransitionLane;
        }
        var updateLane = getCurrentUpdatePriority();
        if (updateLane !== NoLane) {
          return updateLane;
        }
        var eventLane = getCurrentEventPriority();
        return eventLane;
      }
      function requestRetryLane(fiber) {
        var mode = fiber.mode;
        if ((mode & ConcurrentMode) === NoMode) {
          return SyncLane;
        }
        return claimNextRetryLane();
      }
      function scheduleUpdateOnFiber(root2, fiber, lane, eventTime) {
        checkForNestedUpdates();
        {
          if (isRunningInsertionEffect) {
            error("useInsertionEffect must not schedule updates.");
          }
        }
        {
          if (isFlushingPassiveEffects) {
            didScheduleUpdateDuringPassiveEffects = true;
          }
        }
        markRootUpdated(root2, lane, eventTime);
        if ((executionContext & RenderContext) !== NoLanes && root2 === workInProgressRoot) {
          warnAboutRenderPhaseUpdatesInDEV(fiber);
        } else {
          {
            if (isDevToolsPresent) {
              addFiberToLanesMap(root2, fiber, lane);
            }
          }
          warnIfUpdatesNotWrappedWithActDEV(fiber);
          if (root2 === workInProgressRoot) {
            if ((executionContext & RenderContext) === NoContext) {
              workInProgressRootInterleavedUpdatedLanes = mergeLanes(workInProgressRootInterleavedUpdatedLanes, lane);
            }
            if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
              markRootSuspended$1(root2, workInProgressRootRenderLanes);
            }
          }
          ensureRootIsScheduled(root2, eventTime);
          if (lane === SyncLane && executionContext === NoContext && (fiber.mode & ConcurrentMode) === NoMode && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
          !ReactCurrentActQueue$1.isBatchingLegacy) {
            resetRenderTimer();
            flushSyncCallbacksOnlyInLegacyMode();
          }
        }
      }
      function scheduleInitialHydrationOnRoot(root2, lane, eventTime) {
        var current2 = root2.current;
        current2.lanes = lane;
        markRootUpdated(root2, lane, eventTime);
        ensureRootIsScheduled(root2, eventTime);
      }
      function isUnsafeClassRenderPhaseUpdate(fiber) {
        return (
          // TODO: Remove outdated deferRenderPhaseUpdateToNextBatch experiment. We
          // decided not to enable it.
          (executionContext & RenderContext) !== NoContext
        );
      }
      function ensureRootIsScheduled(root2, currentTime) {
        var existingCallbackNode = root2.callbackNode;
        markStarvedLanesAsExpired(root2, currentTime);
        var nextLanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
        if (nextLanes === NoLanes) {
          if (existingCallbackNode !== null) {
            cancelCallback$1(existingCallbackNode);
          }
          root2.callbackNode = null;
          root2.callbackPriority = NoLane;
          return;
        }
        var newCallbackPriority = getHighestPriorityLane(nextLanes);
        var existingCallbackPriority = root2.callbackPriority;
        if (existingCallbackPriority === newCallbackPriority && // Special case related to `act`. If the currently scheduled task is a
        // Scheduler task, rather than an `act` task, cancel it and re-scheduled
        // on the `act` queue.
        !(ReactCurrentActQueue$1.current !== null && existingCallbackNode !== fakeActCallbackNode)) {
          {
            if (existingCallbackNode == null && existingCallbackPriority !== SyncLane) {
              error("Expected scheduled callback to exist. This error is likely caused by a bug in React. Please file an issue.");
            }
          }
          return;
        }
        if (existingCallbackNode != null) {
          cancelCallback$1(existingCallbackNode);
        }
        var newCallbackNode;
        if (newCallbackPriority === SyncLane) {
          if (root2.tag === LegacyRoot) {
            if (ReactCurrentActQueue$1.isBatchingLegacy !== null) {
              ReactCurrentActQueue$1.didScheduleLegacyUpdate = true;
            }
            scheduleLegacySyncCallback(performSyncWorkOnRoot.bind(null, root2));
          } else {
            scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root2));
          }
          {
            if (ReactCurrentActQueue$1.current !== null) {
              ReactCurrentActQueue$1.current.push(flushSyncCallbacks);
            } else {
              scheduleMicrotask(function() {
                if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
                  flushSyncCallbacks();
                }
              });
            }
          }
          newCallbackNode = null;
        } else {
          var schedulerPriorityLevel;
          switch (lanesToEventPriority(nextLanes)) {
            case DiscreteEventPriority:
              schedulerPriorityLevel = ImmediatePriority;
              break;
            case ContinuousEventPriority:
              schedulerPriorityLevel = UserBlockingPriority;
              break;
            case DefaultEventPriority:
              schedulerPriorityLevel = NormalPriority;
              break;
            case IdleEventPriority:
              schedulerPriorityLevel = IdlePriority;
              break;
            default:
              schedulerPriorityLevel = NormalPriority;
              break;
          }
          newCallbackNode = scheduleCallback$1(schedulerPriorityLevel, performConcurrentWorkOnRoot.bind(null, root2));
        }
        root2.callbackPriority = newCallbackPriority;
        root2.callbackNode = newCallbackNode;
      }
      function performConcurrentWorkOnRoot(root2, didTimeout) {
        {
          resetNestedUpdateFlag();
        }
        currentEventTime = NoTimestamp;
        currentEventTransitionLane = NoLanes;
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
          throw new Error("Should not already be working.");
        }
        var originalCallbackNode = root2.callbackNode;
        var didFlushPassiveEffects = flushPassiveEffects();
        if (didFlushPassiveEffects) {
          if (root2.callbackNode !== originalCallbackNode) {
            return null;
          }
        }
        var lanes = getNextLanes(root2, root2 === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
        if (lanes === NoLanes) {
          return null;
        }
        var shouldTimeSlice = !includesBlockingLane(root2, lanes) && !includesExpiredLane(root2, lanes) && !didTimeout;
        var exitStatus = shouldTimeSlice ? renderRootConcurrent(root2, lanes) : renderRootSync(root2, lanes);
        if (exitStatus !== RootInProgress) {
          if (exitStatus === RootErrored) {
            var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2);
            if (errorRetryLanes !== NoLanes) {
              lanes = errorRetryLanes;
              exitStatus = recoverFromConcurrentError(root2, errorRetryLanes);
            }
          }
          if (exitStatus === RootFatalErrored) {
            var fatalError = workInProgressRootFatalError;
            prepareFreshStack(root2, NoLanes);
            markRootSuspended$1(root2, lanes);
            ensureRootIsScheduled(root2, now());
            throw fatalError;
          }
          if (exitStatus === RootDidNotComplete) {
            markRootSuspended$1(root2, lanes);
          } else {
            var renderWasConcurrent = !includesBlockingLane(root2, lanes);
            var finishedWork = root2.current.alternate;
            if (renderWasConcurrent && !isRenderConsistentWithExternalStores(finishedWork)) {
              exitStatus = renderRootSync(root2, lanes);
              if (exitStatus === RootErrored) {
                var _errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2);
                if (_errorRetryLanes !== NoLanes) {
                  lanes = _errorRetryLanes;
                  exitStatus = recoverFromConcurrentError(root2, _errorRetryLanes);
                }
              }
              if (exitStatus === RootFatalErrored) {
                var _fatalError = workInProgressRootFatalError;
                prepareFreshStack(root2, NoLanes);
                markRootSuspended$1(root2, lanes);
                ensureRootIsScheduled(root2, now());
                throw _fatalError;
              }
            }
            root2.finishedWork = finishedWork;
            root2.finishedLanes = lanes;
            finishConcurrentRender(root2, exitStatus, lanes);
          }
        }
        ensureRootIsScheduled(root2, now());
        if (root2.callbackNode === originalCallbackNode) {
          return performConcurrentWorkOnRoot.bind(null, root2);
        }
        return null;
      }
      function recoverFromConcurrentError(root2, errorRetryLanes) {
        var errorsFromFirstAttempt = workInProgressRootConcurrentErrors;
        if (isRootDehydrated(root2)) {
          var rootWorkInProgress = prepareFreshStack(root2, errorRetryLanes);
          rootWorkInProgress.flags |= ForceClientRender;
          {
            errorHydratingContainer(root2.containerInfo);
          }
        }
        var exitStatus = renderRootSync(root2, errorRetryLanes);
        if (exitStatus !== RootErrored) {
          var errorsFromSecondAttempt = workInProgressRootRecoverableErrors;
          workInProgressRootRecoverableErrors = errorsFromFirstAttempt;
          if (errorsFromSecondAttempt !== null) {
            queueRecoverableErrors(errorsFromSecondAttempt);
          }
        }
        return exitStatus;
      }
      function queueRecoverableErrors(errors) {
        if (workInProgressRootRecoverableErrors === null) {
          workInProgressRootRecoverableErrors = errors;
        } else {
          workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors, errors);
        }
      }
      function finishConcurrentRender(root2, exitStatus, lanes) {
        switch (exitStatus) {
          case RootInProgress:
          case RootFatalErrored: {
            throw new Error("Root did not complete. This is a bug in React.");
          }
          // Flow knows about invariant, so it complains if I add a break
          // statement, but eslint doesn't know about invariant, so it complains
          // if I do. eslint-disable-next-line no-fallthrough
          case RootErrored: {
            commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions);
            break;
          }
          case RootSuspended: {
            markRootSuspended$1(root2, lanes);
            if (includesOnlyRetries(lanes) && // do not delay if we're inside an act() scope
            !shouldForceFlushFallbacksInDEV()) {
              var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now();
              if (msUntilTimeout > 10) {
                var nextLanes = getNextLanes(root2, NoLanes);
                if (nextLanes !== NoLanes) {
                  break;
                }
                var suspendedLanes = root2.suspendedLanes;
                if (!isSubsetOfLanes(suspendedLanes, lanes)) {
                  requestEventTime();
                  markRootPinged(root2, suspendedLanes);
                  break;
                }
                root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2, workInProgressRootRecoverableErrors, workInProgressTransitions), msUntilTimeout);
                break;
              }
            }
            commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions);
            break;
          }
          case RootSuspendedWithDelay: {
            markRootSuspended$1(root2, lanes);
            if (includesOnlyTransitions(lanes)) {
              break;
            }
            if (!shouldForceFlushFallbacksInDEV()) {
              var mostRecentEventTime = getMostRecentEventTime(root2, lanes);
              var eventTimeMs = mostRecentEventTime;
              var timeElapsedMs = now() - eventTimeMs;
              var _msUntilTimeout = jnd(timeElapsedMs) - timeElapsedMs;
              if (_msUntilTimeout > 10) {
                root2.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root2, workInProgressRootRecoverableErrors, workInProgressTransitions), _msUntilTimeout);
                break;
              }
            }
            commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions);
            break;
          }
          case RootCompleted: {
            commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions);
            break;
          }
          default: {
            throw new Error("Unknown root exit status.");
          }
        }
      }
      function isRenderConsistentWithExternalStores(finishedWork) {
        var node2 = finishedWork;
        while (true) {
          if (node2.flags & StoreConsistency) {
            var updateQueue = node2.updateQueue;
            if (updateQueue !== null) {
              var checks = updateQueue.stores;
              if (checks !== null) {
                for (var i2 = 0; i2 < checks.length; i2++) {
                  var check = checks[i2];
                  var getSnapshot = check.getSnapshot;
                  var renderedValue = check.value;
                  try {
                    if (!objectIs(getSnapshot(), renderedValue)) {
                      return false;
                    }
                  } catch (error2) {
                    return false;
                  }
                }
              }
            }
          }
          var child = node2.child;
          if (node2.subtreeFlags & StoreConsistency && child !== null) {
            child.return = node2;
            node2 = child;
            continue;
          }
          if (node2 === finishedWork) {
            return true;
          }
          while (node2.sibling === null) {
            if (node2.return === null || node2.return === finishedWork) {
              return true;
            }
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
        return true;
      }
      function markRootSuspended$1(root2, suspendedLanes) {
        suspendedLanes = removeLanes(suspendedLanes, workInProgressRootPingedLanes);
        suspendedLanes = removeLanes(suspendedLanes, workInProgressRootInterleavedUpdatedLanes);
        markRootSuspended(root2, suspendedLanes);
      }
      function performSyncWorkOnRoot(root2) {
        {
          syncNestedUpdateFlag();
        }
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
          throw new Error("Should not already be working.");
        }
        flushPassiveEffects();
        var lanes = getNextLanes(root2, NoLanes);
        if (!includesSomeLane(lanes, SyncLane)) {
          ensureRootIsScheduled(root2, now());
          return null;
        }
        var exitStatus = renderRootSync(root2, lanes);
        if (root2.tag !== LegacyRoot && exitStatus === RootErrored) {
          var errorRetryLanes = getLanesToRetrySynchronouslyOnError(root2);
          if (errorRetryLanes !== NoLanes) {
            lanes = errorRetryLanes;
            exitStatus = recoverFromConcurrentError(root2, errorRetryLanes);
          }
        }
        if (exitStatus === RootFatalErrored) {
          var fatalError = workInProgressRootFatalError;
          prepareFreshStack(root2, NoLanes);
          markRootSuspended$1(root2, lanes);
          ensureRootIsScheduled(root2, now());
          throw fatalError;
        }
        if (exitStatus === RootDidNotComplete) {
          throw new Error("Root did not complete. This is a bug in React.");
        }
        var finishedWork = root2.current.alternate;
        root2.finishedWork = finishedWork;
        root2.finishedLanes = lanes;
        commitRoot(root2, workInProgressRootRecoverableErrors, workInProgressTransitions);
        ensureRootIsScheduled(root2, now());
        return null;
      }
      function flushRoot(root2, lanes) {
        if (lanes !== NoLanes) {
          markRootEntangled(root2, mergeLanes(lanes, SyncLane));
          ensureRootIsScheduled(root2, now());
          if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
            resetRenderTimer();
            flushSyncCallbacks();
          }
        }
      }
      function batchedUpdates$1(fn, a2) {
        var prevExecutionContext = executionContext;
        executionContext |= BatchedContext;
        try {
          return fn(a2);
        } finally {
          executionContext = prevExecutionContext;
          if (executionContext === NoContext && // Treat `act` as if it's inside `batchedUpdates`, even in legacy mode.
          !ReactCurrentActQueue$1.isBatchingLegacy) {
            resetRenderTimer();
            flushSyncCallbacksOnlyInLegacyMode();
          }
        }
      }
      function discreteUpdates(fn, a2, b2, c2, d) {
        var previousPriority = getCurrentUpdatePriority();
        var prevTransition = ReactCurrentBatchConfig$3.transition;
        try {
          ReactCurrentBatchConfig$3.transition = null;
          setCurrentUpdatePriority(DiscreteEventPriority);
          return fn(a2, b2, c2, d);
        } finally {
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig$3.transition = prevTransition;
          if (executionContext === NoContext) {
            resetRenderTimer();
          }
        }
      }
      function flushSync(fn) {
        if (rootWithPendingPassiveEffects !== null && rootWithPendingPassiveEffects.tag === LegacyRoot && (executionContext & (RenderContext | CommitContext)) === NoContext) {
          flushPassiveEffects();
        }
        var prevExecutionContext = executionContext;
        executionContext |= BatchedContext;
        var prevTransition = ReactCurrentBatchConfig$3.transition;
        var previousPriority = getCurrentUpdatePriority();
        try {
          ReactCurrentBatchConfig$3.transition = null;
          setCurrentUpdatePriority(DiscreteEventPriority);
          if (fn) {
            return fn();
          } else {
            return void 0;
          }
        } finally {
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig$3.transition = prevTransition;
          executionContext = prevExecutionContext;
          if ((executionContext & (RenderContext | CommitContext)) === NoContext) {
            flushSyncCallbacks();
          }
        }
      }
      function isAlreadyRendering() {
        return (executionContext & (RenderContext | CommitContext)) !== NoContext;
      }
      function pushRenderLanes(fiber, lanes) {
        push(subtreeRenderLanesCursor, subtreeRenderLanes, fiber);
        subtreeRenderLanes = mergeLanes(subtreeRenderLanes, lanes);
      }
      function popRenderLanes(fiber) {
        subtreeRenderLanes = subtreeRenderLanesCursor.current;
        pop(subtreeRenderLanesCursor, fiber);
      }
      function prepareFreshStack(root2, lanes) {
        root2.finishedWork = null;
        root2.finishedLanes = NoLanes;
        var timeoutHandle = root2.timeoutHandle;
        if (timeoutHandle !== noTimeout) {
          root2.timeoutHandle = noTimeout;
          cancelTimeout(timeoutHandle);
        }
        if (workInProgress !== null) {
          var interruptedWork = workInProgress.return;
          while (interruptedWork !== null) {
            var current2 = interruptedWork.alternate;
            unwindInterruptedWork(current2, interruptedWork);
            interruptedWork = interruptedWork.return;
          }
        }
        workInProgressRoot = root2;
        var rootWorkInProgress = createWorkInProgress(root2.current, null);
        workInProgress = rootWorkInProgress;
        workInProgressRootRenderLanes = subtreeRenderLanes = lanes;
        workInProgressRootExitStatus = RootInProgress;
        workInProgressRootFatalError = null;
        workInProgressRootSkippedLanes = NoLanes;
        workInProgressRootInterleavedUpdatedLanes = NoLanes;
        workInProgressRootPingedLanes = NoLanes;
        workInProgressRootConcurrentErrors = null;
        workInProgressRootRecoverableErrors = null;
        finishQueueingConcurrentUpdates();
        {
          ReactStrictModeWarnings.discardPendingWarnings();
        }
        return rootWorkInProgress;
      }
      function handleError(root2, thrownValue) {
        do {
          var erroredWork = workInProgress;
          try {
            resetContextDependencies();
            resetHooksAfterThrow();
            resetCurrentFiber();
            ReactCurrentOwner$2.current = null;
            if (erroredWork === null || erroredWork.return === null) {
              workInProgressRootExitStatus = RootFatalErrored;
              workInProgressRootFatalError = thrownValue;
              workInProgress = null;
              return;
            }
            if (enableProfilerTimer && erroredWork.mode & ProfileMode) {
              stopProfilerTimerIfRunningAndRecordDelta(erroredWork, true);
            }
            if (enableSchedulingProfiler) {
              markComponentRenderStopped();
              if (thrownValue !== null && typeof thrownValue === "object" && typeof thrownValue.then === "function") {
                var wakeable = thrownValue;
                markComponentSuspended(erroredWork, wakeable, workInProgressRootRenderLanes);
              } else {
                markComponentErrored(erroredWork, thrownValue, workInProgressRootRenderLanes);
              }
            }
            throwException(root2, erroredWork.return, erroredWork, thrownValue, workInProgressRootRenderLanes);
            completeUnitOfWork(erroredWork);
          } catch (yetAnotherThrownValue) {
            thrownValue = yetAnotherThrownValue;
            if (workInProgress === erroredWork && erroredWork !== null) {
              erroredWork = erroredWork.return;
              workInProgress = erroredWork;
            } else {
              erroredWork = workInProgress;
            }
            continue;
          }
          return;
        } while (true);
      }
      function pushDispatcher() {
        var prevDispatcher = ReactCurrentDispatcher$2.current;
        ReactCurrentDispatcher$2.current = ContextOnlyDispatcher;
        if (prevDispatcher === null) {
          return ContextOnlyDispatcher;
        } else {
          return prevDispatcher;
        }
      }
      function popDispatcher(prevDispatcher) {
        ReactCurrentDispatcher$2.current = prevDispatcher;
      }
      function markCommitTimeOfFallback() {
        globalMostRecentFallbackTime = now();
      }
      function markSkippedUpdateLanes(lane) {
        workInProgressRootSkippedLanes = mergeLanes(lane, workInProgressRootSkippedLanes);
      }
      function renderDidSuspend() {
        if (workInProgressRootExitStatus === RootInProgress) {
          workInProgressRootExitStatus = RootSuspended;
        }
      }
      function renderDidSuspendDelayIfPossible() {
        if (workInProgressRootExitStatus === RootInProgress || workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootErrored) {
          workInProgressRootExitStatus = RootSuspendedWithDelay;
        }
        if (workInProgressRoot !== null && (includesNonIdleWork(workInProgressRootSkippedLanes) || includesNonIdleWork(workInProgressRootInterleavedUpdatedLanes))) {
          markRootSuspended$1(workInProgressRoot, workInProgressRootRenderLanes);
        }
      }
      function renderDidError(error2) {
        if (workInProgressRootExitStatus !== RootSuspendedWithDelay) {
          workInProgressRootExitStatus = RootErrored;
        }
        if (workInProgressRootConcurrentErrors === null) {
          workInProgressRootConcurrentErrors = [error2];
        } else {
          workInProgressRootConcurrentErrors.push(error2);
        }
      }
      function renderHasNotSuspendedYet() {
        return workInProgressRootExitStatus === RootInProgress;
      }
      function renderRootSync(root2, lanes) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher();
        if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
          {
            if (isDevToolsPresent) {
              var memoizedUpdaters = root2.memoizedUpdaters;
              if (memoizedUpdaters.size > 0) {
                restorePendingUpdaters(root2, workInProgressRootRenderLanes);
                memoizedUpdaters.clear();
              }
              movePendingFibersToMemoized(root2, lanes);
            }
          }
          workInProgressTransitions = getTransitionsForLanes();
          prepareFreshStack(root2, lanes);
        }
        {
          markRenderStarted(lanes);
        }
        do {
          try {
            workLoopSync();
            break;
          } catch (thrownValue) {
            handleError(root2, thrownValue);
          }
        } while (true);
        resetContextDependencies();
        executionContext = prevExecutionContext;
        popDispatcher(prevDispatcher);
        if (workInProgress !== null) {
          throw new Error("Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.");
        }
        {
          markRenderStopped();
        }
        workInProgressRoot = null;
        workInProgressRootRenderLanes = NoLanes;
        return workInProgressRootExitStatus;
      }
      function workLoopSync() {
        while (workInProgress !== null) {
          performUnitOfWork(workInProgress);
        }
      }
      function renderRootConcurrent(root2, lanes) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher();
        if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
          {
            if (isDevToolsPresent) {
              var memoizedUpdaters = root2.memoizedUpdaters;
              if (memoizedUpdaters.size > 0) {
                restorePendingUpdaters(root2, workInProgressRootRenderLanes);
                memoizedUpdaters.clear();
              }
              movePendingFibersToMemoized(root2, lanes);
            }
          }
          workInProgressTransitions = getTransitionsForLanes();
          resetRenderTimer();
          prepareFreshStack(root2, lanes);
        }
        {
          markRenderStarted(lanes);
        }
        do {
          try {
            workLoopConcurrent();
            break;
          } catch (thrownValue) {
            handleError(root2, thrownValue);
          }
        } while (true);
        resetContextDependencies();
        popDispatcher(prevDispatcher);
        executionContext = prevExecutionContext;
        if (workInProgress !== null) {
          {
            markRenderYielded();
          }
          return RootInProgress;
        } else {
          {
            markRenderStopped();
          }
          workInProgressRoot = null;
          workInProgressRootRenderLanes = NoLanes;
          return workInProgressRootExitStatus;
        }
      }
      function workLoopConcurrent() {
        while (workInProgress !== null && !shouldYield()) {
          performUnitOfWork(workInProgress);
        }
      }
      function performUnitOfWork(unitOfWork) {
        var current2 = unitOfWork.alternate;
        setCurrentFiber(unitOfWork);
        var next;
        if ((unitOfWork.mode & ProfileMode) !== NoMode) {
          startProfilerTimer(unitOfWork);
          next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
          stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
        } else {
          next = beginWork$1(current2, unitOfWork, subtreeRenderLanes);
        }
        resetCurrentFiber();
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        if (next === null) {
          completeUnitOfWork(unitOfWork);
        } else {
          workInProgress = next;
        }
        ReactCurrentOwner$2.current = null;
      }
      function completeUnitOfWork(unitOfWork) {
        var completedWork = unitOfWork;
        do {
          var current2 = completedWork.alternate;
          var returnFiber = completedWork.return;
          if ((completedWork.flags & Incomplete) === NoFlags) {
            setCurrentFiber(completedWork);
            var next = void 0;
            if ((completedWork.mode & ProfileMode) === NoMode) {
              next = completeWork(current2, completedWork, subtreeRenderLanes);
            } else {
              startProfilerTimer(completedWork);
              next = completeWork(current2, completedWork, subtreeRenderLanes);
              stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
            }
            resetCurrentFiber();
            if (next !== null) {
              workInProgress = next;
              return;
            }
          } else {
            var _next = unwindWork(current2, completedWork);
            if (_next !== null) {
              _next.flags &= HostEffectMask;
              workInProgress = _next;
              return;
            }
            if ((completedWork.mode & ProfileMode) !== NoMode) {
              stopProfilerTimerIfRunningAndRecordDelta(completedWork, false);
              var actualDuration = completedWork.actualDuration;
              var child = completedWork.child;
              while (child !== null) {
                actualDuration += child.actualDuration;
                child = child.sibling;
              }
              completedWork.actualDuration = actualDuration;
            }
            if (returnFiber !== null) {
              returnFiber.flags |= Incomplete;
              returnFiber.subtreeFlags = NoFlags;
              returnFiber.deletions = null;
            } else {
              workInProgressRootExitStatus = RootDidNotComplete;
              workInProgress = null;
              return;
            }
          }
          var siblingFiber = completedWork.sibling;
          if (siblingFiber !== null) {
            workInProgress = siblingFiber;
            return;
          }
          completedWork = returnFiber;
          workInProgress = completedWork;
        } while (completedWork !== null);
        if (workInProgressRootExitStatus === RootInProgress) {
          workInProgressRootExitStatus = RootCompleted;
        }
      }
      function commitRoot(root2, recoverableErrors, transitions) {
        var previousUpdateLanePriority = getCurrentUpdatePriority();
        var prevTransition = ReactCurrentBatchConfig$3.transition;
        try {
          ReactCurrentBatchConfig$3.transition = null;
          setCurrentUpdatePriority(DiscreteEventPriority);
          commitRootImpl(root2, recoverableErrors, transitions, previousUpdateLanePriority);
        } finally {
          ReactCurrentBatchConfig$3.transition = prevTransition;
          setCurrentUpdatePriority(previousUpdateLanePriority);
        }
        return null;
      }
      function commitRootImpl(root2, recoverableErrors, transitions, renderPriorityLevel) {
        do {
          flushPassiveEffects();
        } while (rootWithPendingPassiveEffects !== null);
        flushRenderPhaseStrictModeWarningsInDEV();
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
          throw new Error("Should not already be working.");
        }
        var finishedWork = root2.finishedWork;
        var lanes = root2.finishedLanes;
        {
          markCommitStarted(lanes);
        }
        if (finishedWork === null) {
          {
            markCommitStopped();
          }
          return null;
        } else {
          {
            if (lanes === NoLanes) {
              error("root.finishedLanes should not be empty during a commit. This is a bug in React.");
            }
          }
        }
        root2.finishedWork = null;
        root2.finishedLanes = NoLanes;
        if (finishedWork === root2.current) {
          throw new Error("Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.");
        }
        root2.callbackNode = null;
        root2.callbackPriority = NoLane;
        var remainingLanes = mergeLanes(finishedWork.lanes, finishedWork.childLanes);
        markRootFinished(root2, remainingLanes);
        if (root2 === workInProgressRoot) {
          workInProgressRoot = null;
          workInProgress = null;
          workInProgressRootRenderLanes = NoLanes;
        }
        if ((finishedWork.subtreeFlags & PassiveMask) !== NoFlags || (finishedWork.flags & PassiveMask) !== NoFlags) {
          if (!rootDoesHavePassiveEffects) {
            rootDoesHavePassiveEffects = true;
            pendingPassiveTransitions = transitions;
            scheduleCallback$1(NormalPriority, function() {
              flushPassiveEffects();
              return null;
            });
          }
        }
        var subtreeHasEffects = (finishedWork.subtreeFlags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
        var rootHasEffect = (finishedWork.flags & (BeforeMutationMask | MutationMask | LayoutMask | PassiveMask)) !== NoFlags;
        if (subtreeHasEffects || rootHasEffect) {
          var prevTransition = ReactCurrentBatchConfig$3.transition;
          ReactCurrentBatchConfig$3.transition = null;
          var previousPriority = getCurrentUpdatePriority();
          setCurrentUpdatePriority(DiscreteEventPriority);
          var prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          ReactCurrentOwner$2.current = null;
          commitBeforeMutationEffects(root2, finishedWork);
          {
            recordCommitTime();
          }
          commitMutationEffects(root2, finishedWork, lanes);
          resetAfterCommit(root2.containerInfo);
          root2.current = finishedWork;
          {
            markLayoutEffectsStarted(lanes);
          }
          commitLayoutEffects(finishedWork, root2, lanes);
          {
            markLayoutEffectsStopped();
          }
          requestPaint();
          executionContext = prevExecutionContext;
          setCurrentUpdatePriority(previousPriority);
          ReactCurrentBatchConfig$3.transition = prevTransition;
        } else {
          root2.current = finishedWork;
          {
            recordCommitTime();
          }
        }
        var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
        if (rootDoesHavePassiveEffects) {
          rootDoesHavePassiveEffects = false;
          rootWithPendingPassiveEffects = root2;
          pendingPassiveEffectsLanes = lanes;
        } else {
          {
            nestedPassiveUpdateCount = 0;
            rootWithPassiveNestedUpdates = null;
          }
        }
        remainingLanes = root2.pendingLanes;
        if (remainingLanes === NoLanes) {
          legacyErrorBoundariesThatAlreadyFailed = null;
        }
        {
          if (!rootDidHavePassiveEffects) {
            commitDoubleInvokeEffectsInDEV(root2.current, false);
          }
        }
        onCommitRoot(finishedWork.stateNode, renderPriorityLevel);
        {
          if (isDevToolsPresent) {
            root2.memoizedUpdaters.clear();
          }
        }
        {
          onCommitRoot$1();
        }
        ensureRootIsScheduled(root2, now());
        if (recoverableErrors !== null) {
          var onRecoverableError = root2.onRecoverableError;
          for (var i2 = 0; i2 < recoverableErrors.length; i2++) {
            var recoverableError = recoverableErrors[i2];
            var componentStack = recoverableError.stack;
            var digest = recoverableError.digest;
            onRecoverableError(recoverableError.value, {
              componentStack,
              digest
            });
          }
        }
        if (hasUncaughtError) {
          hasUncaughtError = false;
          var error$1 = firstUncaughtError;
          firstUncaughtError = null;
          throw error$1;
        }
        if (includesSomeLane(pendingPassiveEffectsLanes, SyncLane) && root2.tag !== LegacyRoot) {
          flushPassiveEffects();
        }
        remainingLanes = root2.pendingLanes;
        if (includesSomeLane(remainingLanes, SyncLane)) {
          {
            markNestedUpdateScheduled();
          }
          if (root2 === rootWithNestedUpdates) {
            nestedUpdateCount++;
          } else {
            nestedUpdateCount = 0;
            rootWithNestedUpdates = root2;
          }
        } else {
          nestedUpdateCount = 0;
        }
        flushSyncCallbacks();
        {
          markCommitStopped();
        }
        return null;
      }
      function flushPassiveEffects() {
        if (rootWithPendingPassiveEffects !== null) {
          var renderPriority = lanesToEventPriority(pendingPassiveEffectsLanes);
          var priority = lowerEventPriority(DefaultEventPriority, renderPriority);
          var prevTransition = ReactCurrentBatchConfig$3.transition;
          var previousPriority = getCurrentUpdatePriority();
          try {
            ReactCurrentBatchConfig$3.transition = null;
            setCurrentUpdatePriority(priority);
            return flushPassiveEffectsImpl();
          } finally {
            setCurrentUpdatePriority(previousPriority);
            ReactCurrentBatchConfig$3.transition = prevTransition;
          }
        }
        return false;
      }
      function enqueuePendingPassiveProfilerEffect(fiber) {
        {
          pendingPassiveProfilerEffects.push(fiber);
          if (!rootDoesHavePassiveEffects) {
            rootDoesHavePassiveEffects = true;
            scheduleCallback$1(NormalPriority, function() {
              flushPassiveEffects();
              return null;
            });
          }
        }
      }
      function flushPassiveEffectsImpl() {
        if (rootWithPendingPassiveEffects === null) {
          return false;
        }
        var transitions = pendingPassiveTransitions;
        pendingPassiveTransitions = null;
        var root2 = rootWithPendingPassiveEffects;
        var lanes = pendingPassiveEffectsLanes;
        rootWithPendingPassiveEffects = null;
        pendingPassiveEffectsLanes = NoLanes;
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
          throw new Error("Cannot flush passive effects while already rendering.");
        }
        {
          isFlushingPassiveEffects = true;
          didScheduleUpdateDuringPassiveEffects = false;
        }
        {
          markPassiveEffectsStarted(lanes);
        }
        var prevExecutionContext = executionContext;
        executionContext |= CommitContext;
        commitPassiveUnmountEffects(root2.current);
        commitPassiveMountEffects(root2, root2.current, lanes, transitions);
        {
          var profilerEffects = pendingPassiveProfilerEffects;
          pendingPassiveProfilerEffects = [];
          for (var i2 = 0; i2 < profilerEffects.length; i2++) {
            var _fiber = profilerEffects[i2];
            commitPassiveEffectDurations(root2, _fiber);
          }
        }
        {
          markPassiveEffectsStopped();
        }
        {
          commitDoubleInvokeEffectsInDEV(root2.current, true);
        }
        executionContext = prevExecutionContext;
        flushSyncCallbacks();
        {
          if (didScheduleUpdateDuringPassiveEffects) {
            if (root2 === rootWithPassiveNestedUpdates) {
              nestedPassiveUpdateCount++;
            } else {
              nestedPassiveUpdateCount = 0;
              rootWithPassiveNestedUpdates = root2;
            }
          } else {
            nestedPassiveUpdateCount = 0;
          }
          isFlushingPassiveEffects = false;
          didScheduleUpdateDuringPassiveEffects = false;
        }
        onPostCommitRoot(root2);
        {
          var stateNode = root2.current.stateNode;
          stateNode.effectDuration = 0;
          stateNode.passiveEffectDuration = 0;
        }
        return true;
      }
      function isAlreadyFailedLegacyErrorBoundary(instance2) {
        return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance2);
      }
      function markLegacyErrorBoundaryAsFailed(instance2) {
        if (legacyErrorBoundariesThatAlreadyFailed === null) {
          legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([instance2]);
        } else {
          legacyErrorBoundariesThatAlreadyFailed.add(instance2);
        }
      }
      function prepareToThrowUncaughtError(error2) {
        if (!hasUncaughtError) {
          hasUncaughtError = true;
          firstUncaughtError = error2;
        }
      }
      var onUncaughtError = prepareToThrowUncaughtError;
      function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error2) {
        var errorInfo = createCapturedValueAtFiber(error2, sourceFiber);
        var update = createRootErrorUpdate(rootFiber, errorInfo, SyncLane);
        var root2 = enqueueUpdate(rootFiber, update, SyncLane);
        var eventTime = requestEventTime();
        if (root2 !== null) {
          markRootUpdated(root2, SyncLane, eventTime);
          ensureRootIsScheduled(root2, eventTime);
        }
      }
      function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error$1) {
        {
          reportUncaughtErrorInDEV(error$1);
          setIsRunningInsertionEffect(false);
        }
        if (sourceFiber.tag === HostRoot) {
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error$1);
          return;
        }
        var fiber = null;
        {
          fiber = nearestMountedAncestor;
        }
        while (fiber !== null) {
          if (fiber.tag === HostRoot) {
            captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error$1);
            return;
          } else if (fiber.tag === ClassComponent) {
            var ctor = fiber.type;
            var instance2 = fiber.stateNode;
            if (typeof ctor.getDerivedStateFromError === "function" || typeof instance2.componentDidCatch === "function" && !isAlreadyFailedLegacyErrorBoundary(instance2)) {
              var errorInfo = createCapturedValueAtFiber(error$1, sourceFiber);
              var update = createClassErrorUpdate(fiber, errorInfo, SyncLane);
              var root2 = enqueueUpdate(fiber, update, SyncLane);
              var eventTime = requestEventTime();
              if (root2 !== null) {
                markRootUpdated(root2, SyncLane, eventTime);
                ensureRootIsScheduled(root2, eventTime);
              }
              return;
            }
          }
          fiber = fiber.return;
        }
        {
          error("Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Likely causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s", error$1);
        }
      }
      function pingSuspendedRoot(root2, wakeable, pingedLanes) {
        var pingCache = root2.pingCache;
        if (pingCache !== null) {
          pingCache.delete(wakeable);
        }
        var eventTime = requestEventTime();
        markRootPinged(root2, pingedLanes);
        warnIfSuspenseResolutionNotWrappedWithActDEV(root2);
        if (workInProgressRoot === root2 && isSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)) {
          if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && includesOnlyRetries(workInProgressRootRenderLanes) && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
            prepareFreshStack(root2, NoLanes);
          } else {
            workInProgressRootPingedLanes = mergeLanes(workInProgressRootPingedLanes, pingedLanes);
          }
        }
        ensureRootIsScheduled(root2, eventTime);
      }
      function retryTimedOutBoundary(boundaryFiber, retryLane) {
        if (retryLane === NoLane) {
          retryLane = requestRetryLane(boundaryFiber);
        }
        var eventTime = requestEventTime();
        var root2 = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
        if (root2 !== null) {
          markRootUpdated(root2, retryLane, eventTime);
          ensureRootIsScheduled(root2, eventTime);
        }
      }
      function retryDehydratedSuspenseBoundary(boundaryFiber) {
        var suspenseState = boundaryFiber.memoizedState;
        var retryLane = NoLane;
        if (suspenseState !== null) {
          retryLane = suspenseState.retryLane;
        }
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      function resolveRetryWakeable(boundaryFiber, wakeable) {
        var retryLane = NoLane;
        var retryCache;
        switch (boundaryFiber.tag) {
          case SuspenseComponent:
            retryCache = boundaryFiber.stateNode;
            var suspenseState = boundaryFiber.memoizedState;
            if (suspenseState !== null) {
              retryLane = suspenseState.retryLane;
            }
            break;
          case SuspenseListComponent:
            retryCache = boundaryFiber.stateNode;
            break;
          default:
            throw new Error("Pinged unknown suspense boundary type. This is probably a bug in React.");
        }
        if (retryCache !== null) {
          retryCache.delete(wakeable);
        }
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      function jnd(timeElapsed) {
        return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3e3 ? 3e3 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
      }
      function checkForNestedUpdates() {
        if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
          nestedUpdateCount = 0;
          rootWithNestedUpdates = null;
          throw new Error("Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.");
        }
        {
          if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
            nestedPassiveUpdateCount = 0;
            rootWithPassiveNestedUpdates = null;
            error("Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.");
          }
        }
      }
      function flushRenderPhaseStrictModeWarningsInDEV() {
        {
          ReactStrictModeWarnings.flushLegacyContextWarning();
          {
            ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
          }
        }
      }
      function commitDoubleInvokeEffectsInDEV(fiber, hasPassiveEffects) {
        {
          setCurrentFiber(fiber);
          invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectUnmountInDEV);
          if (hasPassiveEffects) {
            invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectUnmountInDEV);
          }
          invokeEffectsInDev(fiber, MountLayoutDev, invokeLayoutEffectMountInDEV);
          if (hasPassiveEffects) {
            invokeEffectsInDev(fiber, MountPassiveDev, invokePassiveEffectMountInDEV);
          }
          resetCurrentFiber();
        }
      }
      function invokeEffectsInDev(firstChild, fiberFlags, invokeEffectFn) {
        {
          var current2 = firstChild;
          var subtreeRoot = null;
          while (current2 !== null) {
            var primarySubtreeFlag = current2.subtreeFlags & fiberFlags;
            if (current2 !== subtreeRoot && current2.child !== null && primarySubtreeFlag !== NoFlags) {
              current2 = current2.child;
            } else {
              if ((current2.flags & fiberFlags) !== NoFlags) {
                invokeEffectFn(current2);
              }
              if (current2.sibling !== null) {
                current2 = current2.sibling;
              } else {
                current2 = subtreeRoot = current2.return;
              }
            }
          }
        }
      }
      var didWarnStateUpdateForNotYetMountedComponent = null;
      function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
        {
          if ((executionContext & RenderContext) !== NoContext) {
            return;
          }
          if (!(fiber.mode & ConcurrentMode)) {
            return;
          }
          var tag = fiber.tag;
          if (tag !== IndeterminateComponent && tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent) {
            return;
          }
          var componentName = getComponentNameFromFiber(fiber) || "ReactComponent";
          if (didWarnStateUpdateForNotYetMountedComponent !== null) {
            if (didWarnStateUpdateForNotYetMountedComponent.has(componentName)) {
              return;
            }
            didWarnStateUpdateForNotYetMountedComponent.add(componentName);
          } else {
            didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([componentName]);
          }
          var previousFiber = current;
          try {
            setCurrentFiber(fiber);
            error("Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously later calls tries to update the component. Move this work to useEffect instead.");
          } finally {
            if (previousFiber) {
              setCurrentFiber(fiber);
            } else {
              resetCurrentFiber();
            }
          }
        }
      }
      var beginWork$1;
      {
        var dummyFiber = null;
        beginWork$1 = function(current2, unitOfWork, lanes) {
          var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
          try {
            return beginWork(current2, unitOfWork, lanes);
          } catch (originalError) {
            if (didSuspendOrErrorWhileHydratingDEV() || originalError !== null && typeof originalError === "object" && typeof originalError.then === "function") {
              throw originalError;
            }
            resetContextDependencies();
            resetHooksAfterThrow();
            unwindInterruptedWork(current2, unitOfWork);
            assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
            if (unitOfWork.mode & ProfileMode) {
              startProfilerTimer(unitOfWork);
            }
            invokeGuardedCallback(null, beginWork, null, current2, unitOfWork, lanes);
            if (hasCaughtError()) {
              var replayError = clearCaughtError();
              if (typeof replayError === "object" && replayError !== null && replayError._suppressLogging && typeof originalError === "object" && originalError !== null && !originalError._suppressLogging) {
                originalError._suppressLogging = true;
              }
            }
            throw originalError;
          }
        };
      }
      var didWarnAboutUpdateInRender = false;
      var didWarnAboutUpdateInRenderForAnotherComponent;
      {
        didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
      }
      function warnAboutRenderPhaseUpdatesInDEV(fiber) {
        {
          if (isRendering && !getIsUpdatingOpaqueValueInRenderPhaseInDEV()) {
            switch (fiber.tag) {
              case FunctionComponent:
              case ForwardRef:
              case SimpleMemoComponent: {
                var renderingComponentName = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
                var dedupeKey = renderingComponentName;
                if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
                  didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
                  var setStateComponentName = getComponentNameFromFiber(fiber) || "Unknown";
                  error("Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render", setStateComponentName, renderingComponentName, renderingComponentName);
                }
                break;
              }
              case ClassComponent: {
                if (!didWarnAboutUpdateInRender) {
                  error("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.");
                  didWarnAboutUpdateInRender = true;
                }
                break;
              }
            }
          }
        }
      }
      function restorePendingUpdaters(root2, lanes) {
        {
          if (isDevToolsPresent) {
            var memoizedUpdaters = root2.memoizedUpdaters;
            memoizedUpdaters.forEach(function(schedulingFiber) {
              addFiberToLanesMap(root2, schedulingFiber, lanes);
            });
          }
        }
      }
      var fakeActCallbackNode = {};
      function scheduleCallback$1(priorityLevel, callback) {
        {
          var actQueue = ReactCurrentActQueue$1.current;
          if (actQueue !== null) {
            actQueue.push(callback);
            return fakeActCallbackNode;
          } else {
            return scheduleCallback(priorityLevel, callback);
          }
        }
      }
      function cancelCallback$1(callbackNode) {
        if (callbackNode === fakeActCallbackNode) {
          return;
        }
        return cancelCallback(callbackNode);
      }
      function shouldForceFlushFallbacksInDEV() {
        return ReactCurrentActQueue$1.current !== null;
      }
      function warnIfUpdatesNotWrappedWithActDEV(fiber) {
        {
          if (fiber.mode & ConcurrentMode) {
            if (!isConcurrentActEnvironment()) {
              return;
            }
          } else {
            if (!isLegacyActEnvironment()) {
              return;
            }
            if (executionContext !== NoContext) {
              return;
            }
            if (fiber.tag !== FunctionComponent && fiber.tag !== ForwardRef && fiber.tag !== SimpleMemoComponent) {
              return;
            }
          }
          if (ReactCurrentActQueue$1.current === null) {
            var previousFiber = current;
            try {
              setCurrentFiber(fiber);
              error("An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act", getComponentNameFromFiber(fiber));
            } finally {
              if (previousFiber) {
                setCurrentFiber(fiber);
              } else {
                resetCurrentFiber();
              }
            }
          }
        }
      }
      function warnIfSuspenseResolutionNotWrappedWithActDEV(root2) {
        {
          if (root2.tag !== LegacyRoot && isConcurrentActEnvironment() && ReactCurrentActQueue$1.current === null) {
            error("A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act");
          }
        }
      }
      function setIsRunningInsertionEffect(isRunning) {
        {
          isRunningInsertionEffect = isRunning;
        }
      }
      var resolveFamily = null;
      var failedBoundaries = null;
      var setRefreshHandler = function(handler) {
        {
          resolveFamily = handler;
        }
      };
      function resolveFunctionForHotReloading(type2) {
        {
          if (resolveFamily === null) {
            return type2;
          }
          var family = resolveFamily(type2);
          if (family === void 0) {
            return type2;
          }
          return family.current;
        }
      }
      function resolveClassForHotReloading(type2) {
        return resolveFunctionForHotReloading(type2);
      }
      function resolveForwardRefForHotReloading(type2) {
        {
          if (resolveFamily === null) {
            return type2;
          }
          var family = resolveFamily(type2);
          if (family === void 0) {
            if (type2 !== null && type2 !== void 0 && typeof type2.render === "function") {
              var currentRender = resolveFunctionForHotReloading(type2.render);
              if (type2.render !== currentRender) {
                var syntheticType = {
                  $$typeof: REACT_FORWARD_REF_TYPE,
                  render: currentRender
                };
                if (type2.displayName !== void 0) {
                  syntheticType.displayName = type2.displayName;
                }
                return syntheticType;
              }
            }
            return type2;
          }
          return family.current;
        }
      }
      function isCompatibleFamilyForHotReloading(fiber, element) {
        {
          if (resolveFamily === null) {
            return false;
          }
          var prevType = fiber.elementType;
          var nextType = element.type;
          var needsCompareFamilies = false;
          var $$typeofNextType = typeof nextType === "object" && nextType !== null ? nextType.$$typeof : null;
          switch (fiber.tag) {
            case ClassComponent: {
              if (typeof nextType === "function") {
                needsCompareFamilies = true;
              }
              break;
            }
            case FunctionComponent: {
              if (typeof nextType === "function") {
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                needsCompareFamilies = true;
              }
              break;
            }
            case ForwardRef: {
              if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                needsCompareFamilies = true;
              }
              break;
            }
            case MemoComponent:
            case SimpleMemoComponent: {
              if ($$typeofNextType === REACT_MEMO_TYPE) {
                needsCompareFamilies = true;
              } else if ($$typeofNextType === REACT_LAZY_TYPE) {
                needsCompareFamilies = true;
              }
              break;
            }
            default:
              return false;
          }
          if (needsCompareFamilies) {
            var prevFamily = resolveFamily(prevType);
            if (prevFamily !== void 0 && prevFamily === resolveFamily(nextType)) {
              return true;
            }
          }
          return false;
        }
      }
      function markFailedErrorBoundaryForHotReloading(fiber) {
        {
          if (resolveFamily === null) {
            return;
          }
          if (typeof WeakSet !== "function") {
            return;
          }
          if (failedBoundaries === null) {
            failedBoundaries = /* @__PURE__ */ new WeakSet();
          }
          failedBoundaries.add(fiber);
        }
      }
      var scheduleRefresh = function(root2, update) {
        {
          if (resolveFamily === null) {
            return;
          }
          var staleFamilies = update.staleFamilies, updatedFamilies = update.updatedFamilies;
          flushPassiveEffects();
          flushSync(function() {
            scheduleFibersWithFamiliesRecursively(root2.current, updatedFamilies, staleFamilies);
          });
        }
      };
      var scheduleRoot = function(root2, element) {
        {
          if (root2.context !== emptyContextObject) {
            return;
          }
          flushPassiveEffects();
          flushSync(function() {
            updateContainer(element, root2, null, null);
          });
        }
      };
      function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
        {
          var alternate = fiber.alternate, child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type2 = fiber.type;
          var candidateType = null;
          switch (tag) {
            case FunctionComponent:
            case SimpleMemoComponent:
            case ClassComponent:
              candidateType = type2;
              break;
            case ForwardRef:
              candidateType = type2.render;
              break;
          }
          if (resolveFamily === null) {
            throw new Error("Expected resolveFamily to be set during hot reload.");
          }
          var needsRender = false;
          var needsRemount = false;
          if (candidateType !== null) {
            var family = resolveFamily(candidateType);
            if (family !== void 0) {
              if (staleFamilies.has(family)) {
                needsRemount = true;
              } else if (updatedFamilies.has(family)) {
                if (tag === ClassComponent) {
                  needsRemount = true;
                } else {
                  needsRender = true;
                }
              }
            }
          }
          if (failedBoundaries !== null) {
            if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
              needsRemount = true;
            }
          }
          if (needsRemount) {
            fiber._debugNeedsRemount = true;
          }
          if (needsRemount || needsRender) {
            var _root = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (_root !== null) {
              scheduleUpdateOnFiber(_root, fiber, SyncLane, NoTimestamp);
            }
          }
          if (child !== null && !needsRemount) {
            scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
          }
          if (sibling !== null) {
            scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
          }
        }
      }
      var findHostInstancesForRefresh = function(root2, families) {
        {
          var hostInstances = /* @__PURE__ */ new Set();
          var types = new Set(families.map(function(family) {
            return family.current;
          }));
          findHostInstancesForMatchingFibersRecursively(root2.current, types, hostInstances);
          return hostInstances;
        }
      };
      function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
        {
          var child = fiber.child, sibling = fiber.sibling, tag = fiber.tag, type2 = fiber.type;
          var candidateType = null;
          switch (tag) {
            case FunctionComponent:
            case SimpleMemoComponent:
            case ClassComponent:
              candidateType = type2;
              break;
            case ForwardRef:
              candidateType = type2.render;
              break;
          }
          var didMatch = false;
          if (candidateType !== null) {
            if (types.has(candidateType)) {
              didMatch = true;
            }
          }
          if (didMatch) {
            findHostInstancesForFiberShallowly(fiber, hostInstances);
          } else {
            if (child !== null) {
              findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
            }
          }
          if (sibling !== null) {
            findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
          }
        }
      }
      function findHostInstancesForFiberShallowly(fiber, hostInstances) {
        {
          var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
          if (foundHostInstances) {
            return;
          }
          var node2 = fiber;
          while (true) {
            switch (node2.tag) {
              case HostComponent:
                hostInstances.add(node2.stateNode);
                return;
              case HostPortal:
                hostInstances.add(node2.stateNode.containerInfo);
                return;
              case HostRoot:
                hostInstances.add(node2.stateNode.containerInfo);
                return;
            }
            if (node2.return === null) {
              throw new Error("Expected to reach root first.");
            }
            node2 = node2.return;
          }
        }
      }
      function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
        {
          var node2 = fiber;
          var foundHostInstances = false;
          while (true) {
            if (node2.tag === HostComponent) {
              foundHostInstances = true;
              hostInstances.add(node2.stateNode);
            } else if (node2.child !== null) {
              node2.child.return = node2;
              node2 = node2.child;
              continue;
            }
            if (node2 === fiber) {
              return foundHostInstances;
            }
            while (node2.sibling === null) {
              if (node2.return === null || node2.return === fiber) {
                return foundHostInstances;
              }
              node2 = node2.return;
            }
            node2.sibling.return = node2.return;
            node2 = node2.sibling;
          }
        }
        return false;
      }
      var hasBadMapPolyfill;
      {
        hasBadMapPolyfill = false;
        try {
          var nonExtensibleObject = Object.preventExtensions({});
          /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
          /* @__PURE__ */ new Set([nonExtensibleObject]);
        } catch (e4) {
          hasBadMapPolyfill = true;
        }
      }
      function FiberNode(tag, pendingProps, key2, mode) {
        this.tag = tag;
        this.key = key2;
        this.elementType = null;
        this.type = null;
        this.stateNode = null;
        this.return = null;
        this.child = null;
        this.sibling = null;
        this.index = 0;
        this.ref = null;
        this.pendingProps = pendingProps;
        this.memoizedProps = null;
        this.updateQueue = null;
        this.memoizedState = null;
        this.dependencies = null;
        this.mode = mode;
        this.flags = NoFlags;
        this.subtreeFlags = NoFlags;
        this.deletions = null;
        this.lanes = NoLanes;
        this.childLanes = NoLanes;
        this.alternate = null;
        {
          this.actualDuration = Number.NaN;
          this.actualStartTime = Number.NaN;
          this.selfBaseDuration = Number.NaN;
          this.treeBaseDuration = Number.NaN;
          this.actualDuration = 0;
          this.actualStartTime = -1;
          this.selfBaseDuration = 0;
          this.treeBaseDuration = 0;
        }
        {
          this._debugSource = null;
          this._debugOwner = null;
          this._debugNeedsRemount = false;
          this._debugHookTypes = null;
          if (!hasBadMapPolyfill && typeof Object.preventExtensions === "function") {
            Object.preventExtensions(this);
          }
        }
      }
      var createFiber = function(tag, pendingProps, key2, mode) {
        return new FiberNode(tag, pendingProps, key2, mode);
      };
      function shouldConstruct$1(Component) {
        var prototype = Component.prototype;
        return !!(prototype && prototype.isReactComponent);
      }
      function isSimpleFunctionComponent(type2) {
        return typeof type2 === "function" && !shouldConstruct$1(type2) && type2.defaultProps === void 0;
      }
      function resolveLazyComponentTag(Component) {
        if (typeof Component === "function") {
          return shouldConstruct$1(Component) ? ClassComponent : FunctionComponent;
        } else if (Component !== void 0 && Component !== null) {
          var $$typeof = Component.$$typeof;
          if ($$typeof === REACT_FORWARD_REF_TYPE) {
            return ForwardRef;
          }
          if ($$typeof === REACT_MEMO_TYPE) {
            return MemoComponent;
          }
        }
        return IndeterminateComponent;
      }
      function createWorkInProgress(current2, pendingProps) {
        var workInProgress2 = current2.alternate;
        if (workInProgress2 === null) {
          workInProgress2 = createFiber(current2.tag, pendingProps, current2.key, current2.mode);
          workInProgress2.elementType = current2.elementType;
          workInProgress2.type = current2.type;
          workInProgress2.stateNode = current2.stateNode;
          {
            workInProgress2._debugSource = current2._debugSource;
            workInProgress2._debugOwner = current2._debugOwner;
            workInProgress2._debugHookTypes = current2._debugHookTypes;
          }
          workInProgress2.alternate = current2;
          current2.alternate = workInProgress2;
        } else {
          workInProgress2.pendingProps = pendingProps;
          workInProgress2.type = current2.type;
          workInProgress2.flags = NoFlags;
          workInProgress2.subtreeFlags = NoFlags;
          workInProgress2.deletions = null;
          {
            workInProgress2.actualDuration = 0;
            workInProgress2.actualStartTime = -1;
          }
        }
        workInProgress2.flags = current2.flags & StaticMask;
        workInProgress2.childLanes = current2.childLanes;
        workInProgress2.lanes = current2.lanes;
        workInProgress2.child = current2.child;
        workInProgress2.memoizedProps = current2.memoizedProps;
        workInProgress2.memoizedState = current2.memoizedState;
        workInProgress2.updateQueue = current2.updateQueue;
        var currentDependencies = current2.dependencies;
        workInProgress2.dependencies = currentDependencies === null ? null : {
          lanes: currentDependencies.lanes,
          firstContext: currentDependencies.firstContext
        };
        workInProgress2.sibling = current2.sibling;
        workInProgress2.index = current2.index;
        workInProgress2.ref = current2.ref;
        {
          workInProgress2.selfBaseDuration = current2.selfBaseDuration;
          workInProgress2.treeBaseDuration = current2.treeBaseDuration;
        }
        {
          workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
          switch (workInProgress2.tag) {
            case IndeterminateComponent:
            case FunctionComponent:
            case SimpleMemoComponent:
              workInProgress2.type = resolveFunctionForHotReloading(current2.type);
              break;
            case ClassComponent:
              workInProgress2.type = resolveClassForHotReloading(current2.type);
              break;
            case ForwardRef:
              workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
              break;
          }
        }
        return workInProgress2;
      }
      function resetWorkInProgress(workInProgress2, renderLanes2) {
        workInProgress2.flags &= StaticMask | Placement;
        var current2 = workInProgress2.alternate;
        if (current2 === null) {
          workInProgress2.childLanes = NoLanes;
          workInProgress2.lanes = renderLanes2;
          workInProgress2.child = null;
          workInProgress2.subtreeFlags = NoFlags;
          workInProgress2.memoizedProps = null;
          workInProgress2.memoizedState = null;
          workInProgress2.updateQueue = null;
          workInProgress2.dependencies = null;
          workInProgress2.stateNode = null;
          {
            workInProgress2.selfBaseDuration = 0;
            workInProgress2.treeBaseDuration = 0;
          }
        } else {
          workInProgress2.childLanes = current2.childLanes;
          workInProgress2.lanes = current2.lanes;
          workInProgress2.child = current2.child;
          workInProgress2.subtreeFlags = NoFlags;
          workInProgress2.deletions = null;
          workInProgress2.memoizedProps = current2.memoizedProps;
          workInProgress2.memoizedState = current2.memoizedState;
          workInProgress2.updateQueue = current2.updateQueue;
          workInProgress2.type = current2.type;
          var currentDependencies = current2.dependencies;
          workInProgress2.dependencies = currentDependencies === null ? null : {
            lanes: currentDependencies.lanes,
            firstContext: currentDependencies.firstContext
          };
          {
            workInProgress2.selfBaseDuration = current2.selfBaseDuration;
            workInProgress2.treeBaseDuration = current2.treeBaseDuration;
          }
        }
        return workInProgress2;
      }
      function createHostRootFiber(tag, isStrictMode, concurrentUpdatesByDefaultOverride) {
        var mode;
        if (tag === ConcurrentRoot) {
          mode = ConcurrentMode;
          if (isStrictMode === true) {
            mode |= StrictLegacyMode;
            {
              mode |= StrictEffectsMode;
            }
          }
        } else {
          mode = NoMode;
        }
        if (isDevToolsPresent) {
          mode |= ProfileMode;
        }
        return createFiber(HostRoot, null, null, mode);
      }
      function createFiberFromTypeAndProps(type2, key2, pendingProps, owner, mode, lanes) {
        var fiberTag = IndeterminateComponent;
        var resolvedType = type2;
        if (typeof type2 === "function") {
          if (shouldConstruct$1(type2)) {
            fiberTag = ClassComponent;
            {
              resolvedType = resolveClassForHotReloading(resolvedType);
            }
          } else {
            {
              resolvedType = resolveFunctionForHotReloading(resolvedType);
            }
          }
        } else if (typeof type2 === "string") {
          fiberTag = HostComponent;
        } else {
          getTag: switch (type2) {
            case REACT_FRAGMENT_TYPE:
              return createFiberFromFragment(pendingProps.children, mode, lanes, key2);
            case REACT_STRICT_MODE_TYPE:
              fiberTag = Mode2;
              mode |= StrictLegacyMode;
              if ((mode & ConcurrentMode) !== NoMode) {
                mode |= StrictEffectsMode;
              }
              break;
            case REACT_PROFILER_TYPE:
              return createFiberFromProfiler(pendingProps, mode, lanes, key2);
            case REACT_SUSPENSE_TYPE:
              return createFiberFromSuspense(pendingProps, mode, lanes, key2);
            case REACT_SUSPENSE_LIST_TYPE:
              return createFiberFromSuspenseList(pendingProps, mode, lanes, key2);
            case REACT_OFFSCREEN_TYPE:
              return createFiberFromOffscreen(pendingProps, mode, lanes, key2);
            case REACT_LEGACY_HIDDEN_TYPE:
            // eslint-disable-next-line no-fallthrough
            case REACT_SCOPE_TYPE:
            // eslint-disable-next-line no-fallthrough
            case REACT_CACHE_TYPE:
            // eslint-disable-next-line no-fallthrough
            case REACT_TRACING_MARKER_TYPE:
            // eslint-disable-next-line no-fallthrough
            case REACT_DEBUG_TRACING_MODE_TYPE:
            // eslint-disable-next-line no-fallthrough
            default: {
              if (typeof type2 === "object" && type2 !== null) {
                switch (type2.$$typeof) {
                  case REACT_PROVIDER_TYPE:
                    fiberTag = ContextProvider;
                    break getTag;
                  case REACT_CONTEXT_TYPE:
                    fiberTag = ContextConsumer;
                    break getTag;
                  case REACT_FORWARD_REF_TYPE:
                    fiberTag = ForwardRef;
                    {
                      resolvedType = resolveForwardRefForHotReloading(resolvedType);
                    }
                    break getTag;
                  case REACT_MEMO_TYPE:
                    fiberTag = MemoComponent;
                    break getTag;
                  case REACT_LAZY_TYPE:
                    fiberTag = LazyComponent;
                    resolvedType = null;
                    break getTag;
                }
              }
              var info = "";
              {
                if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) {
                  info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
                }
                var ownerName = owner ? getComponentNameFromFiber(owner) : null;
                if (ownerName) {
                  info += "\n\nCheck the render method of `" + ownerName + "`.";
                }
              }
              throw new Error("Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) " + ("but got: " + (type2 == null ? type2 : typeof type2) + "." + info));
            }
          }
        }
        var fiber = createFiber(fiberTag, pendingProps, key2, mode);
        fiber.elementType = type2;
        fiber.type = resolvedType;
        fiber.lanes = lanes;
        {
          fiber._debugOwner = owner;
        }
        return fiber;
      }
      function createFiberFromElement(element, mode, lanes) {
        var owner = null;
        {
          owner = element._owner;
        }
        var type2 = element.type;
        var key2 = element.key;
        var pendingProps = element.props;
        var fiber = createFiberFromTypeAndProps(type2, key2, pendingProps, owner, mode, lanes);
        {
          fiber._debugSource = element._source;
          fiber._debugOwner = element._owner;
        }
        return fiber;
      }
      function createFiberFromFragment(elements, mode, lanes, key2) {
        var fiber = createFiber(Fragment, elements, key2, mode);
        fiber.lanes = lanes;
        return fiber;
      }
      function createFiberFromProfiler(pendingProps, mode, lanes, key2) {
        {
          if (typeof pendingProps.id !== "string") {
            error('Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.', typeof pendingProps.id);
          }
        }
        var fiber = createFiber(Profiler, pendingProps, key2, mode | ProfileMode);
        fiber.elementType = REACT_PROFILER_TYPE;
        fiber.lanes = lanes;
        {
          fiber.stateNode = {
            effectDuration: 0,
            passiveEffectDuration: 0
          };
        }
        return fiber;
      }
      function createFiberFromSuspense(pendingProps, mode, lanes, key2) {
        var fiber = createFiber(SuspenseComponent, pendingProps, key2, mode);
        fiber.elementType = REACT_SUSPENSE_TYPE;
        fiber.lanes = lanes;
        return fiber;
      }
      function createFiberFromSuspenseList(pendingProps, mode, lanes, key2) {
        var fiber = createFiber(SuspenseListComponent, pendingProps, key2, mode);
        fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
        fiber.lanes = lanes;
        return fiber;
      }
      function createFiberFromOffscreen(pendingProps, mode, lanes, key2) {
        var fiber = createFiber(OffscreenComponent, pendingProps, key2, mode);
        fiber.elementType = REACT_OFFSCREEN_TYPE;
        fiber.lanes = lanes;
        var primaryChildInstance = {
          isHidden: false
        };
        fiber.stateNode = primaryChildInstance;
        return fiber;
      }
      function createFiberFromText(content, mode, lanes) {
        var fiber = createFiber(HostText, content, null, mode);
        fiber.lanes = lanes;
        return fiber;
      }
      function createFiberFromHostInstanceForDeletion() {
        var fiber = createFiber(HostComponent, null, null, NoMode);
        fiber.elementType = "DELETED";
        return fiber;
      }
      function createFiberFromDehydratedFragment(dehydratedNode) {
        var fiber = createFiber(DehydratedFragment, null, null, NoMode);
        fiber.stateNode = dehydratedNode;
        return fiber;
      }
      function createFiberFromPortal(portal, mode, lanes) {
        var pendingProps = portal.children !== null ? portal.children : [];
        var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
        fiber.lanes = lanes;
        fiber.stateNode = {
          containerInfo: portal.containerInfo,
          pendingChildren: null,
          // Used by persistent updates
          implementation: portal.implementation
        };
        return fiber;
      }
      function assignFiberPropertiesInDEV(target, source) {
        if (target === null) {
          target = createFiber(IndeterminateComponent, null, null, NoMode);
        }
        target.tag = source.tag;
        target.key = source.key;
        target.elementType = source.elementType;
        target.type = source.type;
        target.stateNode = source.stateNode;
        target.return = source.return;
        target.child = source.child;
        target.sibling = source.sibling;
        target.index = source.index;
        target.ref = source.ref;
        target.pendingProps = source.pendingProps;
        target.memoizedProps = source.memoizedProps;
        target.updateQueue = source.updateQueue;
        target.memoizedState = source.memoizedState;
        target.dependencies = source.dependencies;
        target.mode = source.mode;
        target.flags = source.flags;
        target.subtreeFlags = source.subtreeFlags;
        target.deletions = source.deletions;
        target.lanes = source.lanes;
        target.childLanes = source.childLanes;
        target.alternate = source.alternate;
        {
          target.actualDuration = source.actualDuration;
          target.actualStartTime = source.actualStartTime;
          target.selfBaseDuration = source.selfBaseDuration;
          target.treeBaseDuration = source.treeBaseDuration;
        }
        target._debugSource = source._debugSource;
        target._debugOwner = source._debugOwner;
        target._debugNeedsRemount = source._debugNeedsRemount;
        target._debugHookTypes = source._debugHookTypes;
        return target;
      }
      function FiberRootNode(containerInfo, tag, hydrate2, identifierPrefix, onRecoverableError) {
        this.tag = tag;
        this.containerInfo = containerInfo;
        this.pendingChildren = null;
        this.current = null;
        this.pingCache = null;
        this.finishedWork = null;
        this.timeoutHandle = noTimeout;
        this.context = null;
        this.pendingContext = null;
        this.callbackNode = null;
        this.callbackPriority = NoLane;
        this.eventTimes = createLaneMap(NoLanes);
        this.expirationTimes = createLaneMap(NoTimestamp);
        this.pendingLanes = NoLanes;
        this.suspendedLanes = NoLanes;
        this.pingedLanes = NoLanes;
        this.expiredLanes = NoLanes;
        this.mutableReadLanes = NoLanes;
        this.finishedLanes = NoLanes;
        this.entangledLanes = NoLanes;
        this.entanglements = createLaneMap(NoLanes);
        this.identifierPrefix = identifierPrefix;
        this.onRecoverableError = onRecoverableError;
        {
          this.mutableSourceEagerHydrationData = null;
        }
        {
          this.effectDuration = 0;
          this.passiveEffectDuration = 0;
        }
        {
          this.memoizedUpdaters = /* @__PURE__ */ new Set();
          var pendingUpdatersLaneMap = this.pendingUpdatersLaneMap = [];
          for (var _i2 = 0; _i2 < TotalLanes; _i2++) {
            pendingUpdatersLaneMap.push(/* @__PURE__ */ new Set());
          }
        }
        {
          switch (tag) {
            case ConcurrentRoot:
              this._debugRootType = hydrate2 ? "hydrateRoot()" : "createRoot()";
              break;
            case LegacyRoot:
              this._debugRootType = hydrate2 ? "hydrate()" : "render()";
              break;
          }
        }
      }
      function createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
        var root2 = new FiberRootNode(containerInfo, tag, hydrate2, identifierPrefix, onRecoverableError);
        var uninitializedFiber = createHostRootFiber(tag, isStrictMode);
        root2.current = uninitializedFiber;
        uninitializedFiber.stateNode = root2;
        {
          var _initialState2 = {
            element: initialChildren,
            isDehydrated: hydrate2,
            cache: null,
            // not enabled yet
            transitions: null,
            pendingSuspenseBoundaries: null
          };
          uninitializedFiber.memoizedState = _initialState2;
        }
        initializeUpdateQueue(uninitializedFiber);
        return root2;
      }
      var ReactVersion = "18.3.1";
      function createPortal(children, containerInfo, implementation2) {
        var key2 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null;
        {
          checkKeyStringCoercion(key2);
        }
        return {
          // This tag allow us to uniquely identify this as a React Portal
          $$typeof: REACT_PORTAL_TYPE,
          key: key2 == null ? null : "" + key2,
          children,
          containerInfo,
          implementation: implementation2
        };
      }
      var didWarnAboutNestedUpdates;
      var didWarnAboutFindNodeInStrictMode;
      {
        didWarnAboutNestedUpdates = false;
        didWarnAboutFindNodeInStrictMode = {};
      }
      function getContextForSubtree(parentComponent) {
        if (!parentComponent) {
          return emptyContextObject;
        }
        var fiber = get2(parentComponent);
        var parentContext = findCurrentUnmaskedContext(fiber);
        if (fiber.tag === ClassComponent) {
          var Component = fiber.type;
          if (isContextProvider(Component)) {
            return processChildContext(fiber, Component, parentContext);
          }
        }
        return parentContext;
      }
      function findHostInstanceWithWarning(component, methodName) {
        {
          var fiber = get2(component);
          if (fiber === void 0) {
            if (typeof component.render === "function") {
              throw new Error("Unable to find node on an unmounted component.");
            } else {
              var keys = Object.keys(component).join(",");
              throw new Error("Argument appears to not be a ReactComponent. Keys: " + keys);
            }
          }
          var hostFiber = findCurrentHostFiber(fiber);
          if (hostFiber === null) {
            return null;
          }
          if (hostFiber.mode & StrictLegacyMode) {
            var componentName = getComponentNameFromFiber(fiber) || "Component";
            if (!didWarnAboutFindNodeInStrictMode[componentName]) {
              didWarnAboutFindNodeInStrictMode[componentName] = true;
              var previousFiber = current;
              try {
                setCurrentFiber(hostFiber);
                if (fiber.mode & StrictLegacyMode) {
                  error("%s is deprecated in StrictMode. %s was passed an instance of %s which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
                } else {
                  error("%s is deprecated in StrictMode. %s was passed an instance of %s which renders StrictMode children. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node", methodName, methodName, componentName);
                }
              } finally {
                if (previousFiber) {
                  setCurrentFiber(previousFiber);
                } else {
                  resetCurrentFiber();
                }
              }
            }
          }
          return hostFiber.stateNode;
        }
      }
      function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
        var hydrate2 = false;
        var initialChildren = null;
        return createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
      }
      function createHydrationContainer(initialChildren, callback, containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) {
        var hydrate2 = true;
        var root2 = createFiberRoot(containerInfo, tag, hydrate2, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
        root2.context = getContextForSubtree(null);
        var current2 = root2.current;
        var eventTime = requestEventTime();
        var lane = requestUpdateLane(current2);
        var update = createUpdate(eventTime, lane);
        update.callback = callback !== void 0 && callback !== null ? callback : null;
        enqueueUpdate(current2, update, lane);
        scheduleInitialHydrationOnRoot(root2, lane, eventTime);
        return root2;
      }
      function updateContainer(element, container, parentComponent, callback) {
        {
          onScheduleRoot(container, element);
        }
        var current$1 = container.current;
        var eventTime = requestEventTime();
        var lane = requestUpdateLane(current$1);
        {
          markRenderScheduled(lane);
        }
        var context = getContextForSubtree(parentComponent);
        if (container.context === null) {
          container.context = context;
        } else {
          container.pendingContext = context;
        }
        {
          if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
            didWarnAboutNestedUpdates = true;
            error("Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.", getComponentNameFromFiber(current) || "Unknown");
          }
        }
        var update = createUpdate(eventTime, lane);
        update.payload = {
          element
        };
        callback = callback === void 0 ? null : callback;
        if (callback !== null) {
          {
            if (typeof callback !== "function") {
              error("render(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callback);
            }
          }
          update.callback = callback;
        }
        var root2 = enqueueUpdate(current$1, update, lane);
        if (root2 !== null) {
          scheduleUpdateOnFiber(root2, current$1, lane, eventTime);
          entangleTransitions(root2, current$1, lane);
        }
        return lane;
      }
      function getPublicRootInstance(container) {
        var containerFiber = container.current;
        if (!containerFiber.child) {
          return null;
        }
        switch (containerFiber.child.tag) {
          case HostComponent:
            return getPublicInstance(containerFiber.child.stateNode);
          default:
            return containerFiber.child.stateNode;
        }
      }
      function attemptSynchronousHydration$1(fiber) {
        switch (fiber.tag) {
          case HostRoot: {
            var root2 = fiber.stateNode;
            if (isRootDehydrated(root2)) {
              var lanes = getHighestPriorityPendingLanes(root2);
              flushRoot(root2, lanes);
            }
            break;
          }
          case SuspenseComponent: {
            flushSync(function() {
              var root3 = enqueueConcurrentRenderForLane(fiber, SyncLane);
              if (root3 !== null) {
                var eventTime = requestEventTime();
                scheduleUpdateOnFiber(root3, fiber, SyncLane, eventTime);
              }
            });
            var retryLane = SyncLane;
            markRetryLaneIfNotHydrated(fiber, retryLane);
            break;
          }
        }
      }
      function markRetryLaneImpl(fiber, retryLane) {
        var suspenseState = fiber.memoizedState;
        if (suspenseState !== null && suspenseState.dehydrated !== null) {
          suspenseState.retryLane = higherPriorityLane(suspenseState.retryLane, retryLane);
        }
      }
      function markRetryLaneIfNotHydrated(fiber, retryLane) {
        markRetryLaneImpl(fiber, retryLane);
        var alternate = fiber.alternate;
        if (alternate) {
          markRetryLaneImpl(alternate, retryLane);
        }
      }
      function attemptContinuousHydration$1(fiber) {
        if (fiber.tag !== SuspenseComponent) {
          return;
        }
        var lane = SelectiveHydrationLane;
        var root2 = enqueueConcurrentRenderForLane(fiber, lane);
        if (root2 !== null) {
          var eventTime = requestEventTime();
          scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
        }
        markRetryLaneIfNotHydrated(fiber, lane);
      }
      function attemptHydrationAtCurrentPriority$1(fiber) {
        if (fiber.tag !== SuspenseComponent) {
          return;
        }
        var lane = requestUpdateLane(fiber);
        var root2 = enqueueConcurrentRenderForLane(fiber, lane);
        if (root2 !== null) {
          var eventTime = requestEventTime();
          scheduleUpdateOnFiber(root2, fiber, lane, eventTime);
        }
        markRetryLaneIfNotHydrated(fiber, lane);
      }
      function findHostInstanceWithNoPortals(fiber) {
        var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
        if (hostFiber === null) {
          return null;
        }
        return hostFiber.stateNode;
      }
      var shouldErrorImpl = function(fiber) {
        return null;
      };
      function shouldError(fiber) {
        return shouldErrorImpl(fiber);
      }
      var shouldSuspendImpl = function(fiber) {
        return false;
      };
      function shouldSuspend2(fiber) {
        return shouldSuspendImpl(fiber);
      }
      var overrideHookState = null;
      var overrideHookStateDeletePath = null;
      var overrideHookStateRenamePath = null;
      var overrideProps = null;
      var overridePropsDeletePath = null;
      var overridePropsRenamePath = null;
      var scheduleUpdate2 = null;
      var setErrorHandler = null;
      var setSuspenseHandler = null;
      {
        var copyWithDeleteImpl = function(obj, path, index22) {
          var key2 = path[index22];
          var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
          if (index22 + 1 === path.length) {
            if (isArray2(updated)) {
              updated.splice(key2, 1);
            } else {
              delete updated[key2];
            }
            return updated;
          }
          updated[key2] = copyWithDeleteImpl(obj[key2], path, index22 + 1);
          return updated;
        };
        var copyWithDelete = function(obj, path) {
          return copyWithDeleteImpl(obj, path, 0);
        };
        var copyWithRenameImpl = function(obj, oldPath, newPath, index22) {
          var oldKey = oldPath[index22];
          var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
          if (index22 + 1 === oldPath.length) {
            var newKey = newPath[index22];
            updated[newKey] = updated[oldKey];
            if (isArray2(updated)) {
              updated.splice(oldKey, 1);
            } else {
              delete updated[oldKey];
            }
          } else {
            updated[oldKey] = copyWithRenameImpl(
              // $FlowFixMe number or string is fine here
              obj[oldKey],
              oldPath,
              newPath,
              index22 + 1
            );
          }
          return updated;
        };
        var copyWithRename = function(obj, oldPath, newPath) {
          if (oldPath.length !== newPath.length) {
            warn("copyWithRename() expects paths of the same length");
            return;
          } else {
            for (var i2 = 0; i2 < newPath.length - 1; i2++) {
              if (oldPath[i2] !== newPath[i2]) {
                warn("copyWithRename() expects paths to be the same except for the deepest key");
                return;
              }
            }
          }
          return copyWithRenameImpl(obj, oldPath, newPath, 0);
        };
        var copyWithSetImpl = function(obj, path, index22, value) {
          if (index22 >= path.length) {
            return value;
          }
          var key2 = path[index22];
          var updated = isArray2(obj) ? obj.slice() : assign({}, obj);
          updated[key2] = copyWithSetImpl(obj[key2], path, index22 + 1, value);
          return updated;
        };
        var copyWithSet = function(obj, path, value) {
          return copyWithSetImpl(obj, path, 0, value);
        };
        var findHook = function(fiber, id) {
          var currentHook2 = fiber.memoizedState;
          while (currentHook2 !== null && id > 0) {
            currentHook2 = currentHook2.next;
            id--;
          }
          return currentHook2;
        };
        overrideHookState = function(fiber, id, path, value) {
          var hook = findHook(fiber, id);
          if (hook !== null) {
            var newState = copyWithSet(hook.memoizedState, path, value);
            hook.memoizedState = newState;
            hook.baseState = newState;
            fiber.memoizedProps = assign({}, fiber.memoizedProps);
            var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root2 !== null) {
              scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
            }
          }
        };
        overrideHookStateDeletePath = function(fiber, id, path) {
          var hook = findHook(fiber, id);
          if (hook !== null) {
            var newState = copyWithDelete(hook.memoizedState, path);
            hook.memoizedState = newState;
            hook.baseState = newState;
            fiber.memoizedProps = assign({}, fiber.memoizedProps);
            var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root2 !== null) {
              scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
            }
          }
        };
        overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
          var hook = findHook(fiber, id);
          if (hook !== null) {
            var newState = copyWithRename(hook.memoizedState, oldPath, newPath);
            hook.memoizedState = newState;
            hook.baseState = newState;
            fiber.memoizedProps = assign({}, fiber.memoizedProps);
            var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
            if (root2 !== null) {
              scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
            }
          }
        };
        overrideProps = function(fiber, path, value) {
          fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
          if (fiber.alternate) {
            fiber.alternate.pendingProps = fiber.pendingProps;
          }
          var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
          }
        };
        overridePropsDeletePath = function(fiber, path) {
          fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path);
          if (fiber.alternate) {
            fiber.alternate.pendingProps = fiber.pendingProps;
          }
          var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
          }
        };
        overridePropsRenamePath = function(fiber, oldPath, newPath) {
          fiber.pendingProps = copyWithRename(fiber.memoizedProps, oldPath, newPath);
          if (fiber.alternate) {
            fiber.alternate.pendingProps = fiber.pendingProps;
          }
          var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
          }
        };
        scheduleUpdate2 = function(fiber) {
          var root2 = enqueueConcurrentRenderForLane(fiber, SyncLane);
          if (root2 !== null) {
            scheduleUpdateOnFiber(root2, fiber, SyncLane, NoTimestamp);
          }
        };
        setErrorHandler = function(newShouldErrorImpl) {
          shouldErrorImpl = newShouldErrorImpl;
        };
        setSuspenseHandler = function(newShouldSuspendImpl) {
          shouldSuspendImpl = newShouldSuspendImpl;
        };
      }
      function findHostInstanceByFiber(fiber) {
        var hostFiber = findCurrentHostFiber(fiber);
        if (hostFiber === null) {
          return null;
        }
        return hostFiber.stateNode;
      }
      function emptyFindFiberByHostInstance(instance2) {
        return null;
      }
      function getCurrentFiberForDevTools() {
        return current;
      }
      function injectIntoDevTools(devToolsConfig) {
        var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
        var ReactCurrentDispatcher2 = ReactSharedInternals.ReactCurrentDispatcher;
        return injectInternals({
          bundleType: devToolsConfig.bundleType,
          version: devToolsConfig.version,
          rendererPackageName: devToolsConfig.rendererPackageName,
          rendererConfig: devToolsConfig.rendererConfig,
          overrideHookState,
          overrideHookStateDeletePath,
          overrideHookStateRenamePath,
          overrideProps,
          overridePropsDeletePath,
          overridePropsRenamePath,
          setErrorHandler,
          setSuspenseHandler,
          scheduleUpdate: scheduleUpdate2,
          currentDispatcherRef: ReactCurrentDispatcher2,
          findHostInstanceByFiber,
          findFiberByHostInstance: findFiberByHostInstance || emptyFindFiberByHostInstance,
          // React Refresh
          findHostInstancesForRefresh,
          scheduleRefresh,
          scheduleRoot,
          setRefreshHandler,
          // Enables DevTools to append owner stacks to error messages in DEV mode.
          getCurrentFiber: getCurrentFiberForDevTools,
          // Enables DevTools to detect reconciler version rather than renderer version
          // which may not match for third party renderers.
          reconcilerVersion: ReactVersion
        });
      }
      var defaultOnRecoverableError = typeof reportError === "function" ? (
        // In modern browsers, reportError will dispatch an error event,
        // emulating an uncaught JavaScript error.
        reportError
      ) : function(error2) {
        console["error"](error2);
      };
      function ReactDOMRoot(internalRoot) {
        this._internalRoot = internalRoot;
      }
      ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) {
        var root2 = this._internalRoot;
        if (root2 === null) {
          throw new Error("Cannot update an unmounted root.");
        }
        {
          if (typeof arguments[1] === "function") {
            error("render(...): does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
          } else if (isValidContainer(arguments[1])) {
            error("You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root.");
          } else if (typeof arguments[1] !== "undefined") {
            error("You passed a second argument to root.render(...) but it only accepts one argument.");
          }
          var container = root2.containerInfo;
          if (container.nodeType !== COMMENT_NODE) {
            var hostInstance = findHostInstanceWithNoPortals(root2.current);
            if (hostInstance) {
              if (hostInstance.parentNode !== container) {
                error("render(...): It looks like the React-rendered content of the root container was removed without using React. This is not supported and will cause errors. Instead, call root.unmount() to empty a root's container.");
              }
            }
          }
        }
        updateContainer(children, root2, null, null);
      };
      ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
        {
          if (typeof arguments[0] === "function") {
            error("unmount(...): does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect().");
          }
        }
        var root2 = this._internalRoot;
        if (root2 !== null) {
          this._internalRoot = null;
          var container = root2.containerInfo;
          {
            if (isAlreadyRendering()) {
              error("Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition.");
            }
          }
          flushSync(function() {
            updateContainer(null, root2, null, null);
          });
          unmarkContainerAsRoot(container);
        }
      };
      function createRoot(container, options22) {
        if (!isValidContainer(container)) {
          throw new Error("createRoot(...): Target container is not a DOM element.");
        }
        warnIfReactDOMContainerInDEV(container);
        var isStrictMode = false;
        var concurrentUpdatesByDefaultOverride = false;
        var identifierPrefix = "";
        var onRecoverableError = defaultOnRecoverableError;
        if (options22 !== null && options22 !== void 0) {
          {
            if (options22.hydrate) {
              warn("hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead.");
            } else {
              if (typeof options22 === "object" && options22 !== null && options22.$$typeof === REACT_ELEMENT_TYPE) {
                error("You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n  let root = createRoot(domContainer);\n  root.render(<App />);");
              }
            }
          }
          if (options22.unstable_strictMode === true) {
            isStrictMode = true;
          }
          if (options22.identifierPrefix !== void 0) {
            identifierPrefix = options22.identifierPrefix;
          }
          if (options22.onRecoverableError !== void 0) {
            onRecoverableError = options22.onRecoverableError;
          }
          if (options22.transitionCallbacks !== void 0) {
            options22.transitionCallbacks;
          }
        }
        var root2 = createContainer(container, ConcurrentRoot, null, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
        markContainerAsRoot(root2.current, container);
        var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
        listenToAllSupportedEvents(rootContainerElement);
        return new ReactDOMRoot(root2);
      }
      function ReactDOMHydrationRoot(internalRoot) {
        this._internalRoot = internalRoot;
      }
      function scheduleHydration(target) {
        if (target) {
          queueExplicitHydrationTarget(target);
        }
      }
      ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = scheduleHydration;
      function hydrateRoot(container, initialChildren, options22) {
        if (!isValidContainer(container)) {
          throw new Error("hydrateRoot(...): Target container is not a DOM element.");
        }
        warnIfReactDOMContainerInDEV(container);
        {
          if (initialChildren === void 0) {
            error("Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)");
          }
        }
        var hydrationCallbacks = options22 != null ? options22 : null;
        var mutableSources = options22 != null && options22.hydratedSources || null;
        var isStrictMode = false;
        var concurrentUpdatesByDefaultOverride = false;
        var identifierPrefix = "";
        var onRecoverableError = defaultOnRecoverableError;
        if (options22 !== null && options22 !== void 0) {
          if (options22.unstable_strictMode === true) {
            isStrictMode = true;
          }
          if (options22.identifierPrefix !== void 0) {
            identifierPrefix = options22.identifierPrefix;
          }
          if (options22.onRecoverableError !== void 0) {
            onRecoverableError = options22.onRecoverableError;
          }
        }
        var root2 = createHydrationContainer(initialChildren, null, container, ConcurrentRoot, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError);
        markContainerAsRoot(root2.current, container);
        listenToAllSupportedEvents(container);
        if (mutableSources) {
          for (var i2 = 0; i2 < mutableSources.length; i2++) {
            var mutableSource = mutableSources[i2];
            registerMutableSourceForHydration(root2, mutableSource);
          }
        }
        return new ReactDOMHydrationRoot(root2);
      }
      function isValidContainer(node2) {
        return !!(node2 && (node2.nodeType === ELEMENT_NODE || node2.nodeType === DOCUMENT_NODE || node2.nodeType === DOCUMENT_FRAGMENT_NODE || false));
      }
      function isValidContainerLegacy(node2) {
        return !!(node2 && (node2.nodeType === ELEMENT_NODE || node2.nodeType === DOCUMENT_NODE || node2.nodeType === DOCUMENT_FRAGMENT_NODE || node2.nodeType === COMMENT_NODE && node2.nodeValue === " react-mount-point-unstable "));
      }
      function warnIfReactDOMContainerInDEV(container) {
        {
          if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") {
            error("createRoot(): Creating roots directly with document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try using a container element created for your app.");
          }
          if (isContainerMarkedAsRoot(container)) {
            if (container._reactRootContainer) {
              error("You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported.");
            } else {
              error("You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.");
            }
          }
        }
      }
      var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
      var topLevelUpdateWarnings;
      {
        topLevelUpdateWarnings = function(container) {
          if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
            var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer.current);
            if (hostInstance) {
              if (hostInstance.parentNode !== container) {
                error("render(...): It looks like the React-rendered content of this container was removed without using React. This is not supported and will cause errors. Instead, call ReactDOM.unmountComponentAtNode to empty a container.");
              }
            }
          }
          var isRootRenderedBySomeReact = !!container._reactRootContainer;
          var rootEl = getReactRootElementInContainer(container);
          var hasNonRootReactChild = !!(rootEl && getInstanceFromNode(rootEl));
          if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
            error("render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.");
          }
          if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === "BODY") {
            error("render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app.");
          }
        };
      }
      function getReactRootElementInContainer(container) {
        if (!container) {
          return null;
        }
        if (container.nodeType === DOCUMENT_NODE) {
          return container.documentElement;
        } else {
          return container.firstChild;
        }
      }
      function noopOnRecoverableError() {
      }
      function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) {
        if (isHydrationContainer) {
          if (typeof callback === "function") {
            var originalCallback = callback;
            callback = function() {
              var instance2 = getPublicRootInstance(root2);
              originalCallback.call(instance2);
            };
          }
          var root2 = createHydrationContainer(
            initialChildren,
            callback,
            container,
            LegacyRoot,
            null,
            // hydrationCallbacks
            false,
            // isStrictMode
            false,
            // concurrentUpdatesByDefaultOverride,
            "",
            // identifierPrefix
            noopOnRecoverableError
          );
          container._reactRootContainer = root2;
          markContainerAsRoot(root2.current, container);
          var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
          listenToAllSupportedEvents(rootContainerElement);
          flushSync();
          return root2;
        } else {
          var rootSibling;
          while (rootSibling = container.lastChild) {
            container.removeChild(rootSibling);
          }
          if (typeof callback === "function") {
            var _originalCallback = callback;
            callback = function() {
              var instance2 = getPublicRootInstance(_root);
              _originalCallback.call(instance2);
            };
          }
          var _root = createContainer(
            container,
            LegacyRoot,
            null,
            // hydrationCallbacks
            false,
            // isStrictMode
            false,
            // concurrentUpdatesByDefaultOverride,
            "",
            // identifierPrefix
            noopOnRecoverableError
          );
          container._reactRootContainer = _root;
          markContainerAsRoot(_root.current, container);
          var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container;
          listenToAllSupportedEvents(_rootContainerElement);
          flushSync(function() {
            updateContainer(initialChildren, _root, parentComponent, callback);
          });
          return _root;
        }
      }
      function warnOnInvalidCallback$1(callback, callerName) {
        {
          if (callback !== null && typeof callback !== "function") {
            error("%s(...): Expected the last optional `callback` argument to be a function. Instead received: %s.", callerName, callback);
          }
        }
      }
      function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
        {
          topLevelUpdateWarnings(container);
          warnOnInvalidCallback$1(callback === void 0 ? null : callback, "render");
        }
        var maybeRoot = container._reactRootContainer;
        var root2;
        if (!maybeRoot) {
          root2 = legacyCreateRootFromDOMContainer(container, children, parentComponent, callback, forceHydrate);
        } else {
          root2 = maybeRoot;
          if (typeof callback === "function") {
            var originalCallback = callback;
            callback = function() {
              var instance2 = getPublicRootInstance(root2);
              originalCallback.call(instance2);
            };
          }
          updateContainer(children, root2, parentComponent, callback);
        }
        return getPublicRootInstance(root2);
      }
      var didWarnAboutFindDOMNode = false;
      function findDOMNode(componentOrElement) {
        {
          if (!didWarnAboutFindDOMNode) {
            didWarnAboutFindDOMNode = true;
            error("findDOMNode is deprecated and will be removed in the next major release. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node");
          }
          var owner = ReactCurrentOwner$3.current;
          if (owner !== null && owner.stateNode !== null) {
            var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
            if (!warnedAboutRefsInRender) {
              error("%s is accessing findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.", getComponentNameFromType(owner.type) || "A component");
            }
            owner.stateNode._warnedAboutRefsInRender = true;
          }
        }
        if (componentOrElement == null) {
          return null;
        }
        if (componentOrElement.nodeType === ELEMENT_NODE) {
          return componentOrElement;
        }
        {
          return findHostInstanceWithWarning(componentOrElement, "findDOMNode");
        }
      }
      function hydrate(element, container, callback) {
        {
          error("ReactDOM.hydrate is no longer supported in React 18. Use hydrateRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
        }
        if (!isValidContainerLegacy(container)) {
          throw new Error("Target container is not a DOM element.");
        }
        {
          var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
          if (isModernRoot) {
            error("You are calling ReactDOM.hydrate() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call hydrateRoot(container, element)?");
          }
        }
        return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
      }
      function render(element, container, callback) {
        {
          error("ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
        }
        if (!isValidContainerLegacy(container)) {
          throw new Error("Target container is not a DOM element.");
        }
        {
          var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
          if (isModernRoot) {
            error("You are calling ReactDOM.render() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.render(element)?");
          }
        }
        return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
      }
      function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
        {
          error("ReactDOM.unstable_renderSubtreeIntoContainer() is no longer supported in React 18. Consider using a portal instead. Until you switch to the createRoot API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot");
        }
        if (!isValidContainerLegacy(containerNode)) {
          throw new Error("Target container is not a DOM element.");
        }
        if (parentComponent == null || !has(parentComponent)) {
          throw new Error("parentComponent must be a valid React Component");
        }
        return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
      }
      var didWarnAboutUnmountComponentAtNode = false;
      function unmountComponentAtNode(container) {
        {
          if (!didWarnAboutUnmountComponentAtNode) {
            didWarnAboutUnmountComponentAtNode = true;
            error("unmountComponentAtNode is deprecated and will be removed in the next major release. Switch to the createRoot API. Learn more: https://reactjs.org/link/switch-to-createroot");
          }
        }
        if (!isValidContainerLegacy(container)) {
          throw new Error("unmountComponentAtNode(...): Target container is not a DOM element.");
        }
        {
          var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === void 0;
          if (isModernRoot) {
            error("You are calling ReactDOM.unmountComponentAtNode() on a container that was previously passed to ReactDOMClient.createRoot(). This is not supported. Did you mean to call root.unmount()?");
          }
        }
        if (container._reactRootContainer) {
          {
            var rootEl = getReactRootElementInContainer(container);
            var renderedByDifferentReact = rootEl && !getInstanceFromNode(rootEl);
            if (renderedByDifferentReact) {
              error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.");
            }
          }
          flushSync(function() {
            legacyRenderSubtreeIntoContainer(null, null, container, false, function() {
              container._reactRootContainer = null;
              unmarkContainerAsRoot(container);
            });
          });
          return true;
        } else {
          {
            var _rootEl = getReactRootElementInContainer(container);
            var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode(_rootEl));
            var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainerLegacy(container.parentNode) && !!container.parentNode._reactRootContainer;
            if (hasNonRootReactChild) {
              error("unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s", isContainerReactRoot ? "You may have accidentally passed in a React root node instead of its container." : "Instead, have the parent component update its state and rerender in order to remove this component.");
            }
          }
          return false;
        }
      }
      setAttemptSynchronousHydration(attemptSynchronousHydration$1);
      setAttemptContinuousHydration(attemptContinuousHydration$1);
      setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
      setGetCurrentUpdatePriority(getCurrentUpdatePriority);
      setAttemptHydrationAtPriority(runWithPriority);
      {
        if (typeof Map !== "function" || // $FlowIssue Flow incorrectly thinks Map has no prototype
        Map.prototype == null || typeof Map.prototype.forEach !== "function" || typeof Set !== "function" || // $FlowIssue Flow incorrectly thinks Set has no prototype
        Set.prototype == null || typeof Set.prototype.clear !== "function" || typeof Set.prototype.forEach !== "function") {
          error("React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills");
        }
      }
      setRestoreImplementation(restoreControlledState$3);
      setBatchingImplementation(batchedUpdates$1, discreteUpdates, flushSync);
      function createPortal$1(children, container) {
        var key2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null;
        if (!isValidContainer(container)) {
          throw new Error("Target container is not a DOM element.");
        }
        return createPortal(children, container, null, key2);
      }
      function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
        return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
      }
      var Internals = {
        usingClientEntryPoint: false,
        // Keep in sync with ReactTestUtils.js.
        // This is an array for better minification.
        Events: [getInstanceFromNode, getNodeFromInstance, getFiberCurrentPropsFromNode, enqueueStateRestore, restoreStateIfNeeded, batchedUpdates$1]
      };
      function createRoot$1(container, options22) {
        {
          if (!Internals.usingClientEntryPoint && true) {
            error('You are importing createRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".');
          }
        }
        return createRoot(container, options22);
      }
      function hydrateRoot$1(container, initialChildren, options22) {
        {
          if (!Internals.usingClientEntryPoint && true) {
            error('You are importing hydrateRoot from "react-dom" which is not supported. You should instead import it from "react-dom/client".');
          }
        }
        return hydrateRoot(container, initialChildren, options22);
      }
      function flushSync$1(fn) {
        {
          if (isAlreadyRendering()) {
            error("flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.");
          }
        }
        return flushSync(fn);
      }
      var foundDevTools = injectIntoDevTools({
        findFiberByHostInstance: getClosestInstanceFromNode,
        bundleType: 1,
        version: ReactVersion,
        rendererPackageName: "react-dom"
      });
      {
        if (!foundDevTools && canUseDOM && window.top === window.self) {
          if (navigator.userAgent.indexOf("Chrome") > -1 && navigator.userAgent.indexOf("Edge") === -1 || navigator.userAgent.indexOf("Firefox") > -1) {
            var protocol = window.location.protocol;
            if (/^(https?|file):$/.test(protocol)) {
              console.info("%cDownload the React DevTools for a better development experience: https://reactjs.org/link/react-devtools" + (protocol === "file:" ? "\nYou might need to use a local HTTP server (instead of file://): https://reactjs.org/link/react-devtools-faq" : ""), "font-weight:bold");
            }
          }
        }
      }
      reactDom_development.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
      reactDom_development.createPortal = createPortal$1;
      reactDom_development.createRoot = createRoot$1;
      reactDom_development.findDOMNode = findDOMNode;
      reactDom_development.flushSync = flushSync$1;
      reactDom_development.hydrate = hydrate;
      reactDom_development.hydrateRoot = hydrateRoot$1;
      reactDom_development.render = render;
      reactDom_development.unmountComponentAtNode = unmountComponentAtNode;
      reactDom_development.unstable_batchedUpdates = batchedUpdates$1;
      reactDom_development.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
      reactDom_development.version = ReactVersion;
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
      }
    })();
  }
  return reactDom_development;
}
var hasRequiredReactDom;
function requireReactDom() {
  if (hasRequiredReactDom) return reactDom.exports;
  hasRequiredReactDom = 1;
  {
    reactDom.exports = requireReactDom_development();
  }
  return reactDom.exports;
}
var hasRequiredClient;
function requireClient() {
  if (hasRequiredClient) return client;
  hasRequiredClient = 1;
  var m = requireReactDom();
  {
    var i2 = m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
    client.createRoot = function(c2, o2) {
      i2.usingClientEntryPoint = true;
      try {
        return m.createRoot(c2, o2);
      } finally {
        i2.usingClientEntryPoint = false;
      }
    };
    client.hydrateRoot = function(c2, h2, o2) {
      i2.usingClientEntryPoint = true;
      try {
        return m.hydrateRoot(c2, h2, o2);
      } finally {
        i2.usingClientEntryPoint = false;
      }
    };
  }
  return client;
}
var clientExports = requireClient();
var jsxDevRuntime = { exports: {} };
var reactJsxDevRuntime_development = {};
var hasRequiredReactJsxDevRuntime_development;
function requireReactJsxDevRuntime_development() {
  if (hasRequiredReactJsxDevRuntime_development) return reactJsxDevRuntime_development;
  hasRequiredReactJsxDevRuntime_development = 1;
  /**
   * @license React
   * react-jsx-dev-runtime.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  {
    (function() {
      var React2 = requireReact();
      var REACT_ELEMENT_TYPE = Symbol.for("react.element");
      var REACT_PORTAL_TYPE = Symbol.for("react.portal");
      var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
      var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
      var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
      var REACT_CONTEXT_TYPE = Symbol.for("react.context");
      var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
      var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
      var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
      var REACT_MEMO_TYPE = Symbol.for("react.memo");
      var REACT_LAZY_TYPE = Symbol.for("react.lazy");
      var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        if (maybeIterable === null || typeof maybeIterable !== "object") {
          return null;
        }
        var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
        if (typeof maybeIterator === "function") {
          return maybeIterator;
        }
        return null;
      }
      var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      function error(format2) {
        {
          {
            for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }
            printWarning("error", format2, args);
          }
        }
      }
      function printWarning(level, format2, args) {
        {
          var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame2.getStackAddendum();
          if (stack !== "") {
            format2 += "%s";
            args = args.concat([stack]);
          }
          var argsWithFormat = args.map(function(item) {
            return String(item);
          });
          argsWithFormat.unshift("Warning: " + format2);
          Function.prototype.apply.call(console[level], console, argsWithFormat);
        }
      }
      var enableScopeAPI = false;
      var enableCacheElement = false;
      var enableTransitionTracing = false;
      var enableLegacyHidden = false;
      var enableDebugTracing = false;
      var REACT_MODULE_REFERENCE;
      {
        REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
      }
      function isValidElementType(type2) {
        if (typeof type2 === "string" || typeof type2 === "function") {
          return true;
        }
        if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
          return true;
        }
        if (typeof type2 === "object" && type2 !== null) {
          if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
          // types supported by any Flight configuration anywhere since
          // we don't know which Flight build this will end up being used
          // with.
          type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) {
            return true;
          }
        }
        return false;
      }
      function getWrappedName(outerType, innerType, wrapperName) {
        var displayName = outerType.displayName;
        if (displayName) {
          return displayName;
        }
        var functionName = innerType.displayName || innerType.name || "";
        return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
      }
      function getContextName(type2) {
        return type2.displayName || "Context";
      }
      function getComponentNameFromType(type2) {
        if (type2 == null) {
          return null;
        }
        {
          if (typeof type2.tag === "number") {
            error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
          }
        }
        if (typeof type2 === "function") {
          return type2.displayName || type2.name || null;
        }
        if (typeof type2 === "string") {
          return type2;
        }
        switch (type2) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_CONTEXT_TYPE:
              var context = type2;
              return getContextName(context) + ".Consumer";
            case REACT_PROVIDER_TYPE:
              var provider = type2;
              return getContextName(provider._context) + ".Provider";
            case REACT_FORWARD_REF_TYPE:
              return getWrappedName(type2, type2.render, "ForwardRef");
            case REACT_MEMO_TYPE:
              var outerName = type2.displayName || null;
              if (outerName !== null) {
                return outerName;
              }
              return getComponentNameFromType(type2.type) || "Memo";
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return getComponentNameFromType(init2(payload));
              } catch (x2) {
                return null;
              }
            }
          }
        }
        return null;
      }
      var assign = Object.assign;
      var disabledDepth = 0;
      var prevLog;
      var prevInfo;
      var prevWarn;
      var prevError;
      var prevGroup;
      var prevGroupCollapsed;
      var prevGroupEnd;
      function disabledLog() {
      }
      disabledLog.__reactDisabledLog = true;
      function disableLogs() {
        {
          if (disabledDepth === 0) {
            prevLog = console.log;
            prevInfo = console.info;
            prevWarn = console.warn;
            prevError = console.error;
            prevGroup = console.group;
            prevGroupCollapsed = console.groupCollapsed;
            prevGroupEnd = console.groupEnd;
            var props = {
              configurable: true,
              enumerable: true,
              value: disabledLog,
              writable: true
            };
            Object.defineProperties(console, {
              info: props,
              log: props,
              warn: props,
              error: props,
              group: props,
              groupCollapsed: props,
              groupEnd: props
            });
          }
          disabledDepth++;
        }
      }
      function reenableLogs() {
        {
          disabledDepth--;
          if (disabledDepth === 0) {
            var props = {
              configurable: true,
              enumerable: true,
              writable: true
            };
            Object.defineProperties(console, {
              log: assign({}, props, {
                value: prevLog
              }),
              info: assign({}, props, {
                value: prevInfo
              }),
              warn: assign({}, props, {
                value: prevWarn
              }),
              error: assign({}, props, {
                value: prevError
              }),
              group: assign({}, props, {
                value: prevGroup
              }),
              groupCollapsed: assign({}, props, {
                value: prevGroupCollapsed
              }),
              groupEnd: assign({}, props, {
                value: prevGroupEnd
              })
            });
          }
          if (disabledDepth < 0) {
            error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
          }
        }
      }
      var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
      var prefix;
      function describeBuiltInComponentFrame(name, source, ownerFn) {
        {
          if (prefix === void 0) {
            try {
              throw Error();
            } catch (x2) {
              var match = x2.stack.trim().match(/\n( *(at )?)/);
              prefix = match && match[1] || "";
            }
          }
          return "\n" + prefix + name;
        }
      }
      var reentry = false;
      var componentFrameCache;
      {
        var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
        componentFrameCache = new PossiblyWeakMap();
      }
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) {
          return "";
        }
        {
          var frame = componentFrameCache.get(fn);
          if (frame !== void 0) {
            return frame;
          }
        }
        var control;
        reentry = true;
        var previousPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher;
        {
          previousDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = null;
          disableLogs();
        }
        try {
          if (construct) {
            var Fake = function() {
              throw Error();
            };
            Object.defineProperty(Fake.prototype, "props", {
              set: function() {
                throw Error();
              }
            });
            if (typeof Reflect === "object" && Reflect.construct) {
              try {
                Reflect.construct(Fake, []);
              } catch (x2) {
                control = x2;
              }
              Reflect.construct(fn, [], Fake);
            } else {
              try {
                Fake.call();
              } catch (x2) {
                control = x2;
              }
              fn.call(Fake.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (x2) {
              control = x2;
            }
            fn();
          }
        } catch (sample) {
          if (sample && control && typeof sample.stack === "string") {
            var sampleLines = sample.stack.split("\n");
            var controlLines = control.stack.split("\n");
            var s2 = sampleLines.length - 1;
            var c2 = controlLines.length - 1;
            while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) {
              c2--;
            }
            for (; s2 >= 1 && c2 >= 0; s2--, c2--) {
              if (sampleLines[s2] !== controlLines[c2]) {
                if (s2 !== 1 || c2 !== 1) {
                  do {
                    s2--;
                    c2--;
                    if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) {
                      var _frame = "\n" + sampleLines[s2].replace(" at new ", " at ");
                      if (fn.displayName && _frame.includes("<anonymous>")) {
                        _frame = _frame.replace("<anonymous>", fn.displayName);
                      }
                      {
                        if (typeof fn === "function") {
                          componentFrameCache.set(fn, _frame);
                        }
                      }
                      return _frame;
                    }
                  } while (s2 >= 1 && c2 >= 0);
                }
                break;
              }
            }
          }
        } finally {
          reentry = false;
          {
            ReactCurrentDispatcher.current = previousDispatcher;
            reenableLogs();
          }
          Error.prepareStackTrace = previousPrepareStackTrace;
        }
        var name = fn ? fn.displayName || fn.name : "";
        var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
        {
          if (typeof fn === "function") {
            componentFrameCache.set(fn, syntheticFrame);
          }
        }
        return syntheticFrame;
      }
      function describeFunctionComponentFrame(fn, source, ownerFn) {
        {
          return describeNativeComponentFrame(fn, false);
        }
      }
      function shouldConstruct(Component) {
        var prototype = Component.prototype;
        return !!(prototype && prototype.isReactComponent);
      }
      function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) {
        if (type2 == null) {
          return "";
        }
        if (typeof type2 === "function") {
          {
            return describeNativeComponentFrame(type2, shouldConstruct(type2));
          }
        }
        if (typeof type2 === "string") {
          return describeBuiltInComponentFrame(type2);
        }
        switch (type2) {
          case REACT_SUSPENSE_TYPE:
            return describeBuiltInComponentFrame("Suspense");
          case REACT_SUSPENSE_LIST_TYPE:
            return describeBuiltInComponentFrame("SuspenseList");
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              return describeFunctionComponentFrame(type2.render);
            case REACT_MEMO_TYPE:
              return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn);
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn);
              } catch (x2) {
              }
            }
          }
        }
        return "";
      }
      var hasOwnProperty = Object.prototype.hasOwnProperty;
      var loggedTypeFailures = {};
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame.setExtraStackFrame(null);
          }
        }
      }
      function checkPropTypes(typeSpecs, values, location, componentName, element) {
        {
          var has = Function.call.bind(hasOwnProperty);
          for (var typeSpecName in typeSpecs) {
            if (has(typeSpecs, typeSpecName)) {
              var error$1 = void 0;
              try {
                if (typeof typeSpecs[typeSpecName] !== "function") {
                  var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                  err.name = "Invariant Violation";
                  throw err;
                }
                error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
              } catch (ex) {
                error$1 = ex;
              }
              if (error$1 && !(error$1 instanceof Error)) {
                setCurrentlyValidatingElement(element);
                error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
                setCurrentlyValidatingElement(null);
              }
              if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                loggedTypeFailures[error$1.message] = true;
                setCurrentlyValidatingElement(element);
                error("Failed %s type: %s", location, error$1.message);
                setCurrentlyValidatingElement(null);
              }
            }
          }
        }
      }
      var isArrayImpl = Array.isArray;
      function isArray2(a2) {
        return isArrayImpl(a2);
      }
      function typeName(value) {
        {
          var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
          var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          return type2;
        }
      }
      function willCoercionThrow(value) {
        {
          try {
            testStringCoercion(value);
            return false;
          } catch (e4) {
            return true;
          }
        }
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkKeyStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
      var RESERVED_PROPS = {
        key: true,
        ref: true,
        __self: true,
        __source: true
      };
      var specialPropKeyWarningShown;
      var specialPropRefWarningShown;
      var didWarnAboutStringRefs;
      {
        didWarnAboutStringRefs = {};
      }
      function hasValidRef(config) {
        {
          if (hasOwnProperty.call(config, "ref")) {
            var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.ref !== void 0;
      }
      function hasValidKey(config) {
        {
          if (hasOwnProperty.call(config, "key")) {
            var getter = Object.getOwnPropertyDescriptor(config, "key").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.key !== void 0;
      }
      function warnIfStringRefCannotBeAutoConverted(config, self2) {
        {
          if (typeof config.ref === "string" && ReactCurrentOwner.current && self2 && ReactCurrentOwner.current.stateNode !== self2) {
            var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
            if (!didWarnAboutStringRefs[componentName]) {
              error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
              didWarnAboutStringRefs[componentName] = true;
            }
          }
        }
      }
      function defineKeyPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingKey = function() {
            if (!specialPropKeyWarningShown) {
              specialPropKeyWarningShown = true;
              error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingKey.isReactWarning = true;
          Object.defineProperty(props, "key", {
            get: warnAboutAccessingKey,
            configurable: true
          });
        }
      }
      function defineRefPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingRef = function() {
            if (!specialPropRefWarningShown) {
              specialPropRefWarningShown = true;
              error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingRef.isReactWarning = true;
          Object.defineProperty(props, "ref", {
            get: warnAboutAccessingRef,
            configurable: true
          });
        }
      }
      var ReactElement = function(type2, key2, ref2, self2, source, owner, props) {
        var element = {
          // This tag allows us to uniquely identify this as a React Element
          $$typeof: REACT_ELEMENT_TYPE,
          // Built-in properties that belong on the element
          type: type2,
          key: key2,
          ref: ref2,
          props,
          // Record the component responsible for creating this element.
          _owner: owner
        };
        {
          element._store = {};
          Object.defineProperty(element._store, "validated", {
            configurable: false,
            enumerable: false,
            writable: true,
            value: false
          });
          Object.defineProperty(element, "_self", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: self2
          });
          Object.defineProperty(element, "_source", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: source
          });
          if (Object.freeze) {
            Object.freeze(element.props);
            Object.freeze(element);
          }
        }
        return element;
      };
      function jsxDEV(type2, config, maybeKey, source, self2) {
        {
          var propName;
          var props = {};
          var key2 = null;
          var ref2 = null;
          if (maybeKey !== void 0) {
            {
              checkKeyStringCoercion(maybeKey);
            }
            key2 = "" + maybeKey;
          }
          if (hasValidKey(config)) {
            {
              checkKeyStringCoercion(config.key);
            }
            key2 = "" + config.key;
          }
          if (hasValidRef(config)) {
            ref2 = config.ref;
            warnIfStringRefCannotBeAutoConverted(config, self2);
          }
          for (propName in config) {
            if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
              props[propName] = config[propName];
            }
          }
          if (type2 && type2.defaultProps) {
            var defaultProps = type2.defaultProps;
            for (propName in defaultProps) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps[propName];
              }
            }
          }
          if (key2 || ref2) {
            var displayName = typeof type2 === "function" ? type2.displayName || type2.name || "Unknown" : type2;
            if (key2) {
              defineKeyPropWarningGetter(props, displayName);
            }
            if (ref2) {
              defineRefPropWarningGetter(props, displayName);
            }
          }
          return ReactElement(type2, key2, ref2, self2, source, ReactCurrentOwner.current, props);
        }
      }
      var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
      var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement$1(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame$1.setExtraStackFrame(null);
          }
        }
      }
      var propTypesMisspellWarningShown;
      {
        propTypesMisspellWarningShown = false;
      }
      function isValidElement(object) {
        {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
      }
      function getDeclarationErrorAddendum() {
        {
          if (ReactCurrentOwner$1.current) {
            var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
            if (name) {
              return "\n\nCheck the render method of `" + name + "`.";
            }
          }
          return "";
        }
      }
      function getSourceInfoErrorAddendum(source) {
        {
          if (source !== void 0) {
            var fileName = source.fileName.replace(/^.*[\\\/]/, "");
            var lineNumber = source.lineNumber;
            return "\n\nCheck your code at " + fileName + ":" + lineNumber + ".";
          }
          return "";
        }
      }
      var ownerHasKeyUseWarning = {};
      function getCurrentComponentErrorInfo(parentType) {
        {
          var info = getDeclarationErrorAddendum();
          if (!info) {
            var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
            if (parentName) {
              info = "\n\nCheck the top-level render call using <" + parentName + ">.";
            }
          }
          return info;
        }
      }
      function validateExplicitKey(element, parentType) {
        {
          if (!element._store || element._store.validated || element.key != null) {
            return;
          }
          element._store.validated = true;
          var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
          if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
            return;
          }
          ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
          var childOwner = "";
          if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
            childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
          }
          setCurrentlyValidatingElement$1(element);
          error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
          setCurrentlyValidatingElement$1(null);
        }
      }
      function validateChildKeys(node2, parentType) {
        {
          if (typeof node2 !== "object") {
            return;
          }
          if (isArray2(node2)) {
            for (var i2 = 0; i2 < node2.length; i2++) {
              var child = node2[i2];
              if (isValidElement(child)) {
                validateExplicitKey(child, parentType);
              }
            }
          } else if (isValidElement(node2)) {
            if (node2._store) {
              node2._store.validated = true;
            }
          } else if (node2) {
            var iteratorFn = getIteratorFn(node2);
            if (typeof iteratorFn === "function") {
              if (iteratorFn !== node2.entries) {
                var iterator = iteratorFn.call(node2);
                var step;
                while (!(step = iterator.next()).done) {
                  if (isValidElement(step.value)) {
                    validateExplicitKey(step.value, parentType);
                  }
                }
              }
            }
          }
        }
      }
      function validatePropTypes(element) {
        {
          var type2 = element.type;
          if (type2 === null || type2 === void 0 || typeof type2 === "string") {
            return;
          }
          var propTypes;
          if (typeof type2 === "function") {
            propTypes = type2.propTypes;
          } else if (typeof type2 === "object" && (type2.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
          // Inner props are checked in the reconciler.
          type2.$$typeof === REACT_MEMO_TYPE)) {
            propTypes = type2.propTypes;
          } else {
            return;
          }
          if (propTypes) {
            var name = getComponentNameFromType(type2);
            checkPropTypes(propTypes, element.props, "prop", name, element);
          } else if (type2.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
            propTypesMisspellWarningShown = true;
            var _name = getComponentNameFromType(type2);
            error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
          }
          if (typeof type2.getDefaultProps === "function" && !type2.getDefaultProps.isReactClassApproved) {
            error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
          }
        }
      }
      function validateFragmentProps(fragment) {
        {
          var keys = Object.keys(fragment.props);
          for (var i2 = 0; i2 < keys.length; i2++) {
            var key2 = keys[i2];
            if (key2 !== "children" && key2 !== "key") {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key2);
              setCurrentlyValidatingElement$1(null);
              break;
            }
          }
          if (fragment.ref !== null) {
            setCurrentlyValidatingElement$1(fragment);
            error("Invalid attribute `ref` supplied to `React.Fragment`.");
            setCurrentlyValidatingElement$1(null);
          }
        }
      }
      var didWarnAboutKeySpread = {};
      function jsxWithValidation(type2, props, key2, isStaticChildren, source, self2) {
        {
          var validType = isValidElementType(type2);
          if (!validType) {
            var info = "";
            if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) {
              info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            }
            var sourceInfo = getSourceInfoErrorAddendum(source);
            if (sourceInfo) {
              info += sourceInfo;
            } else {
              info += getDeclarationErrorAddendum();
            }
            var typeString;
            if (type2 === null) {
              typeString = "null";
            } else if (isArray2(type2)) {
              typeString = "array";
            } else if (type2 !== void 0 && type2.$$typeof === REACT_ELEMENT_TYPE) {
              typeString = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />";
              info = " Did you accidentally export a JSX literal instead of a component?";
            } else {
              typeString = typeof type2;
            }
            error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
          }
          var element = jsxDEV(type2, props, key2, source, self2);
          if (element == null) {
            return element;
          }
          if (validType) {
            var children = props.children;
            if (children !== void 0) {
              if (isStaticChildren) {
                if (isArray2(children)) {
                  for (var i2 = 0; i2 < children.length; i2++) {
                    validateChildKeys(children[i2], type2);
                  }
                  if (Object.freeze) {
                    Object.freeze(children);
                  }
                } else {
                  error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
                }
              } else {
                validateChildKeys(children, type2);
              }
            }
          }
          {
            if (hasOwnProperty.call(props, "key")) {
              var componentName = getComponentNameFromType(type2);
              var keys = Object.keys(props).filter(function(k2) {
                return k2 !== "key";
              });
              var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
              if (!didWarnAboutKeySpread[componentName + beforeExample]) {
                var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}";
                error('A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
                didWarnAboutKeySpread[componentName + beforeExample] = true;
              }
            }
          }
          if (type2 === REACT_FRAGMENT_TYPE) {
            validateFragmentProps(element);
          } else {
            validatePropTypes(element);
          }
          return element;
        }
      }
      var jsxDEV$1 = jsxWithValidation;
      reactJsxDevRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
      reactJsxDevRuntime_development.jsxDEV = jsxDEV$1;
    })();
  }
  return reactJsxDevRuntime_development;
}
var hasRequiredJsxDevRuntime;
function requireJsxDevRuntime() {
  if (hasRequiredJsxDevRuntime) return jsxDevRuntime.exports;
  hasRequiredJsxDevRuntime = 1;
  {
    jsxDevRuntime.exports = requireReactJsxDevRuntime_development();
  }
  return jsxDevRuntime.exports;
}
var jsxDevRuntimeExports = requireJsxDevRuntime();
function BaseDialog({
  show,
  setShow,
  children,
  style,
  className
}) {
  const ref2 = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (ref2.current) {
      show ? ref2.current.show() : ref2.current.close();
    }
  }, [show]);
  const handleClose = reactExports.useCallback(() => {
    setShow(false);
  }, [setShow]);
  reactExports.useEffect(() => {
    if (ref2.current) {
      ref2.current.addEventListener("close", handleClose);
    }
    return () => {
      if (ref2.current) {
        ref2.current.removeEventListener("close", handleClose);
      }
    };
  }, [handleClose]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("dialog", { title: "BaseDialog", ref: ref2, style, className, onClick: (e4) => {
    e4.stopPropagation();
  }, children }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/BaseDialog.tsx",
    lineNumber: 34,
    columnNumber: 12
  }, this);
}
mcpMesh.implementAction("register", async (params) => {
  const loginProvider = PSUXPInternalStore.getState().loginProvider;
  if (!loginProvider) {
    throw new Error("No login provider available");
  }
  try {
    await loginProvider.register(params);
  } catch (error) {
    throw new Error(`Registration failed: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
  return {};
});
mcpMesh.implementAction("guestLogin", async (params) => {
  mcpMesh.store.setState({
    isGuest: true,
    isLogin: false,
    token: "",
    userInfo: {}
  });
  return {};
});
mcpMesh.implementAction("login", async (params) => {
  const loginProvider = PSUXPInternalStore.getState().loginProvider;
  if (!loginProvider) {
    throw new Error("No login provider available");
  }
  try {
    const user2 = await loginProvider.login(params);
    mcpMesh.store.setState({
      userInfo: user2,
      isLogin: true,
      token: user2.token
    });
  } catch (error) {
    throw new Error(`Login failed: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
  return {};
});
mcpMesh.implementAction("sendPassCode", async (params) => {
  const loginProvider = PSUXPInternalStore.getState().loginProvider;
  if (!loginProvider) {
    throw new Error("No login provider available");
  }
  try {
    await loginProvider.sendPassCode(params);
  } catch (error) {
    throw new Error(`Failed to send passcode: ${error instanceof Error ? error.message : "Unknown error"}`);
  }
  return {};
});
mcpMesh.implementAction("logout", async () => {
  mcpMesh.store.setState({
    token: "",
    isLogin: false,
    userInfo: {}
  });
  return {};
});
const byteToHex = [];
for (let i2 = 0; i2 < 256; ++i2) {
  byteToHex.push((i2 + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
  return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
let getRandomValues;
const rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues) {
    if (typeof crypto === "undefined" || !crypto.getRandomValues) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
    getRandomValues = crypto.getRandomValues.bind(crypto);
  }
  return getRandomValues(rnds8);
}
const randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
const native = { randomUUID };
function v4(options2, buf, offset) {
  var _a3;
  if (native.randomUUID && true && !options2) {
    return native.randomUUID();
  }
  options2 = options2 || {};
  const rnds = options2.random ?? ((_a3 = options2.rng) == null ? void 0 : _a3.call(options2)) ?? rng();
  if (rnds.length < 16) {
    throw new Error("Random bytes length must be >= 16");
  }
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  return unsafeStringify(rnds);
}
const RESOURCE_SCHEME = "uxp://";
function createResourceId(type2, suffix) {
  const idSegment = v4();
  return `${RESOURCE_SCHEME}${type2}/${idSegment}`;
}
function isResourceId(value) {
  return typeof value === "string" && value.startsWith(RESOURCE_SCHEME);
}
const jimpCache = /* @__PURE__ */ new Map();
function storeJimpForResource(resourceId, image, mime2) {
  if (typeof resourceId !== "string" || !resourceId.startsWith("uxp://")) {
    return;
  }
  jimpCache.set(resourceId, {
    image: image.clone(),
    mime: mime2,
    storedAt: Date.now()
  });
}
function getJimpForResource(resourceId) {
  const entry = jimpCache.get(resourceId);
  if (!entry) {
    return void 0;
  }
  return {
    image: entry.image.clone(),
    mime: entry.mime
  };
}
function removeJimpForResource(resourceId) {
  jimpCache.delete(resourceId);
}
const resourceMap = /* @__PURE__ */ new Map();
const legacyPromiseMap = /* @__PURE__ */ new Map();
function toUint8Array$2(data2) {
  if (data2 instanceof Uint8Array) {
    return data2;
  }
  if (ArrayBuffer.isView(data2)) {
    const view = data2;
    return new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
  }
  if (data2 instanceof ArrayBuffer) {
    return new Uint8Array(data2);
  }
  if (Array.isArray(data2)) {
    return Uint8Array.from(data2);
  }
  if (typeof data2 === "string") {
    return new Uint8Array(bufferExports.Buffer.from(data2, "base64"));
  }
  throw new Error("Unsupported buffer data");
}
function createResource(entry) {
  const id = createResourceId(entry.type);
  resourceMap.set(id, entry);
  return id;
}
function resolveResource(resourceId) {
  return resourceMap.get(resourceId);
}
function updateResource(resourceId, entry) {
  const existing = resourceMap.get(resourceId);
  if (!existing) return;
  resourceMap.set(resourceId, {
    ...existing,
    ...entry,
    data: {
      ...existing.data,
      ...entry.data ?? {}
    },
    originalMeta: entry.originalMeta ?? existing.originalMeta,
    thumbnailCache: entry.thumbnailCache !== void 0 ? entry.thumbnailCache : existing.thumbnailCache
  });
}
function deleteResource(resourceId) {
  resourceMap.delete(resourceId);
  legacyPromiseMap.delete(resourceId);
  removeJimpForResource(resourceId);
}
function getResourceThumbnail(resourceId) {
  const entry = resourceMap.get(resourceId);
  return entry == null ? void 0 : entry.thumbnailCache;
}
function setResourceThumbnail(resourceId, thumbnail) {
  const entry = resourceMap.get(resourceId);
  if (!entry) {
    throw new Error("Resource not found");
  }
  const normalized = toUint8Array$2(thumbnail.buffer);
  const mime2 = thumbnail.mime ?? "image/png";
  const base64 = "data:" + mime2 + ";base64," + bufferExports.Buffer.from(normalized).toString("base64");
  updateResource(resourceId, {
    thumbnailCache: {
      buffer: normalized,
      base64,
      width: thumbnail.width,
      height: thumbnail.height,
      originalWidth: thumbnail.originalWidth,
      originalHeight: thumbnail.originalHeight,
      mime: mime2,
      generatedAt: Date.now()
    }
  });
}
async function getImageHolder(fileToken) {
  if (legacyPromiseMap.has(fileToken)) {
    return legacyPromiseMap.get(fileToken);
  }
  if (!isResourceId(fileToken)) {
    return void 0;
  }
  const entry = resolveResource(fileToken);
  if (!entry) return void 0;
  if (entry.data.buffer && entry.data.mime) {
    return {
      file_buffer: entry.data.buffer,
      file_mimetype: entry.data.mime
    };
  }
  return void 0;
}
async function readNativePath(nativePath) {
  const localFileSystem = uxp.storage.localFileSystem;
  const tempFolder = await localFileSystem.getTemporaryFolder();
  try {
    if (nativePath.includes(tempFolder.nativePath)) {
      const relativePath = nativePath.replace(tempFolder.nativePath, "").replace(/^[\\/\\]/, "");
      const tempEntry = await tempFolder.getEntry(relativePath);
      const arrayBuffer2 = await (tempEntry == null ? void 0 : tempEntry.read({ format: uxp.storage.formats.binary }));
      return arrayBuffer2 ? new Uint8Array(arrayBuffer2) : void 0;
    }
    const url = nativePath.startsWith("file://") ? nativePath : `file://${nativePath}`;
    const fileEntry = await localFileSystem.getEntryWithUrl(url);
    const arrayBuffer = await (fileEntry == null ? void 0 : fileEntry.read({ format: uxp.storage.formats.binary }));
    return arrayBuffer ? new Uint8Array(arrayBuffer) : void 0;
  } catch {
    return void 0;
  }
}
async function resolveResourceBuffer(resourceOrToken) {
  const loadLegacy = async () => {
    const legacy2 = await getImageHolder(resourceOrToken);
    if (!legacy2) {
      throw new Error("Resource not found");
    }
    return {
      buffer: toUint8Array$2(legacy2.file_buffer),
      mime: legacy2.file_mimetype
    };
  };
  if (!isResourceId(resourceOrToken)) {
    return loadLegacy();
  }
  const entry = resolveResource(resourceOrToken);
  if (!entry) {
    return loadLegacy();
  }
  if (entry.data.buffer) {
    const buffer2 = toUint8Array$2(entry.data.buffer);
    updateResource(resourceOrToken, {
      data: {
        ...entry.data,
        buffer: buffer2
      }
    });
    return {
      buffer: buffer2,
      mime: entry.data.mime
    };
  }
  if (entry.data.path) {
    const buffer2 = await readNativePath(String(entry.data.path));
    if (buffer2) {
      updateResource(resourceOrToken, {
        data: {
          ...entry.data,
          buffer: buffer2
        }
      });
      return {
        buffer: buffer2,
        mime: entry.data.mime
      };
    }
  }
  return loadLegacy();
}
async function ensureResourceTempFile(resourceOrToken, options2) {
  if (!isResourceId(resourceOrToken)) {
    throw new Error("ensureResourceTempFile expects a resource id");
  }
  const entry = resolveResource(resourceOrToken);
  if (!entry) {
    throw new Error("Resource not found");
  }
  if (entry.data.path) {
    return entry.data.path;
  }
  const { buffer: buffer2, mime: mime2 } = await resolveResourceBuffer(resourceOrToken);
  const localFileSystem = uxp.storage.localFileSystem;
  const tempFolder = await localFileSystem.getTemporaryFolder();
  const ext = (() => {
    var _a3;
    if ((_a3 = entry.originalMeta) == null ? void 0 : _a3.fileName) {
      const name = String(entry.originalMeta.fileName);
      const idx = name.lastIndexOf(".");
      if (idx >= 0) {
        return name.substring(idx);
      }
    }
    if (options2 == null ? void 0 : options2.extensionHint) {
      return options2.extensionHint.startsWith(".") ? options2.extensionHint : `.${options2.extensionHint}`;
    }
    if (mime2) {
      const map = {
        "image/png": ".png",
        "image/jpeg": ".jpg",
        "image/jpg": ".jpg",
        "image/webp": ".webp",
        "image/gif": ".gif",
        "image/bmp": ".bmp",
        "image/tiff": ".tif",
        "image/heic": ".heic"
      };
      if (map[mime2]) {
        return map[mime2];
      }
    }
    return ".bin";
  })();
  const fileName = `resource_${Date.now()}_${Math.random().toString(36).slice(2, 8)}${ext}`;
  const tempFile = await tempFolder.createFile(fileName, { overwrite: true });
  await tempFile.write(new Uint8Array(buffer2), { format: uxp.storage.formats.binary });
  updateResource(resourceOrToken, {
    data: {
      ...entry.data,
      path: tempFile.nativePath
    }
  });
  return tempFile.nativePath;
}
objectType$1({
  getImageParams: objectType$1({
    boundary: enumType$1(["canvas", "curlayer", "selection"]),
    content: enumType$1(["canvas", "curlayer", "selection"]).or(stringType$1()),
    imageSize: numberType$1(),
    imageQuality: numberType$1(),
    cropBySelection: enumType$1(["no", "positive", "negative"])
  }).optional(),
  thumbnail: stringType$1().optional(),
  resource: stringType$1().optional(),
  source: stringType$1().optional(),
  error: stringType$1().optional()
});
objectType$1({
  getMaskParams: objectType$1({
    content: enumType$1(["canvas", "curlayer", "selection"]),
    reverse: booleanType$1(),
    imageSize: numberType$1()
  }).optional(),
  thumbnail: stringType$1().optional(),
  resource: stringType$1().optional(),
  source: stringType$1().optional(),
  error: stringType$1().optional()
});
objectType$1({
  sendImageParams: objectType$1({
    selection: enumType$1([
      "newlayer_canvas",
      "newlayer_curlayer",
      "newlayer_selection",
      "curlayer_canvas",
      "curlayer_curlayer",
      "curlayer_selection",
      "newdoc_canvas"
    ]),
    url: stringType$1(),
    source: stringType$1(),
    cropBySelection: enumType$1(["no", "positive", "negative"]),
    resource: stringType$1().optional(),
    thumbnail: stringType$1().optional()
  }).optional(),
  error: stringType$1().optional()
});
objectType$1({
  active: booleanType$1().default(false),
  config: anyType$1().optional(),
  // ImageSelectionDialogConfig类型
  additionalData: recordType$1(anyType$1()).optional()
  // 额外数据
});
const DialogManagerStore = create((set) => ({
  genericDialog: {
    active: false,
    config: void 0,
    additionalData: void 0
  },
  rejectGenericDialog: () => {
  },
  resolveGenericDialog: () => {
  },
  sendImageLoading: false,
  setSendImageLoading: (loading) => set({ sendImageLoading: loading }),
  keyboardHandlers: []
}));
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
let _defaultBaseGeminiUrl = void 0;
let _defaultBaseVertexUrl = void 0;
function getDefaultBaseUrls() {
  return {
    geminiUrl: _defaultBaseGeminiUrl,
    vertexUrl: _defaultBaseVertexUrl
  };
}
function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) {
  var _a3, _b2;
  if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) {
    const defaultBaseUrls = getDefaultBaseUrls();
    if (vertexai) {
      return (_a3 = defaultBaseUrls.vertexUrl) !== null && _a3 !== void 0 ? _a3 : vertexBaseUrlFromEnv;
    } else {
      return (_b2 = defaultBaseUrls.geminiUrl) !== null && _b2 !== void 0 ? _b2 : geminiBaseUrlFromEnv;
    }
  }
  return httpOptions.baseUrl;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class BaseModule {
}
function formatMap(templateString, valueMap) {
  const regex = /\{([^}]+)\}/g;
  return templateString.replace(regex, (match, key2) => {
    if (Object.prototype.hasOwnProperty.call(valueMap, key2)) {
      const value = valueMap[key2];
      return value !== void 0 && value !== null ? String(value) : "";
    } else {
      throw new Error(`Key '${key2}' not found in valueMap.`);
    }
  });
}
function setValueByPath(data2, keys, value) {
  for (let i2 = 0; i2 < keys.length - 1; i2++) {
    const key2 = keys[i2];
    if (key2.endsWith("[]")) {
      const keyName = key2.slice(0, -2);
      if (!(keyName in data2)) {
        if (Array.isArray(value)) {
          data2[keyName] = Array.from({ length: value.length }, () => ({}));
        } else {
          throw new Error(`Value must be a list given an array path ${key2}`);
        }
      }
      if (Array.isArray(data2[keyName])) {
        const arrayData = data2[keyName];
        if (Array.isArray(value)) {
          for (let j = 0; j < arrayData.length; j++) {
            const entry = arrayData[j];
            setValueByPath(entry, keys.slice(i2 + 1), value[j]);
          }
        } else {
          for (const d of arrayData) {
            setValueByPath(d, keys.slice(i2 + 1), value);
          }
        }
      }
      return;
    } else if (key2.endsWith("[0]")) {
      const keyName = key2.slice(0, -3);
      if (!(keyName in data2)) {
        data2[keyName] = [{}];
      }
      const arrayData = data2[keyName];
      setValueByPath(arrayData[0], keys.slice(i2 + 1), value);
      return;
    }
    if (!data2[key2] || typeof data2[key2] !== "object") {
      data2[key2] = {};
    }
    data2 = data2[key2];
  }
  const keyToSet = keys[keys.length - 1];
  const existingData = data2[keyToSet];
  if (existingData !== void 0) {
    if (!value || typeof value === "object" && Object.keys(value).length === 0) {
      return;
    }
    if (value === existingData) {
      return;
    }
    if (typeof existingData === "object" && typeof value === "object" && existingData !== null && value !== null) {
      Object.assign(existingData, value);
    } else {
      throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);
    }
  } else {
    if (keyToSet === "_self" && typeof value === "object" && value !== null && !Array.isArray(value)) {
      const valueAsRecord = value;
      Object.assign(data2, valueAsRecord);
    } else {
      data2[keyToSet] = value;
    }
  }
}
function getValueByPath(data2, keys) {
  try {
    if (keys.length === 1 && keys[0] === "_self") {
      return data2;
    }
    for (let i2 = 0; i2 < keys.length; i2++) {
      if (typeof data2 !== "object" || data2 === null) {
        return void 0;
      }
      const key2 = keys[i2];
      if (key2.endsWith("[]")) {
        const keyName = key2.slice(0, -2);
        if (keyName in data2) {
          const arrayData = data2[keyName];
          if (!Array.isArray(arrayData)) {
            return void 0;
          }
          return arrayData.map((d) => getValueByPath(d, keys.slice(i2 + 1)));
        } else {
          return void 0;
        }
      } else {
        data2 = data2[key2];
      }
    }
    return data2;
  } catch (error) {
    if (error instanceof TypeError) {
      return void 0;
    }
    throw error;
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function tBytes$1(fromBytes) {
  if (typeof fromBytes !== "string") {
    throw new Error("fromImageBytes must be a string");
  }
  return fromBytes;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function getOperationParametersToMldev(fromObject2) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject2, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function fetchPredictOperationParametersToVertex(fromObject2) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject2, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["operationName"], fromOperationName);
  }
  const fromResourceName = getValueByPath(fromObject2, ["resourceName"]);
  if (fromResourceName != null) {
    setValueByPath(toObject, ["_url", "resourceName"], fromResourceName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function getOperationParametersToVertex(fromObject2) {
  const toObject = {};
  const fromOperationName = getValueByPath(fromObject2, [
    "operationName"
  ]);
  if (fromOperationName != null) {
    setValueByPath(toObject, ["_url", "operationName"], fromOperationName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function videoFromMldev$1(fromObject2) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject2, ["video", "uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject2, [
    "video",
    "encodedVideo"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromMldev$1(fromObject2) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject2, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev$1(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromMldev$1(fromObject2) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject2, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromMldev$1(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject2, [
    "response",
    "generateVideoResponse"
  ]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromMldev$1(fromResponse));
  }
  return toObject;
}
function videoFromVertex$1(fromObject2) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject2, [
    "bytesBase64Encoded"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromVertex$1(fromObject2) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject2, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex$1(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromVertex$1(fromObject2) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject2, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex$1(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromVertex$1(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromVertex$1(fromResponse));
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
var Outcome;
(function(Outcome2) {
  Outcome2["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED";
  Outcome2["OUTCOME_OK"] = "OUTCOME_OK";
  Outcome2["OUTCOME_FAILED"] = "OUTCOME_FAILED";
  Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED";
})(Outcome || (Outcome = {}));
var Language;
(function(Language2) {
  Language2["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED";
  Language2["PYTHON"] = "PYTHON";
})(Language || (Language = {}));
var Type;
(function(Type2) {
  Type2["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED";
  Type2["STRING"] = "STRING";
  Type2["NUMBER"] = "NUMBER";
  Type2["INTEGER"] = "INTEGER";
  Type2["BOOLEAN"] = "BOOLEAN";
  Type2["ARRAY"] = "ARRAY";
  Type2["OBJECT"] = "OBJECT";
  Type2["NULL"] = "NULL";
})(Type || (Type = {}));
var HarmCategory;
(function(HarmCategory2) {
  HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
  HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
  HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
  HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
  HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
  HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
  HarmCategory2["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE";
  HarmCategory2["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT";
  HarmCategory2["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT";
  HarmCategory2["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT";
})(HarmCategory || (HarmCategory = {}));
var HarmBlockMethod;
(function(HarmBlockMethod2) {
  HarmBlockMethod2["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED";
  HarmBlockMethod2["SEVERITY"] = "SEVERITY";
  HarmBlockMethod2["PROBABILITY"] = "PROBABILITY";
})(HarmBlockMethod || (HarmBlockMethod = {}));
var HarmBlockThreshold;
(function(HarmBlockThreshold2) {
  HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
  HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE";
  HarmBlockThreshold2["OFF"] = "OFF";
})(HarmBlockThreshold || (HarmBlockThreshold = {}));
var Mode;
(function(Mode2) {
  Mode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  Mode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(Mode || (Mode = {}));
var AuthType;
(function(AuthType2) {
  AuthType2["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED";
  AuthType2["NO_AUTH"] = "NO_AUTH";
  AuthType2["API_KEY_AUTH"] = "API_KEY_AUTH";
  AuthType2["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH";
  AuthType2["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH";
  AuthType2["OAUTH"] = "OAUTH";
  AuthType2["OIDC_AUTH"] = "OIDC_AUTH";
})(AuthType || (AuthType = {}));
var ApiSpec;
(function(ApiSpec2) {
  ApiSpec2["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED";
  ApiSpec2["SIMPLE_SEARCH"] = "SIMPLE_SEARCH";
  ApiSpec2["ELASTIC_SEARCH"] = "ELASTIC_SEARCH";
})(ApiSpec || (ApiSpec = {}));
var UrlRetrievalStatus;
(function(UrlRetrievalStatus2) {
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL";
  UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE";
})(UrlRetrievalStatus || (UrlRetrievalStatus = {}));
var FinishReason;
(function(FinishReason2) {
  FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
  FinishReason2["STOP"] = "STOP";
  FinishReason2["MAX_TOKENS"] = "MAX_TOKENS";
  FinishReason2["SAFETY"] = "SAFETY";
  FinishReason2["RECITATION"] = "RECITATION";
  FinishReason2["LANGUAGE"] = "LANGUAGE";
  FinishReason2["OTHER"] = "OTHER";
  FinishReason2["BLOCKLIST"] = "BLOCKLIST";
  FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  FinishReason2["SPII"] = "SPII";
  FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  FinishReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
  FinishReason2["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL";
})(FinishReason || (FinishReason = {}));
var HarmProbability;
(function(HarmProbability2) {
  HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
  HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE";
  HarmProbability2["LOW"] = "LOW";
  HarmProbability2["MEDIUM"] = "MEDIUM";
  HarmProbability2["HIGH"] = "HIGH";
})(HarmProbability || (HarmProbability = {}));
var HarmSeverity;
(function(HarmSeverity2) {
  HarmSeverity2["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED";
  HarmSeverity2["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE";
  HarmSeverity2["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW";
  HarmSeverity2["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM";
  HarmSeverity2["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH";
})(HarmSeverity || (HarmSeverity = {}));
var BlockedReason;
(function(BlockedReason2) {
  BlockedReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
  BlockedReason2["SAFETY"] = "SAFETY";
  BlockedReason2["OTHER"] = "OTHER";
  BlockedReason2["BLOCKLIST"] = "BLOCKLIST";
  BlockedReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
  BlockedReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY";
})(BlockedReason || (BlockedReason = {}));
var TrafficType;
(function(TrafficType2) {
  TrafficType2["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED";
  TrafficType2["ON_DEMAND"] = "ON_DEMAND";
  TrafficType2["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT";
})(TrafficType || (TrafficType = {}));
var Modality;
(function(Modality2) {
  Modality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  Modality2["TEXT"] = "TEXT";
  Modality2["IMAGE"] = "IMAGE";
  Modality2["AUDIO"] = "AUDIO";
})(Modality || (Modality = {}));
var MediaResolution;
(function(MediaResolution2) {
  MediaResolution2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED";
  MediaResolution2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW";
  MediaResolution2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM";
  MediaResolution2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
})(MediaResolution || (MediaResolution = {}));
var JobState;
(function(JobState2) {
  JobState2["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED";
  JobState2["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED";
  JobState2["JOB_STATE_PENDING"] = "JOB_STATE_PENDING";
  JobState2["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING";
  JobState2["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED";
  JobState2["JOB_STATE_FAILED"] = "JOB_STATE_FAILED";
  JobState2["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING";
  JobState2["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED";
  JobState2["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED";
  JobState2["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED";
  JobState2["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING";
  JobState2["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED";
})(JobState || (JobState = {}));
var TuningMode;
(function(TuningMode2) {
  TuningMode2["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED";
  TuningMode2["TUNING_MODE_FULL"] = "TUNING_MODE_FULL";
  TuningMode2["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER";
})(TuningMode || (TuningMode = {}));
var AdapterSize;
(function(AdapterSize2) {
  AdapterSize2["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED";
  AdapterSize2["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE";
  AdapterSize2["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO";
  AdapterSize2["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR";
  AdapterSize2["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT";
  AdapterSize2["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN";
  AdapterSize2["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO";
})(AdapterSize || (AdapterSize = {}));
var FeatureSelectionPreference;
(function(FeatureSelectionPreference2) {
  FeatureSelectionPreference2["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED";
  FeatureSelectionPreference2["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY";
  FeatureSelectionPreference2["BALANCED"] = "BALANCED";
  FeatureSelectionPreference2["PRIORITIZE_COST"] = "PRIORITIZE_COST";
})(FeatureSelectionPreference || (FeatureSelectionPreference = {}));
var Behavior;
(function(Behavior2) {
  Behavior2["UNSPECIFIED"] = "UNSPECIFIED";
  Behavior2["BLOCKING"] = "BLOCKING";
  Behavior2["NON_BLOCKING"] = "NON_BLOCKING";
})(Behavior || (Behavior = {}));
var DynamicRetrievalConfigMode;
(function(DynamicRetrievalConfigMode2) {
  DynamicRetrievalConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  DynamicRetrievalConfigMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {}));
var Environment;
(function(Environment2) {
  Environment2["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED";
  Environment2["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
})(Environment || (Environment = {}));
var FunctionCallingConfigMode;
(function(FunctionCallingConfigMode2) {
  FunctionCallingConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
  FunctionCallingConfigMode2["AUTO"] = "AUTO";
  FunctionCallingConfigMode2["ANY"] = "ANY";
  FunctionCallingConfigMode2["NONE"] = "NONE";
  FunctionCallingConfigMode2["VALIDATED"] = "VALIDATED";
})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {}));
var SafetyFilterLevel;
(function(SafetyFilterLevel2) {
  SafetyFilterLevel2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
  SafetyFilterLevel2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
  SafetyFilterLevel2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
  SafetyFilterLevel2["BLOCK_NONE"] = "BLOCK_NONE";
})(SafetyFilterLevel || (SafetyFilterLevel = {}));
var PersonGeneration;
(function(PersonGeneration2) {
  PersonGeneration2["DONT_ALLOW"] = "DONT_ALLOW";
  PersonGeneration2["ALLOW_ADULT"] = "ALLOW_ADULT";
  PersonGeneration2["ALLOW_ALL"] = "ALLOW_ALL";
})(PersonGeneration || (PersonGeneration = {}));
var ImagePromptLanguage;
(function(ImagePromptLanguage2) {
  ImagePromptLanguage2["auto"] = "auto";
  ImagePromptLanguage2["en"] = "en";
  ImagePromptLanguage2["ja"] = "ja";
  ImagePromptLanguage2["ko"] = "ko";
  ImagePromptLanguage2["hi"] = "hi";
  ImagePromptLanguage2["zh"] = "zh";
  ImagePromptLanguage2["pt"] = "pt";
  ImagePromptLanguage2["es"] = "es";
})(ImagePromptLanguage || (ImagePromptLanguage = {}));
var MaskReferenceMode;
(function(MaskReferenceMode2) {
  MaskReferenceMode2["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT";
  MaskReferenceMode2["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED";
  MaskReferenceMode2["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND";
  MaskReferenceMode2["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND";
  MaskReferenceMode2["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC";
})(MaskReferenceMode || (MaskReferenceMode = {}));
var ControlReferenceType;
(function(ControlReferenceType2) {
  ControlReferenceType2["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT";
  ControlReferenceType2["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY";
  ControlReferenceType2["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE";
  ControlReferenceType2["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH";
})(ControlReferenceType || (ControlReferenceType = {}));
var SubjectReferenceType;
(function(SubjectReferenceType2) {
  SubjectReferenceType2["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT";
  SubjectReferenceType2["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON";
  SubjectReferenceType2["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL";
  SubjectReferenceType2["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT";
})(SubjectReferenceType || (SubjectReferenceType = {}));
var EditMode;
(function(EditMode2) {
  EditMode2["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT";
  EditMode2["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL";
  EditMode2["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION";
  EditMode2["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT";
  EditMode2["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING";
  EditMode2["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE";
  EditMode2["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP";
  EditMode2["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE";
})(EditMode || (EditMode = {}));
var SegmentMode;
(function(SegmentMode2) {
  SegmentMode2["FOREGROUND"] = "FOREGROUND";
  SegmentMode2["BACKGROUND"] = "BACKGROUND";
  SegmentMode2["PROMPT"] = "PROMPT";
  SegmentMode2["SEMANTIC"] = "SEMANTIC";
  SegmentMode2["INTERACTIVE"] = "INTERACTIVE";
})(SegmentMode || (SegmentMode = {}));
var VideoGenerationReferenceType;
(function(VideoGenerationReferenceType2) {
  VideoGenerationReferenceType2["ASSET"] = "ASSET";
  VideoGenerationReferenceType2["STYLE"] = "STYLE";
})(VideoGenerationReferenceType || (VideoGenerationReferenceType = {}));
var VideoGenerationMaskMode;
(function(VideoGenerationMaskMode2) {
  VideoGenerationMaskMode2["INSERT"] = "INSERT";
  VideoGenerationMaskMode2["REMOVE"] = "REMOVE";
  VideoGenerationMaskMode2["REMOVE_STATIC"] = "REMOVE_STATIC";
  VideoGenerationMaskMode2["OUTPAINT"] = "OUTPAINT";
})(VideoGenerationMaskMode || (VideoGenerationMaskMode = {}));
var VideoCompressionQuality;
(function(VideoCompressionQuality2) {
  VideoCompressionQuality2["OPTIMIZED"] = "OPTIMIZED";
  VideoCompressionQuality2["LOSSLESS"] = "LOSSLESS";
})(VideoCompressionQuality || (VideoCompressionQuality = {}));
var FileState;
(function(FileState2) {
  FileState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED";
  FileState2["PROCESSING"] = "PROCESSING";
  FileState2["ACTIVE"] = "ACTIVE";
  FileState2["FAILED"] = "FAILED";
})(FileState || (FileState = {}));
var FileSource;
(function(FileSource2) {
  FileSource2["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED";
  FileSource2["UPLOADED"] = "UPLOADED";
  FileSource2["GENERATED"] = "GENERATED";
})(FileSource || (FileSource = {}));
var TurnCompleteReason;
(function(TurnCompleteReason2) {
  TurnCompleteReason2["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED";
  TurnCompleteReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
  TurnCompleteReason2["RESPONSE_REJECTED"] = "RESPONSE_REJECTED";
  TurnCompleteReason2["NEED_MORE_INPUT"] = "NEED_MORE_INPUT";
})(TurnCompleteReason || (TurnCompleteReason = {}));
var MediaModality;
(function(MediaModality2) {
  MediaModality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED";
  MediaModality2["TEXT"] = "TEXT";
  MediaModality2["IMAGE"] = "IMAGE";
  MediaModality2["VIDEO"] = "VIDEO";
  MediaModality2["AUDIO"] = "AUDIO";
  MediaModality2["DOCUMENT"] = "DOCUMENT";
})(MediaModality || (MediaModality = {}));
var StartSensitivity;
(function(StartSensitivity2) {
  StartSensitivity2["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED";
  StartSensitivity2["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH";
  StartSensitivity2["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW";
})(StartSensitivity || (StartSensitivity = {}));
var EndSensitivity;
(function(EndSensitivity2) {
  EndSensitivity2["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED";
  EndSensitivity2["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH";
  EndSensitivity2["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW";
})(EndSensitivity || (EndSensitivity = {}));
var ActivityHandling;
(function(ActivityHandling2) {
  ActivityHandling2["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED";
  ActivityHandling2["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS";
  ActivityHandling2["NO_INTERRUPTION"] = "NO_INTERRUPTION";
})(ActivityHandling || (ActivityHandling = {}));
var TurnCoverage;
(function(TurnCoverage2) {
  TurnCoverage2["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED";
  TurnCoverage2["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY";
  TurnCoverage2["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT";
})(TurnCoverage || (TurnCoverage = {}));
var FunctionResponseScheduling;
(function(FunctionResponseScheduling2) {
  FunctionResponseScheduling2["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED";
  FunctionResponseScheduling2["SILENT"] = "SILENT";
  FunctionResponseScheduling2["WHEN_IDLE"] = "WHEN_IDLE";
  FunctionResponseScheduling2["INTERRUPT"] = "INTERRUPT";
})(FunctionResponseScheduling || (FunctionResponseScheduling = {}));
var Scale;
(function(Scale2) {
  Scale2["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED";
  Scale2["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR";
  Scale2["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR";
  Scale2["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR";
  Scale2["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR";
  Scale2["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR";
  Scale2["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR";
  Scale2["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR";
  Scale2["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR";
  Scale2["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR";
  Scale2["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR";
  Scale2["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR";
  Scale2["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR";
})(Scale || (Scale = {}));
var MusicGenerationMode;
(function(MusicGenerationMode2) {
  MusicGenerationMode2["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED";
  MusicGenerationMode2["QUALITY"] = "QUALITY";
  MusicGenerationMode2["DIVERSITY"] = "DIVERSITY";
  MusicGenerationMode2["VOCALIZATION"] = "VOCALIZATION";
})(MusicGenerationMode || (MusicGenerationMode = {}));
var LiveMusicPlaybackControl;
(function(LiveMusicPlaybackControl2) {
  LiveMusicPlaybackControl2["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED";
  LiveMusicPlaybackControl2["PLAY"] = "PLAY";
  LiveMusicPlaybackControl2["PAUSE"] = "PAUSE";
  LiveMusicPlaybackControl2["STOP"] = "STOP";
  LiveMusicPlaybackControl2["RESET_CONTEXT"] = "RESET_CONTEXT";
})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {}));
class HttpResponse {
  constructor(response) {
    const headers = {};
    for (const pair of response.headers.entries()) {
      headers[pair[0]] = pair[1];
    }
    this.headers = headers;
    this.responseInternal = response;
  }
  json() {
    return this.responseInternal.json();
  }
}
class GenerateContentResponse {
  /**
   * Returns the concatenation of all text parts from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the text from the first
   * one will be returned.
   * If there are non-text parts in the response, the concatenation of all text
   * parts will be returned, and a warning will be logged.
   * If there are thought parts in the response, the concatenation of all text
   * parts excluding the thought parts will be returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'Why is the sky blue?',
   * });
   *
   * console.debug(response.text);
   * ```
   */
  get text() {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    if (((_d2 = (_c2 = (_b2 = (_a3 = this.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d2 === void 0 ? void 0 : _d2.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning text from the first one.");
    }
    let text = "";
    let anyTextPartText = false;
    const nonTextParts = [];
    for (const part of (_h2 = (_g2 = (_f2 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f2 === void 0 ? void 0 : _f2.content) === null || _g2 === void 0 ? void 0 : _g2.parts) !== null && _h2 !== void 0 ? _h2 : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "text" && fieldName !== "thought" && (fieldValue !== null || fieldValue !== void 0)) {
          nonTextParts.push(fieldName);
        }
      }
      if (typeof part.text === "string") {
        if (typeof part.thought === "boolean" && part.thought) {
          continue;
        }
        anyTextPartText = true;
        text += part.text;
      }
    }
    if (nonTextParts.length > 0) {
      console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
    }
    return anyTextPartText ? text : void 0;
  }
  /**
   * Returns the concatenation of all inline data parts from the first candidate
   * in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the inline data from the
   * first one will be returned. If there are non-inline data parts in the
   * response, the concatenation of all inline data parts will be returned, and
   * a warning will be logged.
   */
  get data() {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    if (((_d2 = (_c2 = (_b2 = (_a3 = this.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d2 === void 0 ? void 0 : _d2.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning data from the first one.");
    }
    let data2 = "";
    const nonDataParts = [];
    for (const part of (_h2 = (_g2 = (_f2 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f2 === void 0 ? void 0 : _f2.content) === null || _g2 === void 0 ? void 0 : _g2.parts) !== null && _h2 !== void 0 ? _h2 : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "inlineData" && (fieldValue !== null || fieldValue !== void 0)) {
          nonDataParts.push(fieldName);
        }
      }
      if (part.inlineData && typeof part.inlineData.data === "string") {
        data2 += atob(part.inlineData.data);
      }
    }
    if (nonDataParts.length > 0) {
      console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
    }
    return data2.length > 0 ? btoa(data2) : void 0;
  }
  /**
   * Returns the function calls from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the function calls from
   * the first one will be returned.
   * If there are no function calls in the response, undefined will be returned.
   *
   * @example
   * ```ts
   * const controlLightFunctionDeclaration: FunctionDeclaration = {
   *   name: 'controlLight',
   *   parameters: {
   *   type: Type.OBJECT,
   *   description: 'Set the brightness and color temperature of a room light.',
   *   properties: {
   *     brightness: {
   *       type: Type.NUMBER,
   *       description:
   *         'Light level from 0 to 100. Zero is off and 100 is full brightness.',
   *     },
   *     colorTemperature: {
   *       type: Type.STRING,
   *       description:
   *         'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',
   *     },
   *   },
   *   required: ['brightness', 'colorTemperature'],
   *  };
   *  const response = await ai.models.generateContent({
   *     model: 'gemini-2.0-flash',
   *     contents: 'Dim the lights so the room feels cozy and warm.',
   *     config: {
   *       tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],
   *       toolConfig: {
   *         functionCallingConfig: {
   *           mode: FunctionCallingConfigMode.ANY,
   *           allowedFunctionNames: ['controlLight'],
   *         },
   *       },
   *     },
   *   });
   *  console.debug(JSON.stringify(response.functionCalls));
   * ```
   */
  get functionCalls() {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    if (((_d2 = (_c2 = (_b2 = (_a3 = this.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d2 === void 0 ? void 0 : _d2.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning function calls from the first one.");
    }
    const functionCalls = (_h2 = (_g2 = (_f2 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f2 === void 0 ? void 0 : _f2.content) === null || _g2 === void 0 ? void 0 : _g2.parts) === null || _h2 === void 0 ? void 0 : _h2.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall2) => functionCall2 !== void 0);
    if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) {
      return void 0;
    }
    return functionCalls;
  }
  /**
   * Returns the first executable code from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the executable code from
   * the first one will be returned.
   * If there are no executable code in the response, undefined will be
   * returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
   *   config: {
   *     tools: [{codeExecution: {}}],
   *   },
   * });
   *
   * console.debug(response.executableCode);
   * ```
   */
  get executableCode() {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j2;
    if (((_d2 = (_c2 = (_b2 = (_a3 = this.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d2 === void 0 ? void 0 : _d2.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning executable code from the first one.");
    }
    const executableCode = (_h2 = (_g2 = (_f2 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f2 === void 0 ? void 0 : _f2.content) === null || _g2 === void 0 ? void 0 : _g2.parts) === null || _h2 === void 0 ? void 0 : _h2.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode2) => executableCode2 !== void 0);
    if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) {
      return void 0;
    }
    return (_j2 = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j2 === void 0 ? void 0 : _j2.code;
  }
  /**
   * Returns the first code execution result from the first candidate in the response.
   *
   * @remarks
   * If there are multiple candidates in the response, the code execution result from
   * the first one will be returned.
   * If there are no code execution result in the response, undefined will be returned.
   *
   * @example
   * ```ts
   * const response = await ai.models.generateContent({
   *   model: 'gemini-2.0-flash',
   *   contents:
   *     'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'
   *   config: {
   *     tools: [{codeExecution: {}}],
   *   },
   * });
   *
   * console.debug(response.codeExecutionResult);
   * ```
   */
  get codeExecutionResult() {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j2;
    if (((_d2 = (_c2 = (_b2 = (_a3 = this.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content) === null || _c2 === void 0 ? void 0 : _c2.parts) === null || _d2 === void 0 ? void 0 : _d2.length) === 0) {
      return void 0;
    }
    if (this.candidates && this.candidates.length > 1) {
      console.warn("there are multiple candidates in the response, returning code execution result from the first one.");
    }
    const codeExecutionResult = (_h2 = (_g2 = (_f2 = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f2 === void 0 ? void 0 : _f2.content) === null || _g2 === void 0 ? void 0 : _g2.parts) === null || _h2 === void 0 ? void 0 : _h2.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult2) => codeExecutionResult2 !== void 0);
    if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) {
      return void 0;
    }
    return (_j2 = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j2 === void 0 ? void 0 : _j2.output;
  }
}
class EmbedContentResponse {
}
class GenerateImagesResponse {
}
class EditImageResponse {
}
class UpscaleImageResponse {
}
class RecontextImageResponse {
}
class SegmentImageResponse {
}
class ListModelsResponse {
}
class DeleteModelResponse {
}
class CountTokensResponse {
}
class ComputeTokensResponse {
}
class GenerateVideosOperation {
  /**
   * Instantiates an Operation of the same type as the one being called with the fields set from the API response.
   * @internal
   */
  _fromAPIResponse({ apiResponse, isVertexAI }) {
    const operation = new GenerateVideosOperation();
    let response;
    const op = apiResponse;
    if (isVertexAI) {
      response = generateVideosOperationFromVertex$1(op);
    } else {
      response = generateVideosOperationFromMldev$1(op);
    }
    Object.assign(operation, response);
    return operation;
  }
}
class ListTuningJobsResponse {
}
class DeleteCachedContentResponse {
}
class ListCachedContentsResponse {
}
class ListFilesResponse {
}
class CreateFileResponse {
}
class DeleteFileResponse {
}
class ListBatchJobsResponse {
}
class LiveServerMessage {
  /**
   * Returns the concatenation of all text parts from the server content if present.
   *
   * @remarks
   * If there are non-text parts in the response, the concatenation of all text
   * parts will be returned, and a warning will be logged.
   */
  get text() {
    var _a3, _b2, _c2;
    let text = "";
    let anyTextPartFound = false;
    const nonTextParts = [];
    for (const part of (_c2 = (_b2 = (_a3 = this.serverContent) === null || _a3 === void 0 ? void 0 : _a3.modelTurn) === null || _b2 === void 0 ? void 0 : _b2.parts) !== null && _c2 !== void 0 ? _c2 : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "text" && fieldName !== "thought" && fieldValue !== null) {
          nonTextParts.push(fieldName);
        }
      }
      if (typeof part.text === "string") {
        if (typeof part.thought === "boolean" && part.thought) {
          continue;
        }
        anyTextPartFound = true;
        text += part.text;
      }
    }
    if (nonTextParts.length > 0) {
      console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`);
    }
    return anyTextPartFound ? text : void 0;
  }
  /**
   * Returns the concatenation of all inline data parts from the server content if present.
   *
   * @remarks
   * If there are non-inline data parts in the
   * response, the concatenation of all inline data parts will be returned, and
   * a warning will be logged.
   */
  get data() {
    var _a3, _b2, _c2;
    let data2 = "";
    const nonDataParts = [];
    for (const part of (_c2 = (_b2 = (_a3 = this.serverContent) === null || _a3 === void 0 ? void 0 : _a3.modelTurn) === null || _b2 === void 0 ? void 0 : _b2.parts) !== null && _c2 !== void 0 ? _c2 : []) {
      for (const [fieldName, fieldValue] of Object.entries(part)) {
        if (fieldName !== "inlineData" && fieldValue !== null) {
          nonDataParts.push(fieldName);
        }
      }
      if (part.inlineData && typeof part.inlineData.data === "string") {
        data2 += atob(part.inlineData.data);
      }
    }
    if (nonDataParts.length > 0) {
      console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`);
    }
    return data2.length > 0 ? btoa(data2) : void 0;
  }
}
class LiveMusicServerMessage {
  /**
   * Returns the first audio chunk from the server content, if present.
   *
   * @remarks
   * If there are no audio chunks in the response, undefined will be returned.
   */
  get audioChunk() {
    if (this.serverContent && this.serverContent.audioChunks && this.serverContent.audioChunks.length > 0) {
      return this.serverContent.audioChunks[0];
    }
    return void 0;
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function tModel(apiClient, model) {
  if (!model || typeof model !== "string") {
    throw new Error("model is required and must be a string");
  }
  if (apiClient.isVertexAI()) {
    if (model.startsWith("publishers/") || model.startsWith("projects/") || model.startsWith("models/")) {
      return model;
    } else if (model.indexOf("/") >= 0) {
      const parts = model.split("/", 2);
      return `publishers/${parts[0]}/models/${parts[1]}`;
    } else {
      return `publishers/google/models/${model}`;
    }
  } else {
    if (model.startsWith("models/") || model.startsWith("tunedModels/")) {
      return model;
    } else {
      return `models/${model}`;
    }
  }
}
function tCachesModel(apiClient, model) {
  const transformedModel = tModel(apiClient, model);
  if (!transformedModel) {
    return "";
  }
  if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;
  } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) {
    return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;
  } else {
    return transformedModel;
  }
}
function tBlobs(blobs) {
  if (Array.isArray(blobs)) {
    return blobs.map((blob) => tBlob(blob));
  } else {
    return [tBlob(blobs)];
  }
}
function tBlob(blob) {
  if (typeof blob === "object" && blob !== null) {
    return blob;
  }
  throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`);
}
function tImageBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("image/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tAudioBlob(blob) {
  const transformedBlob = tBlob(blob);
  if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("audio/")) {
    return transformedBlob;
  }
  throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`);
}
function tPart(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("PartUnion is required");
  }
  if (typeof origin === "object") {
    return origin;
  }
  if (typeof origin === "string") {
    return { text: origin };
  }
  throw new Error(`Unsupported part type: ${typeof origin}`);
}
function tParts(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("PartListUnion is required");
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tPart(item));
  }
  return [tPart(origin)];
}
function _isContent(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "parts" in origin && Array.isArray(origin.parts);
}
function _isFunctionCallPart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionCall" in origin;
}
function _isFunctionResponsePart(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "functionResponse" in origin;
}
function tContent(origin) {
  if (origin === null || origin === void 0) {
    throw new Error("ContentUnion is required");
  }
  if (_isContent(origin)) {
    return origin;
  }
  return {
    role: "user",
    parts: tParts(origin)
  };
}
function tContentsForEmbed(apiClient, origin) {
  if (!origin) {
    return [];
  }
  if (apiClient.isVertexAI() && Array.isArray(origin)) {
    return origin.flatMap((item) => {
      const content = tContent(item);
      if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
        return [content.parts[0].text];
      }
      return [];
    });
  } else if (apiClient.isVertexAI()) {
    const content = tContent(origin);
    if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) {
      return [content.parts[0].text];
    }
    return [];
  }
  if (Array.isArray(origin)) {
    return origin.map((item) => tContent(item));
  }
  return [tContent(origin)];
}
function tContents(origin) {
  if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) {
    throw new Error("contents are required");
  }
  if (!Array.isArray(origin)) {
    if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");
    }
    return [tContent(origin)];
  }
  const result = [];
  const accumulatedParts = [];
  const isContentArray = _isContent(origin[0]);
  for (const item of origin) {
    const isContent = _isContent(item);
    if (isContent != isContentArray) {
      throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");
    }
    if (isContent) {
      result.push(item);
    } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {
      throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");
    } else {
      accumulatedParts.push(item);
    }
  }
  if (!isContentArray) {
    result.push({ role: "user", parts: tParts(accumulatedParts) });
  }
  return result;
}
function flattenTypeArrayToAnyOf(typeList, resultingSchema) {
  if (typeList.includes("null")) {
    resultingSchema["nullable"] = true;
  }
  const listWithoutNull = typeList.filter((type2) => type2 !== "null");
  if (listWithoutNull.length === 1) {
    resultingSchema["type"] = Object.values(Type).includes(listWithoutNull[0].toUpperCase()) ? listWithoutNull[0].toUpperCase() : Type.TYPE_UNSPECIFIED;
  } else {
    resultingSchema["anyOf"] = [];
    for (const i2 of listWithoutNull) {
      resultingSchema["anyOf"].push({
        "type": Object.values(Type).includes(i2.toUpperCase()) ? i2.toUpperCase() : Type.TYPE_UNSPECIFIED
      });
    }
  }
}
function processJsonSchema(_jsonSchema) {
  const genAISchema = {};
  const schemaFieldNames = ["items"];
  const listSchemaFieldNames = ["anyOf"];
  const dictSchemaFieldNames = ["properties"];
  if (_jsonSchema["type"] && _jsonSchema["anyOf"]) {
    throw new Error("type and anyOf cannot be both populated.");
  }
  const incomingAnyOf = _jsonSchema["anyOf"];
  if (incomingAnyOf != null && incomingAnyOf.length == 2) {
    if (incomingAnyOf[0]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[1];
    } else if (incomingAnyOf[1]["type"] === "null") {
      genAISchema["nullable"] = true;
      _jsonSchema = incomingAnyOf[0];
    }
  }
  if (_jsonSchema["type"] instanceof Array) {
    flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema);
  }
  for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {
    if (fieldValue == null) {
      continue;
    }
    if (fieldName == "type") {
      if (fieldValue === "null") {
        throw new Error("type: null can not be the only possible type for the field.");
      }
      if (fieldValue instanceof Array) {
        continue;
      }
      genAISchema["type"] = Object.values(Type).includes(fieldValue.toUpperCase()) ? fieldValue.toUpperCase() : Type.TYPE_UNSPECIFIED;
    } else if (schemaFieldNames.includes(fieldName)) {
      genAISchema[fieldName] = processJsonSchema(fieldValue);
    } else if (listSchemaFieldNames.includes(fieldName)) {
      const listSchemaFieldValue = [];
      for (const item of fieldValue) {
        if (item["type"] == "null") {
          genAISchema["nullable"] = true;
          continue;
        }
        listSchemaFieldValue.push(processJsonSchema(item));
      }
      genAISchema[fieldName] = listSchemaFieldValue;
    } else if (dictSchemaFieldNames.includes(fieldName)) {
      const dictSchemaFieldValue = {};
      for (const [key2, value] of Object.entries(fieldValue)) {
        dictSchemaFieldValue[key2] = processJsonSchema(value);
      }
      genAISchema[fieldName] = dictSchemaFieldValue;
    } else {
      if (fieldName === "additionalProperties") {
        continue;
      }
      genAISchema[fieldName] = fieldValue;
    }
  }
  return genAISchema;
}
function tSchema(schema) {
  return processJsonSchema(schema);
}
function tSpeechConfig(speechConfig) {
  if (typeof speechConfig === "object") {
    return speechConfig;
  } else if (typeof speechConfig === "string") {
    return {
      voiceConfig: {
        prebuiltVoiceConfig: {
          voiceName: speechConfig
        }
      }
    };
  } else {
    throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);
  }
}
function tLiveSpeechConfig(speechConfig) {
  if ("multiSpeakerVoiceConfig" in speechConfig) {
    throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");
  }
  return speechConfig;
}
function tTool(tool) {
  if (tool.functionDeclarations) {
    for (const functionDeclaration of tool.functionDeclarations) {
      if (functionDeclaration.parameters) {
        if (!Object.keys(functionDeclaration.parameters).includes("$schema")) {
          functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters);
        } else {
          if (!functionDeclaration.parametersJsonSchema) {
            functionDeclaration.parametersJsonSchema = functionDeclaration.parameters;
            delete functionDeclaration.parameters;
          }
        }
      }
      if (functionDeclaration.response) {
        if (!Object.keys(functionDeclaration.response).includes("$schema")) {
          functionDeclaration.response = processJsonSchema(functionDeclaration.response);
        } else {
          if (!functionDeclaration.responseJsonSchema) {
            functionDeclaration.responseJsonSchema = functionDeclaration.response;
            delete functionDeclaration.response;
          }
        }
      }
    }
  }
  return tool;
}
function tTools(tools) {
  if (tools === void 0 || tools === null) {
    throw new Error("tools is required");
  }
  if (!Array.isArray(tools)) {
    throw new Error("tools is required and must be an array of Tools");
  }
  const result = [];
  for (const tool of tools) {
    result.push(tool);
  }
  return result;
}
function resourceName(client2, resourceName2, resourcePrefix, splitsAfterPrefix = 1) {
  const shouldAppendPrefix = !resourceName2.startsWith(`${resourcePrefix}/`) && resourceName2.split("/").length === splitsAfterPrefix;
  if (client2.isVertexAI()) {
    if (resourceName2.startsWith("projects/")) {
      return resourceName2;
    } else if (resourceName2.startsWith("locations/")) {
      return `projects/${client2.getProject()}/${resourceName2}`;
    } else if (resourceName2.startsWith(`${resourcePrefix}/`)) {
      return `projects/${client2.getProject()}/locations/${client2.getLocation()}/${resourceName2}`;
    } else if (shouldAppendPrefix) {
      return `projects/${client2.getProject()}/locations/${client2.getLocation()}/${resourcePrefix}/${resourceName2}`;
    } else {
      return resourceName2;
    }
  }
  if (shouldAppendPrefix) {
    return `${resourcePrefix}/${resourceName2}`;
  }
  return resourceName2;
}
function tCachedContentName(apiClient, name) {
  if (typeof name !== "string") {
    throw new Error("name must be a string");
  }
  return resourceName(apiClient, name, "cachedContents");
}
function tTuningJobStatus(status) {
  switch (status) {
    case "STATE_UNSPECIFIED":
      return "JOB_STATE_UNSPECIFIED";
    case "CREATING":
      return "JOB_STATE_RUNNING";
    case "ACTIVE":
      return "JOB_STATE_SUCCEEDED";
    case "FAILED":
      return "JOB_STATE_FAILED";
    default:
      return status;
  }
}
function tBytes(fromImageBytes) {
  return tBytes$1(fromImageBytes);
}
function _isFile(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "name" in origin;
}
function isGeneratedVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "video" in origin;
}
function isVideo(origin) {
  return origin !== null && origin !== void 0 && typeof origin === "object" && "uri" in origin;
}
function tFileName(fromName) {
  var _a3;
  let name;
  if (_isFile(fromName)) {
    name = fromName.name;
  }
  if (isVideo(fromName)) {
    name = fromName.uri;
    if (name === void 0) {
      return void 0;
    }
  }
  if (isGeneratedVideo(fromName)) {
    name = (_a3 = fromName.video) === null || _a3 === void 0 ? void 0 : _a3.uri;
    if (name === void 0) {
      return void 0;
    }
  }
  if (typeof fromName === "string") {
    name = fromName;
  }
  if (name === void 0) {
    throw new Error("Could not extract file name from the provided input.");
  }
  if (name.startsWith("https://")) {
    const suffix = name.split("files/")[1];
    const match = suffix.match(/[a-z0-9]+/);
    if (match === null) {
      throw new Error(`Could not extract file name from URI ${name}`);
    }
    name = match[0];
  } else if (name.startsWith("files/")) {
    name = name.split("files/")[1];
  }
  return name;
}
function tModelsUrl(apiClient, baseModels) {
  let res;
  if (apiClient.isVertexAI()) {
    res = baseModels ? "publishers/google/models" : "models";
  } else {
    res = baseModels ? "models" : "tunedModels";
  }
  return res;
}
function tExtractModels(response) {
  for (const key2 of ["models", "tunedModels", "publisherModels"]) {
    if (hasField(response, key2)) {
      return response[key2];
    }
  }
  return [];
}
function hasField(data2, fieldName) {
  return data2 !== null && typeof data2 === "object" && fieldName in data2;
}
function mcpToGeminiTool(mcpTool, config = {}) {
  const mcpToolSchema = mcpTool;
  const functionDeclaration = {
    name: mcpToolSchema["name"],
    description: mcpToolSchema["description"],
    parametersJsonSchema: mcpToolSchema["inputSchema"]
  };
  if (mcpToolSchema["outputSchema"]) {
    functionDeclaration["responseJsonSchema"] = mcpToolSchema["outputSchema"];
  }
  if (config.behavior) {
    functionDeclaration["behavior"] = config.behavior;
  }
  const geminiTool = {
    functionDeclarations: [
      functionDeclaration
    ]
  };
  return geminiTool;
}
function mcpToolsToGeminiTool(mcpTools, config = {}) {
  const functionDeclarations = [];
  const toolNames = /* @__PURE__ */ new Set();
  for (const mcpTool of mcpTools) {
    const mcpToolName = mcpTool.name;
    if (toolNames.has(mcpToolName)) {
      throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
    }
    toolNames.add(mcpToolName);
    const geminiTool = mcpToGeminiTool(mcpTool, config);
    if (geminiTool.functionDeclarations) {
      functionDeclarations.push(...geminiTool.functionDeclarations);
    }
  }
  return { functionDeclarations };
}
function tBatchJobSource(client2, src2) {
  let sourceObj;
  if (typeof src2 === "string") {
    if (client2.isVertexAI()) {
      if (src2.startsWith("gs://")) {
        sourceObj = { format: "jsonl", gcsUri: [src2] };
      } else if (src2.startsWith("bq://")) {
        sourceObj = { format: "bigquery", bigqueryUri: src2 };
      } else {
        throw new Error(`Unsupported string source for Vertex AI: ${src2}`);
      }
    } else {
      if (src2.startsWith("files/")) {
        sourceObj = { fileName: src2 };
      } else {
        throw new Error(`Unsupported string source for Gemini API: ${src2}`);
      }
    }
  } else if (Array.isArray(src2)) {
    if (client2.isVertexAI()) {
      throw new Error("InlinedRequest[] is not supported in Vertex AI.");
    }
    sourceObj = { inlinedRequests: src2 };
  } else {
    sourceObj = src2;
  }
  const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(Boolean).length;
  const mldevSourcesCount = [
    sourceObj.inlinedRequests,
    sourceObj.fileName
  ].filter(Boolean).length;
  if (client2.isVertexAI()) {
    if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) {
      throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.");
    }
  } else {
    if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) {
      throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");
    }
  }
  return sourceObj;
}
function tBatchJobDestination(dest) {
  if (typeof dest !== "string") {
    return dest;
  }
  const destString = dest;
  if (destString.startsWith("gs://")) {
    return {
      format: "jsonl",
      gcsUri: destString
    };
  } else if (destString.startsWith("bq://")) {
    return {
      format: "bigquery",
      bigqueryUri: destString
    };
  } else {
    throw new Error(`Unsupported destination: ${destString}`);
  }
}
function tRecvBatchJobDestination(dest) {
  if (typeof dest !== "object" || dest === null) {
    return {};
  }
  const obj = dest;
  const inlineResponsesVal = obj["inlinedResponses"];
  if (typeof inlineResponsesVal !== "object" || inlineResponsesVal === null) {
    return dest;
  }
  const inlineResponsesObj = inlineResponsesVal;
  const responsesArray = inlineResponsesObj["inlinedResponses"];
  if (!Array.isArray(responsesArray) || responsesArray.length === 0) {
    return dest;
  }
  let hasEmbedding = false;
  for (const responseItem of responsesArray) {
    if (typeof responseItem !== "object" || responseItem === null) {
      continue;
    }
    const responseItemObj = responseItem;
    const responseVal = responseItemObj["response"];
    if (typeof responseVal !== "object" || responseVal === null) {
      continue;
    }
    const responseObj = responseVal;
    if (responseObj["embedding"] !== void 0) {
      hasEmbedding = true;
      break;
    }
  }
  if (hasEmbedding) {
    obj["inlinedEmbedContentResponses"] = obj["inlinedResponses"];
    delete obj["inlinedResponses"];
  }
  return dest;
}
function tBatchJobName(apiClient, name) {
  const nameString = name;
  if (!apiClient.isVertexAI()) {
    const mldevPattern = /batches\/[^/]+$/;
    if (mldevPattern.test(nameString)) {
      return nameString.split("/").pop();
    } else {
      throw new Error(`Invalid batch job name: ${nameString}.`);
    }
  }
  const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/;
  if (vertexPattern.test(nameString)) {
    return nameString.split("/").pop();
  } else if (/^\d+$/.test(nameString)) {
    return nameString;
  } else {
    throw new Error(`Invalid batch job name: ${nameString}.`);
  }
}
function tJobState(state) {
  const stateString = state;
  if (stateString === "BATCH_STATE_UNSPECIFIED") {
    return "JOB_STATE_UNSPECIFIED";
  } else if (stateString === "BATCH_STATE_PENDING") {
    return "JOB_STATE_PENDING";
  } else if (stateString === "BATCH_STATE_SUCCEEDED") {
    return "JOB_STATE_SUCCEEDED";
  } else if (stateString === "BATCH_STATE_FAILED") {
    return "JOB_STATE_FAILED";
  } else if (stateString === "BATCH_STATE_CANCELLED") {
    return "JOB_STATE_CANCELLED";
  } else {
    return stateString;
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function videoMetadataToMldev$4(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$4(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$4(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$4(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToMldev$4(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$4(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$4(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$4(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToMldev$1(fromObject2) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject2, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject2, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject2, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject2, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject2, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject2, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject2, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject2, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject2, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject2, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject2, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject2, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject2, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject2, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject2, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject2, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject2, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject2, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject2, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject2, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function safetySettingToMldev$1(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromCategory = getValueByPath(fromObject2, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject2, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToMldev$4(fromObject2) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject2, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$4(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$4(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$4(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$4(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$4(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$4() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$4(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$4(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$4(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$4());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$4(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject2, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev$2(fromObject2) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject2, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject2, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject2, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject2, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$2(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject2, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev$2(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject2, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$3(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject2, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$3(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject2, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject2, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject2, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToMldev$1(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$4(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject2, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject2, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject2, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject2, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject2, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject2, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject2, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToMldev$1(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject2, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject2, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev$1(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$4(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$2(fromToolConfig));
  }
  if (getValueByPath(fromObject2, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject2, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)));
  }
  if (getValueByPath(fromObject2, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject2, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToMldev$1(fromThinkingConfig));
  }
  return toObject;
}
function inlinedRequestToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["request", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$4(item);
      });
    }
    setValueByPath(toObject, ["request", "contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["request", "generationConfig"], generateContentConfigToMldev$1(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function batchJobSourceToMldev(apiClient, fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["format"]) !== void 0) {
    throw new Error("format parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["bigqueryUri"]) !== void 0) {
    throw new Error("bigqueryUri parameter is not supported in Gemini API.");
  }
  const fromFileName = getValueByPath(fromObject2, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject2, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    let transformedList = fromInlinedRequests;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedRequestToMldev(apiClient, item);
      });
    }
    setValueByPath(toObject, ["requests", "requests"], transformedList);
  }
  return toObject;
}
function createBatchJobConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  if (getValueByPath(fromObject2, ["dest"]) !== void 0) {
    throw new Error("dest parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createBatchJobParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject2, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["batch", "inputConfig"], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createBatchJobConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function embedContentConfigToMldev$1(fromObject2, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject2, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["requests[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject2, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality);
  }
  if (getValueByPath(fromObject2, ["mimeType"]) !== void 0) {
    throw new Error("mimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["autoTruncate"]) !== void 0) {
    throw new Error("autoTruncate parameter is not supported in Gemini API.");
  }
  return toObject;
}
function embedContentBatchToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    setValueByPath(toObject, ["requests[]", "request", "content"], tContentsForEmbed(apiClient, fromContents));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], embedContentConfigToMldev$1(fromConfig, toObject));
  }
  return toObject;
}
function embeddingsBatchJobSourceToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject2, ["fileName"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["file_name"], fromFileName);
  }
  const fromInlinedRequests = getValueByPath(fromObject2, [
    "inlinedRequests"
  ]);
  if (fromInlinedRequests != null) {
    setValueByPath(toObject, ["requests"], embedContentBatchToMldev(apiClient, fromInlinedRequests));
  }
  return toObject;
}
function createEmbeddingsBatchJobConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName);
  }
  return toObject;
}
function createEmbeddingsBatchJobParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject2, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["batch", "inputConfig"], embeddingsBatchJobSourceToMldev(apiClient, fromSrc));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getBatchJobParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function cancelBatchJobParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listBatchJobsConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  if (getValueByPath(fromObject2, ["filter"]) !== void 0) {
    throw new Error("filter parameter is not supported in Gemini API.");
  }
  return toObject;
}
function listBatchJobsParametersToMldev(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listBatchJobsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function deleteBatchJobParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function batchJobSourceToVertex(fromObject2) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject2, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["instancesFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject2, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject2, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject2, ["inlinedRequests"]) !== void 0) {
    throw new Error("inlinedRequests parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function batchJobDestinationToVertex(fromObject2) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject2, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["predictionsFormat"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject2, ["bigqueryUri"]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryDestination", "outputUri"], fromBigqueryUri);
  }
  if (getValueByPath(fromObject2, ["fileName"]) !== void 0) {
    throw new Error("fileName parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject2, ["inlinedResponses"]) !== void 0) {
    throw new Error("inlinedResponses parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject2, ["inlinedEmbedContentResponses"]) !== void 0) {
    throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function createBatchJobConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDest = getValueByPath(fromObject2, ["dest"]);
  if (parentObject !== void 0 && fromDest != null) {
    setValueByPath(parentObject, ["outputConfig"], batchJobDestinationToVertex(tBatchJobDestination(fromDest)));
  }
  return toObject;
}
function createBatchJobParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tModel(apiClient, fromModel));
  }
  const fromSrc = getValueByPath(fromObject2, ["src"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["inputConfig"], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createBatchJobConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getBatchJobParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function cancelBatchJobParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listBatchJobsConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject2, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listBatchJobsParametersToVertex(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listBatchJobsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function deleteBatchJobParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function videoMetadataFromMldev$2(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev$2(fromObject2) {
  const toObject = {};
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev$2(fromObject2) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallFromMldev$2(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partFromMldev$2(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallFromMldev$2(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev$2(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromMldev$1(fromObject2) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject2, ["citationSources"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromMldev$2(fromObject2) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject2, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject2, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev$2(fromObject2) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject2, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev$2(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromMldev$1(fromObject2) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject2, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject2, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev$1(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject2, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject2, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev$2(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject2, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject2, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject2, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject2, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject2, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromMldev$1(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject2, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject2, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject2, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function jobErrorFromMldev(fromObject2) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject2, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromCode = getValueByPath(fromObject2, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  const fromMessage = getValueByPath(fromObject2, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  return toObject;
}
function inlinedResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateContentResponseFromMldev$1(fromResponse));
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError));
  }
  return toObject;
}
function contentEmbeddingFromMldev$1(fromObject2) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject2, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  return toObject;
}
function singleEmbedContentResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromEmbedding = getValueByPath(fromObject2, ["embedding"]);
  if (fromEmbedding != null) {
    setValueByPath(toObject, ["embedding"], contentEmbeddingFromMldev$1(fromEmbedding));
  }
  const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function inlinedEmbedContentResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], singleEmbedContentResponseFromMldev(fromResponse));
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError));
  }
  return toObject;
}
function batchJobDestinationFromMldev(fromObject2) {
  const toObject = {};
  const fromFileName = getValueByPath(fromObject2, ["responsesFile"]);
  if (fromFileName != null) {
    setValueByPath(toObject, ["fileName"], fromFileName);
  }
  const fromInlinedResponses = getValueByPath(fromObject2, [
    "inlinedResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedResponses != null) {
    let transformedList = fromInlinedResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedResponseFromMldev(item);
      });
    }
    setValueByPath(toObject, ["inlinedResponses"], transformedList);
  }
  const fromInlinedEmbedContentResponses = getValueByPath(fromObject2, [
    "inlinedEmbedContentResponses",
    "inlinedResponses"
  ]);
  if (fromInlinedEmbedContentResponses != null) {
    let transformedList = fromInlinedEmbedContentResponses;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return inlinedEmbedContentResponseFromMldev(item);
      });
    }
    setValueByPath(toObject, ["inlinedEmbedContentResponses"], transformedList);
  }
  return toObject;
}
function batchJobFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, [
    "metadata",
    "displayName"
  ]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject2, ["metadata", "state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject2, [
    "metadata",
    "createTime"
  ]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromEndTime = getValueByPath(fromObject2, [
    "metadata",
    "endTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, [
    "metadata",
    "updateTime"
  ]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject2, ["metadata", "model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromDest = getValueByPath(fromObject2, ["metadata", "output"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest)));
  }
  return toObject;
}
function listBatchJobsResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject2, ["operations"]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function deleteResourceJobFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError));
  }
  return toObject;
}
function jobErrorFromVertex(fromObject2) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject2, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromCode = getValueByPath(fromObject2, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  const fromMessage = getValueByPath(fromObject2, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  return toObject;
}
function batchJobSourceFromVertex(fromObject2) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject2, ["instancesFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject2, ["gcsSource", "uris"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject2, [
    "bigquerySource",
    "inputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobDestinationFromVertex(fromObject2) {
  const toObject = {};
  const fromFormat = getValueByPath(fromObject2, ["predictionsFormat"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromGcsUri = getValueByPath(fromObject2, [
    "gcsDestination",
    "outputUriPrefix"
  ]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromBigqueryUri = getValueByPath(fromObject2, [
    "bigqueryDestination",
    "outputUri"
  ]);
  if (fromBigqueryUri != null) {
    setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri);
  }
  return toObject;
}
function batchJobFromVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromState = getValueByPath(fromObject2, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tJobState(fromState));
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError));
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromSrc = getValueByPath(fromObject2, ["inputConfig"]);
  if (fromSrc != null) {
    setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc));
  }
  const fromDest = getValueByPath(fromObject2, ["outputConfig"]);
  if (fromDest != null) {
    setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest)));
  }
  return toObject;
}
function listBatchJobsResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromBatchJobs = getValueByPath(fromObject2, [
    "batchPredictionJobs"
  ]);
  if (fromBatchJobs != null) {
    let transformedList = fromBatchJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return batchJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["batchJobs"], transformedList);
  }
  return toObject;
}
function deleteResourceJobFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError));
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
var PagedItem;
(function(PagedItem2) {
  PagedItem2["PAGED_ITEM_BATCH_JOBS"] = "batchJobs";
  PagedItem2["PAGED_ITEM_MODELS"] = "models";
  PagedItem2["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs";
  PagedItem2["PAGED_ITEM_FILES"] = "files";
  PagedItem2["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents";
})(PagedItem || (PagedItem = {}));
class Pager {
  constructor(name, request, response, params) {
    this.pageInternal = [];
    this.paramsInternal = {};
    this.requestInternal = request;
    this.init(name, response, params);
  }
  init(name, response, params) {
    var _a3, _b2;
    this.nameInternal = name;
    this.pageInternal = response[this.nameInternal] || [];
    this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse;
    this.idxInternal = 0;
    let requestParams = { config: {} };
    if (!params || Object.keys(params).length === 0) {
      requestParams = { config: {} };
    } else if (typeof params === "object") {
      requestParams = Object.assign({}, params);
    } else {
      requestParams = params;
    }
    if (requestParams["config"]) {
      requestParams["config"]["pageToken"] = response["nextPageToken"];
    }
    this.paramsInternal = requestParams;
    this.pageInternalSize = (_b2 = (_a3 = requestParams["config"]) === null || _a3 === void 0 ? void 0 : _a3["pageSize"]) !== null && _b2 !== void 0 ? _b2 : this.pageInternal.length;
  }
  initNextPage(response) {
    this.init(this.nameInternal, response, this.paramsInternal);
  }
  /**
   * Returns the current page, which is a list of items.
   *
   * @remarks
   * The first page is retrieved when the pager is created. The returned list of
   * items could be a subset of the entire list.
   */
  get page() {
    return this.pageInternal;
  }
  /**
   * Returns the type of paged item (for example, ``batch_jobs``).
   */
  get name() {
    return this.nameInternal;
  }
  /**
   * Returns the length of the page fetched each time by this pager.
   *
   * @remarks
   * The number of items in the page is less than or equal to the page length.
   */
  get pageSize() {
    return this.pageInternalSize;
  }
  /**
   * Returns the headers of the API response.
   */
  get sdkHttpResponse() {
    return this.sdkHttpResponseInternal;
  }
  /**
   * Returns the parameters when making the API request for the next page.
   *
   * @remarks
   * Parameters contain a set of optional configs that can be
   * used to customize the API request. For example, the `pageToken` parameter
   * contains the token to request the next page.
   */
  get params() {
    return this.paramsInternal;
  }
  /**
   * Returns the total number of items in the current page.
   */
  get pageLength() {
    return this.pageInternal.length;
  }
  /**
   * Returns the item at the given index.
   */
  getItem(index2) {
    return this.pageInternal[index2];
  }
  /**
   * Returns an async iterator that support iterating through all items
   * retrieved from the API.
   *
   * @remarks
   * The iterator will automatically fetch the next page if there are more items
   * to fetch from the API.
   *
   * @example
   *
   * ```ts
   * const pager = await ai.files.list({config: {pageSize: 10}});
   * for await (const file of pager) {
   *   console.log(file.name);
   * }
   * ```
   */
  [Symbol.asyncIterator]() {
    return {
      next: async () => {
        if (this.idxInternal >= this.pageLength) {
          if (this.hasNextPage()) {
            await this.nextPage();
          } else {
            return { value: void 0, done: true };
          }
        }
        const item = this.getItem(this.idxInternal);
        this.idxInternal += 1;
        return { value: item, done: false };
      },
      return: async () => {
        return { value: void 0, done: true };
      }
    };
  }
  /**
   * Fetches the next page of items. This makes a new API request.
   *
   * @throws {Error} If there are no more pages to fetch.
   *
   * @example
   *
   * ```ts
   * const pager = await ai.files.list({config: {pageSize: 10}});
   * let page = pager.page;
   * while (true) {
   *   for (const file of page) {
   *     console.log(file.name);
   *   }
   *   if (!pager.hasNextPage()) {
   *     break;
   *   }
   *   page = await pager.nextPage();
   * }
   * ```
   */
  async nextPage() {
    if (!this.hasNextPage()) {
      throw new Error("No more pages to fetch.");
    }
    const response = await this.requestInternal(this.params);
    this.initNextPage(response);
    return this.page;
  }
  /**
   * Returns true if there are more pages to fetch from the API.
   */
  hasNextPage() {
    var _a3;
    if (((_a3 = this.params["config"]) === null || _a3 === void 0 ? void 0 : _a3["pageToken"]) !== void 0) {
      return true;
    }
    return false;
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Batches extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.create = async (params) => {
      var _a3, _b2;
      if (this.apiClient.isVertexAI()) {
        params.config = this.formatDestination(params.src, params.config);
        return this.createInternal(params);
      }
      const src2 = params.src;
      const is_inlined = Array.isArray(params.src) || src2.inlinedRequests !== void 0;
      if (!is_inlined) {
        return this.createInternal(params);
      }
      const result = this.createInlinedGenerateContentRequest(params);
      const path = result.path;
      const requestBody = result.body;
      const queryParams = createBatchJobParametersToMldev(this.apiClient, params)["_query"] || {};
      const response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(requestBody),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    };
    this.createEmbeddings = async (params) => {
      var _a3, _b2;
      console.warn("batches.createEmbeddings() is experimental and may change without notice.");
      if (this.apiClient.isVertexAI()) {
        throw new Error("Vertex AI does not support batches.createEmbeddings.");
      }
      const src2 = params.src;
      const is_inlined = src2.inlinedRequests !== void 0;
      if (!is_inlined) {
        return this.createEmbeddingsInternal(params);
      }
      const result = this.createInlinedEmbedContentRequest(params);
      const path = result.path;
      const requestBody = result.body;
      const queryParams = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params)["_query"] || {};
      const response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(requestBody),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    };
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  // Helper function to handle inlined generate content requests
  createInlinedGenerateContentRequest(params) {
    const body = createBatchJobParametersToMldev(
      this.apiClient,
      // Use instance apiClient
      params
    );
    const urlParams = body["_url"];
    const path = formatMap("{model}:batchGenerateContent", urlParams);
    const batch = body["batch"];
    const inputConfig = batch["inputConfig"];
    const requestsWrapper = inputConfig["requests"];
    const requests = requestsWrapper["requests"];
    const newRequests = [];
    for (const request of requests) {
      const requestDict = Object.assign({}, request);
      if (requestDict["systemInstruction"]) {
        const systemInstructionValue = requestDict["systemInstruction"];
        delete requestDict["systemInstruction"];
        const requestContent = requestDict["request"];
        requestContent["systemInstruction"] = systemInstructionValue;
        requestDict["request"] = requestContent;
      }
      newRequests.push(requestDict);
    }
    requestsWrapper["requests"] = newRequests;
    delete body["config"];
    delete body["_url"];
    delete body["_query"];
    return { path, body };
  }
  // Helper function to handle inlined embedding requests
  createInlinedEmbedContentRequest(params) {
    const body = createEmbeddingsBatchJobParametersToMldev(
      this.apiClient,
      // Use instance apiClient
      params
    );
    const urlParams = body["_url"];
    const path = formatMap("{model}:asyncBatchEmbedContent", urlParams);
    const batch = body["batch"];
    const inputConfig = batch["inputConfig"];
    const requestsWrapper = inputConfig["requests"];
    const requests = requestsWrapper["requests"];
    const newRequests = [];
    delete requestsWrapper["config"];
    for (const request of requests) {
      const requestDict = Object.assign({}, request);
      const innerRequest = requestDict["request"];
      for (const key2 in requestDict) {
        if (key2 !== "request") {
          innerRequest[key2] = requestDict[key2];
          delete requestDict[key2];
        }
      }
      newRequests.push(requestDict);
    }
    requestsWrapper["requests"] = newRequests;
    delete body["config"];
    delete body["_url"];
    delete body["_query"];
    return { path, body };
  }
  // Helper function to get the first GCS URI
  getGcsUri(src2) {
    if (typeof src2 === "string") {
      return src2.startsWith("gs://") ? src2 : void 0;
    }
    if (!Array.isArray(src2) && src2.gcsUri && src2.gcsUri.length > 0) {
      return src2.gcsUri[0];
    }
    return void 0;
  }
  // Helper function to get the BigQuery URI
  getBigqueryUri(src2) {
    if (typeof src2 === "string") {
      return src2.startsWith("bq://") ? src2 : void 0;
    }
    if (!Array.isArray(src2)) {
      return src2.bigqueryUri;
    }
    return void 0;
  }
  // Function to format the destination configuration for Vertex AI
  formatDestination(src2, config) {
    const newConfig = config ? Object.assign({}, config) : {};
    const timestampStr = Date.now().toString();
    if (!newConfig.displayName) {
      newConfig.displayName = `genaiBatchJob_${timestampStr}`;
    }
    if (newConfig.dest === void 0) {
      const gcsUri = this.getGcsUri(src2);
      const bigqueryUri = this.getBigqueryUri(src2);
      if (gcsUri) {
        if (gcsUri.endsWith(".jsonl")) {
          newConfig.dest = `${gcsUri.slice(0, -6)}/dest`;
        } else {
          newConfig.dest = `${gcsUri}_dest_${timestampStr}`;
        }
      } else if (bigqueryUri) {
        newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`;
      } else {
        throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.");
      }
    }
    return newConfig;
  }
  /**
   * Internal method to create batch job.
   *
   * @param params - The parameters for create batch job request.
   * @return The created batch job.
   *
   */
  async createInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createBatchJobParametersToVertex(this.apiClient, params);
      path = formatMap("batchPredictionJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = createBatchJobParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:batchGenerateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Internal method to create batch job.
   *
   * @param params - The parameters for create batch job request.
   * @return The created batch job.
   *
   */
  async createEmbeddingsInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:asyncBatchEmbedContent", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Gets batch job configurations.
   *
   * @param params - The parameters for the get request.
   * @return The batch job.
   *
   * @example
   * ```ts
   * await ai.batches.get({name: '...'}); // The server-generated resource name.
   * ```
   */
  async get(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getBatchJobParametersToVertex(this.apiClient, params);
      path = formatMap("batchPredictionJobs/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getBatchJobParametersToMldev(this.apiClient, params);
      path = formatMap("batches/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = batchJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Cancels a batch job.
   *
   * @param params - The parameters for the cancel request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.batches.cancel({name: '...'}); // The server-generated resource name.
   * ```
   */
  async cancel(params) {
    var _a3, _b2, _c2, _d2;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = cancelBatchJobParametersToVertex(this.apiClient, params);
      path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      });
    } else {
      const body = cancelBatchJobParametersToMldev(this.apiClient, params);
      path = formatMap("batches/{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      });
    }
  }
  async listInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listBatchJobsParametersToVertex(params);
      path = formatMap("batchPredictionJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listBatchJobsResponseFromVertex(apiResponse);
        const typedResp = new ListBatchJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listBatchJobsParametersToMldev(params);
      path = formatMap("batches", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listBatchJobsResponseFromMldev(apiResponse);
        const typedResp = new ListBatchJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Deletes a batch job.
   *
   * @param params - The parameters for the delete request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.batches.delete({name: '...'}); // The server-generated resource name.
   * ```
   */
  async delete(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteBatchJobParametersToVertex(this.apiClient, params);
      path = formatMap("batchPredictionJobs/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteResourceJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = deleteBatchJobParametersToMldev(this.apiClient, params);
      path = formatMap("batches/{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteResourceJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function videoMetadataToMldev$3(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$3(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$3(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$3(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToMldev$3(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$3(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$3(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$3(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev$3(fromObject2) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject2, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$3(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$3(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$3(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$3(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$3(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$3() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$3(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$3(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$3(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$3(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$3());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$3(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject2, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev$1(fromObject2) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject2, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject2, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject2, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject2, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$1(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject2, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev$1(fromRetrievalConfig));
  }
  return toObject;
}
function createCachedContentConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject2, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$3(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$3(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$1(fromToolConfig));
  }
  if (getValueByPath(fromObject2, ["kmsKeyName"]) !== void 0) {
    throw new Error("kmsKeyName parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createCachedContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createCachedContentConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getCachedContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteCachedContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function updateCachedContentConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject2, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateCachedContentConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function listCachedContentsConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsParametersToMldev(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listCachedContentsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataToVertex$2(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex$2(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex$2(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToVertex$2(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToVertex$2(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToVertex$2(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex$2(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToVertex$2(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex$2(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex$2(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex$2(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex$2(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex$2(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex$2(fromObject2) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex$2(fromObject2) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject2, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex$2(fromObject2) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject2, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex$2(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject2, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject2, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject2, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject2, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject2, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex$2(fromObject2) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex$2(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex$2() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex$2(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex$2(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$2(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex$2(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject2, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex$2(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex$2(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex$2());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex$2(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject2, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToVertex$1(fromObject2) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject2, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject2, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject2, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject2, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToVertex$1(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject2, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToVertex$1(fromRetrievalConfig));
  }
  return toObject;
}
function createCachedContentConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject2, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (parentObject !== void 0 && fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex$2(item);
      });
    }
    setValueByPath(parentObject, ["contents"], transformedList);
  }
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex$2(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$2(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToVertex$1(fromToolConfig));
  }
  const fromKmsKeyName = getValueByPath(fromObject2, ["kmsKeyName"]);
  if (parentObject !== void 0 && fromKmsKeyName != null) {
    setValueByPath(parentObject, ["encryption_spec", "kmsKeyName"], fromKmsKeyName);
  }
  return toObject;
}
function createCachedContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createCachedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getCachedContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteCachedContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function updateCachedContentConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromTtl = getValueByPath(fromObject2, ["ttl"]);
  if (parentObject !== void 0 && fromTtl != null) {
    setValueByPath(parentObject, ["ttl"], fromTtl);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  return toObject;
}
function updateCachedContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateCachedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function listCachedContentsConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listCachedContentsParametersToVertex(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listCachedContentsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function cachedContentFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (fromExpireTime != null) {
    setValueByPath(toObject, ["expireTime"], fromExpireTime);
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function deleteCachedContentResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function listCachedContentsResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject2, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return cachedContentFromMldev(item);
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
function cachedContentFromVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (fromExpireTime != null) {
    setValueByPath(toObject, ["expireTime"], fromExpireTime);
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function deleteCachedContentResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function listCachedContentsResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromCachedContents = getValueByPath(fromObject2, [
    "cachedContents"
  ]);
  if (fromCachedContents != null) {
    let transformedList = fromCachedContents;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return cachedContentFromVertex(item);
      });
    }
    setValueByPath(toObject, ["cachedContents"], transformedList);
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Caches extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  /**
   * Creates a cached contents resource.
   *
   * @remarks
   * Context caching is only supported for specific models. See [Gemini
   * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)
   * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)
   * for more information.
   *
   * @param params - The parameters for the create request.
   * @return The created cached content.
   *
   * @example
   * ```ts
   * const contents = ...; // Initialize the content to cache.
   * const response = await ai.caches.create({
   *   model: 'gemini-2.0-flash-001',
   *   config: {
   *    'contents': contents,
   *    'displayName': 'test cache',
   *    'systemInstruction': 'What is the sum of the two pdfs?',
   *    'ttl': '86400s',
   *  }
   * });
   * ```
   */
  async create(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createCachedContentParametersToVertex(this.apiClient, params);
      path = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = createCachedContentParametersToMldev(this.apiClient, params);
      path = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Gets cached content configurations.
   *
   * @param params - The parameters for the get request.
   * @return The cached content.
   *
   * @example
   * ```ts
   * await ai.caches.get({name: '...'}); // The server-generated resource name.
   * ```
   */
  async get(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getCachedContentParametersToVertex(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getCachedContentParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Deletes cached content.
   *
   * @param params - The parameters for the delete request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.caches.delete({name: '...'}); // The server-generated resource name.
   * ```
   */
  async delete(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteCachedContentParametersToVertex(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteCachedContentResponseFromVertex(apiResponse);
        const typedResp = new DeleteCachedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = deleteCachedContentParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteCachedContentResponseFromMldev(apiResponse);
        const typedResp = new DeleteCachedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Updates cached content configurations.
   *
   * @param params - The parameters for the update request.
   * @return The updated cached content.
   *
   * @example
   * ```ts
   * const response = await ai.caches.update({
   *   name: '...',  // The server-generated resource name.
   *   config: {'ttl': '7600s'}
   * });
   * ```
   */
  async update(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = updateCachedContentParametersToVertex(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = updateCachedContentParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = cachedContentFromMldev(apiResponse);
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listCachedContentsParametersToVertex(params);
      path = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listCachedContentsResponseFromVertex(apiResponse);
        const typedResp = new ListCachedContentsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listCachedContentsParametersToMldev(params);
      path = formatMap("cachedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listCachedContentsResponseFromMldev(apiResponse);
        const typedResp = new ListCachedContentsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
}
function __values(o2) {
  var s2 = typeof Symbol === "function" && Symbol.iterator, m = s2 && o2[s2], i2 = 0;
  if (m) return m.call(o2);
  if (o2 && typeof o2.length === "number") return {
    next: function() {
      if (o2 && i2 >= o2.length) o2 = void 0;
      return { value: o2 && o2[i2++], done: !o2 };
    }
  };
  throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __await(v2) {
  return this instanceof __await ? (this.v = v2, this) : new __await(v2);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i2, q = [];
  return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2;
  function awaitReturn(f2) {
    return function(v2) {
      return Promise.resolve(v2).then(f2, reject2);
    };
  }
  function verb(n2, f2) {
    if (g[n2]) {
      i2[n2] = function(v2) {
        return new Promise(function(a2, b2) {
          q.push([n2, v2, a2, b2]) > 1 || resume(n2, v2);
        });
      };
      if (f2) i2[n2] = f2(i2[n2]);
    }
  }
  function resume(n2, v2) {
    try {
      step(g[n2](v2));
    } catch (e4) {
      settle2(q[0][3], e4);
    }
  }
  function step(r2) {
    r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject2) : settle2(q[0][2], r2);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject2(value) {
    resume("throw", value);
  }
  function settle2(f2, v2) {
    if (f2(v2), q.shift(), q.length) resume(q[0][0], q[0][1]);
  }
}
function __asyncValues(o2) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o2[Symbol.asyncIterator], i2;
  return m ? m.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() {
    return this;
  }, i2);
  function verb(n2) {
    i2[n2] = o2[n2] && function(v2) {
      return new Promise(function(resolve2, reject2) {
        v2 = o2[n2](v2), settle2(resolve2, reject2, v2.done, v2.value);
      });
    };
  }
  function settle2(resolve2, reject2, d, v2) {
    Promise.resolve(v2).then(function(v3) {
      resolve2({ value: v3, done: d });
    }, reject2);
  }
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e4 = new Error(message);
  return e4.name = "SuppressedError", e4.error = error, e4.suppressed = suppressed, e4;
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function isValidResponse(response) {
  var _a3;
  if (response.candidates == void 0 || response.candidates.length === 0) {
    return false;
  }
  const content = (_a3 = response.candidates[0]) === null || _a3 === void 0 ? void 0 : _a3.content;
  if (content === void 0) {
    return false;
  }
  return isValidContent(content);
}
function isValidContent(content) {
  if (content.parts === void 0 || content.parts.length === 0) {
    return false;
  }
  for (const part of content.parts) {
    if (part === void 0 || Object.keys(part).length === 0) {
      return false;
    }
  }
  return true;
}
function validateHistory(history) {
  if (history.length === 0) {
    return;
  }
  for (const content of history) {
    if (content.role !== "user" && content.role !== "model") {
      throw new Error(`Role must be user or model, but got ${content.role}.`);
    }
  }
}
function extractCuratedHistory(comprehensiveHistory) {
  if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) {
    return [];
  }
  const curatedHistory = [];
  const length = comprehensiveHistory.length;
  let i2 = 0;
  while (i2 < length) {
    if (comprehensiveHistory[i2].role === "user") {
      curatedHistory.push(comprehensiveHistory[i2]);
      i2++;
    } else {
      const modelOutput = [];
      let isValid2 = true;
      while (i2 < length && comprehensiveHistory[i2].role === "model") {
        modelOutput.push(comprehensiveHistory[i2]);
        if (isValid2 && !isValidContent(comprehensiveHistory[i2])) {
          isValid2 = false;
        }
        i2++;
      }
      if (isValid2) {
        curatedHistory.push(...modelOutput);
      } else {
        curatedHistory.pop();
      }
    }
  }
  return curatedHistory;
}
class Chats {
  constructor(modelsModule, apiClient) {
    this.modelsModule = modelsModule;
    this.apiClient = apiClient;
  }
  /**
   * Creates a new chat session.
   *
   * @remarks
   * The config in the params will be used for all requests within the chat
   * session unless overridden by a per-request `config` in
   * @see {@link types.SendMessageParameters#config}.
   *
   * @param params - Parameters for creating a chat session.
   * @returns A new chat session.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({
   *   model: 'gemini-2.0-flash'
   *   config: {
   *     temperature: 0.5,
   *     maxOutputTokens: 1024,
   *   }
   * });
   * ```
   */
  create(params) {
    return new Chat(
      this.apiClient,
      this.modelsModule,
      params.model,
      params.config,
      // Deep copy the history to avoid mutating the history outside of the
      // chat session.
      structuredClone(params.history)
    );
  }
}
class Chat {
  constructor(apiClient, modelsModule, model, config = {}, history = []) {
    this.apiClient = apiClient;
    this.modelsModule = modelsModule;
    this.model = model;
    this.config = config;
    this.history = history;
    this.sendPromise = Promise.resolve();
    validateHistory(history);
  }
  /**
   * Sends a message to the model and returns the response.
   *
   * @remarks
   * This method will wait for the previous message to be processed before
   * sending the next message.
   *
   * @see {@link Chat#sendMessageStream} for streaming method.
   * @param params - parameters for sending messages within a chat session.
   * @returns The model's response.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
   * const response = await chat.sendMessage({
   *   message: 'Why is the sky blue?'
   * });
   * console.log(response.text);
   * ```
   */
  async sendMessage(params) {
    var _a3;
    await this.sendPromise;
    const inputContent = tContent(params.message);
    const responsePromise = this.modelsModule.generateContent({
      model: this.model,
      contents: this.getHistory(true).concat(inputContent),
      config: (_a3 = params.config) !== null && _a3 !== void 0 ? _a3 : this.config
    });
    this.sendPromise = (async () => {
      var _a4, _b2, _c2;
      const response = await responsePromise;
      const outputContent = (_b2 = (_a4 = response.candidates) === null || _a4 === void 0 ? void 0 : _a4[0]) === null || _b2 === void 0 ? void 0 : _b2.content;
      const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory;
      const index2 = this.getHistory(true).length;
      let automaticFunctionCallingHistory = [];
      if (fullAutomaticFunctionCallingHistory != null) {
        automaticFunctionCallingHistory = (_c2 = fullAutomaticFunctionCallingHistory.slice(index2)) !== null && _c2 !== void 0 ? _c2 : [];
      }
      const modelOutput = outputContent ? [outputContent] : [];
      this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory);
      return;
    })();
    await this.sendPromise.catch(() => {
      this.sendPromise = Promise.resolve();
    });
    return responsePromise;
  }
  /**
   * Sends a message to the model and returns the response in chunks.
   *
   * @remarks
   * This method will wait for the previous message to be processed before
   * sending the next message.
   *
   * @see {@link Chat#sendMessage} for non-streaming method.
   * @param params - parameters for sending the message.
   * @return The model's response.
   *
   * @example
   * ```ts
   * const chat = ai.chats.create({model: 'gemini-2.0-flash'});
   * const response = await chat.sendMessageStream({
   *   message: 'Why is the sky blue?'
   * });
   * for await (const chunk of response) {
   *   console.log(chunk.text);
   * }
   * ```
   */
  async sendMessageStream(params) {
    var _a3;
    await this.sendPromise;
    const inputContent = tContent(params.message);
    const streamResponse = this.modelsModule.generateContentStream({
      model: this.model,
      contents: this.getHistory(true).concat(inputContent),
      config: (_a3 = params.config) !== null && _a3 !== void 0 ? _a3 : this.config
    });
    this.sendPromise = streamResponse.then(() => void 0).catch(() => void 0);
    const response = await streamResponse;
    const result = this.processStreamResponse(response, inputContent);
    return result;
  }
  /**
   * Returns the chat history.
   *
   * @remarks
   * The history is a list of contents alternating between user and model.
   *
   * There are two types of history:
   * - The `curated history` contains only the valid turns between user and
   * model, which will be included in the subsequent requests sent to the model.
   * - The `comprehensive history` contains all turns, including invalid or
   *   empty model outputs, providing a complete record of the history.
   *
   * The history is updated after receiving the response from the model,
   * for streaming response, it means receiving the last chunk of the response.
   *
   * The `comprehensive history` is returned by default. To get the `curated
   * history`, set the `curated` parameter to `true`.
   *
   * @param curated - whether to return the curated history or the comprehensive
   *     history.
   * @return History contents alternating between user and model for the entire
   *     chat session.
   */
  getHistory(curated = false) {
    const history = curated ? extractCuratedHistory(this.history) : this.history;
    return structuredClone(history);
  }
  processStreamResponse(streamResponse, inputContent) {
    var _a3, _b2;
    return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
      var _c2, e_1, _d2, _e2;
      const outputContent = [];
      try {
        for (var _f2 = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _c2 = streamResponse_1_1.done, !_c2; _f2 = true) {
          _e2 = streamResponse_1_1.value;
          _f2 = false;
          const chunk = _e2;
          if (isValidResponse(chunk)) {
            const content = (_b2 = (_a3 = chunk.candidates) === null || _a3 === void 0 ? void 0 : _a3[0]) === null || _b2 === void 0 ? void 0 : _b2.content;
            if (content !== void 0) {
              outputContent.push(content);
            }
          }
          yield yield __await(chunk);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_f2 && !_c2 && (_d2 = streamResponse_1.return)) yield __await(_d2.call(streamResponse_1));
        } finally {
          if (e_1) throw e_1.error;
        }
      }
      this.recordHistory(inputContent, outputContent);
    });
  }
  recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) {
    let outputContents = [];
    if (modelOutput.length > 0 && modelOutput.every((content) => content.role !== void 0)) {
      outputContents = modelOutput;
    } else {
      outputContents.push({
        role: "model",
        parts: []
      });
    }
    if (automaticFunctionCallingHistory && automaticFunctionCallingHistory.length > 0) {
      this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory));
    } else {
      this.history.push(userInput);
    }
    this.history.push(...outputContents);
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class ApiError extends Error {
  constructor(options2) {
    super(options2.message);
    this.name = "ApiError";
    this.status = options2.status;
    Object.setPrototypeOf(this, ApiError.prototype);
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function listFilesConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  return toObject;
}
function listFilesParametersToMldev(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listFilesConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function fileStatusToMldev(fromObject2) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject2, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromMessage = getValueByPath(fromObject2, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  const fromCode = getValueByPath(fromObject2, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  return toObject;
}
function fileToMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSizeBytes = getValueByPath(fromObject2, ["sizeBytes"]);
  if (fromSizeBytes != null) {
    setValueByPath(toObject, ["sizeBytes"], fromSizeBytes);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromExpirationTime = getValueByPath(fromObject2, [
    "expirationTime"
  ]);
  if (fromExpirationTime != null) {
    setValueByPath(toObject, ["expirationTime"], fromExpirationTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromSha256Hash = getValueByPath(fromObject2, ["sha256Hash"]);
  if (fromSha256Hash != null) {
    setValueByPath(toObject, ["sha256Hash"], fromSha256Hash);
  }
  const fromUri = getValueByPath(fromObject2, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromDownloadUri = getValueByPath(fromObject2, ["downloadUri"]);
  if (fromDownloadUri != null) {
    setValueByPath(toObject, ["downloadUri"], fromDownloadUri);
  }
  const fromState = getValueByPath(fromObject2, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], fromState);
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["source"], fromSource);
  }
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fileStatusToMldev(fromError));
  }
  return toObject;
}
function createFileParametersToMldev(fromObject2) {
  const toObject = {};
  const fromFile = getValueByPath(fromObject2, ["file"]);
  if (fromFile != null) {
    setValueByPath(toObject, ["file"], fileToMldev(fromFile));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function getFileParametersToMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function deleteFileParametersToMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "file"], tFileName(fromName));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function fileStatusFromMldev(fromObject2) {
  const toObject = {};
  const fromDetails = getValueByPath(fromObject2, ["details"]);
  if (fromDetails != null) {
    setValueByPath(toObject, ["details"], fromDetails);
  }
  const fromMessage = getValueByPath(fromObject2, ["message"]);
  if (fromMessage != null) {
    setValueByPath(toObject, ["message"], fromMessage);
  }
  const fromCode = getValueByPath(fromObject2, ["code"]);
  if (fromCode != null) {
    setValueByPath(toObject, ["code"], fromCode);
  }
  return toObject;
}
function fileFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSizeBytes = getValueByPath(fromObject2, ["sizeBytes"]);
  if (fromSizeBytes != null) {
    setValueByPath(toObject, ["sizeBytes"], fromSizeBytes);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromExpirationTime = getValueByPath(fromObject2, [
    "expirationTime"
  ]);
  if (fromExpirationTime != null) {
    setValueByPath(toObject, ["expirationTime"], fromExpirationTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromSha256Hash = getValueByPath(fromObject2, ["sha256Hash"]);
  if (fromSha256Hash != null) {
    setValueByPath(toObject, ["sha256Hash"], fromSha256Hash);
  }
  const fromUri = getValueByPath(fromObject2, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromDownloadUri = getValueByPath(fromObject2, ["downloadUri"]);
  if (fromDownloadUri != null) {
    setValueByPath(toObject, ["downloadUri"], fromDownloadUri);
  }
  const fromState = getValueByPath(fromObject2, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], fromState);
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["source"], fromSource);
  }
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError));
  }
  return toObject;
}
function listFilesResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromFiles = getValueByPath(fromObject2, ["files"]);
  if (fromFiles != null) {
    let transformedList = fromFiles;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return fileFromMldev(item);
      });
    }
    setValueByPath(toObject, ["files"], transformedList);
  }
  return toObject;
}
function createFileResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function deleteFileResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Files extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_FILES, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
  }
  /**
   * Uploads a file asynchronously to the Gemini API.
   * This method is not available in Vertex AI.
   * Supported upload sources:
   * - Node.js: File path (string) or Blob object.
   * - Browser: Blob object (e.g., File).
   *
   * @remarks
   * The `mimeType` can be specified in the `config` parameter. If omitted:
   *  - For file path (string) inputs, the `mimeType` will be inferred from the
   *     file extension.
   *  - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
   *     property.
   * Somex eamples for file extension to mimeType mapping:
   * .txt -> text/plain
   * .json -> application/json
   * .jpg  -> image/jpeg
   * .png -> image/png
   * .mp3 -> audio/mpeg
   * .mp4 -> video/mp4
   *
   * This section can contain multiple paragraphs and code examples.
   *
   * @param params - Optional parameters specified in the
   *        `types.UploadFileParameters` interface.
   *         @see {@link types.UploadFileParameters#config} for the optional
   *         config in the parameters.
   * @return A promise that resolves to a `types.File` object.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   * the `mimeType` can be provided in the `params.config` parameter.
   * @throws An error occurs if a suitable upload location cannot be established.
   *
   * @example
   * The following code uploads a file to Gemini API.
   *
   * ```ts
   * const file = await ai.files.upload({file: 'file.txt', config: {
   *   mimeType: 'text/plain',
   * }});
   * console.log(file.name);
   * ```
   */
  async upload(params) {
    if (this.apiClient.isVertexAI()) {
      throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");
    }
    return this.apiClient.uploadFile(params.file, params.config).then((response) => {
      const file = fileFromMldev(response);
      return file;
    });
  }
  /**
   * Downloads a remotely stored file asynchronously to a location specified in
   * the `params` object. This method only works on Node environment, to
   * download files in the browser, use a browser compliant method like an <a>
   * tag.
   *
   * @param params - The parameters for the download request.
   *
   * @example
   * The following code downloads an example file named "files/mehozpxf877d" as
   * "file.txt".
   *
   * ```ts
   * await ai.files.download({file: file.name, downloadPath: 'file.txt'});
   * ```
   */
  async download(params) {
    await this.apiClient.downloadFile(params);
  }
  async listInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = listFilesParametersToMldev(params);
      path = formatMap("files", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listFilesResponseFromMldev(apiResponse);
        const typedResp = new ListFilesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async createInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createFileParametersToMldev(params);
      path = formatMap("upload/v1beta/files", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = createFileResponseFromMldev(apiResponse);
        const typedResp = new CreateFileResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Retrieves the file information from the service.
   *
   * @param params - The parameters for the get request
   * @return The Promise that resolves to the types.File object requested.
   *
   * @example
   * ```ts
   * const config: GetFileParameters = {
   *   name: fileName,
   * };
   * file = await ai.files.get(config);
   * console.log(file.name);
   * ```
   */
  async get(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = getFileParametersToMldev(params);
      path = formatMap("files/{file}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = fileFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Deletes a remotely stored file.
   *
   * @param params - The parameters for the delete request.
   * @return The DeleteFileResponse, the response for the delete method.
   *
   * @example
   * The following code deletes an example file named "files/mehozpxf877d".
   *
   * ```ts
   * await ai.files.delete({name: file.name});
   * ```
   */
  async delete(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = deleteFileParametersToMldev(params);
      path = formatMap("files/{file}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteFileResponseFromMldev(apiResponse);
        const typedResp = new DeleteFileResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function prebuiltVoiceConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject2, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$2(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject2, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$2(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject2, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToMldev$2(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$2(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$2(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$2(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToMldev$2(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$2(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$2(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$2(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev$2(fromObject2) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject2, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$2(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$2(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$2(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$2(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$2(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$2() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$2(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$2(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$2(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$2(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$2());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$2(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject2, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject2, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function audioTranscriptionConfigToMldev$1() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToMldev$1(fromObject2) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject2, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject2, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject2, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject2, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject2, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject2, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject2, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject2, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToMldev$1(fromObject2) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject2, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject2, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject2, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToMldev$1(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject2, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToMldev$1(fromObject2, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject2, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject2, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev$2(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$2(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject2, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev$1(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject2, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev$1());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject2, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev$1());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject2, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToMldev$1(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject2, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToMldev$1(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject2, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToMldev$1(fromProactivity));
  }
  return toObject;
}
function liveConnectParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev$1(fromConfig, toObject));
  }
  return toObject;
}
function activityStartToMldev() {
  const toObject = {};
  return toObject;
}
function activityEndToMldev() {
  const toObject = {};
  return toObject;
}
function liveSendRealtimeInputParametersToMldev(fromObject2) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject2, ["media"]);
  if (fromMedia != null) {
    setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia));
  }
  const fromAudio = getValueByPath(fromObject2, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject2, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject2, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], tImageBlob(fromVideo));
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject2, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], activityStartToMldev());
  }
  const fromActivityEnd = getValueByPath(fromObject2, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], activityEndToMldev());
  }
  return toObject;
}
function weightedPromptToMldev(fromObject2) {
  const toObject = {};
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromWeight = getValueByPath(fromObject2, ["weight"]);
  if (fromWeight != null) {
    setValueByPath(toObject, ["weight"], fromWeight);
  }
  return toObject;
}
function liveMusicSetWeightedPromptsParametersToMldev(fromObject2) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject2, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptToMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicGenerationConfigToMldev(fromObject2) {
  const toObject = {};
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromGuidance = getValueByPath(fromObject2, ["guidance"]);
  if (fromGuidance != null) {
    setValueByPath(toObject, ["guidance"], fromGuidance);
  }
  const fromBpm = getValueByPath(fromObject2, ["bpm"]);
  if (fromBpm != null) {
    setValueByPath(toObject, ["bpm"], fromBpm);
  }
  const fromDensity = getValueByPath(fromObject2, ["density"]);
  if (fromDensity != null) {
    setValueByPath(toObject, ["density"], fromDensity);
  }
  const fromBrightness = getValueByPath(fromObject2, ["brightness"]);
  if (fromBrightness != null) {
    setValueByPath(toObject, ["brightness"], fromBrightness);
  }
  const fromScale = getValueByPath(fromObject2, ["scale"]);
  if (fromScale != null) {
    setValueByPath(toObject, ["scale"], fromScale);
  }
  const fromMuteBass = getValueByPath(fromObject2, ["muteBass"]);
  if (fromMuteBass != null) {
    setValueByPath(toObject, ["muteBass"], fromMuteBass);
  }
  const fromMuteDrums = getValueByPath(fromObject2, ["muteDrums"]);
  if (fromMuteDrums != null) {
    setValueByPath(toObject, ["muteDrums"], fromMuteDrums);
  }
  const fromOnlyBassAndDrums = getValueByPath(fromObject2, [
    "onlyBassAndDrums"
  ]);
  if (fromOnlyBassAndDrums != null) {
    setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums);
  }
  const fromMusicGenerationMode = getValueByPath(fromObject2, [
    "musicGenerationMode"
  ]);
  if (fromMusicGenerationMode != null) {
    setValueByPath(toObject, ["musicGenerationMode"], fromMusicGenerationMode);
  }
  return toObject;
}
function liveMusicSetConfigParametersToMldev(fromObject2) {
  const toObject = {};
  const fromMusicGenerationConfig = getValueByPath(fromObject2, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig));
  }
  return toObject;
}
function liveMusicClientSetupToMldev(fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  return toObject;
}
function liveMusicClientContentToMldev(fromObject2) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject2, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptToMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicClientMessageToMldev(fromObject2) {
  const toObject = {};
  const fromSetup = getValueByPath(fromObject2, ["setup"]);
  if (fromSetup != null) {
    setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup));
  }
  const fromClientContent = getValueByPath(fromObject2, [
    "clientContent"
  ]);
  if (fromClientContent != null) {
    setValueByPath(toObject, ["clientContent"], liveMusicClientContentToMldev(fromClientContent));
  }
  const fromMusicGenerationConfig = getValueByPath(fromObject2, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigToMldev(fromMusicGenerationConfig));
  }
  const fromPlaybackControl = getValueByPath(fromObject2, [
    "playbackControl"
  ]);
  if (fromPlaybackControl != null) {
    setValueByPath(toObject, ["playbackControl"], fromPlaybackControl);
  }
  return toObject;
}
function prebuiltVoiceConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speechConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToVertex$1(fromVoiceConfig));
  }
  if (getValueByPath(fromObject2, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToVertex$1(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex$1(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex$1(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToVertex$1(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToVertex$1(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToVertex$1(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex$1(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToVertex$1(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex$1(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex$1(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex$1(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex$1(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex$1(fromObject2) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject2, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex$1(fromObject2) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject2, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex$1(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject2, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject2, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject2, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject2, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject2, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex$1(fromObject2) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex$1(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex$1() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex$1(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex$1(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex$1(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex$1(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject2, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex$1(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex$1(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex$1());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex$1(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToVertex(fromObject2) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject2, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  const fromTransparent = getValueByPath(fromObject2, ["transparent"]);
  if (fromTransparent != null) {
    setValueByPath(toObject, ["transparent"], fromTransparent);
  }
  return toObject;
}
function audioTranscriptionConfigToVertex() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToVertex(fromObject2) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject2, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject2, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject2, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject2, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject2, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToVertex(fromObject2) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject2, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToVertex(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject2, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject2, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToVertex(fromObject2) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject2, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToVertex(fromObject2) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject2, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject2, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToVertex(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToVertex(fromObject2) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject2, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject2, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject2, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToVertex$1(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject2, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToVertex(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject2, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToVertex());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject2, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToVertex());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject2, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToVertex(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject2, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToVertex(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject2, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToVertex(fromProactivity));
  }
  return toObject;
}
function liveConnectParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function activityStartToVertex() {
  const toObject = {};
  return toObject;
}
function activityEndToVertex() {
  const toObject = {};
  return toObject;
}
function liveSendRealtimeInputParametersToVertex(fromObject2) {
  const toObject = {};
  const fromMedia = getValueByPath(fromObject2, ["media"]);
  if (fromMedia != null) {
    setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia));
  }
  const fromAudio = getValueByPath(fromObject2, ["audio"]);
  if (fromAudio != null) {
    setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio));
  }
  const fromAudioStreamEnd = getValueByPath(fromObject2, [
    "audioStreamEnd"
  ]);
  if (fromAudioStreamEnd != null) {
    setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd);
  }
  const fromVideo = getValueByPath(fromObject2, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], tImageBlob(fromVideo));
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromActivityStart = getValueByPath(fromObject2, [
    "activityStart"
  ]);
  if (fromActivityStart != null) {
    setValueByPath(toObject, ["activityStart"], activityStartToVertex());
  }
  const fromActivityEnd = getValueByPath(fromObject2, ["activityEnd"]);
  if (fromActivityEnd != null) {
    setValueByPath(toObject, ["activityEnd"], activityEndToVertex());
  }
  return toObject;
}
function liveServerSetupCompleteFromMldev() {
  const toObject = {};
  return toObject;
}
function videoMetadataFromMldev$1(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev$1(fromObject2) {
  const toObject = {};
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev$1(fromObject2) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallFromMldev$1(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partFromMldev$1(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallFromMldev$1(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev$1(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function transcriptionFromMldev(fromObject2) {
  const toObject = {};
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFinished = getValueByPath(fromObject2, ["finished"]);
  if (fromFinished != null) {
    setValueByPath(toObject, ["finished"], fromFinished);
  }
  return toObject;
}
function urlMetadataFromMldev$1(fromObject2) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject2, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject2, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev$1(fromObject2) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject2, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function liveServerContentFromMldev(fromObject2) {
  const toObject = {};
  const fromModelTurn = getValueByPath(fromObject2, ["modelTurn"]);
  if (fromModelTurn != null) {
    setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn));
  }
  const fromTurnComplete = getValueByPath(fromObject2, ["turnComplete"]);
  if (fromTurnComplete != null) {
    setValueByPath(toObject, ["turnComplete"], fromTurnComplete);
  }
  const fromInterrupted = getValueByPath(fromObject2, ["interrupted"]);
  if (fromInterrupted != null) {
    setValueByPath(toObject, ["interrupted"], fromInterrupted);
  }
  const fromGroundingMetadata = getValueByPath(fromObject2, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromGenerationComplete = getValueByPath(fromObject2, [
    "generationComplete"
  ]);
  if (fromGenerationComplete != null) {
    setValueByPath(toObject, ["generationComplete"], fromGenerationComplete);
  }
  const fromInputTranscription = getValueByPath(fromObject2, [
    "inputTranscription"
  ]);
  if (fromInputTranscription != null) {
    setValueByPath(toObject, ["inputTranscription"], transcriptionFromMldev(fromInputTranscription));
  }
  const fromOutputTranscription = getValueByPath(fromObject2, [
    "outputTranscription"
  ]);
  if (fromOutputTranscription != null) {
    setValueByPath(toObject, ["outputTranscription"], transcriptionFromMldev(fromOutputTranscription));
  }
  const fromUrlContextMetadata = getValueByPath(fromObject2, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev$1(fromUrlContextMetadata));
  }
  const fromTurnCompleteReason = getValueByPath(fromObject2, [
    "turnCompleteReason"
  ]);
  if (fromTurnCompleteReason != null) {
    setValueByPath(toObject, ["turnCompleteReason"], fromTurnCompleteReason);
  }
  const fromWaitingForInput = getValueByPath(fromObject2, [
    "waitingForInput"
  ]);
  if (fromWaitingForInput != null) {
    setValueByPath(toObject, ["waitingForInput"], fromWaitingForInput);
  }
  return toObject;
}
function liveServerToolCallFromMldev(fromObject2) {
  const toObject = {};
  const fromFunctionCalls = getValueByPath(fromObject2, [
    "functionCalls"
  ]);
  if (fromFunctionCalls != null) {
    let transformedList = fromFunctionCalls;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionCallFromMldev$1(item);
      });
    }
    setValueByPath(toObject, ["functionCalls"], transformedList);
  }
  return toObject;
}
function liveServerToolCallCancellationFromMldev(fromObject2) {
  const toObject = {};
  const fromIds = getValueByPath(fromObject2, ["ids"]);
  if (fromIds != null) {
    setValueByPath(toObject, ["ids"], fromIds);
  }
  return toObject;
}
function modalityTokenCountFromMldev(fromObject2) {
  const toObject = {};
  const fromModality = getValueByPath(fromObject2, ["modality"]);
  if (fromModality != null) {
    setValueByPath(toObject, ["modality"], fromModality);
  }
  const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function usageMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromPromptTokenCount = getValueByPath(fromObject2, [
    "promptTokenCount"
  ]);
  if (fromPromptTokenCount != null) {
    setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject2, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  const fromResponseTokenCount = getValueByPath(fromObject2, [
    "responseTokenCount"
  ]);
  if (fromResponseTokenCount != null) {
    setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount);
  }
  const fromToolUsePromptTokenCount = getValueByPath(fromObject2, [
    "toolUsePromptTokenCount"
  ]);
  if (fromToolUsePromptTokenCount != null) {
    setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount);
  }
  const fromThoughtsTokenCount = getValueByPath(fromObject2, [
    "thoughtsTokenCount"
  ]);
  if (fromThoughtsTokenCount != null) {
    setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount);
  }
  const fromTotalTokenCount = getValueByPath(fromObject2, [
    "totalTokenCount"
  ]);
  if (fromTotalTokenCount != null) {
    setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount);
  }
  const fromPromptTokensDetails = getValueByPath(fromObject2, [
    "promptTokensDetails"
  ]);
  if (fromPromptTokensDetails != null) {
    let transformedList = fromPromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["promptTokensDetails"], transformedList);
  }
  const fromCacheTokensDetails = getValueByPath(fromObject2, [
    "cacheTokensDetails"
  ]);
  if (fromCacheTokensDetails != null) {
    let transformedList = fromCacheTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["cacheTokensDetails"], transformedList);
  }
  const fromResponseTokensDetails = getValueByPath(fromObject2, [
    "responseTokensDetails"
  ]);
  if (fromResponseTokensDetails != null) {
    let transformedList = fromResponseTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["responseTokensDetails"], transformedList);
  }
  const fromToolUsePromptTokensDetails = getValueByPath(fromObject2, [
    "toolUsePromptTokensDetails"
  ]);
  if (fromToolUsePromptTokensDetails != null) {
    let transformedList = fromToolUsePromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromMldev(item);
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  return toObject;
}
function liveServerGoAwayFromMldev(fromObject2) {
  const toObject = {};
  const fromTimeLeft = getValueByPath(fromObject2, ["timeLeft"]);
  if (fromTimeLeft != null) {
    setValueByPath(toObject, ["timeLeft"], fromTimeLeft);
  }
  return toObject;
}
function liveServerSessionResumptionUpdateFromMldev(fromObject2) {
  const toObject = {};
  const fromNewHandle = getValueByPath(fromObject2, ["newHandle"]);
  if (fromNewHandle != null) {
    setValueByPath(toObject, ["newHandle"], fromNewHandle);
  }
  const fromResumable = getValueByPath(fromObject2, ["resumable"]);
  if (fromResumable != null) {
    setValueByPath(toObject, ["resumable"], fromResumable);
  }
  const fromLastConsumedClientMessageIndex = getValueByPath(fromObject2, [
    "lastConsumedClientMessageIndex"
  ]);
  if (fromLastConsumedClientMessageIndex != null) {
    setValueByPath(toObject, ["lastConsumedClientMessageIndex"], fromLastConsumedClientMessageIndex);
  }
  return toObject;
}
function liveServerMessageFromMldev(fromObject2) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject2, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveServerSetupCompleteFromMldev());
  }
  const fromServerContent = getValueByPath(fromObject2, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveServerContentFromMldev(fromServerContent));
  }
  const fromToolCall = getValueByPath(fromObject2, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], liveServerToolCallFromMldev(fromToolCall));
  }
  const fromToolCallCancellation = getValueByPath(fromObject2, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], liveServerToolCallCancellationFromMldev(fromToolCallCancellation));
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], usageMetadataFromMldev(fromUsageMetadata));
  }
  const fromGoAway = getValueByPath(fromObject2, ["goAway"]);
  if (fromGoAway != null) {
    setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway));
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject2, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate));
  }
  return toObject;
}
function liveMusicServerSetupCompleteFromMldev() {
  const toObject = {};
  return toObject;
}
function weightedPromptFromMldev(fromObject2) {
  const toObject = {};
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromWeight = getValueByPath(fromObject2, ["weight"]);
  if (fromWeight != null) {
    setValueByPath(toObject, ["weight"], fromWeight);
  }
  return toObject;
}
function liveMusicClientContentFromMldev(fromObject2) {
  const toObject = {};
  const fromWeightedPrompts = getValueByPath(fromObject2, [
    "weightedPrompts"
  ]);
  if (fromWeightedPrompts != null) {
    let transformedList = fromWeightedPrompts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return weightedPromptFromMldev(item);
      });
    }
    setValueByPath(toObject, ["weightedPrompts"], transformedList);
  }
  return toObject;
}
function liveMusicGenerationConfigFromMldev(fromObject2) {
  const toObject = {};
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromGuidance = getValueByPath(fromObject2, ["guidance"]);
  if (fromGuidance != null) {
    setValueByPath(toObject, ["guidance"], fromGuidance);
  }
  const fromBpm = getValueByPath(fromObject2, ["bpm"]);
  if (fromBpm != null) {
    setValueByPath(toObject, ["bpm"], fromBpm);
  }
  const fromDensity = getValueByPath(fromObject2, ["density"]);
  if (fromDensity != null) {
    setValueByPath(toObject, ["density"], fromDensity);
  }
  const fromBrightness = getValueByPath(fromObject2, ["brightness"]);
  if (fromBrightness != null) {
    setValueByPath(toObject, ["brightness"], fromBrightness);
  }
  const fromScale = getValueByPath(fromObject2, ["scale"]);
  if (fromScale != null) {
    setValueByPath(toObject, ["scale"], fromScale);
  }
  const fromMuteBass = getValueByPath(fromObject2, ["muteBass"]);
  if (fromMuteBass != null) {
    setValueByPath(toObject, ["muteBass"], fromMuteBass);
  }
  const fromMuteDrums = getValueByPath(fromObject2, ["muteDrums"]);
  if (fromMuteDrums != null) {
    setValueByPath(toObject, ["muteDrums"], fromMuteDrums);
  }
  const fromOnlyBassAndDrums = getValueByPath(fromObject2, [
    "onlyBassAndDrums"
  ]);
  if (fromOnlyBassAndDrums != null) {
    setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums);
  }
  const fromMusicGenerationMode = getValueByPath(fromObject2, [
    "musicGenerationMode"
  ]);
  if (fromMusicGenerationMode != null) {
    setValueByPath(toObject, ["musicGenerationMode"], fromMusicGenerationMode);
  }
  return toObject;
}
function liveMusicSourceMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromClientContent = getValueByPath(fromObject2, [
    "clientContent"
  ]);
  if (fromClientContent != null) {
    setValueByPath(toObject, ["clientContent"], liveMusicClientContentFromMldev(fromClientContent));
  }
  const fromMusicGenerationConfig = getValueByPath(fromObject2, [
    "musicGenerationConfig"
  ]);
  if (fromMusicGenerationConfig != null) {
    setValueByPath(toObject, ["musicGenerationConfig"], liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig));
  }
  return toObject;
}
function audioChunkFromMldev(fromObject2) {
  const toObject = {};
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  const fromSourceMetadata = getValueByPath(fromObject2, [
    "sourceMetadata"
  ]);
  if (fromSourceMetadata != null) {
    setValueByPath(toObject, ["sourceMetadata"], liveMusicSourceMetadataFromMldev(fromSourceMetadata));
  }
  return toObject;
}
function liveMusicServerContentFromMldev(fromObject2) {
  const toObject = {};
  const fromAudioChunks = getValueByPath(fromObject2, ["audioChunks"]);
  if (fromAudioChunks != null) {
    let transformedList = fromAudioChunks;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return audioChunkFromMldev(item);
      });
    }
    setValueByPath(toObject, ["audioChunks"], transformedList);
  }
  return toObject;
}
function liveMusicFilteredPromptFromMldev(fromObject2) {
  const toObject = {};
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFilteredReason = getValueByPath(fromObject2, [
    "filteredReason"
  ]);
  if (fromFilteredReason != null) {
    setValueByPath(toObject, ["filteredReason"], fromFilteredReason);
  }
  return toObject;
}
function liveMusicServerMessageFromMldev(fromObject2) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject2, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveMusicServerSetupCompleteFromMldev());
  }
  const fromServerContent = getValueByPath(fromObject2, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveMusicServerContentFromMldev(fromServerContent));
  }
  const fromFilteredPrompt = getValueByPath(fromObject2, [
    "filteredPrompt"
  ]);
  if (fromFilteredPrompt != null) {
    setValueByPath(toObject, ["filteredPrompt"], liveMusicFilteredPromptFromMldev(fromFilteredPrompt));
  }
  return toObject;
}
function liveServerSetupCompleteFromVertex(fromObject2) {
  const toObject = {};
  const fromSessionId = getValueByPath(fromObject2, ["sessionId"]);
  if (fromSessionId != null) {
    setValueByPath(toObject, ["sessionId"], fromSessionId);
  }
  return toObject;
}
function videoMetadataFromVertex$1(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromVertex$1(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromVertex$1(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallFromVertex$1(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partFromVertex$1(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromVertex$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallFromVertex$1(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromVertex$1(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromVertex$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function transcriptionFromVertex(fromObject2) {
  const toObject = {};
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  const fromFinished = getValueByPath(fromObject2, ["finished"]);
  if (fromFinished != null) {
    setValueByPath(toObject, ["finished"], fromFinished);
  }
  return toObject;
}
function liveServerContentFromVertex(fromObject2) {
  const toObject = {};
  const fromModelTurn = getValueByPath(fromObject2, ["modelTurn"]);
  if (fromModelTurn != null) {
    setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn));
  }
  const fromTurnComplete = getValueByPath(fromObject2, ["turnComplete"]);
  if (fromTurnComplete != null) {
    setValueByPath(toObject, ["turnComplete"], fromTurnComplete);
  }
  const fromInterrupted = getValueByPath(fromObject2, ["interrupted"]);
  if (fromInterrupted != null) {
    setValueByPath(toObject, ["interrupted"], fromInterrupted);
  }
  const fromGroundingMetadata = getValueByPath(fromObject2, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromGenerationComplete = getValueByPath(fromObject2, [
    "generationComplete"
  ]);
  if (fromGenerationComplete != null) {
    setValueByPath(toObject, ["generationComplete"], fromGenerationComplete);
  }
  const fromInputTranscription = getValueByPath(fromObject2, [
    "inputTranscription"
  ]);
  if (fromInputTranscription != null) {
    setValueByPath(toObject, ["inputTranscription"], transcriptionFromVertex(fromInputTranscription));
  }
  const fromOutputTranscription = getValueByPath(fromObject2, [
    "outputTranscription"
  ]);
  if (fromOutputTranscription != null) {
    setValueByPath(toObject, ["outputTranscription"], transcriptionFromVertex(fromOutputTranscription));
  }
  const fromTurnCompleteReason = getValueByPath(fromObject2, [
    "turnCompleteReason"
  ]);
  if (fromTurnCompleteReason != null) {
    setValueByPath(toObject, ["turnCompleteReason"], fromTurnCompleteReason);
  }
  const fromWaitingForInput = getValueByPath(fromObject2, [
    "waitingForInput"
  ]);
  if (fromWaitingForInput != null) {
    setValueByPath(toObject, ["waitingForInput"], fromWaitingForInput);
  }
  return toObject;
}
function liveServerToolCallFromVertex(fromObject2) {
  const toObject = {};
  const fromFunctionCalls = getValueByPath(fromObject2, [
    "functionCalls"
  ]);
  if (fromFunctionCalls != null) {
    let transformedList = fromFunctionCalls;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionCallFromVertex$1(item);
      });
    }
    setValueByPath(toObject, ["functionCalls"], transformedList);
  }
  return toObject;
}
function liveServerToolCallCancellationFromVertex(fromObject2) {
  const toObject = {};
  const fromIds = getValueByPath(fromObject2, ["ids"]);
  if (fromIds != null) {
    setValueByPath(toObject, ["ids"], fromIds);
  }
  return toObject;
}
function modalityTokenCountFromVertex(fromObject2) {
  const toObject = {};
  const fromModality = getValueByPath(fromObject2, ["modality"]);
  if (fromModality != null) {
    setValueByPath(toObject, ["modality"], fromModality);
  }
  const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function usageMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromPromptTokenCount = getValueByPath(fromObject2, [
    "promptTokenCount"
  ]);
  if (fromPromptTokenCount != null) {
    setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject2, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  const fromResponseTokenCount = getValueByPath(fromObject2, [
    "candidatesTokenCount"
  ]);
  if (fromResponseTokenCount != null) {
    setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount);
  }
  const fromToolUsePromptTokenCount = getValueByPath(fromObject2, [
    "toolUsePromptTokenCount"
  ]);
  if (fromToolUsePromptTokenCount != null) {
    setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount);
  }
  const fromThoughtsTokenCount = getValueByPath(fromObject2, [
    "thoughtsTokenCount"
  ]);
  if (fromThoughtsTokenCount != null) {
    setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount);
  }
  const fromTotalTokenCount = getValueByPath(fromObject2, [
    "totalTokenCount"
  ]);
  if (fromTotalTokenCount != null) {
    setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount);
  }
  const fromPromptTokensDetails = getValueByPath(fromObject2, [
    "promptTokensDetails"
  ]);
  if (fromPromptTokensDetails != null) {
    let transformedList = fromPromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["promptTokensDetails"], transformedList);
  }
  const fromCacheTokensDetails = getValueByPath(fromObject2, [
    "cacheTokensDetails"
  ]);
  if (fromCacheTokensDetails != null) {
    let transformedList = fromCacheTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["cacheTokensDetails"], transformedList);
  }
  const fromResponseTokensDetails = getValueByPath(fromObject2, [
    "candidatesTokensDetails"
  ]);
  if (fromResponseTokensDetails != null) {
    let transformedList = fromResponseTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["responseTokensDetails"], transformedList);
  }
  const fromToolUsePromptTokensDetails = getValueByPath(fromObject2, [
    "toolUsePromptTokensDetails"
  ]);
  if (fromToolUsePromptTokensDetails != null) {
    let transformedList = fromToolUsePromptTokensDetails;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modalityTokenCountFromVertex(item);
      });
    }
    setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList);
  }
  const fromTrafficType = getValueByPath(fromObject2, ["trafficType"]);
  if (fromTrafficType != null) {
    setValueByPath(toObject, ["trafficType"], fromTrafficType);
  }
  return toObject;
}
function liveServerGoAwayFromVertex(fromObject2) {
  const toObject = {};
  const fromTimeLeft = getValueByPath(fromObject2, ["timeLeft"]);
  if (fromTimeLeft != null) {
    setValueByPath(toObject, ["timeLeft"], fromTimeLeft);
  }
  return toObject;
}
function liveServerSessionResumptionUpdateFromVertex(fromObject2) {
  const toObject = {};
  const fromNewHandle = getValueByPath(fromObject2, ["newHandle"]);
  if (fromNewHandle != null) {
    setValueByPath(toObject, ["newHandle"], fromNewHandle);
  }
  const fromResumable = getValueByPath(fromObject2, ["resumable"]);
  if (fromResumable != null) {
    setValueByPath(toObject, ["resumable"], fromResumable);
  }
  const fromLastConsumedClientMessageIndex = getValueByPath(fromObject2, [
    "lastConsumedClientMessageIndex"
  ]);
  if (fromLastConsumedClientMessageIndex != null) {
    setValueByPath(toObject, ["lastConsumedClientMessageIndex"], fromLastConsumedClientMessageIndex);
  }
  return toObject;
}
function liveServerMessageFromVertex(fromObject2) {
  const toObject = {};
  const fromSetupComplete = getValueByPath(fromObject2, [
    "setupComplete"
  ]);
  if (fromSetupComplete != null) {
    setValueByPath(toObject, ["setupComplete"], liveServerSetupCompleteFromVertex(fromSetupComplete));
  }
  const fromServerContent = getValueByPath(fromObject2, [
    "serverContent"
  ]);
  if (fromServerContent != null) {
    setValueByPath(toObject, ["serverContent"], liveServerContentFromVertex(fromServerContent));
  }
  const fromToolCall = getValueByPath(fromObject2, ["toolCall"]);
  if (fromToolCall != null) {
    setValueByPath(toObject, ["toolCall"], liveServerToolCallFromVertex(fromToolCall));
  }
  const fromToolCallCancellation = getValueByPath(fromObject2, [
    "toolCallCancellation"
  ]);
  if (fromToolCallCancellation != null) {
    setValueByPath(toObject, ["toolCallCancellation"], liveServerToolCallCancellationFromVertex(fromToolCallCancellation));
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], usageMetadataFromVertex(fromUsageMetadata));
  }
  const fromGoAway = getValueByPath(fromObject2, ["goAway"]);
  if (fromGoAway != null) {
    setValueByPath(toObject, ["goAway"], liveServerGoAwayFromVertex(fromGoAway));
  }
  const fromSessionResumptionUpdate = getValueByPath(fromObject2, [
    "sessionResumptionUpdate"
  ]);
  if (fromSessionResumptionUpdate != null) {
    setValueByPath(toObject, ["sessionResumptionUpdate"], liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate));
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function videoMetadataToMldev$1(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev$1(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev$1(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev$1(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToMldev$1(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev$1(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev$1(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev$1(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToMldev(fromObject2) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject2, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject2, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject2, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject2, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject2, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject2, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject2, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject2, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject2, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject2, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject2, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject2, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject2, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject2, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject2, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject2, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject2, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject2, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject2, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject2, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function safetySettingToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["method"]) !== void 0) {
    throw new Error("method parameter is not supported in Gemini API.");
  }
  const fromCategory = getValueByPath(fromObject2, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject2, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToMldev$1(fromObject2) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject2, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev$1(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev$1(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev$1(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev$1(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev$1() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev$1(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev$1(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$1(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev$1());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev$1(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToMldev(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject2, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToMldev(fromObject2) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject2, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject2, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToMldev(fromObject2) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject2, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToMldev(fromObject2) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject2, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject2, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToMldev(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject2, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$1(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject2, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev$1(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev$1(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject2, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToMldev(fromObject2) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject2, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject2, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToMldev(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToMldev$1(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject2, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject2, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject2, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject2, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject2, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject2, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject2, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToMldev(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  if (getValueByPath(fromObject2, ["routingConfig"]) !== void 0) {
    throw new Error("routingConfig parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["modelSelectionConfig"]) !== void 0) {
    throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");
  }
  const fromSafetySettings = getValueByPath(fromObject2, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToMldev(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev$1(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev(fromToolConfig));
  }
  if (getValueByPath(fromObject2, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  const fromCachedContent = getValueByPath(fromObject2, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)));
  }
  if (getValueByPath(fromObject2, ["audioTimestamp"]) !== void 0) {
    throw new Error("audioTimestamp parameter is not supported in Gemini API.");
  }
  const fromThinkingConfig = getValueByPath(fromObject2, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToMldev(fromThinkingConfig));
  }
  return toObject;
}
function generateContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function embedContentConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject2, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["requests[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject2, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality);
  }
  if (getValueByPath(fromObject2, ["mimeType"]) !== void 0) {
    throw new Error("mimeType parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["autoTruncate"]) !== void 0) {
    throw new Error("autoTruncate parameter is not supported in Gemini API.");
  }
  return toObject;
}
function embedContentParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    setValueByPath(toObject, ["requests[]", "content"], tContentsForEmbed(apiClient, fromContents));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], embedContentConfigToMldev(fromConfig, toObject));
  }
  const fromModelForEmbedContent = getValueByPath(fromObject2, ["model"]);
  if (fromModelForEmbedContent !== void 0) {
    setValueByPath(toObject, ["requests[]", "model"], tModel(apiClient, fromModelForEmbedContent));
  }
  return toObject;
}
function generateImagesConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["negativePrompt"]) !== void 0) {
    throw new Error("negativePrompt parameter is not supported in Gemini API.");
  }
  const fromNumberOfImages = getValueByPath(fromObject2, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject2, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  if (getValueByPath(fromObject2, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject2, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject2, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject2, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject2, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject2, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  if (getValueByPath(fromObject2, ["addWatermark"]) !== void 0) {
    throw new Error("addWatermark parameter is not supported in Gemini API.");
  }
  const fromImageSize = getValueByPath(fromObject2, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  if (getValueByPath(fromObject2, ["enhancePrompt"]) !== void 0) {
    throw new Error("enhancePrompt parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateImagesParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateImagesConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getModelParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listModelsConfigToMldev(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject2, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject2, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listModelsConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function updateModelConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject2, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateModelConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function deleteModelParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function countTokensConfigToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["systemInstruction"]) !== void 0) {
    throw new Error("systemInstruction parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["tools"]) !== void 0) {
    throw new Error("tools parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["generationConfig"]) !== void 0) {
    throw new Error("generationConfig parameter is not supported in Gemini API.");
  }
  return toObject;
}
function countTokensParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToMldev$1(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig));
  }
  return toObject;
}
function imageToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  const fromImageBytes = getValueByPath(fromObject2, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generateVideosSourceToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  if (getValueByPath(fromObject2, ["video"]) !== void 0) {
    throw new Error("video parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateVideosConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject2, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  if (getValueByPath(fromObject2, ["outputGcsUri"]) !== void 0) {
    throw new Error("outputGcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["fps"]) !== void 0) {
    throw new Error("fps parameter is not supported in Gemini API.");
  }
  const fromDurationSeconds = getValueByPath(fromObject2, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  if (getValueByPath(fromObject2, ["seed"]) !== void 0) {
    throw new Error("seed parameter is not supported in Gemini API.");
  }
  const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromResolution = getValueByPath(fromObject2, ["resolution"]);
  if (parentObject !== void 0 && fromResolution != null) {
    setValueByPath(parentObject, ["parameters", "resolution"], fromResolution);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  if (getValueByPath(fromObject2, ["pubsubTopic"]) !== void 0) {
    throw new Error("pubsubTopic parameter is not supported in Gemini API.");
  }
  const fromNegativePrompt = getValueByPath(fromObject2, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject2, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  if (getValueByPath(fromObject2, ["generateAudio"]) !== void 0) {
    throw new Error("generateAudio parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["lastFrame"]) !== void 0) {
    throw new Error("lastFrame parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["referenceImages"]) !== void 0) {
    throw new Error("referenceImages parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["mask"]) !== void 0) {
    throw new Error("mask parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["compressionQuality"]) !== void 0) {
    throw new Error("compressionQuality parameter is not supported in Gemini API.");
  }
  return toObject;
}
function generateVideosParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToMldev(fromImage));
  }
  if (getValueByPath(fromObject2, ["video"]) !== void 0) {
    throw new Error("video parameter is not supported in Gemini API.");
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], generateVideosSourceToMldev(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateVideosConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataToVertex(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToVertex(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToVertex(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToVertex(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToVertex(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToVertex(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToVertex(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToVertex(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToVertex(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function schemaToVertex(fromObject2) {
  const toObject = {};
  const fromAnyOf = getValueByPath(fromObject2, ["anyOf"]);
  if (fromAnyOf != null) {
    setValueByPath(toObject, ["anyOf"], fromAnyOf);
  }
  const fromDefault = getValueByPath(fromObject2, ["default"]);
  if (fromDefault != null) {
    setValueByPath(toObject, ["default"], fromDefault);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromEnum = getValueByPath(fromObject2, ["enum"]);
  if (fromEnum != null) {
    setValueByPath(toObject, ["enum"], fromEnum);
  }
  const fromExample = getValueByPath(fromObject2, ["example"]);
  if (fromExample != null) {
    setValueByPath(toObject, ["example"], fromExample);
  }
  const fromFormat = getValueByPath(fromObject2, ["format"]);
  if (fromFormat != null) {
    setValueByPath(toObject, ["format"], fromFormat);
  }
  const fromItems = getValueByPath(fromObject2, ["items"]);
  if (fromItems != null) {
    setValueByPath(toObject, ["items"], fromItems);
  }
  const fromMaxItems = getValueByPath(fromObject2, ["maxItems"]);
  if (fromMaxItems != null) {
    setValueByPath(toObject, ["maxItems"], fromMaxItems);
  }
  const fromMaxLength = getValueByPath(fromObject2, ["maxLength"]);
  if (fromMaxLength != null) {
    setValueByPath(toObject, ["maxLength"], fromMaxLength);
  }
  const fromMaxProperties = getValueByPath(fromObject2, [
    "maxProperties"
  ]);
  if (fromMaxProperties != null) {
    setValueByPath(toObject, ["maxProperties"], fromMaxProperties);
  }
  const fromMaximum = getValueByPath(fromObject2, ["maximum"]);
  if (fromMaximum != null) {
    setValueByPath(toObject, ["maximum"], fromMaximum);
  }
  const fromMinItems = getValueByPath(fromObject2, ["minItems"]);
  if (fromMinItems != null) {
    setValueByPath(toObject, ["minItems"], fromMinItems);
  }
  const fromMinLength = getValueByPath(fromObject2, ["minLength"]);
  if (fromMinLength != null) {
    setValueByPath(toObject, ["minLength"], fromMinLength);
  }
  const fromMinProperties = getValueByPath(fromObject2, [
    "minProperties"
  ]);
  if (fromMinProperties != null) {
    setValueByPath(toObject, ["minProperties"], fromMinProperties);
  }
  const fromMinimum = getValueByPath(fromObject2, ["minimum"]);
  if (fromMinimum != null) {
    setValueByPath(toObject, ["minimum"], fromMinimum);
  }
  const fromNullable = getValueByPath(fromObject2, ["nullable"]);
  if (fromNullable != null) {
    setValueByPath(toObject, ["nullable"], fromNullable);
  }
  const fromPattern = getValueByPath(fromObject2, ["pattern"]);
  if (fromPattern != null) {
    setValueByPath(toObject, ["pattern"], fromPattern);
  }
  const fromProperties = getValueByPath(fromObject2, ["properties"]);
  if (fromProperties != null) {
    setValueByPath(toObject, ["properties"], fromProperties);
  }
  const fromPropertyOrdering = getValueByPath(fromObject2, [
    "propertyOrdering"
  ]);
  if (fromPropertyOrdering != null) {
    setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering);
  }
  const fromRequired = getValueByPath(fromObject2, ["required"]);
  if (fromRequired != null) {
    setValueByPath(toObject, ["required"], fromRequired);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (fromTitle != null) {
    setValueByPath(toObject, ["title"], fromTitle);
  }
  const fromType = getValueByPath(fromObject2, ["type"]);
  if (fromType != null) {
    setValueByPath(toObject, ["type"], fromType);
  }
  return toObject;
}
function modelSelectionConfigToVertex(fromObject2) {
  const toObject = {};
  const fromFeatureSelectionPreference = getValueByPath(fromObject2, [
    "featureSelectionPreference"
  ]);
  if (fromFeatureSelectionPreference != null) {
    setValueByPath(toObject, ["featureSelectionPreference"], fromFeatureSelectionPreference);
  }
  return toObject;
}
function safetySettingToVertex(fromObject2) {
  const toObject = {};
  const fromMethod = getValueByPath(fromObject2, ["method"]);
  if (fromMethod != null) {
    setValueByPath(toObject, ["method"], fromMethod);
  }
  const fromCategory = getValueByPath(fromObject2, ["category"]);
  if (fromCategory != null) {
    setValueByPath(toObject, ["category"], fromCategory);
  }
  const fromThreshold = getValueByPath(fromObject2, ["threshold"]);
  if (fromThreshold != null) {
    setValueByPath(toObject, ["threshold"], fromThreshold);
  }
  return toObject;
}
function functionDeclarationToVertex(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["behavior"]) !== void 0) {
    throw new Error("behavior parameter is not supported in Vertex AI.");
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToVertex(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToVertex(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToVertex(fromTimeRangeFilter));
  }
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function dynamicRetrievalConfigToVertex(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToVertex(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function enterpriseWebSearchToVertex(fromObject2) {
  const toObject = {};
  const fromExcludeDomains = getValueByPath(fromObject2, [
    "excludeDomains"
  ]);
  if (fromExcludeDomains != null) {
    setValueByPath(toObject, ["excludeDomains"], fromExcludeDomains);
  }
  return toObject;
}
function apiKeyConfigToVertex(fromObject2) {
  const toObject = {};
  const fromApiKeyString = getValueByPath(fromObject2, ["apiKeyString"]);
  if (fromApiKeyString != null) {
    setValueByPath(toObject, ["apiKeyString"], fromApiKeyString);
  }
  return toObject;
}
function authConfigToVertex(fromObject2) {
  const toObject = {};
  const fromApiKeyConfig = getValueByPath(fromObject2, ["apiKeyConfig"]);
  if (fromApiKeyConfig != null) {
    setValueByPath(toObject, ["apiKeyConfig"], apiKeyConfigToVertex(fromApiKeyConfig));
  }
  const fromAuthType = getValueByPath(fromObject2, ["authType"]);
  if (fromAuthType != null) {
    setValueByPath(toObject, ["authType"], fromAuthType);
  }
  const fromGoogleServiceAccountConfig = getValueByPath(fromObject2, [
    "googleServiceAccountConfig"
  ]);
  if (fromGoogleServiceAccountConfig != null) {
    setValueByPath(toObject, ["googleServiceAccountConfig"], fromGoogleServiceAccountConfig);
  }
  const fromHttpBasicAuthConfig = getValueByPath(fromObject2, [
    "httpBasicAuthConfig"
  ]);
  if (fromHttpBasicAuthConfig != null) {
    setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig);
  }
  const fromOauthConfig = getValueByPath(fromObject2, ["oauthConfig"]);
  if (fromOauthConfig != null) {
    setValueByPath(toObject, ["oauthConfig"], fromOauthConfig);
  }
  const fromOidcConfig = getValueByPath(fromObject2, ["oidcConfig"]);
  if (fromOidcConfig != null) {
    setValueByPath(toObject, ["oidcConfig"], fromOidcConfig);
  }
  return toObject;
}
function googleMapsToVertex(fromObject2) {
  const toObject = {};
  const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]);
  if (fromAuthConfig != null) {
    setValueByPath(toObject, ["authConfig"], authConfigToVertex(fromAuthConfig));
  }
  return toObject;
}
function urlContextToVertex() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToVertex(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToVertex(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToVertex(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]);
  if (fromRetrieval != null) {
    setValueByPath(toObject, ["retrieval"], fromRetrieval);
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToVertex(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToVertex(fromGoogleSearchRetrieval));
  }
  const fromEnterpriseWebSearch = getValueByPath(fromObject2, [
    "enterpriseWebSearch"
  ]);
  if (fromEnterpriseWebSearch != null) {
    setValueByPath(toObject, ["enterpriseWebSearch"], enterpriseWebSearchToVertex(fromEnterpriseWebSearch));
  }
  const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]);
  if (fromGoogleMaps != null) {
    setValueByPath(toObject, ["googleMaps"], googleMapsToVertex(fromGoogleMaps));
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToVertex());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToVertex(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function functionCallingConfigToVertex(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromAllowedFunctionNames = getValueByPath(fromObject2, [
    "allowedFunctionNames"
  ]);
  if (fromAllowedFunctionNames != null) {
    setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames);
  }
  return toObject;
}
function latLngToVertex(fromObject2) {
  const toObject = {};
  const fromLatitude = getValueByPath(fromObject2, ["latitude"]);
  if (fromLatitude != null) {
    setValueByPath(toObject, ["latitude"], fromLatitude);
  }
  const fromLongitude = getValueByPath(fromObject2, ["longitude"]);
  if (fromLongitude != null) {
    setValueByPath(toObject, ["longitude"], fromLongitude);
  }
  return toObject;
}
function retrievalConfigToVertex(fromObject2) {
  const toObject = {};
  const fromLatLng = getValueByPath(fromObject2, ["latLng"]);
  if (fromLatLng != null) {
    setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function toolConfigToVertex(fromObject2) {
  const toObject = {};
  const fromFunctionCallingConfig = getValueByPath(fromObject2, [
    "functionCallingConfig"
  ]);
  if (fromFunctionCallingConfig != null) {
    setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToVertex(fromFunctionCallingConfig));
  }
  const fromRetrievalConfig = getValueByPath(fromObject2, [
    "retrievalConfig"
  ]);
  if (fromRetrievalConfig != null) {
    setValueByPath(toObject, ["retrievalConfig"], retrievalConfigToVertex(fromRetrievalConfig));
  }
  return toObject;
}
function prebuiltVoiceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speechConfigToVertex(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToVertex(fromVoiceConfig));
  }
  if (getValueByPath(fromObject2, ["multiSpeakerVoiceConfig"]) !== void 0) {
    throw new Error("multiSpeakerVoiceConfig parameter is not supported in Vertex AI.");
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function thinkingConfigToVertex(fromObject2) {
  const toObject = {};
  const fromIncludeThoughts = getValueByPath(fromObject2, [
    "includeThoughts"
  ]);
  if (fromIncludeThoughts != null) {
    setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts);
  }
  const fromThinkingBudget = getValueByPath(fromObject2, [
    "thinkingBudget"
  ]);
  if (fromThinkingBudget != null) {
    setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget);
  }
  return toObject;
}
function generateContentConfigToVertex(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex(tContent(fromSystemInstruction)));
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (fromTemperature != null) {
    setValueByPath(toObject, ["temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (fromTopP != null) {
    setValueByPath(toObject, ["topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (fromTopK != null) {
    setValueByPath(toObject, ["topK"], fromTopK);
  }
  const fromCandidateCount = getValueByPath(fromObject2, [
    "candidateCount"
  ]);
  if (fromCandidateCount != null) {
    setValueByPath(toObject, ["candidateCount"], fromCandidateCount);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (fromMaxOutputTokens != null) {
    setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromStopSequences = getValueByPath(fromObject2, [
    "stopSequences"
  ]);
  if (fromStopSequences != null) {
    setValueByPath(toObject, ["stopSequences"], fromStopSequences);
  }
  const fromResponseLogprobs = getValueByPath(fromObject2, [
    "responseLogprobs"
  ]);
  if (fromResponseLogprobs != null) {
    setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs);
  }
  const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]);
  if (fromLogprobs != null) {
    setValueByPath(toObject, ["logprobs"], fromLogprobs);
  }
  const fromPresencePenalty = getValueByPath(fromObject2, [
    "presencePenalty"
  ]);
  if (fromPresencePenalty != null) {
    setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty);
  }
  const fromFrequencyPenalty = getValueByPath(fromObject2, [
    "frequencyPenalty"
  ]);
  if (fromFrequencyPenalty != null) {
    setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (fromSeed != null) {
    setValueByPath(toObject, ["seed"], fromSeed);
  }
  const fromResponseMimeType = getValueByPath(fromObject2, [
    "responseMimeType"
  ]);
  if (fromResponseMimeType != null) {
    setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType);
  }
  const fromResponseSchema = getValueByPath(fromObject2, [
    "responseSchema"
  ]);
  if (fromResponseSchema != null) {
    setValueByPath(toObject, ["responseSchema"], schemaToVertex(tSchema(fromResponseSchema)));
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  const fromRoutingConfig = getValueByPath(fromObject2, [
    "routingConfig"
  ]);
  if (fromRoutingConfig != null) {
    setValueByPath(toObject, ["routingConfig"], fromRoutingConfig);
  }
  const fromModelSelectionConfig = getValueByPath(fromObject2, [
    "modelSelectionConfig"
  ]);
  if (fromModelSelectionConfig != null) {
    setValueByPath(toObject, ["modelConfig"], modelSelectionConfigToVertex(fromModelSelectionConfig));
  }
  const fromSafetySettings = getValueByPath(fromObject2, [
    "safetySettings"
  ]);
  if (parentObject !== void 0 && fromSafetySettings != null) {
    let transformedList = fromSafetySettings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return safetySettingToVertex(item);
      });
    }
    setValueByPath(parentObject, ["safetySettings"], transformedList);
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(tTool(item));
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]);
  if (parentObject !== void 0 && fromToolConfig != null) {
    setValueByPath(parentObject, ["toolConfig"], toolConfigToVertex(fromToolConfig));
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  const fromCachedContent = getValueByPath(fromObject2, [
    "cachedContent"
  ]);
  if (parentObject !== void 0 && fromCachedContent != null) {
    setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent));
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (fromResponseModalities != null) {
    setValueByPath(toObject, ["responseModalities"], fromResponseModalities);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (fromMediaResolution != null) {
    setValueByPath(toObject, ["mediaResolution"], fromMediaResolution);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (fromSpeechConfig != null) {
    setValueByPath(toObject, ["speechConfig"], speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));
  }
  const fromAudioTimestamp = getValueByPath(fromObject2, [
    "audioTimestamp"
  ]);
  if (fromAudioTimestamp != null) {
    setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp);
  }
  const fromThinkingConfig = getValueByPath(fromObject2, [
    "thinkingConfig"
  ]);
  if (fromThinkingConfig != null) {
    setValueByPath(toObject, ["thinkingConfig"], thinkingConfigToVertex(fromThinkingConfig));
  }
  return toObject;
}
function generateContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["generationConfig"], generateContentConfigToVertex(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function embedContentConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromTaskType = getValueByPath(fromObject2, ["taskType"]);
  if (parentObject !== void 0 && fromTaskType != null) {
    setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType);
  }
  const fromTitle = getValueByPath(fromObject2, ["title"]);
  if (parentObject !== void 0 && fromTitle != null) {
    setValueByPath(parentObject, ["instances[]", "title"], fromTitle);
  }
  const fromOutputDimensionality = getValueByPath(fromObject2, [
    "outputDimensionality"
  ]);
  if (parentObject !== void 0 && fromOutputDimensionality != null) {
    setValueByPath(parentObject, ["parameters", "outputDimensionality"], fromOutputDimensionality);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (parentObject !== void 0 && fromMimeType != null) {
    setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType);
  }
  const fromAutoTruncate = getValueByPath(fromObject2, ["autoTruncate"]);
  if (parentObject !== void 0 && fromAutoTruncate != null) {
    setValueByPath(parentObject, ["parameters", "autoTruncate"], fromAutoTruncate);
  }
  return toObject;
}
function embedContentParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    setValueByPath(toObject, ["instances[]", "content"], tContentsForEmbed(apiClient, fromContents));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], embedContentConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function generateImagesConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject2, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject2, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject2, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject2, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject2, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject2, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject2, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject2, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromImageSize = getValueByPath(fromObject2, ["imageSize"]);
  if (parentObject !== void 0 && fromImageSize != null) {
    setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize);
  }
  const fromEnhancePrompt = getValueByPath(fromObject2, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  return toObject;
}
function generateImagesParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateImagesConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function imageToVertex(fromObject2) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject2, ["imageBytes"]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function maskReferenceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromMaskMode = getValueByPath(fromObject2, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  const fromSegmentationClasses = getValueByPath(fromObject2, [
    "segmentationClasses"
  ]);
  if (fromSegmentationClasses != null) {
    setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses);
  }
  const fromMaskDilation = getValueByPath(fromObject2, ["maskDilation"]);
  if (fromMaskDilation != null) {
    setValueByPath(toObject, ["dilation"], fromMaskDilation);
  }
  return toObject;
}
function controlReferenceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromControlType = getValueByPath(fromObject2, ["controlType"]);
  if (fromControlType != null) {
    setValueByPath(toObject, ["controlType"], fromControlType);
  }
  const fromEnableControlImageComputation = getValueByPath(fromObject2, [
    "enableControlImageComputation"
  ]);
  if (fromEnableControlImageComputation != null) {
    setValueByPath(toObject, ["computeControl"], fromEnableControlImageComputation);
  }
  return toObject;
}
function styleReferenceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromStyleDescription = getValueByPath(fromObject2, [
    "styleDescription"
  ]);
  if (fromStyleDescription != null) {
    setValueByPath(toObject, ["styleDescription"], fromStyleDescription);
  }
  return toObject;
}
function subjectReferenceConfigToVertex(fromObject2) {
  const toObject = {};
  const fromSubjectType = getValueByPath(fromObject2, ["subjectType"]);
  if (fromSubjectType != null) {
    setValueByPath(toObject, ["subjectType"], fromSubjectType);
  }
  const fromSubjectDescription = getValueByPath(fromObject2, [
    "subjectDescription"
  ]);
  if (fromSubjectDescription != null) {
    setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription);
  }
  return toObject;
}
function referenceImageAPIInternalToVertex(fromObject2) {
  const toObject = {};
  const fromReferenceImage = getValueByPath(fromObject2, [
    "referenceImage"
  ]);
  if (fromReferenceImage != null) {
    setValueByPath(toObject, ["referenceImage"], imageToVertex(fromReferenceImage));
  }
  const fromReferenceId = getValueByPath(fromObject2, ["referenceId"]);
  if (fromReferenceId != null) {
    setValueByPath(toObject, ["referenceId"], fromReferenceId);
  }
  const fromReferenceType = getValueByPath(fromObject2, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  const fromMaskImageConfig = getValueByPath(fromObject2, [
    "maskImageConfig"
  ]);
  if (fromMaskImageConfig != null) {
    setValueByPath(toObject, ["maskImageConfig"], maskReferenceConfigToVertex(fromMaskImageConfig));
  }
  const fromControlImageConfig = getValueByPath(fromObject2, [
    "controlImageConfig"
  ]);
  if (fromControlImageConfig != null) {
    setValueByPath(toObject, ["controlImageConfig"], controlReferenceConfigToVertex(fromControlImageConfig));
  }
  const fromStyleImageConfig = getValueByPath(fromObject2, [
    "styleImageConfig"
  ]);
  if (fromStyleImageConfig != null) {
    setValueByPath(toObject, ["styleImageConfig"], styleReferenceConfigToVertex(fromStyleImageConfig));
  }
  const fromSubjectImageConfig = getValueByPath(fromObject2, [
    "subjectImageConfig"
  ]);
  if (fromSubjectImageConfig != null) {
    setValueByPath(toObject, ["subjectImageConfig"], subjectReferenceConfigToVertex(fromSubjectImageConfig));
  }
  return toObject;
}
function editImageConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromNegativePrompt = getValueByPath(fromObject2, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromNumberOfImages = getValueByPath(fromObject2, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromGuidanceScale = getValueByPath(fromObject2, [
    "guidanceScale"
  ]);
  if (parentObject !== void 0 && fromGuidanceScale != null) {
    setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject2, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [
    "includeSafetyAttributes"
  ]);
  if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) {
    setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject2, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromLanguage = getValueByPath(fromObject2, ["language"]);
  if (parentObject !== void 0 && fromLanguage != null) {
    setValueByPath(parentObject, ["parameters", "language"], fromLanguage);
  }
  const fromOutputMimeType = getValueByPath(fromObject2, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject2, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromEditMode = getValueByPath(fromObject2, ["editMode"]);
  if (parentObject !== void 0 && fromEditMode != null) {
    setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode);
  }
  const fromBaseSteps = getValueByPath(fromObject2, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps);
  }
  return toObject;
}
function editImageParametersInternalToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromReferenceImages = getValueByPath(fromObject2, [
    "referenceImages"
  ]);
  if (fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return referenceImageAPIInternalToVertex(item);
      });
    }
    setValueByPath(toObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], editImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function upscaleImageAPIConfigInternalToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromIncludeRaiReason = getValueByPath(fromObject2, [
    "includeRaiReason"
  ]);
  if (parentObject !== void 0 && fromIncludeRaiReason != null) {
    setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason);
  }
  const fromOutputMimeType = getValueByPath(fromObject2, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject2, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhanceInputImage = getValueByPath(fromObject2, [
    "enhanceInputImage"
  ]);
  if (parentObject !== void 0 && fromEnhanceInputImage != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "enhanceInputImage"], fromEnhanceInputImage);
  }
  const fromImagePreservationFactor = getValueByPath(fromObject2, [
    "imagePreservationFactor"
  ]);
  if (parentObject !== void 0 && fromImagePreservationFactor != null) {
    setValueByPath(parentObject, ["parameters", "upscaleConfig", "imagePreservationFactor"], fromImagePreservationFactor);
  }
  const fromNumberOfImages = getValueByPath(fromObject2, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  return toObject;
}
function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromUpscaleFactor = getValueByPath(fromObject2, [
    "upscaleFactor"
  ]);
  if (fromUpscaleFactor != null) {
    setValueByPath(toObject, ["parameters", "upscaleConfig", "upscaleFactor"], fromUpscaleFactor);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], upscaleImageAPIConfigInternalToVertex(fromConfig, toObject));
  }
  return toObject;
}
function productImageToVertex(fromObject2) {
  const toObject = {};
  const fromProductImage = getValueByPath(fromObject2, ["productImage"]);
  if (fromProductImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromProductImage));
  }
  return toObject;
}
function recontextImageSourceToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromPersonImage = getValueByPath(fromObject2, ["personImage"]);
  if (parentObject !== void 0 && fromPersonImage != null) {
    setValueByPath(parentObject, ["instances[0]", "personImage", "image"], imageToVertex(fromPersonImage));
  }
  const fromProductImages = getValueByPath(fromObject2, [
    "productImages"
  ]);
  if (parentObject !== void 0 && fromProductImages != null) {
    let transformedList = fromProductImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return productImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "productImages"], transformedList);
  }
  return toObject;
}
function recontextImageConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromNumberOfImages = getValueByPath(fromObject2, [
    "numberOfImages"
  ]);
  if (parentObject !== void 0 && fromNumberOfImages != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages);
  }
  const fromBaseSteps = getValueByPath(fromObject2, ["baseSteps"]);
  if (parentObject !== void 0 && fromBaseSteps != null) {
    setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps);
  }
  const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromSafetyFilterLevel = getValueByPath(fromObject2, [
    "safetyFilterLevel"
  ]);
  if (parentObject !== void 0 && fromSafetyFilterLevel != null) {
    setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]);
  if (parentObject !== void 0 && fromAddWatermark != null) {
    setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark);
  }
  const fromOutputMimeType = getValueByPath(fromObject2, [
    "outputMimeType"
  ]);
  if (parentObject !== void 0 && fromOutputMimeType != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType);
  }
  const fromOutputCompressionQuality = getValueByPath(fromObject2, [
    "outputCompressionQuality"
  ]);
  if (parentObject !== void 0 && fromOutputCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality);
  }
  const fromEnhancePrompt = getValueByPath(fromObject2, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  return toObject;
}
function recontextImageParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], recontextImageSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], recontextImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function scribbleImageToVertex(fromObject2) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  return toObject;
}
function segmentImageSourceToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromScribbleImage = getValueByPath(fromObject2, [
    "scribbleImage"
  ]);
  if (parentObject !== void 0 && fromScribbleImage != null) {
    setValueByPath(parentObject, ["instances[0]", "scribble"], scribbleImageToVertex(fromScribbleImage));
  }
  return toObject;
}
function segmentImageConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (parentObject !== void 0 && fromMode != null) {
    setValueByPath(parentObject, ["parameters", "mode"], fromMode);
  }
  const fromMaxPredictions = getValueByPath(fromObject2, [
    "maxPredictions"
  ]);
  if (parentObject !== void 0 && fromMaxPredictions != null) {
    setValueByPath(parentObject, ["parameters", "maxPredictions"], fromMaxPredictions);
  }
  const fromConfidenceThreshold = getValueByPath(fromObject2, [
    "confidenceThreshold"
  ]);
  if (parentObject !== void 0 && fromConfidenceThreshold != null) {
    setValueByPath(parentObject, ["parameters", "confidenceThreshold"], fromConfidenceThreshold);
  }
  const fromMaskDilation = getValueByPath(fromObject2, ["maskDilation"]);
  if (parentObject !== void 0 && fromMaskDilation != null) {
    setValueByPath(parentObject, ["parameters", "maskDilation"], fromMaskDilation);
  }
  const fromBinaryColorThreshold = getValueByPath(fromObject2, [
    "binaryColorThreshold"
  ]);
  if (parentObject !== void 0 && fromBinaryColorThreshold != null) {
    setValueByPath(parentObject, ["parameters", "binaryColorThreshold"], fromBinaryColorThreshold);
  }
  return toObject;
}
function segmentImageParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], segmentImageSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], segmentImageConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function getModelParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listModelsConfigToVertex(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject2, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  const fromQueryBase = getValueByPath(fromObject2, ["queryBase"]);
  if (parentObject !== void 0 && fromQueryBase != null) {
    setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase));
  }
  return toObject;
}
function listModelsParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listModelsConfigToVertex(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function updateModelConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (parentObject !== void 0 && fromDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject2, [
    "defaultCheckpointId"
  ]);
  if (parentObject !== void 0 && fromDefaultCheckpointId != null) {
    setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  return toObject;
}
function updateModelParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], updateModelConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function deleteModelParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function countTokensConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["systemInstruction"], contentToVertex(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = fromTools;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToVertex(item);
      });
    }
    setValueByPath(parentObject, ["tools"], transformedList);
  }
  const fromGenerationConfig = getValueByPath(fromObject2, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig);
  }
  return toObject;
}
function countTokensParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], countTokensConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function computeTokensParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromContents = getValueByPath(fromObject2, ["contents"]);
  if (fromContents != null) {
    let transformedList = tContents(fromContents);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentToVertex(item);
      });
    }
    setValueByPath(toObject, ["contents"], transformedList);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function videoToVertex(fromObject2) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject2, ["uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject2, ["videoBytes"]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generateVideosSourceToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (parentObject !== void 0 && fromPrompt != null) {
    setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (parentObject !== void 0 && fromImage != null) {
    setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject2, ["video"]);
  if (parentObject !== void 0 && fromVideo != null) {
    setValueByPath(parentObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  return toObject;
}
function videoGenerationReferenceImageToVertex(fromObject2) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageToVertex(fromImage));
  }
  const fromReferenceType = getValueByPath(fromObject2, [
    "referenceType"
  ]);
  if (fromReferenceType != null) {
    setValueByPath(toObject, ["referenceType"], fromReferenceType);
  }
  return toObject;
}
function videoGenerationMaskToVertex(fromObject2) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["_self"], imageToVertex(fromImage));
  }
  const fromMaskMode = getValueByPath(fromObject2, ["maskMode"]);
  if (fromMaskMode != null) {
    setValueByPath(toObject, ["maskMode"], fromMaskMode);
  }
  return toObject;
}
function generateVideosConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromNumberOfVideos = getValueByPath(fromObject2, [
    "numberOfVideos"
  ]);
  if (parentObject !== void 0 && fromNumberOfVideos != null) {
    setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos);
  }
  const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]);
  if (parentObject !== void 0 && fromOutputGcsUri != null) {
    setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri);
  }
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (parentObject !== void 0 && fromFps != null) {
    setValueByPath(parentObject, ["parameters", "fps"], fromFps);
  }
  const fromDurationSeconds = getValueByPath(fromObject2, [
    "durationSeconds"
  ]);
  if (parentObject !== void 0 && fromDurationSeconds != null) {
    setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["parameters", "seed"], fromSeed);
  }
  const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]);
  if (parentObject !== void 0 && fromAspectRatio != null) {
    setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio);
  }
  const fromResolution = getValueByPath(fromObject2, ["resolution"]);
  if (parentObject !== void 0 && fromResolution != null) {
    setValueByPath(parentObject, ["parameters", "resolution"], fromResolution);
  }
  const fromPersonGeneration = getValueByPath(fromObject2, [
    "personGeneration"
  ]);
  if (parentObject !== void 0 && fromPersonGeneration != null) {
    setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration);
  }
  const fromPubsubTopic = getValueByPath(fromObject2, ["pubsubTopic"]);
  if (parentObject !== void 0 && fromPubsubTopic != null) {
    setValueByPath(parentObject, ["parameters", "pubsubTopic"], fromPubsubTopic);
  }
  const fromNegativePrompt = getValueByPath(fromObject2, [
    "negativePrompt"
  ]);
  if (parentObject !== void 0 && fromNegativePrompt != null) {
    setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt);
  }
  const fromEnhancePrompt = getValueByPath(fromObject2, [
    "enhancePrompt"
  ]);
  if (parentObject !== void 0 && fromEnhancePrompt != null) {
    setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt);
  }
  const fromGenerateAudio = getValueByPath(fromObject2, [
    "generateAudio"
  ]);
  if (parentObject !== void 0 && fromGenerateAudio != null) {
    setValueByPath(parentObject, ["parameters", "generateAudio"], fromGenerateAudio);
  }
  const fromLastFrame = getValueByPath(fromObject2, ["lastFrame"]);
  if (parentObject !== void 0 && fromLastFrame != null) {
    setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToVertex(fromLastFrame));
  }
  const fromReferenceImages = getValueByPath(fromObject2, [
    "referenceImages"
  ]);
  if (parentObject !== void 0 && fromReferenceImages != null) {
    let transformedList = fromReferenceImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return videoGenerationReferenceImageToVertex(item);
      });
    }
    setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList);
  }
  const fromMask = getValueByPath(fromObject2, ["mask"]);
  if (parentObject !== void 0 && fromMask != null) {
    setValueByPath(parentObject, ["instances[0]", "mask"], videoGenerationMaskToVertex(fromMask));
  }
  const fromCompressionQuality = getValueByPath(fromObject2, [
    "compressionQuality"
  ]);
  if (parentObject !== void 0 && fromCompressionQuality != null) {
    setValueByPath(parentObject, ["parameters", "compressionQuality"], fromCompressionQuality);
  }
  return toObject;
}
function generateVideosParametersToVertex(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel));
  }
  const fromPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromPrompt != null) {
    setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt);
  }
  const fromImage = getValueByPath(fromObject2, ["image"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage));
  }
  const fromVideo = getValueByPath(fromObject2, ["video"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["instances[0]", "video"], videoToVertex(fromVideo));
  }
  const fromSource = getValueByPath(fromObject2, ["source"]);
  if (fromSource != null) {
    setValueByPath(toObject, ["config"], generateVideosSourceToVertex(fromSource, toObject));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], generateVideosConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function videoMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromMldev(fromObject2) {
  const toObject = {};
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromMldev(fromObject2) {
  const toObject = {};
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallFromMldev(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partFromMldev(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromMldev(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallFromMldev(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromMldev(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromMldev(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject2, ["citationSources"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject2, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject2, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromMldev(fromObject2) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject2, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromMldev(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromMldev(fromObject2) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject2, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromMldev(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject2, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev(fromCitationMetadata));
  }
  const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  const fromFinishReason = getValueByPath(fromObject2, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject2, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromMldev(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject2, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject2, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject2, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject2, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject2, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject2, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromMldev(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject2, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject2, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function contentEmbeddingFromMldev(fromObject2) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject2, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  return toObject;
}
function embedContentMetadataFromMldev() {
  const toObject = {};
  return toObject;
}
function embedContentResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject2, ["embeddings"]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentEmbeddingFromMldev(item);
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev());
  }
  return toObject;
}
function imageFromMldev(fromObject2) {
  const toObject = {};
  const fromImageBytes = getValueByPath(fromObject2, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function safetyAttributesFromMldev(fromObject2) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject2, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject2, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject2, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function generatedImageFromMldev(fromObject2) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject2, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromMldev(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject2, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject2, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromMldev(fromSafetyAttributes));
  }
  return toObject;
}
function generateImagesResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject2, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject2, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function tunedModelInfoFromMldev(fromObject2) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function modelFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject2, ["version"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromTunedModelInfo = getValueByPath(fromObject2, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromMldev(fromTunedModelInfo));
  }
  const fromInputTokenLimit = getValueByPath(fromObject2, [
    "inputTokenLimit"
  ]);
  if (fromInputTokenLimit != null) {
    setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit);
  }
  const fromOutputTokenLimit = getValueByPath(fromObject2, [
    "outputTokenLimit"
  ]);
  if (fromOutputTokenLimit != null) {
    setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit);
  }
  const fromSupportedActions = getValueByPath(fromObject2, [
    "supportedGenerationMethods"
  ]);
  if (fromSupportedActions != null) {
    setValueByPath(toObject, ["supportedActions"], fromSupportedActions);
  }
  return toObject;
}
function listModelsResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject2, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromMldev(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function deleteModelResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function countTokensResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject2, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  const fromCachedContentTokenCount = getValueByPath(fromObject2, [
    "cachedContentTokenCount"
  ]);
  if (fromCachedContentTokenCount != null) {
    setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount);
  }
  return toObject;
}
function videoFromMldev(fromObject2) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject2, ["video", "uri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject2, [
    "video",
    "encodedVideo"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["encoding"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromMldev(fromObject2) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject2, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromMldev(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject2, [
    "generatedSamples"
  ]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromMldev(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject2, [
    "response",
    "generateVideoResponse"
  ]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromMldev(fromResponse));
  }
  return toObject;
}
function videoMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobFromVertex(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataFromVertex(fromObject2) {
  const toObject = {};
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallFromVertex(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partFromVertex(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataFromVertex(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallFromVertex(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentFromVertex(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partFromVertex(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function citationMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromCitations = getValueByPath(fromObject2, ["citations"]);
  if (fromCitations != null) {
    setValueByPath(toObject, ["citations"], fromCitations);
  }
  return toObject;
}
function urlMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromRetrievedUrl = getValueByPath(fromObject2, ["retrievedUrl"]);
  if (fromRetrievedUrl != null) {
    setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl);
  }
  const fromUrlRetrievalStatus = getValueByPath(fromObject2, [
    "urlRetrievalStatus"
  ]);
  if (fromUrlRetrievalStatus != null) {
    setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus);
  }
  return toObject;
}
function urlContextMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromUrlMetadata = getValueByPath(fromObject2, ["urlMetadata"]);
  if (fromUrlMetadata != null) {
    let transformedList = fromUrlMetadata;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return urlMetadataFromVertex(item);
      });
    }
    setValueByPath(toObject, ["urlMetadata"], transformedList);
  }
  return toObject;
}
function candidateFromVertex(fromObject2) {
  const toObject = {};
  const fromContent = getValueByPath(fromObject2, ["content"]);
  if (fromContent != null) {
    setValueByPath(toObject, ["content"], contentFromVertex(fromContent));
  }
  const fromCitationMetadata = getValueByPath(fromObject2, [
    "citationMetadata"
  ]);
  if (fromCitationMetadata != null) {
    setValueByPath(toObject, ["citationMetadata"], citationMetadataFromVertex(fromCitationMetadata));
  }
  const fromFinishMessage = getValueByPath(fromObject2, [
    "finishMessage"
  ]);
  if (fromFinishMessage != null) {
    setValueByPath(toObject, ["finishMessage"], fromFinishMessage);
  }
  const fromFinishReason = getValueByPath(fromObject2, ["finishReason"]);
  if (fromFinishReason != null) {
    setValueByPath(toObject, ["finishReason"], fromFinishReason);
  }
  const fromUrlContextMetadata = getValueByPath(fromObject2, [
    "urlContextMetadata"
  ]);
  if (fromUrlContextMetadata != null) {
    setValueByPath(toObject, ["urlContextMetadata"], urlContextMetadataFromVertex(fromUrlContextMetadata));
  }
  const fromAvgLogprobs = getValueByPath(fromObject2, ["avgLogprobs"]);
  if (fromAvgLogprobs != null) {
    setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs);
  }
  const fromGroundingMetadata = getValueByPath(fromObject2, [
    "groundingMetadata"
  ]);
  if (fromGroundingMetadata != null) {
    setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata);
  }
  const fromIndex = getValueByPath(fromObject2, ["index"]);
  if (fromIndex != null) {
    setValueByPath(toObject, ["index"], fromIndex);
  }
  const fromLogprobsResult = getValueByPath(fromObject2, [
    "logprobsResult"
  ]);
  if (fromLogprobsResult != null) {
    setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult);
  }
  const fromSafetyRatings = getValueByPath(fromObject2, [
    "safetyRatings"
  ]);
  if (fromSafetyRatings != null) {
    setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings);
  }
  return toObject;
}
function generateContentResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromCandidates = getValueByPath(fromObject2, ["candidates"]);
  if (fromCandidates != null) {
    let transformedList = fromCandidates;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return candidateFromVertex(item);
      });
    }
    setValueByPath(toObject, ["candidates"], transformedList);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]);
  if (fromModelVersion != null) {
    setValueByPath(toObject, ["modelVersion"], fromModelVersion);
  }
  const fromPromptFeedback = getValueByPath(fromObject2, [
    "promptFeedback"
  ]);
  if (fromPromptFeedback != null) {
    setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback);
  }
  const fromResponseId = getValueByPath(fromObject2, ["responseId"]);
  if (fromResponseId != null) {
    setValueByPath(toObject, ["responseId"], fromResponseId);
  }
  const fromUsageMetadata = getValueByPath(fromObject2, [
    "usageMetadata"
  ]);
  if (fromUsageMetadata != null) {
    setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata);
  }
  return toObject;
}
function contentEmbeddingStatisticsFromVertex(fromObject2) {
  const toObject = {};
  const fromTruncated = getValueByPath(fromObject2, ["truncated"]);
  if (fromTruncated != null) {
    setValueByPath(toObject, ["truncated"], fromTruncated);
  }
  const fromTokenCount = getValueByPath(fromObject2, ["token_count"]);
  if (fromTokenCount != null) {
    setValueByPath(toObject, ["tokenCount"], fromTokenCount);
  }
  return toObject;
}
function contentEmbeddingFromVertex(fromObject2) {
  const toObject = {};
  const fromValues = getValueByPath(fromObject2, ["values"]);
  if (fromValues != null) {
    setValueByPath(toObject, ["values"], fromValues);
  }
  const fromStatistics = getValueByPath(fromObject2, ["statistics"]);
  if (fromStatistics != null) {
    setValueByPath(toObject, ["statistics"], contentEmbeddingStatisticsFromVertex(fromStatistics));
  }
  return toObject;
}
function embedContentMetadataFromVertex(fromObject2) {
  const toObject = {};
  const fromBillableCharacterCount = getValueByPath(fromObject2, [
    "billableCharacterCount"
  ]);
  if (fromBillableCharacterCount != null) {
    setValueByPath(toObject, ["billableCharacterCount"], fromBillableCharacterCount);
  }
  return toObject;
}
function embedContentResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromEmbeddings = getValueByPath(fromObject2, [
    "predictions[]",
    "embeddings"
  ]);
  if (fromEmbeddings != null) {
    let transformedList = fromEmbeddings;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return contentEmbeddingFromVertex(item);
      });
    }
    setValueByPath(toObject, ["embeddings"], transformedList);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], embedContentMetadataFromVertex(fromMetadata));
  }
  return toObject;
}
function imageFromVertex(fromObject2) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["gcsUri"], fromGcsUri);
  }
  const fromImageBytes = getValueByPath(fromObject2, [
    "bytesBase64Encoded"
  ]);
  if (fromImageBytes != null) {
    setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function safetyAttributesFromVertex(fromObject2) {
  const toObject = {};
  const fromCategories = getValueByPath(fromObject2, [
    "safetyAttributes",
    "categories"
  ]);
  if (fromCategories != null) {
    setValueByPath(toObject, ["categories"], fromCategories);
  }
  const fromScores = getValueByPath(fromObject2, [
    "safetyAttributes",
    "scores"
  ]);
  if (fromScores != null) {
    setValueByPath(toObject, ["scores"], fromScores);
  }
  const fromContentType = getValueByPath(fromObject2, ["contentType"]);
  if (fromContentType != null) {
    setValueByPath(toObject, ["contentType"], fromContentType);
  }
  return toObject;
}
function generatedImageFromVertex(fromObject2) {
  const toObject = {};
  const fromImage = getValueByPath(fromObject2, ["_self"]);
  if (fromImage != null) {
    setValueByPath(toObject, ["image"], imageFromVertex(fromImage));
  }
  const fromRaiFilteredReason = getValueByPath(fromObject2, [
    "raiFilteredReason"
  ]);
  if (fromRaiFilteredReason != null) {
    setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason);
  }
  const fromSafetyAttributes = getValueByPath(fromObject2, ["_self"]);
  if (fromSafetyAttributes != null) {
    setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromVertex(fromSafetyAttributes));
  }
  const fromEnhancedPrompt = getValueByPath(fromObject2, ["prompt"]);
  if (fromEnhancedPrompt != null) {
    setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt);
  }
  return toObject;
}
function generateImagesResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject2, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  const fromPositivePromptSafetyAttributes = getValueByPath(fromObject2, [
    "positivePromptSafetyAttributes"
  ]);
  if (fromPositivePromptSafetyAttributes != null) {
    setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes));
  }
  return toObject;
}
function editImageResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject2, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function upscaleImageResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromGeneratedImages = getValueByPath(fromObject2, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function recontextImageResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromGeneratedImages = getValueByPath(fromObject2, [
    "predictions"
  ]);
  if (fromGeneratedImages != null) {
    let transformedList = fromGeneratedImages;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedImages"], transformedList);
  }
  return toObject;
}
function entityLabelFromVertex(fromObject2) {
  const toObject = {};
  const fromLabel = getValueByPath(fromObject2, ["label"]);
  if (fromLabel != null) {
    setValueByPath(toObject, ["label"], fromLabel);
  }
  const fromScore = getValueByPath(fromObject2, ["score"]);
  if (fromScore != null) {
    setValueByPath(toObject, ["score"], fromScore);
  }
  return toObject;
}
function generatedImageMaskFromVertex(fromObject2) {
  const toObject = {};
  const fromMask = getValueByPath(fromObject2, ["_self"]);
  if (fromMask != null) {
    setValueByPath(toObject, ["mask"], imageFromVertex(fromMask));
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (fromLabels != null) {
    let transformedList = fromLabels;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return entityLabelFromVertex(item);
      });
    }
    setValueByPath(toObject, ["labels"], transformedList);
  }
  return toObject;
}
function segmentImageResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromGeneratedMasks = getValueByPath(fromObject2, ["predictions"]);
  if (fromGeneratedMasks != null) {
    let transformedList = fromGeneratedMasks;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedImageMaskFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedMasks"], transformedList);
  }
  return toObject;
}
function endpointFromVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["endpoint"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDeployedModelId = getValueByPath(fromObject2, [
    "deployedModelId"
  ]);
  if (fromDeployedModelId != null) {
    setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId);
  }
  return toObject;
}
function tunedModelInfoFromVertex(fromObject2) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject2, [
    "labels",
    "google-vertex-llm-tuning-base-model-id"
  ]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  return toObject;
}
function checkpointFromVertex(fromObject2) {
  const toObject = {};
  const fromCheckpointId = getValueByPath(fromObject2, ["checkpointId"]);
  if (fromCheckpointId != null) {
    setValueByPath(toObject, ["checkpointId"], fromCheckpointId);
  }
  const fromEpoch = getValueByPath(fromObject2, ["epoch"]);
  if (fromEpoch != null) {
    setValueByPath(toObject, ["epoch"], fromEpoch);
  }
  const fromStep = getValueByPath(fromObject2, ["step"]);
  if (fromStep != null) {
    setValueByPath(toObject, ["step"], fromStep);
  }
  return toObject;
}
function modelFromVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromDisplayName = getValueByPath(fromObject2, ["displayName"]);
  if (fromDisplayName != null) {
    setValueByPath(toObject, ["displayName"], fromDisplayName);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromVersion = getValueByPath(fromObject2, ["versionId"]);
  if (fromVersion != null) {
    setValueByPath(toObject, ["version"], fromVersion);
  }
  const fromEndpoints = getValueByPath(fromObject2, ["deployedModels"]);
  if (fromEndpoints != null) {
    let transformedList = fromEndpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return endpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["endpoints"], transformedList);
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromTunedModelInfo = getValueByPath(fromObject2, ["_self"]);
  if (fromTunedModelInfo != null) {
    setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromVertex(fromTunedModelInfo));
  }
  const fromDefaultCheckpointId = getValueByPath(fromObject2, [
    "defaultCheckpointId"
  ]);
  if (fromDefaultCheckpointId != null) {
    setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId);
  }
  const fromCheckpoints = getValueByPath(fromObject2, ["checkpoints"]);
  if (fromCheckpoints != null) {
    let transformedList = fromCheckpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return checkpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function listModelsResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromModels = getValueByPath(fromObject2, ["_self"]);
  if (fromModels != null) {
    let transformedList = tExtractModels(fromModels);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return modelFromVertex(item);
      });
    }
    setValueByPath(toObject, ["models"], transformedList);
  }
  return toObject;
}
function deleteModelResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  return toObject;
}
function countTokensResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTotalTokens = getValueByPath(fromObject2, ["totalTokens"]);
  if (fromTotalTokens != null) {
    setValueByPath(toObject, ["totalTokens"], fromTotalTokens);
  }
  return toObject;
}
function computeTokensResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromTokensInfo = getValueByPath(fromObject2, ["tokensInfo"]);
  if (fromTokensInfo != null) {
    setValueByPath(toObject, ["tokensInfo"], fromTokensInfo);
  }
  return toObject;
}
function videoFromVertex(fromObject2) {
  const toObject = {};
  const fromUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromUri != null) {
    setValueByPath(toObject, ["uri"], fromUri);
  }
  const fromVideoBytes = getValueByPath(fromObject2, [
    "bytesBase64Encoded"
  ]);
  if (fromVideoBytes != null) {
    setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes));
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function generatedVideoFromVertex(fromObject2) {
  const toObject = {};
  const fromVideo = getValueByPath(fromObject2, ["_self"]);
  if (fromVideo != null) {
    setValueByPath(toObject, ["video"], videoFromVertex(fromVideo));
  }
  return toObject;
}
function generateVideosResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromGeneratedVideos = getValueByPath(fromObject2, ["videos"]);
  if (fromGeneratedVideos != null) {
    let transformedList = fromGeneratedVideos;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return generatedVideoFromVertex(item);
      });
    }
    setValueByPath(toObject, ["generatedVideos"], transformedList);
  }
  const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [
    "raiMediaFilteredCount"
  ]);
  if (fromRaiMediaFilteredCount != null) {
    setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount);
  }
  const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [
    "raiMediaFilteredReasons"
  ]);
  if (fromRaiMediaFilteredReasons != null) {
    setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons);
  }
  return toObject;
}
function generateVideosOperationFromVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], generateVideosResponseFromVertex(fromResponse));
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const CONTENT_TYPE_HEADER = "Content-Type";
const SERVER_TIMEOUT_HEADER = "X-Server-Timeout";
const USER_AGENT_HEADER = "User-Agent";
const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client";
const SDK_VERSION = "1.20.0";
const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1";
const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta";
const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
class ApiClient {
  constructor(opts) {
    var _a3, _b2;
    this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai });
    const initHttpOptions = {};
    if (this.clientOptions.vertexai) {
      initHttpOptions.apiVersion = (_a3 = this.clientOptions.apiVersion) !== null && _a3 !== void 0 ? _a3 : VERTEX_AI_API_DEFAULT_VERSION;
      initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();
      this.normalizeAuthParameters();
    } else {
      initHttpOptions.apiVersion = (_b2 = this.clientOptions.apiVersion) !== null && _b2 !== void 0 ? _b2 : GOOGLE_AI_API_DEFAULT_VERSION;
      initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;
    }
    initHttpOptions.headers = this.getDefaultHeaders();
    this.clientOptions.httpOptions = initHttpOptions;
    if (opts.httpOptions) {
      this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);
    }
  }
  /**
   * Determines the base URL for Vertex AI based on project and location.
   * Uses the global endpoint if location is 'global' or if project/location
   * are not specified (implying API key usage).
   * @private
   */
  baseUrlFromProjectLocation() {
    if (this.clientOptions.project && this.clientOptions.location && this.clientOptions.location !== "global") {
      return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;
    }
    return `https://aiplatform.googleapis.com/`;
  }
  /**
   * Normalizes authentication parameters for Vertex AI.
   * If project and location are provided, API key is cleared.
   * If project and location are not provided (implying API key usage),
   * project and location are cleared.
   * @private
   */
  normalizeAuthParameters() {
    if (this.clientOptions.project && this.clientOptions.location) {
      this.clientOptions.apiKey = void 0;
      return;
    }
    this.clientOptions.project = void 0;
    this.clientOptions.location = void 0;
  }
  isVertexAI() {
    var _a3;
    return (_a3 = this.clientOptions.vertexai) !== null && _a3 !== void 0 ? _a3 : false;
  }
  getProject() {
    return this.clientOptions.project;
  }
  getLocation() {
    return this.clientOptions.location;
  }
  getApiVersion() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.apiVersion !== void 0) {
      return this.clientOptions.httpOptions.apiVersion;
    }
    throw new Error("API version is not set.");
  }
  getBaseUrl() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.baseUrl !== void 0) {
      return this.clientOptions.httpOptions.baseUrl;
    }
    throw new Error("Base URL is not set.");
  }
  getRequestUrl() {
    return this.getRequestUrlInternal(this.clientOptions.httpOptions);
  }
  getHeaders() {
    if (this.clientOptions.httpOptions && this.clientOptions.httpOptions.headers !== void 0) {
      return this.clientOptions.httpOptions.headers;
    } else {
      throw new Error("Headers are not set.");
    }
  }
  getRequestUrlInternal(httpOptions) {
    if (!httpOptions || httpOptions.baseUrl === void 0 || httpOptions.apiVersion === void 0) {
      throw new Error("HTTP options are not correctly set.");
    }
    const baseUrl = httpOptions.baseUrl.endsWith("/") ? httpOptions.baseUrl.slice(0, -1) : httpOptions.baseUrl;
    const urlElement = [baseUrl];
    if (httpOptions.apiVersion && httpOptions.apiVersion !== "") {
      urlElement.push(httpOptions.apiVersion);
    }
    return urlElement.join("/");
  }
  getBaseResourcePath() {
    return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;
  }
  getApiKey() {
    return this.clientOptions.apiKey;
  }
  getWebsocketBaseUrl() {
    const baseUrl = this.getBaseUrl();
    const urlParts = new URL(baseUrl);
    urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss";
    return urlParts.toString();
  }
  setBaseUrl(url) {
    if (this.clientOptions.httpOptions) {
      this.clientOptions.httpOptions.baseUrl = url;
    } else {
      throw new Error("HTTP options are not correctly set.");
    }
  }
  constructUrl(path, httpOptions, prependProjectLocation) {
    const urlElement = [this.getRequestUrlInternal(httpOptions)];
    if (prependProjectLocation) {
      urlElement.push(this.getBaseResourcePath());
    }
    if (path !== "") {
      urlElement.push(path);
    }
    const url = new URL(`${urlElement.join("/")}`);
    return url;
  }
  shouldPrependVertexProjectPath(request) {
    if (this.clientOptions.apiKey) {
      return false;
    }
    if (!this.clientOptions.vertexai) {
      return false;
    }
    if (request.path.startsWith("projects/")) {
      return false;
    }
    if (request.httpMethod === "GET" && request.path.startsWith("publishers/google/models")) {
      return false;
    }
    return true;
  }
  async request(request) {
    let patchedHttpOptions = this.clientOptions.httpOptions;
    if (request.httpOptions) {
      patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
    }
    const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
    const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
    if (request.queryParams) {
      for (const [key2, value] of Object.entries(request.queryParams)) {
        url.searchParams.append(key2, String(value));
      }
    }
    let requestInit = {};
    if (request.httpMethod === "GET") {
      if (request.body && request.body !== "{}") {
        throw new Error("Request body should be empty for GET request, but got non empty request body");
      }
    } else {
      requestInit.body = request.body;
    }
    requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal);
    return this.unaryApiCall(url, requestInit, request.httpMethod);
  }
  patchHttpOptions(baseHttpOptions, requestHttpOptions) {
    const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));
    for (const [key2, value] of Object.entries(requestHttpOptions)) {
      if (typeof value === "object") {
        patchedHttpOptions[key2] = Object.assign(Object.assign({}, patchedHttpOptions[key2]), value);
      } else if (value !== void 0) {
        patchedHttpOptions[key2] = value;
      }
    }
    return patchedHttpOptions;
  }
  async requestStream(request) {
    let patchedHttpOptions = this.clientOptions.httpOptions;
    if (request.httpOptions) {
      patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
    }
    const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
    const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
    if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") {
      url.searchParams.set("alt", "sse");
    }
    let requestInit = {};
    requestInit.body = request.body;
    requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, request.abortSignal);
    return this.streamApiCall(url, requestInit, request.httpMethod);
  }
  async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, abortSignal) {
    if (httpOptions && httpOptions.timeout || abortSignal) {
      const abortController = new AbortController();
      const signal = abortController.signal;
      if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
        const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
        if (timeoutHandle && typeof timeoutHandle.unref === "function") {
          timeoutHandle.unref();
        }
      }
      if (abortSignal) {
        abortSignal.addEventListener("abort", () => {
          abortController.abort();
        });
      }
      requestInit.signal = signal;
    }
    if (httpOptions && httpOptions.extraBody !== null) {
      includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);
    }
    requestInit.headers = await this.getHeadersInternal(httpOptions);
    return requestInit;
  }
  async unaryApiCall(url, requestInit, httpMethod) {
    return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
      await throwErrorIfNotOK(response);
      return new HttpResponse(response);
    }).catch((e4) => {
      if (e4 instanceof Error) {
        throw e4;
      } else {
        throw new Error(JSON.stringify(e4));
      }
    });
  }
  async streamApiCall(url, requestInit, httpMethod) {
    return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => {
      await throwErrorIfNotOK(response);
      return this.processStreamResponse(response);
    }).catch((e4) => {
      if (e4 instanceof Error) {
        throw e4;
      } else {
        throw new Error(JSON.stringify(e4));
      }
    });
  }
  processStreamResponse(response) {
    var _a3;
    return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
      const reader = (_a3 = response === null || response === void 0 ? void 0 : response.body) === null || _a3 === void 0 ? void 0 : _a3.getReader();
      const decoder2 = new TextDecoder("utf-8");
      if (!reader) {
        throw new Error("Response body is empty");
      }
      try {
        let buffer2 = "";
        while (true) {
          const { done, value } = yield __await(reader.read());
          if (done) {
            if (buffer2.trim().length > 0) {
              throw new Error("Incomplete JSON segment at the end");
            }
            break;
          }
          const chunkString = decoder2.decode(value, { stream: true });
          try {
            const chunkJson = JSON.parse(chunkString);
            if ("error" in chunkJson) {
              const errorJson = JSON.parse(JSON.stringify(chunkJson["error"]));
              const status = errorJson["status"];
              const code = errorJson["code"];
              const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;
              if (code >= 400 && code < 600) {
                const apiError = new ApiError({
                  message: errorMessage,
                  status: code
                });
                throw apiError;
              }
            }
          } catch (e4) {
            const error = e4;
            if (error.name === "ApiError") {
              throw e4;
            }
          }
          buffer2 += chunkString;
          let match = buffer2.match(responseLineRE);
          while (match) {
            const processedChunkString = match[1];
            try {
              const partialResponse = new Response(processedChunkString, {
                headers: response === null || response === void 0 ? void 0 : response.headers,
                status: response === null || response === void 0 ? void 0 : response.status,
                statusText: response === null || response === void 0 ? void 0 : response.statusText
              });
              yield yield __await(new HttpResponse(partialResponse));
              buffer2 = buffer2.slice(match[0].length);
              match = buffer2.match(responseLineRE);
            } catch (e4) {
              throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e4}`);
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    });
  }
  async apiCall(url, requestInit) {
    return fetch(url, requestInit).catch((e4) => {
      throw new Error(`exception ${e4} sending request`);
    });
  }
  getDefaultHeaders() {
    const headers = {};
    const versionHeaderValue = LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra;
    headers[USER_AGENT_HEADER] = versionHeaderValue;
    headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;
    headers[CONTENT_TYPE_HEADER] = "application/json";
    return headers;
  }
  async getHeadersInternal(httpOptions) {
    const headers = new Headers();
    if (httpOptions && httpOptions.headers) {
      for (const [key2, value] of Object.entries(httpOptions.headers)) {
        headers.append(key2, value);
      }
      if (httpOptions.timeout && httpOptions.timeout > 0) {
        headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1e3)));
      }
    }
    await this.clientOptions.auth.addAuthHeaders(headers);
    return headers;
  }
  /**
   * Uploads a file asynchronously using Gemini API only, this is not supported
   * in Vertex AI.
   *
   * @param file The string path to the file to be uploaded or a Blob object.
   * @param config Optional parameters specified in the `UploadFileConfig`
   *     interface. @see {@link UploadFileConfig}
   * @return A promise that resolves to a `File` object.
   * @throws An error if called on a Vertex AI client.
   * @throws An error if the `mimeType` is not provided and can not be inferred,
   */
  async uploadFile(file, config) {
    var _a3;
    const fileToUpload = {};
    if (config != null) {
      fileToUpload.mimeType = config.mimeType;
      fileToUpload.name = config.name;
      fileToUpload.displayName = config.displayName;
    }
    if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) {
      fileToUpload.name = `files/${fileToUpload.name}`;
    }
    const uploader = this.clientOptions.uploader;
    const fileStat = await uploader.stat(file);
    fileToUpload.sizeBytes = String(fileStat.size);
    const mimeType = (_a3 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a3 !== void 0 ? _a3 : fileStat.type;
    if (mimeType === void 0 || mimeType === "") {
      throw new Error("Can not determine mimeType. Please provide mimeType in the config.");
    }
    fileToUpload.mimeType = mimeType;
    const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);
    return uploader.upload(file, uploadUrl, this);
  }
  /**
   * Downloads a file asynchronously to the specified path.
   *
   * @params params - The parameters for the download request, see {@link
   * DownloadFileParameters}
   */
  async downloadFile(params) {
    const downloader = this.clientOptions.downloader;
    await downloader.download(params, this);
  }
  async fetchUploadUrl(file, config) {
    var _a3;
    let httpOptions = {};
    if (config === null || config === void 0 ? void 0 : config.httpOptions) {
      httpOptions = config.httpOptions;
    } else {
      httpOptions = {
        apiVersion: "",
        headers: {
          "Content-Type": "application/json",
          "X-Goog-Upload-Protocol": "resumable",
          "X-Goog-Upload-Command": "start",
          "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`,
          "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`
        }
      };
    }
    const body = {
      "file": file
    };
    const httpResponse = await this.request({
      path: formatMap("upload/v1beta/files", body["_url"]),
      body: JSON.stringify(body),
      httpMethod: "POST",
      httpOptions
    });
    if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {
      throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");
    }
    const uploadUrl = (_a3 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a3 === void 0 ? void 0 : _a3["x-goog-upload-url"];
    if (uploadUrl === void 0) {
      throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");
    }
    return uploadUrl;
  }
}
async function throwErrorIfNotOK(response) {
  var _a3;
  if (response === void 0) {
    throw new Error("response is undefined");
  }
  if (!response.ok) {
    const status = response.status;
    let errorBody;
    if ((_a3 = response.headers.get("content-type")) === null || _a3 === void 0 ? void 0 : _a3.includes("application/json")) {
      errorBody = await response.json();
    } else {
      errorBody = {
        error: {
          message: await response.text(),
          code: response.status,
          status: response.statusText
        }
      };
    }
    const errorMessage = JSON.stringify(errorBody);
    if (status >= 400 && status < 600) {
      const apiError = new ApiError({
        message: errorMessage,
        status
      });
      throw apiError;
    }
    throw new Error(errorMessage);
  }
}
function includeExtraBodyToRequestInit(requestInit, extraBody) {
  if (!extraBody || Object.keys(extraBody).length === 0) {
    return;
  }
  if (requestInit.body instanceof Blob) {
    console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");
    return;
  }
  let currentBodyObject = {};
  if (typeof requestInit.body === "string" && requestInit.body.length > 0) {
    try {
      const parsedBody = JSON.parse(requestInit.body);
      if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) {
        currentBodyObject = parsedBody;
      } else {
        console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");
        return;
      }
    } catch (e4) {
      console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");
      return;
    }
  }
  function deepMerge(target, source) {
    const output = Object.assign({}, target);
    for (const key2 in source) {
      if (Object.prototype.hasOwnProperty.call(source, key2)) {
        const sourceValue = source[key2];
        const targetValue = output[key2];
        if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) {
          output[key2] = deepMerge(targetValue, sourceValue);
        } else {
          if (targetValue && sourceValue && typeof targetValue !== typeof sourceValue) {
            console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key2}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);
          }
          output[key2] = sourceValue;
        }
      }
    }
    return output;
  }
  const mergedBody = deepMerge(currentBodyObject, extraBody);
  requestInit.body = JSON.stringify(mergedBody);
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const MCP_LABEL = "mcp_used/unknown";
let hasMcpToolUsageFromMcpToTool = false;
function hasMcpToolUsage(tools) {
  for (const tool of tools) {
    if (isMcpCallableTool(tool)) {
      return true;
    }
    if (typeof tool === "object" && "inputSchema" in tool) {
      return true;
    }
  }
  return hasMcpToolUsageFromMcpToTool;
}
function setMcpUsageHeader(headers) {
  var _a3;
  const existingHeader = (_a3 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a3 !== void 0 ? _a3 : "";
  headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart();
}
function isMcpCallableTool(object) {
  return object !== null && typeof object === "object" && object instanceof McpCallableTool;
}
function listAllTools(mcpClient, maxTools = 100) {
  return __asyncGenerator(this, arguments, function* listAllTools_1() {
    let cursor = void 0;
    let numTools = 0;
    while (numTools < maxTools) {
      const t2 = yield __await(mcpClient.listTools({ cursor }));
      for (const tool of t2.tools) {
        yield yield __await(tool);
        numTools++;
      }
      if (!t2.nextCursor) {
        break;
      }
      cursor = t2.nextCursor;
    }
  });
}
class McpCallableTool {
  constructor(mcpClients = [], config) {
    this.mcpTools = [];
    this.functionNameToMcpClient = {};
    this.mcpClients = mcpClients;
    this.config = config;
  }
  /**
   * Creates a McpCallableTool.
   */
  static create(mcpClients, config) {
    return new McpCallableTool(mcpClients, config);
  }
  /**
   * Validates the function names are not duplicate and initialize the function
   * name to MCP client mapping.
   *
   * @throws {Error} if the MCP tools from the MCP clients have duplicate tool
   *     names.
   */
  async initialize() {
    var _a3, e_1, _b2, _c2;
    if (this.mcpTools.length > 0) {
      return;
    }
    const functionMap = {};
    const mcpTools = [];
    for (const mcpClient of this.mcpClients) {
      try {
        for (var _d2 = true, _e2 = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f2; _f2 = await _e2.next(), _a3 = _f2.done, !_a3; _d2 = true) {
          _c2 = _f2.value;
          _d2 = false;
          const mcpTool = _c2;
          mcpTools.push(mcpTool);
          const mcpToolName = mcpTool.name;
          if (functionMap[mcpToolName]) {
            throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`);
          }
          functionMap[mcpToolName] = mcpClient;
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_d2 && !_a3 && (_b2 = _e2.return)) await _b2.call(_e2);
        } finally {
          if (e_1) throw e_1.error;
        }
      }
    }
    this.mcpTools = mcpTools;
    this.functionNameToMcpClient = functionMap;
  }
  async tool() {
    await this.initialize();
    return mcpToolsToGeminiTool(this.mcpTools, this.config);
  }
  async callTool(functionCalls) {
    await this.initialize();
    const functionCallResponseParts = [];
    for (const functionCall2 of functionCalls) {
      if (functionCall2.name in this.functionNameToMcpClient) {
        const mcpClient = this.functionNameToMcpClient[functionCall2.name];
        let requestOptions = void 0;
        if (this.config.timeout) {
          requestOptions = {
            timeout: this.config.timeout
          };
        }
        const callToolResponse = await mcpClient.callTool(
          {
            name: functionCall2.name,
            arguments: functionCall2.args
          },
          // Set the result schema to undefined to allow MCP to rely on the
          // default schema.
          void 0,
          requestOptions
        );
        functionCallResponseParts.push({
          functionResponse: {
            name: functionCall2.name,
            response: callToolResponse.isError ? { error: callToolResponse } : callToolResponse
          }
        });
      }
    }
    return functionCallResponseParts;
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
async function handleWebSocketMessage$1(apiClient, onmessage, event) {
  const serverMessage = new LiveMusicServerMessage();
  let data2;
  if (event.data instanceof Blob) {
    data2 = JSON.parse(await event.data.text());
  } else {
    data2 = JSON.parse(event.data);
  }
  const response = liveMusicServerMessageFromMldev(data2);
  Object.assign(serverMessage, response);
  onmessage(serverMessage);
}
class LiveMusic {
  constructor(apiClient, auth, webSocketFactory) {
    this.apiClient = apiClient;
    this.auth = auth;
    this.webSocketFactory = webSocketFactory;
  }
  /**
       Establishes a connection to the specified model and returns a
       LiveMusicSession object representing that connection.
  
       @experimental
  
       @remarks
  
       @param params - The parameters for establishing a connection to the model.
       @return A live session.
  
       @example
       ```ts
       let model = 'models/lyria-realtime-exp';
       const session = await ai.live.music.connect({
         model: model,
         callbacks: {
           onmessage: (e: MessageEvent) => {
             console.log('Received message from the server: %s\n', debug(e.data));
           },
           onerror: (e: ErrorEvent) => {
             console.log('Error occurred: %s\n', debug(e.error));
           },
           onclose: (e: CloseEvent) => {
             console.log('Connection closed.');
           },
         },
       });
       ```
      */
  async connect(params) {
    var _a3, _b2;
    if (this.apiClient.isVertexAI()) {
      throw new Error("Live music is not supported for Vertex AI.");
    }
    console.warn("Live music generation is experimental and may change in future versions.");
    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
    const apiVersion = this.apiClient.getApiVersion();
    const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders());
    const apiKey = this.apiClient.getApiKey();
    const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`;
    let onopenResolve = () => {
    };
    const onopenPromise = new Promise((resolve2) => {
      onopenResolve = resolve2;
    });
    const callbacks = params.callbacks;
    const onopenAwaitedCallback = function() {
      onopenResolve({});
    };
    const apiClient = this.apiClient;
    const websocketCallbacks = {
      onopen: onopenAwaitedCallback,
      onmessage: (event) => {
        void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event);
      },
      onerror: (_a3 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a3 !== void 0 ? _a3 : function(e4) {
      },
      onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e4) {
      }
    };
    const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks);
    conn.connect();
    await onopenPromise;
    const model = tModel(this.apiClient, params.model);
    const setup = liveMusicClientSetupToMldev({
      model
    });
    const clientMessage = liveMusicClientMessageToMldev({ setup });
    conn.send(JSON.stringify(clientMessage));
    return new LiveMusicSession(conn, this.apiClient);
  }
}
class LiveMusicSession {
  constructor(conn, apiClient) {
    this.conn = conn;
    this.apiClient = apiClient;
  }
  /**
      Sets inputs to steer music generation. Updates the session's current
      weighted prompts.
  
      @param params - Contains one property, `weightedPrompts`.
  
        - `weightedPrompts` to send to the model; weights are normalized to
          sum to 1.0.
  
      @experimental
     */
  async setWeightedPrompts(params) {
    if (!params.weightedPrompts || Object.keys(params.weightedPrompts).length === 0) {
      throw new Error("Weighted prompts must be set and contain at least one entry.");
    }
    const setWeightedPromptsParameters = liveMusicSetWeightedPromptsParametersToMldev(params);
    const clientContent = liveMusicClientContentToMldev(setWeightedPromptsParameters);
    this.conn.send(JSON.stringify({ clientContent }));
  }
  /**
      Sets a configuration to the model. Updates the session's current
      music generation config.
  
      @param params - Contains one property, `musicGenerationConfig`.
  
        - `musicGenerationConfig` to set in the model. Passing an empty or
      undefined config to the model will reset the config to defaults.
  
      @experimental
     */
  async setMusicGenerationConfig(params) {
    if (!params.musicGenerationConfig) {
      params.musicGenerationConfig = {};
    }
    const setConfigParameters = liveMusicSetConfigParametersToMldev(params);
    const clientMessage = liveMusicClientMessageToMldev(setConfigParameters);
    this.conn.send(JSON.stringify(clientMessage));
  }
  sendPlaybackControl(playbackControl) {
    const clientMessage = liveMusicClientMessageToMldev({
      playbackControl
    });
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
   * Start the music stream.
   *
   * @experimental
   */
  play() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY);
  }
  /**
   * Temporarily halt the music stream. Use `play` to resume from the current
   * position.
   *
   * @experimental
   */
  pause() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE);
  }
  /**
   * Stop the music stream and reset the state. Retains the current prompts
   * and config.
   *
   * @experimental
   */
  stop() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.STOP);
  }
  /**
   * Resets the context of the music generation without stopping it.
   * Retains the current prompts and config.
   *
   * @experimental
   */
  resetContext() {
    this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT);
  }
  /**
       Terminates the WebSocket connection.
  
       @experimental
     */
  close() {
    this.conn.close();
  }
}
function headersToMap$1(headers) {
  const headerMap = {};
  headers.forEach((value, key2) => {
    headerMap[key2] = value;
  });
  return headerMap;
}
function mapToHeaders$1(map) {
  const headers = new Headers();
  for (const [key2, value] of Object.entries(map)) {
    headers.append(key2, value);
  }
  return headers;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const FUNCTION_RESPONSE_REQUIRES_ID = "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";
async function handleWebSocketMessage(apiClient, onmessage, event) {
  const serverMessage = new LiveServerMessage();
  let jsonData;
  if (event.data instanceof Blob) {
    jsonData = await event.data.text();
  } else if (event.data instanceof ArrayBuffer) {
    jsonData = new TextDecoder().decode(event.data);
  } else {
    jsonData = event.data;
  }
  const data2 = JSON.parse(jsonData);
  if (apiClient.isVertexAI()) {
    const resp = liveServerMessageFromVertex(data2);
    Object.assign(serverMessage, resp);
  } else {
    const resp = liveServerMessageFromMldev(data2);
    Object.assign(serverMessage, resp);
  }
  onmessage(serverMessage);
}
class Live {
  constructor(apiClient, auth, webSocketFactory) {
    this.apiClient = apiClient;
    this.auth = auth;
    this.webSocketFactory = webSocketFactory;
    this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory);
  }
  /**
       Establishes a connection to the specified model with the given
       configuration and returns a Session object representing that connection.
  
       @experimental Built-in MCP support is an experimental feature, may change in
       future versions.
  
       @remarks
  
       @param params - The parameters for establishing a connection to the model.
       @return A live session.
  
       @example
       ```ts
       let model: string;
       if (GOOGLE_GENAI_USE_VERTEXAI) {
         model = 'gemini-2.0-flash-live-preview-04-09';
       } else {
         model = 'gemini-live-2.5-flash-preview';
       }
       const session = await ai.live.connect({
         model: model,
         config: {
           responseModalities: [Modality.AUDIO],
         },
         callbacks: {
           onopen: () => {
             console.log('Connected to the socket.');
           },
           onmessage: (e: MessageEvent) => {
             console.log('Received message from the server: %s\n', debug(e.data));
           },
           onerror: (e: ErrorEvent) => {
             console.log('Error occurred: %s\n', debug(e.error));
           },
           onclose: (e: CloseEvent) => {
             console.log('Connection closed.');
           },
         },
       });
       ```
      */
  async connect(params) {
    var _a3, _b2, _c2, _d2, _e2, _f2;
    if (params.config && params.config.httpOptions) {
      throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");
    }
    const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();
    const apiVersion = this.apiClient.getApiVersion();
    let url;
    const clientHeaders = this.apiClient.getHeaders();
    if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
      setMcpUsageHeader(clientHeaders);
    }
    const headers = mapToHeaders(clientHeaders);
    if (this.apiClient.isVertexAI()) {
      url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`;
      await this.auth.addAuthHeaders(headers);
    } else {
      const apiKey = this.apiClient.getApiKey();
      let method = "BidiGenerateContent";
      let keyName = "key";
      if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith("auth_tokens/")) {
        console.warn("Warning: Ephemeral token support is experimental and may change in future versions.");
        if (apiVersion !== "v1alpha") {
          console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection.");
        }
        method = "BidiGenerateContentConstrained";
        keyName = "access_token";
      }
      url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`;
    }
    let onopenResolve = () => {
    };
    const onopenPromise = new Promise((resolve2) => {
      onopenResolve = resolve2;
    });
    const callbacks = params.callbacks;
    const onopenAwaitedCallback = function() {
      var _a4;
      (_a4 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a4 === void 0 ? void 0 : _a4.call(callbacks);
      onopenResolve({});
    };
    const apiClient = this.apiClient;
    const websocketCallbacks = {
      onopen: onopenAwaitedCallback,
      onmessage: (event) => {
        void handleWebSocketMessage(apiClient, callbacks.onmessage, event);
      },
      onerror: (_a3 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a3 !== void 0 ? _a3 : function(e4) {
      },
      onclose: (_b2 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b2 !== void 0 ? _b2 : function(e4) {
      }
    };
    const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks);
    conn.connect();
    await onopenPromise;
    let transformedModel = tModel(this.apiClient, params.model);
    if (this.apiClient.isVertexAI() && transformedModel.startsWith("publishers/")) {
      const project = this.apiClient.getProject();
      const location = this.apiClient.getLocation();
      transformedModel = `projects/${project}/locations/${location}/` + transformedModel;
    }
    let clientMessage = {};
    if (this.apiClient.isVertexAI() && ((_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.responseModalities) === void 0) {
      if (params.config === void 0) {
        params.config = { responseModalities: [Modality.AUDIO] };
      } else {
        params.config.responseModalities = [Modality.AUDIO];
      }
    }
    if ((_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.generationConfig) {
      console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");
    }
    const inputTools = (_f2 = (_e2 = params.config) === null || _e2 === void 0 ? void 0 : _e2.tools) !== null && _f2 !== void 0 ? _f2 : [];
    const convertedTools = [];
    for (const tool of inputTools) {
      if (this.isCallableTool(tool)) {
        const callableTool = tool;
        convertedTools.push(await callableTool.tool());
      } else {
        convertedTools.push(tool);
      }
    }
    if (convertedTools.length > 0) {
      params.config.tools = convertedTools;
    }
    const liveConnectParameters = {
      model: transformedModel,
      config: params.config,
      callbacks: params.callbacks
    };
    if (this.apiClient.isVertexAI()) {
      clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters);
    } else {
      clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters);
    }
    delete clientMessage["config"];
    conn.send(JSON.stringify(clientMessage));
    return new Session(conn, this.apiClient);
  }
  // TODO: b/416041229 - Abstract this method to a common place.
  isCallableTool(tool) {
    return "callTool" in tool && typeof tool.callTool === "function";
  }
}
const defaultLiveSendClientContentParamerters = {
  turnComplete: true
};
class Session {
  constructor(conn, apiClient) {
    this.conn = conn;
    this.apiClient = apiClient;
  }
  tLiveClientContent(apiClient, params) {
    if (params.turns !== null && params.turns !== void 0) {
      let contents = [];
      try {
        contents = tContents(params.turns);
        if (apiClient.isVertexAI()) {
          contents = contents.map((item) => contentToVertex(item));
        } else {
          contents = contents.map((item) => contentToMldev$1(item));
        }
      } catch (_a3) {
        throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`);
      }
      return {
        clientContent: { turns: contents, turnComplete: params.turnComplete }
      };
    }
    return {
      clientContent: { turnComplete: params.turnComplete }
    };
  }
  tLiveClienttToolResponse(apiClient, params) {
    let functionResponses = [];
    if (params.functionResponses == null) {
      throw new Error("functionResponses is required.");
    }
    if (!Array.isArray(params.functionResponses)) {
      functionResponses = [params.functionResponses];
    } else {
      functionResponses = params.functionResponses;
    }
    if (functionResponses.length === 0) {
      throw new Error("functionResponses is required.");
    }
    for (const functionResponse of functionResponses) {
      if (typeof functionResponse !== "object" || functionResponse === null || !("name" in functionResponse) || !("response" in functionResponse)) {
        throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`);
      }
      if (!apiClient.isVertexAI() && !("id" in functionResponse)) {
        throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);
      }
    }
    const clientMessage = {
      toolResponse: { functionResponses }
    };
    return clientMessage;
  }
  /**
      Send a message over the established connection.
  
      @param params - Contains two **optional** properties, `turns` and
          `turnComplete`.
  
        - `turns` will be converted to a `Content[]`
        - `turnComplete: true` [default] indicates that you are done sending
          content and expect a response. If `turnComplete: false`, the server
          will wait for additional messages before starting generation.
  
      @experimental
  
      @remarks
      There are two ways to send messages to the live API:
      `sendClientContent` and `sendRealtimeInput`.
  
      `sendClientContent` messages are added to the model context **in order**.
      Having a conversation using `sendClientContent` messages is roughly
      equivalent to using the `Chat.sendMessageStream`, except that the state of
      the `chat` history is stored on the API server instead of locally.
  
      Because of `sendClientContent`'s order guarantee, the model cannot respons
      as quickly to `sendClientContent` messages as to `sendRealtimeInput`
      messages. This makes the biggest difference when sending objects that have
      significant preprocessing time (typically images).
  
      The `sendClientContent` message sends a `Content[]`
      which has more options than the `Blob` sent by `sendRealtimeInput`.
  
      So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:
  
      - Sending anything that can't be represented as a `Blob` (text,
      `sendClientContent({turns="Hello?"}`)).
      - Managing turns when not using audio input and voice activity detection.
        (`sendClientContent({turnComplete:true})` or the short form
      `sendClientContent()`)
      - Prefilling a conversation context
        ```
        sendClientContent({
            turns: [
              Content({role:user, parts:...}),
              Content({role:user, parts:...}),
              ...
            ]
        })
        ```
      @experimental
     */
  sendClientContent(params) {
    params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params);
    const clientMessage = this.tLiveClientContent(this.apiClient, params);
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
      Send a realtime message over the established connection.
  
      @param params - Contains one property, `media`.
  
        - `media` will be converted to a `Blob`
  
      @experimental
  
      @remarks
      Use `sendRealtimeInput` for realtime audio chunks and video frames (images).
  
      With `sendRealtimeInput` the api will respond to audio automatically
      based on voice activity detection (VAD).
  
      `sendRealtimeInput` is optimized for responsivness at the expense of
      deterministic ordering guarantees. Audio and video tokens are to the
      context when they become available.
  
      Note: The Call signature expects a `Blob` object, but only a subset
      of audio and image mimetypes are allowed.
     */
  sendRealtimeInput(params) {
    let clientMessage = {};
    if (this.apiClient.isVertexAI()) {
      clientMessage = {
        "realtimeInput": liveSendRealtimeInputParametersToVertex(params)
      };
    } else {
      clientMessage = {
        "realtimeInput": liveSendRealtimeInputParametersToMldev(params)
      };
    }
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
      Send a function response message over the established connection.
  
      @param params - Contains property `functionResponses`.
  
        - `functionResponses` will be converted to a `functionResponses[]`
  
      @remarks
      Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.
  
      Use {@link types.LiveConnectConfig#tools} to configure the callable functions.
  
      @experimental
     */
  sendToolResponse(params) {
    if (params.functionResponses == null) {
      throw new Error("Tool response parameters are required.");
    }
    const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params);
    this.conn.send(JSON.stringify(clientMessage));
  }
  /**
       Terminates the WebSocket connection.
  
       @experimental
  
       @example
       ```ts
       let model: string;
       if (GOOGLE_GENAI_USE_VERTEXAI) {
         model = 'gemini-2.0-flash-live-preview-04-09';
       } else {
         model = 'gemini-live-2.5-flash-preview';
       }
       const session = await ai.live.connect({
         model: model,
         config: {
           responseModalities: [Modality.AUDIO],
         }
       });
  
       session.close();
       ```
     */
  close() {
    this.conn.close();
  }
}
function headersToMap(headers) {
  const headerMap = {};
  headers.forEach((value, key2) => {
    headerMap[key2] = value;
  });
  return headerMap;
}
function mapToHeaders(map) {
  const headers = new Headers();
  for (const [key2, value] of Object.entries(map)) {
    headers.append(key2, value);
  }
  return headers;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const DEFAULT_MAX_REMOTE_CALLS = 10;
function shouldDisableAfc(config) {
  var _a3, _b2, _c2;
  if ((_a3 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a3 === void 0 ? void 0 : _a3.disable) {
    return true;
  }
  let callableToolsPresent = false;
  for (const tool of (_b2 = config === null || config === void 0 ? void 0 : config.tools) !== null && _b2 !== void 0 ? _b2 : []) {
    if (isCallableTool(tool)) {
      callableToolsPresent = true;
      break;
    }
  }
  if (!callableToolsPresent) {
    return true;
  }
  const maxCalls = (_c2 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c2 === void 0 ? void 0 : _c2.maximumRemoteCalls;
  if (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls)) || maxCalls == 0) {
    console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:", maxCalls);
    return true;
  }
  return false;
}
function isCallableTool(tool) {
  return "callTool" in tool && typeof tool.callTool === "function";
}
function hasCallableTools(params) {
  var _a3, _b2, _c2;
  return (_c2 = (_b2 = (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.tools) === null || _b2 === void 0 ? void 0 : _b2.some((tool) => isCallableTool(tool))) !== null && _c2 !== void 0 ? _c2 : false;
}
function hasNonCallableTools(params) {
  var _a3, _b2, _c2;
  return (_c2 = (_b2 = (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.tools) === null || _b2 === void 0 ? void 0 : _b2.some((tool) => !isCallableTool(tool))) !== null && _c2 !== void 0 ? _c2 : false;
}
function shouldAppendAfcHistory(config) {
  var _a3;
  return !((_a3 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a3 === void 0 ? void 0 : _a3.ignoreCallHistory);
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Models extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.generateContent = async (params) => {
      var _a3, _b2, _c2, _d2, _e2;
      const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
      this.maybeMoveToResponseJsonSchem(params);
      if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {
        return await this.generateContentInternal(transformedParams);
      }
      if (hasNonCallableTools(params)) {
        throw new Error("Automatic function calling with CallableTools and Tools is not yet supported.");
      }
      let response;
      let functionResponseContent;
      const automaticFunctionCallingHistory = tContents(transformedParams.contents);
      const maxRemoteCalls = (_c2 = (_b2 = (_a3 = transformedParams.config) === null || _a3 === void 0 ? void 0 : _a3.automaticFunctionCalling) === null || _b2 === void 0 ? void 0 : _b2.maximumRemoteCalls) !== null && _c2 !== void 0 ? _c2 : DEFAULT_MAX_REMOTE_CALLS;
      let remoteCalls = 0;
      while (remoteCalls < maxRemoteCalls) {
        response = await this.generateContentInternal(transformedParams);
        if (!response.functionCalls || response.functionCalls.length === 0) {
          break;
        }
        const responseContent = response.candidates[0].content;
        const functionResponseParts = [];
        for (const tool of (_e2 = (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.tools) !== null && _e2 !== void 0 ? _e2 : []) {
          if (isCallableTool(tool)) {
            const callableTool = tool;
            const parts = await callableTool.callTool(response.functionCalls);
            functionResponseParts.push(...parts);
          }
        }
        remoteCalls++;
        functionResponseContent = {
          role: "user",
          parts: functionResponseParts
        };
        transformedParams.contents = tContents(transformedParams.contents);
        transformedParams.contents.push(responseContent);
        transformedParams.contents.push(functionResponseContent);
        if (shouldAppendAfcHistory(transformedParams.config)) {
          automaticFunctionCallingHistory.push(responseContent);
          automaticFunctionCallingHistory.push(functionResponseContent);
        }
      }
      if (shouldAppendAfcHistory(transformedParams.config)) {
        response.automaticFunctionCallingHistory = automaticFunctionCallingHistory;
      }
      return response;
    };
    this.generateContentStream = async (params) => {
      this.maybeMoveToResponseJsonSchem(params);
      if (shouldDisableAfc(params.config)) {
        const transformedParams = await this.processParamsMaybeAddMcpUsage(params);
        return await this.generateContentStreamInternal(transformedParams);
      } else {
        return await this.processAfcStream(params);
      }
    };
    this.generateImages = async (params) => {
      return await this.generateImagesInternal(params).then((apiResponse) => {
        var _a3;
        let positivePromptSafetyAttributes;
        const generatedImages = [];
        if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) {
          for (const generatedImage of apiResponse.generatedImages) {
            if (generatedImage && (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && ((_a3 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a3 === void 0 ? void 0 : _a3.contentType) === "Positive Prompt") {
              positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes;
            } else {
              generatedImages.push(generatedImage);
            }
          }
        }
        let response;
        if (positivePromptSafetyAttributes) {
          response = {
            generatedImages,
            positivePromptSafetyAttributes,
            sdkHttpResponse: apiResponse.sdkHttpResponse
          };
        } else {
          response = {
            generatedImages,
            sdkHttpResponse: apiResponse.sdkHttpResponse
          };
        }
        return response;
      });
    };
    this.list = async (params) => {
      var _a3;
      const defaultConfig = {
        queryBase: true
      };
      const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config);
      const actualParams = {
        config: actualConfig
      };
      if (this.apiClient.isVertexAI()) {
        if (!actualParams.config.queryBase) {
          if ((_a3 = actualParams.config) === null || _a3 === void 0 ? void 0 : _a3.filter) {
            throw new Error("Filtering tuned models list for Vertex AI is not currently supported");
          } else {
            actualParams.config.filter = "labels.tune-type:*";
          }
        }
      }
      return new Pager(PagedItem.PAGED_ITEM_MODELS, (x2) => this.listInternal(x2), await this.listInternal(actualParams), actualParams);
    };
    this.editImage = async (params) => {
      const paramsInternal = {
        model: params.model,
        prompt: params.prompt,
        referenceImages: [],
        config: params.config
      };
      if (params.referenceImages) {
        if (params.referenceImages) {
          paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI());
        }
      }
      return await this.editImageInternal(paramsInternal);
    };
    this.upscaleImage = async (params) => {
      let apiConfig = {
        numberOfImages: 1,
        mode: "upscale"
      };
      if (params.config) {
        apiConfig = Object.assign(Object.assign({}, apiConfig), params.config);
      }
      const apiParams = {
        model: params.model,
        image: params.image,
        upscaleFactor: params.upscaleFactor,
        config: apiConfig
      };
      return await this.upscaleImageInternal(apiParams);
    };
    this.generateVideos = async (params) => {
      if ((params.prompt || params.image || params.video) && params.source) {
        throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");
      }
      return await this.generateVideosInternal(params);
    };
  }
  /**
   * This logic is needed for GenerateContentConfig only.
   * Previously we made GenerateContentConfig.responseSchema field to accept
   * unknown. Since v1.9.0, we switch to use backend JSON schema support.
   * To maintain backward compatibility, we move the data that was treated as
   * JSON schema from the responseSchema field to the responseJsonSchema field.
   */
  maybeMoveToResponseJsonSchem(params) {
    if (params.config && params.config.responseSchema) {
      if (!params.config.responseJsonSchema) {
        if (Object.keys(params.config.responseSchema).includes("$schema")) {
          params.config.responseJsonSchema = params.config.responseSchema;
          delete params.config.responseSchema;
        }
      }
    }
    return;
  }
  /**
   * Transforms the CallableTools in the parameters to be simply Tools, it
   * copies the params into a new object and replaces the tools, it does not
   * modify the original params. Also sets the MCP usage header if there are
   * MCP tools in the parameters.
   */
  async processParamsMaybeAddMcpUsage(params) {
    var _a3, _b2, _c2;
    const tools = (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.tools;
    if (!tools) {
      return params;
    }
    const transformedTools = await Promise.all(tools.map(async (tool) => {
      if (isCallableTool(tool)) {
        const callableTool = tool;
        return await callableTool.tool();
      }
      return tool;
    }));
    const newParams = {
      model: params.model,
      contents: params.contents,
      config: Object.assign(Object.assign({}, params.config), { tools: transformedTools })
    };
    newParams.config.tools = transformedTools;
    if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) {
      const headers = (_c2 = (_b2 = params.config.httpOptions) === null || _b2 === void 0 ? void 0 : _b2.headers) !== null && _c2 !== void 0 ? _c2 : {};
      let newHeaders = Object.assign({}, headers);
      if (Object.keys(newHeaders).length === 0) {
        newHeaders = this.apiClient.getDefaultHeaders();
      }
      setMcpUsageHeader(newHeaders);
      newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders });
    }
    return newParams;
  }
  async initAfcToolsMap(params) {
    var _a3, _b2, _c2;
    const afcTools = /* @__PURE__ */ new Map();
    for (const tool of (_b2 = (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.tools) !== null && _b2 !== void 0 ? _b2 : []) {
      if (isCallableTool(tool)) {
        const callableTool = tool;
        const toolDeclaration = await callableTool.tool();
        for (const declaration of (_c2 = toolDeclaration.functionDeclarations) !== null && _c2 !== void 0 ? _c2 : []) {
          if (!declaration.name) {
            throw new Error("Function declaration name is required.");
          }
          if (afcTools.has(declaration.name)) {
            throw new Error(`Duplicate tool declaration name: ${declaration.name}`);
          }
          afcTools.set(declaration.name, callableTool);
        }
      }
    }
    return afcTools;
  }
  async processAfcStream(params) {
    var _a3, _b2, _c2;
    const maxRemoteCalls = (_c2 = (_b2 = (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.automaticFunctionCalling) === null || _b2 === void 0 ? void 0 : _b2.maximumRemoteCalls) !== null && _c2 !== void 0 ? _c2 : DEFAULT_MAX_REMOTE_CALLS;
    let wereFunctionsCalled = false;
    let remoteCallCount = 0;
    const afcToolsMap = await this.initAfcToolsMap(params);
    return function(models, afcTools, params2) {
      var _a4, _b3;
      return __asyncGenerator(this, arguments, function* () {
        var _c3, e_1, _d2, _e2;
        while (remoteCallCount < maxRemoteCalls) {
          if (wereFunctionsCalled) {
            remoteCallCount++;
            wereFunctionsCalled = false;
          }
          const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params2));
          const response = yield __await(models.generateContentStreamInternal(transformedParams));
          const functionResponses = [];
          const responseContents = [];
          try {
            for (var _f2 = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _c3 = response_1_1.done, !_c3; _f2 = true) {
              _e2 = response_1_1.value;
              _f2 = false;
              const chunk = _e2;
              yield yield __await(chunk);
              if (chunk.candidates && ((_a4 = chunk.candidates[0]) === null || _a4 === void 0 ? void 0 : _a4.content)) {
                responseContents.push(chunk.candidates[0].content);
                for (const part of (_b3 = chunk.candidates[0].content.parts) !== null && _b3 !== void 0 ? _b3 : []) {
                  if (remoteCallCount < maxRemoteCalls && part.functionCall) {
                    if (!part.functionCall.name) {
                      throw new Error("Function call name was not returned by the model.");
                    }
                    if (!afcTools.has(part.functionCall.name)) {
                      throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`);
                    } else {
                      const responseParts = yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall]));
                      functionResponses.push(...responseParts);
                    }
                  }
                }
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_f2 && !_c3 && (_d2 = response_1.return)) yield __await(_d2.call(response_1));
            } finally {
              if (e_1) throw e_1.error;
            }
          }
          if (functionResponses.length > 0) {
            wereFunctionsCalled = true;
            const typedResponseChunk = new GenerateContentResponse();
            typedResponseChunk.candidates = [
              {
                content: {
                  role: "user",
                  parts: functionResponses
                }
              }
            ];
            yield yield __await(typedResponseChunk);
            const newContents = [];
            newContents.push(...responseContents);
            newContents.push({
              role: "user",
              parts: functionResponses
            });
            const updatedContents = tContents(params2.contents).concat(newContents);
            params2.contents = updatedContents;
          } else {
            break;
          }
        }
      });
    }(this, afcToolsMap, params);
  }
  async generateContentInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateContentParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:generateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateContentResponseFromVertex(apiResponse);
        const typedResp = new GenerateContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateContentParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:generateContent", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateContentResponseFromMldev(apiResponse);
        const typedResp = new GenerateContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  async generateContentStreamInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateContentParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      const apiClient = this.apiClient;
      response = apiClient.requestStream({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      });
      return response.then(function(apiResponse) {
        return __asyncGenerator(this, arguments, function* () {
          var _a4, e_2, _b3, _c3;
          try {
            for (var _d3 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a4 = apiResponse_1_1.done, !_a4; _d3 = true) {
              _c3 = apiResponse_1_1.value;
              _d3 = false;
              const chunk = _c3;
              const resp = generateContentResponseFromVertex(yield __await(chunk.json()));
              resp["sdkHttpResponse"] = {
                headers: chunk.headers
              };
              const typedResp = new GenerateContentResponse();
              Object.assign(typedResp, resp);
              yield yield __await(typedResp);
            }
          } catch (e_2_1) {
            e_2 = { error: e_2_1 };
          } finally {
            try {
              if (!_d3 && !_a4 && (_b3 = apiResponse_1.return)) yield __await(_b3.call(apiResponse_1));
            } finally {
              if (e_2) throw e_2.error;
            }
          }
        });
      });
    } else {
      const body = generateContentParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      const apiClient = this.apiClient;
      response = apiClient.requestStream({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      });
      return response.then(function(apiResponse) {
        return __asyncGenerator(this, arguments, function* () {
          var _a4, e_3, _b3, _c3;
          try {
            for (var _d3 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a4 = apiResponse_2_1.done, !_a4; _d3 = true) {
              _c3 = apiResponse_2_1.value;
              _d3 = false;
              const chunk = _c3;
              const resp = generateContentResponseFromMldev(yield __await(chunk.json()));
              resp["sdkHttpResponse"] = {
                headers: chunk.headers
              };
              const typedResp = new GenerateContentResponse();
              Object.assign(typedResp, resp);
              yield yield __await(typedResp);
            }
          } catch (e_3_1) {
            e_3 = { error: e_3_1 };
          } finally {
            try {
              if (!_d3 && !_a4 && (_b3 = apiResponse_2.return)) yield __await(_b3.call(apiResponse_2));
            } finally {
              if (e_3) throw e_3.error;
            }
          }
        });
      });
    }
  }
  /**
   * Calculates embeddings for the given contents. Only text is supported.
   *
   * @param params - The parameters for embedding contents.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.embedContent({
   *  model: 'text-embedding-004',
   *  contents: [
   *    'What is your name?',
   *    'What is your favorite color?',
   *  ],
   *  config: {
   *    outputDimensionality: 64,
   *  },
   * });
   * console.log(response);
   * ```
   */
  async embedContent(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = embedContentParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = embedContentResponseFromVertex(apiResponse);
        const typedResp = new EmbedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = embedContentParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:batchEmbedContents", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = embedContentResponseFromMldev(apiResponse);
        const typedResp = new EmbedContentResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Private method for generating images.
   */
  async generateImagesInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateImagesParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateImagesResponseFromVertex(apiResponse);
        const typedResp = new GenerateImagesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateImagesParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = generateImagesResponseFromMldev(apiResponse);
        const typedResp = new GenerateImagesResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Private method for editing an image.
   */
  async editImageInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = editImageParametersInternalToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = editImageResponseFromVertex(apiResponse);
        const typedResp = new EditImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Private method for upscaling an image.
   */
  async upscaleImageInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = upscaleImageResponseFromVertex(apiResponse);
        const typedResp = new UpscaleImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Recontextualizes an image.
   *
   * There are two types of recontextualization currently supported:
   * 1) Imagen Product Recontext - Generate images of products in new scenes
   *    and contexts.
   * 2) Virtual Try-On: Generate images of persons modeling fashion products.
   *
   * @param params - The parameters for recontextualizing an image.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response1 = await ai.models.recontextImage({
   *  model: 'imagen-product-recontext-preview-06-30',
   *  source: {
   *    prompt: 'In a modern kitchen setting.',
   *    productImages: [productImage],
   *  },
   *  config: {
   *    numberOfImages: 1,
   *  },
   * });
   * console.log(response1?.generatedImages?.[0]?.image?.imageBytes);
   *
   * const response2 = await ai.models.recontextImage({
   *  model: 'virtual-try-on-preview-08-04',
   *  source: {
   *    personImage: personImage,
   *    productImages: [productImage],
   *  },
   *  config: {
   *    numberOfImages: 1,
   *  },
   * });
   * console.log(response2?.generatedImages?.[0]?.image?.imageBytes);
   * ```
   */
  async recontextImage(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = recontextImageParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = recontextImageResponseFromVertex(apiResponse);
        const typedResp = new RecontextImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Segments an image, creating a mask of a specified area.
   *
   * @param params - The parameters for segmenting an image.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.segmentImage({
   *  model: 'image-segmentation-001',
   *  source: {
   *    image: image,
   *  },
   *  config: {
   *    mode: 'foreground',
   *  },
   * });
   * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes);
   * ```
   */
  async segmentImage(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = segmentImageParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:predict", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = segmentImageResponseFromVertex(apiResponse);
        const typedResp = new SegmentImageResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Fetches information about a model by name.
   *
   * @example
   * ```ts
   * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});
   * ```
   */
  async get(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getModelParametersToVertex(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getModelParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromMldev(apiResponse);
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listModelsParametersToVertex(this.apiClient, params);
      path = formatMap("{models_url}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listModelsResponseFromVertex(apiResponse);
        const typedResp = new ListModelsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listModelsParametersToMldev(this.apiClient, params);
      path = formatMap("{models_url}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listModelsResponseFromMldev(apiResponse);
        const typedResp = new ListModelsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Updates a tuned model by its name.
   *
   * @param params - The parameters for updating the model.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.update({
   *   model: 'tuned-model-name',
   *   config: {
   *     displayName: 'New display name',
   *     description: 'New description',
   *   },
   * });
   * ```
   */
  async update(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = updateModelParametersToVertex(this.apiClient, params);
      path = formatMap("{model}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = updateModelParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "PATCH",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = modelFromMldev(apiResponse);
        return resp;
      });
    }
  }
  /**
   * Deletes a tuned model by its name.
   *
   * @param params - The parameters for deleting the model.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.delete({model: 'tuned-model-name'});
   * ```
   */
  async delete(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = deleteModelParametersToVertex(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteModelResponseFromVertex(apiResponse);
        const typedResp = new DeleteModelResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = deleteModelParametersToMldev(this.apiClient, params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "DELETE",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = deleteModelResponseFromMldev(apiResponse);
        const typedResp = new DeleteModelResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Counts the number of tokens in the given contents. Multimodal input is
   * supported for Gemini models.
   *
   * @param params - The parameters for counting tokens.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.countTokens({
   *  model: 'gemini-2.0-flash',
   *  contents: 'The quick brown fox jumps over the lazy dog.'
   * });
   * console.log(response);
   * ```
   */
  async countTokens(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = countTokensParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:countTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = countTokensResponseFromVertex(apiResponse);
        const typedResp = new CountTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = countTokensParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:countTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = countTokensResponseFromMldev(apiResponse);
        const typedResp = new CountTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Given a list of contents, returns a corresponding TokensInfo containing
   * the list of tokens and list of token ids.
   *
   * This method is not supported by the Gemini Developer API.
   *
   * @param params - The parameters for computing tokens.
   * @return The response from the API.
   *
   * @example
   * ```ts
   * const response = await ai.models.computeTokens({
   *  model: 'gemini-2.0-flash',
   *  contents: 'What is your name?'
   * });
   * console.log(response);
   * ```
   */
  async computeTokens(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = computeTokensParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:computeTokens", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = computeTokensResponseFromVertex(apiResponse);
        const typedResp = new ComputeTokensResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  /**
   * Private method for generating videos.
   */
  async generateVideosInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = generateVideosParametersToVertex(this.apiClient, params);
      path = formatMap("{model}:predictLongRunning", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = generateVideosOperationFromVertex(apiResponse);
        const typedResp = new GenerateVideosOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = generateVideosParametersToMldev(this.apiClient, params);
      path = formatMap("{model}:predictLongRunning", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = generateVideosOperationFromMldev(apiResponse);
        const typedResp = new GenerateVideosOperation();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Operations extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
  }
  /**
   * Gets the status of a long-running operation.
   *
   * @param parameters The parameters for the get operation request.
   * @return The updated Operation object, with the latest status or result.
   */
  async getVideosOperation(parameters) {
    const operation = parameters.operation;
    const config = parameters.config;
    if (operation.name === void 0 || operation.name === "") {
      throw new Error("Operation name is required.");
    }
    if (this.apiClient.isVertexAI()) {
      const resourceName2 = operation.name.split("/operations/")[0];
      let httpOptions = void 0;
      if (config && "httpOptions" in config) {
        httpOptions = config.httpOptions;
      }
      const rawOperation = await this.fetchPredictVideosOperationInternal({
        operationName: operation.name,
        resourceName: resourceName2,
        config: { httpOptions }
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        isVertexAI: true
      });
    } else {
      const rawOperation = await this.getVideosOperationInternal({
        operationName: operation.name,
        config
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        isVertexAI: false
      });
    }
  }
  /**
   * Gets the status of a long-running operation.
   *
   * @param parameters The parameters for the get operation request.
   * @return The updated Operation object, with the latest status or result.
   */
  async get(parameters) {
    const operation = parameters.operation;
    const config = parameters.config;
    if (operation.name === void 0 || operation.name === "") {
      throw new Error("Operation name is required.");
    }
    if (this.apiClient.isVertexAI()) {
      const resourceName2 = operation.name.split("/operations/")[0];
      let httpOptions = void 0;
      if (config && "httpOptions" in config) {
        httpOptions = config.httpOptions;
      }
      const rawOperation = await this.fetchPredictVideosOperationInternal({
        operationName: operation.name,
        resourceName: resourceName2,
        config: { httpOptions }
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        isVertexAI: true
      });
    } else {
      const rawOperation = await this.getVideosOperationInternal({
        operationName: operation.name,
        config
      });
      return operation._fromAPIResponse({
        apiResponse: rawOperation,
        isVertexAI: false
      });
    }
  }
  async getVideosOperationInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getOperationParametersToVertex(params);
      path = formatMap("{operationName}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    } else {
      const body = getOperationParametersToMldev(params);
      path = formatMap("{operationName}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    }
  }
  async fetchPredictVideosOperationInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = fetchPredictOperationParametersToVertex(params);
      path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response;
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function prebuiltVoiceConfigToMldev(fromObject2) {
  const toObject = {};
  const fromVoiceName = getValueByPath(fromObject2, ["voiceName"]);
  if (fromVoiceName != null) {
    setValueByPath(toObject, ["voiceName"], fromVoiceName);
  }
  return toObject;
}
function voiceConfigToMldev(fromObject2) {
  const toObject = {};
  const fromPrebuiltVoiceConfig = getValueByPath(fromObject2, [
    "prebuiltVoiceConfig"
  ]);
  if (fromPrebuiltVoiceConfig != null) {
    setValueByPath(toObject, ["prebuiltVoiceConfig"], prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig));
  }
  return toObject;
}
function speakerVoiceConfigToMldev(fromObject2) {
  const toObject = {};
  const fromSpeaker = getValueByPath(fromObject2, ["speaker"]);
  if (fromSpeaker != null) {
    setValueByPath(toObject, ["speaker"], fromSpeaker);
  }
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev(fromVoiceConfig));
  }
  return toObject;
}
function multiSpeakerVoiceConfigToMldev(fromObject2) {
  const toObject = {};
  const fromSpeakerVoiceConfigs = getValueByPath(fromObject2, [
    "speakerVoiceConfigs"
  ]);
  if (fromSpeakerVoiceConfigs != null) {
    let transformedList = fromSpeakerVoiceConfigs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return speakerVoiceConfigToMldev(item);
      });
    }
    setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList);
  }
  return toObject;
}
function speechConfigToMldev(fromObject2) {
  const toObject = {};
  const fromVoiceConfig = getValueByPath(fromObject2, ["voiceConfig"]);
  if (fromVoiceConfig != null) {
    setValueByPath(toObject, ["voiceConfig"], voiceConfigToMldev(fromVoiceConfig));
  }
  const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject2, [
    "multiSpeakerVoiceConfig"
  ]);
  if (fromMultiSpeakerVoiceConfig != null) {
    setValueByPath(toObject, ["multiSpeakerVoiceConfig"], multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig));
  }
  const fromLanguageCode = getValueByPath(fromObject2, ["languageCode"]);
  if (fromLanguageCode != null) {
    setValueByPath(toObject, ["languageCode"], fromLanguageCode);
  }
  return toObject;
}
function videoMetadataToMldev(fromObject2) {
  const toObject = {};
  const fromFps = getValueByPath(fromObject2, ["fps"]);
  if (fromFps != null) {
    setValueByPath(toObject, ["fps"], fromFps);
  }
  const fromEndOffset = getValueByPath(fromObject2, ["endOffset"]);
  if (fromEndOffset != null) {
    setValueByPath(toObject, ["endOffset"], fromEndOffset);
  }
  const fromStartOffset = getValueByPath(fromObject2, ["startOffset"]);
  if (fromStartOffset != null) {
    setValueByPath(toObject, ["startOffset"], fromStartOffset);
  }
  return toObject;
}
function blobToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromData = getValueByPath(fromObject2, ["data"]);
  if (fromData != null) {
    setValueByPath(toObject, ["data"], fromData);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function fileDataToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["displayName"]) !== void 0) {
    throw new Error("displayName parameter is not supported in Gemini API.");
  }
  const fromFileUri = getValueByPath(fromObject2, ["fileUri"]);
  if (fromFileUri != null) {
    setValueByPath(toObject, ["fileUri"], fromFileUri);
  }
  const fromMimeType = getValueByPath(fromObject2, ["mimeType"]);
  if (fromMimeType != null) {
    setValueByPath(toObject, ["mimeType"], fromMimeType);
  }
  return toObject;
}
function functionCallToMldev(fromObject2) {
  const toObject = {};
  const fromId = getValueByPath(fromObject2, ["id"]);
  if (fromId != null) {
    setValueByPath(toObject, ["id"], fromId);
  }
  const fromArgs = getValueByPath(fromObject2, ["args"]);
  if (fromArgs != null) {
    setValueByPath(toObject, ["args"], fromArgs);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
function partToMldev(fromObject2) {
  const toObject = {};
  const fromVideoMetadata = getValueByPath(fromObject2, [
    "videoMetadata"
  ]);
  if (fromVideoMetadata != null) {
    setValueByPath(toObject, ["videoMetadata"], videoMetadataToMldev(fromVideoMetadata));
  }
  const fromThought = getValueByPath(fromObject2, ["thought"]);
  if (fromThought != null) {
    setValueByPath(toObject, ["thought"], fromThought);
  }
  const fromInlineData = getValueByPath(fromObject2, ["inlineData"]);
  if (fromInlineData != null) {
    setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData));
  }
  const fromFileData = getValueByPath(fromObject2, ["fileData"]);
  if (fromFileData != null) {
    setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData));
  }
  const fromThoughtSignature = getValueByPath(fromObject2, [
    "thoughtSignature"
  ]);
  if (fromThoughtSignature != null) {
    setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature);
  }
  const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]);
  if (fromFunctionCall != null) {
    setValueByPath(toObject, ["functionCall"], functionCallToMldev(fromFunctionCall));
  }
  const fromCodeExecutionResult = getValueByPath(fromObject2, [
    "codeExecutionResult"
  ]);
  if (fromCodeExecutionResult != null) {
    setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult);
  }
  const fromExecutableCode = getValueByPath(fromObject2, [
    "executableCode"
  ]);
  if (fromExecutableCode != null) {
    setValueByPath(toObject, ["executableCode"], fromExecutableCode);
  }
  const fromFunctionResponse = getValueByPath(fromObject2, [
    "functionResponse"
  ]);
  if (fromFunctionResponse != null) {
    setValueByPath(toObject, ["functionResponse"], fromFunctionResponse);
  }
  const fromText = getValueByPath(fromObject2, ["text"]);
  if (fromText != null) {
    setValueByPath(toObject, ["text"], fromText);
  }
  return toObject;
}
function contentToMldev(fromObject2) {
  const toObject = {};
  const fromParts = getValueByPath(fromObject2, ["parts"]);
  if (fromParts != null) {
    let transformedList = fromParts;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return partToMldev(item);
      });
    }
    setValueByPath(toObject, ["parts"], transformedList);
  }
  const fromRole = getValueByPath(fromObject2, ["role"]);
  if (fromRole != null) {
    setValueByPath(toObject, ["role"], fromRole);
  }
  return toObject;
}
function functionDeclarationToMldev(fromObject2) {
  const toObject = {};
  const fromBehavior = getValueByPath(fromObject2, ["behavior"]);
  if (fromBehavior != null) {
    setValueByPath(toObject, ["behavior"], fromBehavior);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromParameters = getValueByPath(fromObject2, ["parameters"]);
  if (fromParameters != null) {
    setValueByPath(toObject, ["parameters"], fromParameters);
  }
  const fromParametersJsonSchema = getValueByPath(fromObject2, [
    "parametersJsonSchema"
  ]);
  if (fromParametersJsonSchema != null) {
    setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema);
  }
  const fromResponse = getValueByPath(fromObject2, ["response"]);
  if (fromResponse != null) {
    setValueByPath(toObject, ["response"], fromResponse);
  }
  const fromResponseJsonSchema = getValueByPath(fromObject2, [
    "responseJsonSchema"
  ]);
  if (fromResponseJsonSchema != null) {
    setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema);
  }
  return toObject;
}
function intervalToMldev(fromObject2) {
  const toObject = {};
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  return toObject;
}
function googleSearchToMldev(fromObject2) {
  const toObject = {};
  const fromTimeRangeFilter = getValueByPath(fromObject2, [
    "timeRangeFilter"
  ]);
  if (fromTimeRangeFilter != null) {
    setValueByPath(toObject, ["timeRangeFilter"], intervalToMldev(fromTimeRangeFilter));
  }
  if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) {
    throw new Error("excludeDomains parameter is not supported in Gemini API.");
  }
  return toObject;
}
function dynamicRetrievalConfigToMldev(fromObject2) {
  const toObject = {};
  const fromMode = getValueByPath(fromObject2, ["mode"]);
  if (fromMode != null) {
    setValueByPath(toObject, ["mode"], fromMode);
  }
  const fromDynamicThreshold = getValueByPath(fromObject2, [
    "dynamicThreshold"
  ]);
  if (fromDynamicThreshold != null) {
    setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold);
  }
  return toObject;
}
function googleSearchRetrievalToMldev(fromObject2) {
  const toObject = {};
  const fromDynamicRetrievalConfig = getValueByPath(fromObject2, [
    "dynamicRetrievalConfig"
  ]);
  if (fromDynamicRetrievalConfig != null) {
    setValueByPath(toObject, ["dynamicRetrievalConfig"], dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig));
  }
  return toObject;
}
function urlContextToMldev() {
  const toObject = {};
  return toObject;
}
function toolComputerUseToMldev(fromObject2) {
  const toObject = {};
  const fromEnvironment = getValueByPath(fromObject2, ["environment"]);
  if (fromEnvironment != null) {
    setValueByPath(toObject, ["environment"], fromEnvironment);
  }
  return toObject;
}
function toolToMldev(fromObject2) {
  const toObject = {};
  const fromFunctionDeclarations = getValueByPath(fromObject2, [
    "functionDeclarations"
  ]);
  if (fromFunctionDeclarations != null) {
    let transformedList = fromFunctionDeclarations;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return functionDeclarationToMldev(item);
      });
    }
    setValueByPath(toObject, ["functionDeclarations"], transformedList);
  }
  if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) {
    throw new Error("retrieval parameter is not supported in Gemini API.");
  }
  const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]);
  if (fromGoogleSearch != null) {
    setValueByPath(toObject, ["googleSearch"], googleSearchToMldev(fromGoogleSearch));
  }
  const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [
    "googleSearchRetrieval"
  ]);
  if (fromGoogleSearchRetrieval != null) {
    setValueByPath(toObject, ["googleSearchRetrieval"], googleSearchRetrievalToMldev(fromGoogleSearchRetrieval));
  }
  if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) {
    throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["googleMaps"]) !== void 0) {
    throw new Error("googleMaps parameter is not supported in Gemini API.");
  }
  const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]);
  if (fromUrlContext != null) {
    setValueByPath(toObject, ["urlContext"], urlContextToMldev());
  }
  const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]);
  if (fromComputerUse != null) {
    setValueByPath(toObject, ["computerUse"], toolComputerUseToMldev(fromComputerUse));
  }
  const fromCodeExecution = getValueByPath(fromObject2, [
    "codeExecution"
  ]);
  if (fromCodeExecution != null) {
    setValueByPath(toObject, ["codeExecution"], fromCodeExecution);
  }
  return toObject;
}
function sessionResumptionConfigToMldev(fromObject2) {
  const toObject = {};
  const fromHandle = getValueByPath(fromObject2, ["handle"]);
  if (fromHandle != null) {
    setValueByPath(toObject, ["handle"], fromHandle);
  }
  if (getValueByPath(fromObject2, ["transparent"]) !== void 0) {
    throw new Error("transparent parameter is not supported in Gemini API.");
  }
  return toObject;
}
function audioTranscriptionConfigToMldev() {
  const toObject = {};
  return toObject;
}
function automaticActivityDetectionToMldev(fromObject2) {
  const toObject = {};
  const fromDisabled = getValueByPath(fromObject2, ["disabled"]);
  if (fromDisabled != null) {
    setValueByPath(toObject, ["disabled"], fromDisabled);
  }
  const fromStartOfSpeechSensitivity = getValueByPath(fromObject2, [
    "startOfSpeechSensitivity"
  ]);
  if (fromStartOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["startOfSpeechSensitivity"], fromStartOfSpeechSensitivity);
  }
  const fromEndOfSpeechSensitivity = getValueByPath(fromObject2, [
    "endOfSpeechSensitivity"
  ]);
  if (fromEndOfSpeechSensitivity != null) {
    setValueByPath(toObject, ["endOfSpeechSensitivity"], fromEndOfSpeechSensitivity);
  }
  const fromPrefixPaddingMs = getValueByPath(fromObject2, [
    "prefixPaddingMs"
  ]);
  if (fromPrefixPaddingMs != null) {
    setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs);
  }
  const fromSilenceDurationMs = getValueByPath(fromObject2, [
    "silenceDurationMs"
  ]);
  if (fromSilenceDurationMs != null) {
    setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs);
  }
  return toObject;
}
function realtimeInputConfigToMldev(fromObject2) {
  const toObject = {};
  const fromAutomaticActivityDetection = getValueByPath(fromObject2, [
    "automaticActivityDetection"
  ]);
  if (fromAutomaticActivityDetection != null) {
    setValueByPath(toObject, ["automaticActivityDetection"], automaticActivityDetectionToMldev(fromAutomaticActivityDetection));
  }
  const fromActivityHandling = getValueByPath(fromObject2, [
    "activityHandling"
  ]);
  if (fromActivityHandling != null) {
    setValueByPath(toObject, ["activityHandling"], fromActivityHandling);
  }
  const fromTurnCoverage = getValueByPath(fromObject2, ["turnCoverage"]);
  if (fromTurnCoverage != null) {
    setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage);
  }
  return toObject;
}
function slidingWindowToMldev(fromObject2) {
  const toObject = {};
  const fromTargetTokens = getValueByPath(fromObject2, ["targetTokens"]);
  if (fromTargetTokens != null) {
    setValueByPath(toObject, ["targetTokens"], fromTargetTokens);
  }
  return toObject;
}
function contextWindowCompressionConfigToMldev(fromObject2) {
  const toObject = {};
  const fromTriggerTokens = getValueByPath(fromObject2, [
    "triggerTokens"
  ]);
  if (fromTriggerTokens != null) {
    setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens);
  }
  const fromSlidingWindow = getValueByPath(fromObject2, [
    "slidingWindow"
  ]);
  if (fromSlidingWindow != null) {
    setValueByPath(toObject, ["slidingWindow"], slidingWindowToMldev(fromSlidingWindow));
  }
  return toObject;
}
function proactivityConfigToMldev(fromObject2) {
  const toObject = {};
  const fromProactiveAudio = getValueByPath(fromObject2, [
    "proactiveAudio"
  ]);
  if (fromProactiveAudio != null) {
    setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio);
  }
  return toObject;
}
function liveConnectConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromGenerationConfig = getValueByPath(fromObject2, [
    "generationConfig"
  ]);
  if (parentObject !== void 0 && fromGenerationConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig);
  }
  const fromResponseModalities = getValueByPath(fromObject2, [
    "responseModalities"
  ]);
  if (parentObject !== void 0 && fromResponseModalities != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities);
  }
  const fromTemperature = getValueByPath(fromObject2, ["temperature"]);
  if (parentObject !== void 0 && fromTemperature != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature);
  }
  const fromTopP = getValueByPath(fromObject2, ["topP"]);
  if (parentObject !== void 0 && fromTopP != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP);
  }
  const fromTopK = getValueByPath(fromObject2, ["topK"]);
  if (parentObject !== void 0 && fromTopK != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK);
  }
  const fromMaxOutputTokens = getValueByPath(fromObject2, [
    "maxOutputTokens"
  ]);
  if (parentObject !== void 0 && fromMaxOutputTokens != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens);
  }
  const fromMediaResolution = getValueByPath(fromObject2, [
    "mediaResolution"
  ]);
  if (parentObject !== void 0 && fromMediaResolution != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution);
  }
  const fromSeed = getValueByPath(fromObject2, ["seed"]);
  if (parentObject !== void 0 && fromSeed != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed);
  }
  const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]);
  if (parentObject !== void 0 && fromSpeechConfig != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)));
  }
  const fromEnableAffectiveDialog = getValueByPath(fromObject2, [
    "enableAffectiveDialog"
  ]);
  if (parentObject !== void 0 && fromEnableAffectiveDialog != null) {
    setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog);
  }
  const fromSystemInstruction = getValueByPath(fromObject2, [
    "systemInstruction"
  ]);
  if (parentObject !== void 0 && fromSystemInstruction != null) {
    setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev(tContent(fromSystemInstruction)));
  }
  const fromTools = getValueByPath(fromObject2, ["tools"]);
  if (parentObject !== void 0 && fromTools != null) {
    let transformedList = tTools(fromTools);
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return toolToMldev(tTool(item));
      });
    }
    setValueByPath(parentObject, ["setup", "tools"], transformedList);
  }
  const fromSessionResumption = getValueByPath(fromObject2, [
    "sessionResumption"
  ]);
  if (parentObject !== void 0 && fromSessionResumption != null) {
    setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev(fromSessionResumption));
  }
  const fromInputAudioTranscription = getValueByPath(fromObject2, [
    "inputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromInputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev());
  }
  const fromOutputAudioTranscription = getValueByPath(fromObject2, [
    "outputAudioTranscription"
  ]);
  if (parentObject !== void 0 && fromOutputAudioTranscription != null) {
    setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev());
  }
  const fromRealtimeInputConfig = getValueByPath(fromObject2, [
    "realtimeInputConfig"
  ]);
  if (parentObject !== void 0 && fromRealtimeInputConfig != null) {
    setValueByPath(parentObject, ["setup", "realtimeInputConfig"], realtimeInputConfigToMldev(fromRealtimeInputConfig));
  }
  const fromContextWindowCompression = getValueByPath(fromObject2, [
    "contextWindowCompression"
  ]);
  if (parentObject !== void 0 && fromContextWindowCompression != null) {
    setValueByPath(parentObject, ["setup", "contextWindowCompression"], contextWindowCompressionConfigToMldev(fromContextWindowCompression));
  }
  const fromProactivity = getValueByPath(fromObject2, ["proactivity"]);
  if (parentObject !== void 0 && fromProactivity != null) {
    setValueByPath(parentObject, ["setup", "proactivity"], proactivityConfigToMldev(fromProactivity));
  }
  return toObject;
}
function liveConnectConstraintsToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], liveConnectConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function createAuthTokenConfigToMldev(apiClient, fromObject2, parentObject) {
  const toObject = {};
  const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]);
  if (parentObject !== void 0 && fromExpireTime != null) {
    setValueByPath(parentObject, ["expireTime"], fromExpireTime);
  }
  const fromNewSessionExpireTime = getValueByPath(fromObject2, [
    "newSessionExpireTime"
  ]);
  if (parentObject !== void 0 && fromNewSessionExpireTime != null) {
    setValueByPath(parentObject, ["newSessionExpireTime"], fromNewSessionExpireTime);
  }
  const fromUses = getValueByPath(fromObject2, ["uses"]);
  if (parentObject !== void 0 && fromUses != null) {
    setValueByPath(parentObject, ["uses"], fromUses);
  }
  const fromLiveConnectConstraints = getValueByPath(fromObject2, [
    "liveConnectConstraints"
  ]);
  if (parentObject !== void 0 && fromLiveConnectConstraints != null) {
    setValueByPath(parentObject, ["bidiGenerateContentSetup"], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints));
  }
  const fromLockAdditionalFields = getValueByPath(fromObject2, [
    "lockAdditionalFields"
  ]);
  if (parentObject !== void 0 && fromLockAdditionalFields != null) {
    setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields);
  }
  return toObject;
}
function createAuthTokenParametersToMldev(apiClient, fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject));
  }
  return toObject;
}
function authTokenFromMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function getFieldMasks(setup) {
  const fields = [];
  for (const key2 in setup) {
    if (Object.prototype.hasOwnProperty.call(setup, key2)) {
      const value = setup[key2];
      if (typeof value === "object" && value != null && Object.keys(value).length > 0) {
        const field = Object.keys(value).map((kk) => `${key2}.${kk}`);
        fields.push(...field);
      } else {
        fields.push(key2);
      }
    }
  }
  return fields.join(",");
}
function convertBidiSetupToTokenSetup(requestDict, config) {
  let setupForMaskGeneration = null;
  const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"];
  if (typeof bidiGenerateContentSetupValue === "object" && bidiGenerateContentSetupValue !== null && "setup" in bidiGenerateContentSetupValue) {
    const innerSetup = bidiGenerateContentSetupValue.setup;
    if (typeof innerSetup === "object" && innerSetup !== null) {
      requestDict["bidiGenerateContentSetup"] = innerSetup;
      setupForMaskGeneration = innerSetup;
    } else {
      delete requestDict["bidiGenerateContentSetup"];
    }
  } else if (bidiGenerateContentSetupValue !== void 0) {
    delete requestDict["bidiGenerateContentSetup"];
  }
  const preExistingFieldMask = requestDict["fieldMask"];
  if (setupForMaskGeneration) {
    const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);
    if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) {
      if (generatedMaskFromBidi) {
        requestDict["fieldMask"] = generatedMaskFromBidi;
      } else {
        delete requestDict["fieldMask"];
      }
    } else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && config.lockAdditionalFields.length > 0 && preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      const generationConfigFields = [
        "temperature",
        "topK",
        "topP",
        "maxOutputTokens",
        "responseModalities",
        "seed",
        "speechConfig"
      ];
      let mappedFieldsFromPreExisting = [];
      if (preExistingFieldMask.length > 0) {
        mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {
          if (generationConfigFields.includes(field)) {
            return `generationConfig.${field}`;
          }
          return field;
        });
      }
      const finalMaskParts = [];
      if (generatedMaskFromBidi) {
        finalMaskParts.push(generatedMaskFromBidi);
      }
      if (mappedFieldsFromPreExisting.length > 0) {
        finalMaskParts.push(...mappedFieldsFromPreExisting);
      }
      if (finalMaskParts.length > 0) {
        requestDict["fieldMask"] = finalMaskParts.join(",");
      } else {
        delete requestDict["fieldMask"];
      }
    } else {
      delete requestDict["fieldMask"];
    }
  } else {
    if (preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) {
      requestDict["fieldMask"] = preExistingFieldMask.join(",");
    } else {
      delete requestDict["fieldMask"];
    }
  }
  return requestDict;
}
class Tokens extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
  }
  /**
   * Creates an ephemeral auth token resource.
   *
   * @experimental
   *
   * @remarks
   * Ephemeral auth tokens is only supported in the Gemini Developer API.
   * It can be used for the session connection to the Live constrained API.
   * Support in v1alpha only.
   *
   * @param params - The parameters for the create request.
   * @return The created auth token.
   *
   * @example
   * ```ts
   * const ai = new GoogleGenAI({
   *     apiKey: token.name,
   *     httpOptions: { apiVersion: 'v1alpha' }  // Support in v1alpha only.
   * });
   *
   * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig
   * // when using the token in Live API sessions. Each session connection can
   * // use a different configuration.
   * const config: CreateAuthTokenConfig = {
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 2: If LiveEphemeralParameters is set, lock all fields in
   * // LiveConnectConfig when using the token in Live API sessions. For
   * // example, changing `outputAudioTranscription` in the Live API
   * // connection will be ignored by the API.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     }
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is
   * // set, lock LiveConnectConfig with set and additional fields (e.g.
   * // responseModalities, systemInstruction, temperature in this example) when
   * // using the token in Live API sessions.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     },
   *     lockAdditionalFields: ['temperature'],
   * }
   * const token = await ai.tokens.create(config);
   *
   * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is
   * // empty array, lock LiveConnectConfig with set fields (e.g.
   * // responseModalities, systemInstruction in this example) when using the
   * // token in Live API sessions.
   * const config: CreateAuthTokenConfig =
   *     uses: 3,
   *     expireTime: '2025-05-01T00:00:00Z',
   *     LiveEphemeralParameters: {
   *        model: 'gemini-2.0-flash-001',
   *        config: {
   *           'responseModalities': ['AUDIO'],
   *           'systemInstruction': 'Always answer in English.',
   *        }
   *     },
   *     lockAdditionalFields: [],
   * }
   * const token = await ai.tokens.create(config);
   * ```
   */
  async create(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");
    } else {
      const body = createAuthTokenParametersToMldev(this.apiClient, params);
      path = formatMap("auth_tokens", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      const transformedBody = convertBidiSetupToTokenSetup(body, params.config);
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(transformedBody),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json();
      });
      return response.then((apiResponse) => {
        const resp = authTokenFromMldev(apiResponse);
        return resp;
      });
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
function getTuningJobParametersToMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listTuningJobsConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject2, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsParametersToMldev(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listTuningJobsConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function cancelTuningJobParametersToMldev(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function tuningExampleToMldev(fromObject2) {
  const toObject = {};
  const fromTextInput = getValueByPath(fromObject2, ["textInput"]);
  if (fromTextInput != null) {
    setValueByPath(toObject, ["textInput"], fromTextInput);
  }
  const fromOutput = getValueByPath(fromObject2, ["output"]);
  if (fromOutput != null) {
    setValueByPath(toObject, ["output"], fromOutput);
  }
  return toObject;
}
function tuningDatasetToMldev(fromObject2) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) {
    throw new Error("gcsUri parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["vertexDatasetResource"]) !== void 0) {
    throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");
  }
  const fromExamples = getValueByPath(fromObject2, ["examples"]);
  if (fromExamples != null) {
    let transformedList = fromExamples;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningExampleToMldev(item);
      });
    }
    setValueByPath(toObject, ["examples", "examples"], transformedList);
  }
  return toObject;
}
function createTuningJobConfigToMldev(fromObject2, parentObject) {
  const toObject = {};
  if (getValueByPath(fromObject2, ["validationDataset"]) !== void 0) {
    throw new Error("validationDataset parameter is not supported in Gemini API.");
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject2, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName);
  }
  if (getValueByPath(fromObject2, ["description"]) !== void 0) {
    throw new Error("description parameter is not supported in Gemini API.");
  }
  const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]);
  if (parentObject !== void 0 && fromEpochCount != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "epochCount"], fromEpochCount);
  }
  const fromLearningRateMultiplier = getValueByPath(fromObject2, [
    "learningRateMultiplier"
  ]);
  if (fromLearningRateMultiplier != null) {
    setValueByPath(toObject, ["tuningTask", "hyperparameters", "learningRateMultiplier"], fromLearningRateMultiplier);
  }
  if (getValueByPath(fromObject2, ["exportLastCheckpointOnly"]) !== void 0) {
    throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["preTunedModelCheckpointId"]) !== void 0) {
    throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");
  }
  if (getValueByPath(fromObject2, ["adapterSize"]) !== void 0) {
    throw new Error("adapterSize parameter is not supported in Gemini API.");
  }
  const fromBatchSize = getValueByPath(fromObject2, ["batchSize"]);
  if (parentObject !== void 0 && fromBatchSize != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "batchSize"], fromBatchSize);
  }
  const fromLearningRate = getValueByPath(fromObject2, ["learningRate"]);
  if (parentObject !== void 0 && fromLearningRate != null) {
    setValueByPath(parentObject, ["tuningTask", "hyperparameters", "learningRate"], fromLearningRate);
  }
  if (getValueByPath(fromObject2, ["labels"]) !== void 0) {
    throw new Error("labels parameter is not supported in Gemini API.");
  }
  return toObject;
}
function createTuningJobParametersPrivateToMldev(fromObject2) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject2, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject2, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    setValueByPath(toObject, ["tuningTask", "trainingData"], tuningDatasetToMldev(fromTrainingDataset));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createTuningJobConfigToMldev(fromConfig, toObject));
  }
  return toObject;
}
function getTuningJobParametersToVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function listTuningJobsConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromPageSize = getValueByPath(fromObject2, ["pageSize"]);
  if (parentObject !== void 0 && fromPageSize != null) {
    setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize);
  }
  const fromPageToken = getValueByPath(fromObject2, ["pageToken"]);
  if (parentObject !== void 0 && fromPageToken != null) {
    setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken);
  }
  const fromFilter = getValueByPath(fromObject2, ["filter"]);
  if (parentObject !== void 0 && fromFilter != null) {
    setValueByPath(parentObject, ["_query", "filter"], fromFilter);
  }
  return toObject;
}
function listTuningJobsParametersToVertex(fromObject2) {
  const toObject = {};
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], listTuningJobsConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function cancelTuningJobParametersToVertex(fromObject2) {
  const toObject = {};
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["_url", "name"], fromName);
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], fromConfig);
  }
  return toObject;
}
function tuningDatasetToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (parentObject !== void 0 && fromGcsUri != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject2, [
    "vertexDatasetResource"
  ]);
  if (parentObject !== void 0 && fromVertexDatasetResource != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
  }
  if (getValueByPath(fromObject2, ["examples"]) !== void 0) {
    throw new Error("examples parameter is not supported in Vertex AI.");
  }
  return toObject;
}
function tuningValidationDatasetToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]);
  if (fromGcsUri != null) {
    setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri);
  }
  const fromVertexDatasetResource = getValueByPath(fromObject2, [
    "vertexDatasetResource"
  ]);
  if (parentObject !== void 0 && fromVertexDatasetResource != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource);
  }
  return toObject;
}
function createTuningJobConfigToVertex(fromObject2, parentObject) {
  const toObject = {};
  const fromValidationDataset = getValueByPath(fromObject2, [
    "validationDataset"
  ]);
  if (parentObject !== void 0 && fromValidationDataset != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec"], tuningValidationDatasetToVertex(fromValidationDataset, toObject));
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject2, [
    "tunedModelDisplayName"
  ]);
  if (parentObject !== void 0 && fromTunedModelDisplayName != null) {
    setValueByPath(parentObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (parentObject !== void 0 && fromDescription != null) {
    setValueByPath(parentObject, ["description"], fromDescription);
  }
  const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]);
  if (parentObject !== void 0 && fromEpochCount != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "epochCount"], fromEpochCount);
  }
  const fromLearningRateMultiplier = getValueByPath(fromObject2, [
    "learningRateMultiplier"
  ]);
  if (parentObject !== void 0 && fromLearningRateMultiplier != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier);
  }
  const fromExportLastCheckpointOnly = getValueByPath(fromObject2, [
    "exportLastCheckpointOnly"
  ]);
  if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly);
  }
  const fromPreTunedModelCheckpointId = getValueByPath(fromObject2, [
    "preTunedModelCheckpointId"
  ]);
  if (fromPreTunedModelCheckpointId != null) {
    setValueByPath(toObject, ["preTunedModel", "checkpointId"], fromPreTunedModelCheckpointId);
  }
  const fromAdapterSize = getValueByPath(fromObject2, ["adapterSize"]);
  if (parentObject !== void 0 && fromAdapterSize != null) {
    setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "adapterSize"], fromAdapterSize);
  }
  if (getValueByPath(fromObject2, ["batchSize"]) !== void 0) {
    throw new Error("batchSize parameter is not supported in Vertex AI.");
  }
  if (getValueByPath(fromObject2, ["learningRate"]) !== void 0) {
    throw new Error("learningRate parameter is not supported in Vertex AI.");
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (parentObject !== void 0 && fromLabels != null) {
    setValueByPath(parentObject, ["labels"], fromLabels);
  }
  return toObject;
}
function createTuningJobParametersPrivateToVertex(fromObject2) {
  const toObject = {};
  const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromPreTunedModel = getValueByPath(fromObject2, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromTrainingDataset = getValueByPath(fromObject2, [
    "trainingDataset"
  ]);
  if (fromTrainingDataset != null) {
    setValueByPath(toObject, ["supervisedTuningSpec", "trainingDatasetUri"], tuningDatasetToVertex(fromTrainingDataset, toObject));
  }
  const fromConfig = getValueByPath(fromObject2, ["config"]);
  if (fromConfig != null) {
    setValueByPath(toObject, ["config"], createTuningJobConfigToVertex(fromConfig, toObject));
  }
  return toObject;
}
function tunedModelFromMldev(fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["name"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromEndpoint = getValueByPath(fromObject2, ["name"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  return toObject;
}
function tuningJobFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject2, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject2, [
    "tuningTask",
    "startTime"
  ]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, [
    "tuningTask",
    "completeTime"
  ]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject2, ["_self"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], tunedModelFromMldev(fromTunedModel));
  }
  const fromCustomBaseModel = getValueByPath(fromObject2, [
    "customBaseModel"
  ]);
  if (fromCustomBaseModel != null) {
    setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel);
  }
  const fromExperiment = getValueByPath(fromObject2, ["experiment"]);
  if (fromExperiment != null) {
    setValueByPath(toObject, ["experiment"], fromExperiment);
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromOutputUri = getValueByPath(fromObject2, ["outputUri"]);
  if (fromOutputUri != null) {
    setValueByPath(toObject, ["outputUri"], fromOutputUri);
  }
  const fromPipelineJob = getValueByPath(fromObject2, ["pipelineJob"]);
  if (fromPipelineJob != null) {
    setValueByPath(toObject, ["pipelineJob"], fromPipelineJob);
  }
  const fromServiceAccount = getValueByPath(fromObject2, [
    "serviceAccount"
  ]);
  if (fromServiceAccount != null) {
    setValueByPath(toObject, ["serviceAccount"], fromServiceAccount);
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject2, [
    "tunedModelDisplayName"
  ]);
  if (fromTunedModelDisplayName != null) {
    setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  return toObject;
}
function listTuningJobsResponseFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject2, ["tunedModels"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromMldev(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
function tuningOperationFromMldev(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromMetadata = getValueByPath(fromObject2, ["metadata"]);
  if (fromMetadata != null) {
    setValueByPath(toObject, ["metadata"], fromMetadata);
  }
  const fromDone = getValueByPath(fromObject2, ["done"]);
  if (fromDone != null) {
    setValueByPath(toObject, ["done"], fromDone);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  return toObject;
}
function tunedModelCheckpointFromVertex(fromObject2) {
  const toObject = {};
  const fromCheckpointId = getValueByPath(fromObject2, ["checkpointId"]);
  if (fromCheckpointId != null) {
    setValueByPath(toObject, ["checkpointId"], fromCheckpointId);
  }
  const fromEpoch = getValueByPath(fromObject2, ["epoch"]);
  if (fromEpoch != null) {
    setValueByPath(toObject, ["epoch"], fromEpoch);
  }
  const fromStep = getValueByPath(fromObject2, ["step"]);
  if (fromStep != null) {
    setValueByPath(toObject, ["step"], fromStep);
  }
  const fromEndpoint = getValueByPath(fromObject2, ["endpoint"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  return toObject;
}
function tunedModelFromVertex(fromObject2) {
  const toObject = {};
  const fromModel = getValueByPath(fromObject2, ["model"]);
  if (fromModel != null) {
    setValueByPath(toObject, ["model"], fromModel);
  }
  const fromEndpoint = getValueByPath(fromObject2, ["endpoint"]);
  if (fromEndpoint != null) {
    setValueByPath(toObject, ["endpoint"], fromEndpoint);
  }
  const fromCheckpoints = getValueByPath(fromObject2, ["checkpoints"]);
  if (fromCheckpoints != null) {
    let transformedList = fromCheckpoints;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tunedModelCheckpointFromVertex(item);
      });
    }
    setValueByPath(toObject, ["checkpoints"], transformedList);
  }
  return toObject;
}
function tuningJobFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromName = getValueByPath(fromObject2, ["name"]);
  if (fromName != null) {
    setValueByPath(toObject, ["name"], fromName);
  }
  const fromState = getValueByPath(fromObject2, ["state"]);
  if (fromState != null) {
    setValueByPath(toObject, ["state"], tTuningJobStatus(fromState));
  }
  const fromCreateTime = getValueByPath(fromObject2, ["createTime"]);
  if (fromCreateTime != null) {
    setValueByPath(toObject, ["createTime"], fromCreateTime);
  }
  const fromStartTime = getValueByPath(fromObject2, ["startTime"]);
  if (fromStartTime != null) {
    setValueByPath(toObject, ["startTime"], fromStartTime);
  }
  const fromEndTime = getValueByPath(fromObject2, ["endTime"]);
  if (fromEndTime != null) {
    setValueByPath(toObject, ["endTime"], fromEndTime);
  }
  const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]);
  if (fromUpdateTime != null) {
    setValueByPath(toObject, ["updateTime"], fromUpdateTime);
  }
  const fromError = getValueByPath(fromObject2, ["error"]);
  if (fromError != null) {
    setValueByPath(toObject, ["error"], fromError);
  }
  const fromDescription = getValueByPath(fromObject2, ["description"]);
  if (fromDescription != null) {
    setValueByPath(toObject, ["description"], fromDescription);
  }
  const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]);
  if (fromBaseModel != null) {
    setValueByPath(toObject, ["baseModel"], fromBaseModel);
  }
  const fromTunedModel = getValueByPath(fromObject2, ["tunedModel"]);
  if (fromTunedModel != null) {
    setValueByPath(toObject, ["tunedModel"], tunedModelFromVertex(fromTunedModel));
  }
  const fromPreTunedModel = getValueByPath(fromObject2, [
    "preTunedModel"
  ]);
  if (fromPreTunedModel != null) {
    setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel);
  }
  const fromSupervisedTuningSpec = getValueByPath(fromObject2, [
    "supervisedTuningSpec"
  ]);
  if (fromSupervisedTuningSpec != null) {
    setValueByPath(toObject, ["supervisedTuningSpec"], fromSupervisedTuningSpec);
  }
  const fromTuningDataStats = getValueByPath(fromObject2, [
    "tuningDataStats"
  ]);
  if (fromTuningDataStats != null) {
    setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats);
  }
  const fromEncryptionSpec = getValueByPath(fromObject2, [
    "encryptionSpec"
  ]);
  if (fromEncryptionSpec != null) {
    setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec);
  }
  const fromPartnerModelTuningSpec = getValueByPath(fromObject2, [
    "partnerModelTuningSpec"
  ]);
  if (fromPartnerModelTuningSpec != null) {
    setValueByPath(toObject, ["partnerModelTuningSpec"], fromPartnerModelTuningSpec);
  }
  const fromCustomBaseModel = getValueByPath(fromObject2, [
    "customBaseModel"
  ]);
  if (fromCustomBaseModel != null) {
    setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel);
  }
  const fromExperiment = getValueByPath(fromObject2, ["experiment"]);
  if (fromExperiment != null) {
    setValueByPath(toObject, ["experiment"], fromExperiment);
  }
  const fromLabels = getValueByPath(fromObject2, ["labels"]);
  if (fromLabels != null) {
    setValueByPath(toObject, ["labels"], fromLabels);
  }
  const fromOutputUri = getValueByPath(fromObject2, ["outputUri"]);
  if (fromOutputUri != null) {
    setValueByPath(toObject, ["outputUri"], fromOutputUri);
  }
  const fromPipelineJob = getValueByPath(fromObject2, ["pipelineJob"]);
  if (fromPipelineJob != null) {
    setValueByPath(toObject, ["pipelineJob"], fromPipelineJob);
  }
  const fromServiceAccount = getValueByPath(fromObject2, [
    "serviceAccount"
  ]);
  if (fromServiceAccount != null) {
    setValueByPath(toObject, ["serviceAccount"], fromServiceAccount);
  }
  const fromTunedModelDisplayName = getValueByPath(fromObject2, [
    "tunedModelDisplayName"
  ]);
  if (fromTunedModelDisplayName != null) {
    setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName);
  }
  return toObject;
}
function listTuningJobsResponseFromVertex(fromObject2) {
  const toObject = {};
  const fromSdkHttpResponse = getValueByPath(fromObject2, [
    "sdkHttpResponse"
  ]);
  if (fromSdkHttpResponse != null) {
    setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse);
  }
  const fromNextPageToken = getValueByPath(fromObject2, [
    "nextPageToken"
  ]);
  if (fromNextPageToken != null) {
    setValueByPath(toObject, ["nextPageToken"], fromNextPageToken);
  }
  const fromTuningJobs = getValueByPath(fromObject2, ["tuningJobs"]);
  if (fromTuningJobs != null) {
    let transformedList = fromTuningJobs;
    if (Array.isArray(transformedList)) {
      transformedList = transformedList.map((item) => {
        return tuningJobFromVertex(item);
      });
    }
    setValueByPath(toObject, ["tuningJobs"], transformedList);
  }
  return toObject;
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class Tunings extends BaseModule {
  constructor(apiClient) {
    super();
    this.apiClient = apiClient;
    this.get = async (params) => {
      return await this.getInternal(params);
    };
    this.list = async (params = {}) => {
      return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params);
    };
    this.tune = async (params) => {
      if (this.apiClient.isVertexAI()) {
        if (params.baseModel.startsWith("projects/")) {
          const preTunedModel = {
            tunedModelName: params.baseModel
          };
          const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel });
          paramsPrivate.baseModel = void 0;
          return await this.tuneInternal(paramsPrivate);
        } else {
          const paramsPrivate = Object.assign({}, params);
          return await this.tuneInternal(paramsPrivate);
        }
      } else {
        const paramsPrivate = Object.assign({}, params);
        const operation = await this.tuneMldevInternal(paramsPrivate);
        let tunedModelName = "";
        if (operation["metadata"] !== void 0 && operation["metadata"]["tunedModel"] !== void 0) {
          tunedModelName = operation["metadata"]["tunedModel"];
        } else if (operation["name"] !== void 0 && operation["name"].includes("/operations/")) {
          tunedModelName = operation["name"].split("/operations/")[0];
        }
        const tuningJob = {
          name: tunedModelName,
          state: JobState.JOB_STATE_QUEUED
        };
        return tuningJob;
      }
    };
  }
  async getInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = getTuningJobParametersToVertex(params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      const body = getTuningJobParametersToMldev(params);
      path = formatMap("{name}", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromMldev(apiResponse);
        return resp;
      });
    }
  }
  async listInternal(params) {
    var _a3, _b2, _c2, _d2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = listTuningJobsParametersToVertex(params);
      path = formatMap("tuningJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listTuningJobsResponseFromVertex(apiResponse);
        const typedResp = new ListTuningJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    } else {
      const body = listTuningJobsParametersToMldev(params);
      path = formatMap("tunedModels", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "GET",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = listTuningJobsResponseFromMldev(apiResponse);
        const typedResp = new ListTuningJobsResponse();
        Object.assign(typedResp, resp);
        return typedResp;
      });
    }
  }
  /**
   * Cancels a tuning job.
   *
   * @param params - The parameters for the cancel request.
   * @return The empty response returned by the API.
   *
   * @example
   * ```ts
   * await ai.tunings.cancel({name: '...'}); // The server-generated resource name.
   * ```
   */
  async cancel(params) {
    var _a3, _b2, _c2, _d2;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = cancelTuningJobParametersToVertex(params);
      path = formatMap("{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      });
    } else {
      const body = cancelTuningJobParametersToMldev(params);
      path = formatMap("{name}:cancel", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      await this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_c2 = params.config) === null || _c2 === void 0 ? void 0 : _c2.httpOptions,
        abortSignal: (_d2 = params.config) === null || _d2 === void 0 ? void 0 : _d2.abortSignal
      });
    }
  }
  async tuneInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      const body = createTuningJobParametersPrivateToVertex(params);
      path = formatMap("tuningJobs", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningJobFromVertex(apiResponse);
        return resp;
      });
    } else {
      throw new Error("This method is only supported by the Vertex AI.");
    }
  }
  async tuneMldevInternal(params) {
    var _a3, _b2;
    let response;
    let path = "";
    let queryParams = {};
    if (this.apiClient.isVertexAI()) {
      throw new Error("This method is only supported by the Gemini Developer API.");
    } else {
      const body = createTuningJobParametersPrivateToMldev(params);
      path = formatMap("tunedModels", body["_url"]);
      queryParams = body["_query"];
      delete body["config"];
      delete body["_url"];
      delete body["_query"];
      response = this.apiClient.request({
        path,
        queryParams,
        body: JSON.stringify(body),
        httpMethod: "POST",
        httpOptions: (_a3 = params.config) === null || _a3 === void 0 ? void 0 : _a3.httpOptions,
        abortSignal: (_b2 = params.config) === null || _b2 === void 0 ? void 0 : _b2.abortSignal
      }).then((httpResponse) => {
        return httpResponse.json().then((jsonResponse) => {
          const response2 = jsonResponse;
          response2.sdkHttpResponse = {
            headers: httpResponse.headers
          };
          return response2;
        });
      });
      return response.then((apiResponse) => {
        const resp = tuningOperationFromMldev(apiResponse);
        return resp;
      });
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class BrowserDownloader {
  async download(_params, _apiClient) {
    throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.");
  }
}
const MAX_CHUNK_SIZE = 1024 * 1024 * 8;
const MAX_RETRY_COUNT = 3;
const INITIAL_RETRY_DELAY_MS = 1e3;
const DELAY_MULTIPLIER = 2;
const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status";
async function uploadBlob(file, uploadUrl, apiClient) {
  var _a3, _b2, _c2;
  let fileSize = 0;
  let offset = 0;
  let response = new HttpResponse(new Response());
  let uploadCommand = "upload";
  fileSize = file.size;
  while (offset < fileSize) {
    const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
    const chunk = file.slice(offset, offset + chunkSize);
    if (offset + chunkSize >= fileSize) {
      uploadCommand += ", finalize";
    }
    let retryCount = 0;
    let currentDelayMs = INITIAL_RETRY_DELAY_MS;
    while (retryCount < MAX_RETRY_COUNT) {
      response = await apiClient.request({
        path: "",
        body: chunk,
        httpMethod: "POST",
        httpOptions: {
          apiVersion: "",
          baseUrl: uploadUrl,
          headers: {
            "X-Goog-Upload-Command": uploadCommand,
            "X-Goog-Upload-Offset": String(offset),
            "Content-Length": String(chunkSize)
          }
        }
      });
      if ((_a3 = response === null || response === void 0 ? void 0 : response.headers) === null || _a3 === void 0 ? void 0 : _a3[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
        break;
      }
      retryCount++;
      await sleep$1(currentDelayMs);
      currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
    }
    offset += chunkSize;
    if (((_b2 = response === null || response === void 0 ? void 0 : response.headers) === null || _b2 === void 0 ? void 0 : _b2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active") {
      break;
    }
    if (fileSize <= offset) {
      throw new Error("All content has been uploaded, but the upload status is not finalized.");
    }
  }
  const responseJson = await (response === null || response === void 0 ? void 0 : response.json());
  if (((_c2 = response === null || response === void 0 ? void 0 : response.headers) === null || _c2 === void 0 ? void 0 : _c2[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") {
    throw new Error("Failed to upload file: Upload status is not finalized.");
  }
  return responseJson["file"];
}
async function getBlobStat(file) {
  const fileStat = { size: file.size, type: file.type };
  return fileStat;
}
function sleep$1(ms2) {
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms2));
}
class BrowserUploader {
  async upload(file, uploadUrl, apiClient) {
    if (typeof file === "string") {
      throw new Error("File path is not supported in browser uploader.");
    }
    return await uploadBlob(file, uploadUrl, apiClient);
  }
  async stat(file) {
    if (typeof file === "string") {
      throw new Error("File path is not supported in browser uploader.");
    } else {
      return await getBlobStat(file);
    }
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
class BrowserWebSocketFactory {
  create(url, headers, callbacks) {
    return new BrowserWebSocket(url, headers, callbacks);
  }
}
class BrowserWebSocket {
  constructor(url, headers, callbacks) {
    this.url = url;
    this.headers = headers;
    this.callbacks = callbacks;
  }
  connect() {
    this.ws = new WebSocket(this.url);
    this.ws.onopen = this.callbacks.onopen;
    this.ws.onerror = this.callbacks.onerror;
    this.ws.onclose = this.callbacks.onclose;
    this.ws.onmessage = this.callbacks.onmessage;
  }
  send(message) {
    if (this.ws === void 0) {
      throw new Error("WebSocket is not connected");
    }
    this.ws.send(message);
  }
  close() {
    if (this.ws === void 0) {
      throw new Error("WebSocket is not connected");
    }
    this.ws.close();
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const GOOGLE_API_KEY_HEADER = "x-goog-api-key";
class WebAuth {
  constructor(apiKey) {
    this.apiKey = apiKey;
  }
  async addAuthHeaders(headers) {
    if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {
      return;
    }
    if (this.apiKey.startsWith("auth_tokens/")) {
      throw new Error("Ephemeral tokens are only supported by the live API.");
    }
    if (!this.apiKey) {
      throw new Error("API key is missing. Please provide a valid API key.");
    }
    headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);
  }
}
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
const LANGUAGE_LABEL_PREFIX = "gl-node/";
class GoogleGenAI {
  constructor(options2) {
    var _a3;
    if (options2.apiKey == null) {
      throw new Error("An API Key must be set when running in a browser");
    }
    if (options2.project || options2.location) {
      throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");
    }
    this.vertexai = (_a3 = options2.vertexai) !== null && _a3 !== void 0 ? _a3 : false;
    this.apiKey = options2.apiKey;
    const baseUrl = getBaseUrl(
      options2.httpOptions,
      options2.vertexai,
      /*vertexBaseUrlFromEnv*/
      void 0,
      /*geminiBaseUrlFromEnv*/
      void 0
    );
    if (baseUrl) {
      if (options2.httpOptions) {
        options2.httpOptions.baseUrl = baseUrl;
      } else {
        options2.httpOptions = { baseUrl };
      }
    }
    this.apiVersion = options2.apiVersion;
    const auth = new WebAuth(this.apiKey);
    this.apiClient = new ApiClient({
      auth,
      apiVersion: this.apiVersion,
      apiKey: this.apiKey,
      vertexai: this.vertexai,
      httpOptions: options2.httpOptions,
      userAgentExtra: LANGUAGE_LABEL_PREFIX + "web",
      uploader: new BrowserUploader(),
      downloader: new BrowserDownloader()
    });
    this.models = new Models(this.apiClient);
    this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());
    this.batches = new Batches(this.apiClient);
    this.chats = new Chats(this.models, this.apiClient);
    this.caches = new Caches(this.apiClient);
    this.files = new Files(this.apiClient);
    this.operations = new Operations(this.apiClient);
    this.authTokens = new Tokens(this.apiClient);
    this.tunings = new Tunings(this.apiClient);
  }
}
mcpMesh.implementAction("log", async (params) => {
  {
    console[params.level](...params.messages);
  }
  sdpppXLog.push(params.messages.join(" "));
  return {};
});
mcpMesh.implementAction("openExternalLink", async (params) => {
  try {
    await uxp.shell.openExternal(params.url);
    return {};
  } catch (error) {
    return {
      error: error.message
    };
  }
});
mcpMesh.implementAction("getStorage", async (params) => {
  try {
    const value = localStorage.getItem(params.key);
    return { value: value || "" };
  } catch (error) {
    return {
      value: "",
      error: error.message
    };
  }
});
mcpMesh.implementAction("setStorage", async (params) => {
  try {
    localStorage.setItem(params.key, params.value);
    return {};
  } catch (error) {
    return {
      error: error.message
    };
  }
});
let sptextElement = document.createElement("sp-textfield");
sptextElement.style.position = "absolute";
sptextElement.style.top = "-10000px";
sptextElement.style.left = "-10000px";
document.body.appendChild(sptextElement);
sptextElement.addEventListener("focus", (e4) => {
  mcpMesh.store.setState({
    sdkWebviewFocusing: false
  });
  sptextElement.blur();
});
mcpMesh.implementAction("keyboardAction", async (params) => {
  const handlers = DialogManagerStore.getState().keyboardHandlers;
  const handled = handlers.filter((h2) => h2(params.keycode));
  if (handled.length > 0) {
    return {};
  }
  sptextElement.focus();
  return {};
});
mcpMesh.implementAction("setComfyWebviewURL", async (params) => {
  let url = params.url.split("?")[0].split("#")[0];
  mcpMesh.store.setState({
    comfyURL: url
  });
  PSUXPInternalStore.setState({
    comfyWebviewNeedRefresh: true
  });
  return {};
});
const globalFetch = globalThis.fetch;
globalThis.fetch = async (input, init2) => {
  if (init2 && !init2.signal) {
    delete init2.signal;
  }
  return globalFetch(input, init2);
};
mcpMesh.implementAction("getImageBase64", async (params) => {
  try {
    try {
      const { buffer: buffer2, mime: mime2 } = await resolveResourceBuffer(params.token);
      const data64 = "data:" + (mime2 || "application/octet-stream") + ";base64," + Buffer.from(buffer2).toString("base64");
      return { base64: data64, mimeType: mime2 || "application/octet-stream" };
    } catch {
    }
    const imageHolderResult = await getImageHolder(params.token);
    if (!imageHolderResult) {
      return { error: "Invalid image token" };
    }
    const { file_buffer, file_mimetype } = imageHolderResult;
    const base64 = "data:" + file_mimetype + ";base64," + Buffer.from(file_buffer).toString("base64");
    return { base64, mimeType: file_mimetype };
  } catch (error) {
    return { error: error.message };
  }
});
mcpMesh.implementAction("proxiedFetch", async (params) => {
  try {
    const { url, method = "GET", headers = {}, body, bodyType = "json" } = params;
    const fetchOptions = {
      method,
      headers: {
        ...headers
      }
    };
    if (body && method !== "GET" && method !== "HEAD") {
      if (bodyType === "formData") {
        const formData = new FormData();
        if (Array.isArray(body)) {
          for (const [key2, value] of body) {
            if (value && typeof value === "object" && "type" in value && value.type === "file") {
              const fileData = value;
              if (fileData.data) {
                if (value.mimeType == "image/uxp") {
                  const resourceUri = Buffer.from(fileData.data, "base64").toString();
                  const imageHolderResult = await getImageHolder(resourceUri);
                  if (!imageHolderResult) {
                    throw new Error("Invalid resource uri");
                  }
                  const { file_buffer, file_mimetype } = imageHolderResult;
                  const file = new Blob([file_buffer], {
                    type: file_mimetype || "application/octet-stream"
                  });
                  formData.append(key2, file);
                } else {
                  const file = new Blob([Buffer.from(fileData.data, "base64")], {
                    type: fileData.mimeType || "application/octet-stream"
                  });
                  formData.append(key2, file);
                }
              }
            } else {
              formData.append(key2, String(value));
            }
          }
        } else if (typeof body === "object" && body !== null) {
          Object.entries(body).forEach(([key2, value]) => {
            if (value && typeof value === "object" && "type" in value && value.type === "file") {
              const fileData = value;
              if (fileData.data) {
                const file = new Blob([Buffer.from(fileData.data, "base64")], {
                  type: fileData.type || "application/octet-stream"
                });
                formData.append(key2, file);
              }
            } else {
              formData.append(key2, String(value));
            }
          });
        }
        fetchOptions.body = formData;
      } else if (bodyType === "text") {
        fetchOptions.body = body;
      } else {
        if (!headers["Content-Type"]) {
          fetchOptions.headers = {
            "Content-Type": "application/json",
            ...headers
          };
        }
        fetchOptions.body = typeof body === "string" ? body : JSON.stringify(body);
      }
    }
    const response = await fetch(url, fetchOptions);
    const responseText = await response.text();
    let responseData;
    try {
      responseData = JSON.parse(responseText);
    } catch {
      responseData = responseText;
    }
    const headersObj = {};
    response.headers.forEach((value, key2) => {
      headersObj[key2] = value;
    });
    return {
      success: true,
      status: response.status,
      statusText: response.statusText,
      headers: headersObj,
      data: responseData
    };
  } catch (e4) {
    return {
      success: false,
      error: e4.message
    };
  }
});
mcpMesh.implementAction("pickLocalFile", async (params) => {
  var _a3;
  try {
    const { acceptExtensions = [], kind } = params || {};
    const localFileSystem = uxp.storage.localFileSystem;
    try {
      console.log("[pickLocalFile] inbound", { acceptExtensions, kind, hasGetFileForOpening: !!localFileSystem.getFileForOpening });
    } catch {
    }
    const types = acceptExtensions.length ? [{
      description: "Allowed files",
      extension: acceptExtensions.map((ext) => ext.replace(/^\./, "").toLowerCase())
    }] : void 0;
    let fileEntry;
    try {
      fileEntry = await ((_a3 = localFileSystem.getFileForOpening) == null ? void 0 : _a3.call(localFileSystem, {
        allowMultiple: false,
        types
      }));
    } catch (error) {
      const message = ((error == null ? void 0 : error.message) || "").toLowerCase();
      try {
        console.warn("[pickLocalFile] getFileForOpening error", { message: (error == null ? void 0 : error.message) || String(error), params: { acceptExtensions, kind, types } });
      } catch {
      }
      if (message.includes("cancel")) {
        return { cancelled: true };
      }
      return { error: (error == null ? void 0 : error.message) || String(error) };
    }
    if (!fileEntry) {
      try {
        console.warn("[pickLocalFile] no fileEntry returned");
      } catch {
      }
      return { cancelled: true };
    }
    let arrayBuffer;
    try {
      arrayBuffer = await fileEntry.read({ format: uxp.storage.formats.binary });
    } catch (readError) {
      try {
        console.warn("[pickLocalFile] read error", { message: (readError == null ? void 0 : readError.message) || String(readError) });
      } catch {
      }
      return { error: (readError == null ? void 0 : readError.message) || String(readError) };
    }
    const buffer2 = new Uint8Array(arrayBuffer);
    const fileName = typeof fileEntry.name === "string" && fileEntry.name ? fileEntry.name : `local-file-${Date.now()}`;
    const extension = (() => {
      const idx = fileName.lastIndexOf(".");
      return idx >= 0 ? fileName.substring(idx + 1).toLowerCase() : "";
    })();
    const mimeMap = {
      png: "image/png",
      jpg: "image/jpeg",
      jpeg: "image/jpeg",
      webp: "image/webp",
      gif: "image/gif",
      bmp: "image/bmp",
      tiff: "image/tiff",
      tif: "image/tiff",
      svg: "image/svg+xml",
      heic: "image/heic"
    };
    let mimeType = mimeMap[extension];
    if (!mimeType && kind === "image") {
      mimeType = "image/png";
    }
    if (!mimeType) {
      mimeType = "application/octet-stream";
    }
    const resourceType = mimeType.startsWith("image/") ? "image" : "file";
    const resourceId = createResource({
      type: resourceType,
      data: {
        buffer: buffer2,
        mime: mimeType,
        path: fileEntry.nativePath
      },
      originalMeta: {
        fileName,
        nativePath: fileEntry.nativePath,
        size: buffer2.byteLength
      }
    });
    try {
      console.log("[pickLocalFile] success", { resourceId, fileName, mimeType, size: buffer2.byteLength });
    } catch {
    }
    return {
      cancelled: false,
      resource: resourceId,
      fileName,
      mimeType,
      size: buffer2.byteLength
    };
  } catch (error) {
    try {
      console.warn("[pickLocalFile] unexpected error", { message: (error == null ? void 0 : error.message) || String(error), stack: error == null ? void 0 : error.stack });
    } catch {
    }
    return { error: (error == null ? void 0 : error.message) || String(error) };
  }
});
const resolveUploadContent = async (uploadInput) => {
  let uint8Array;
  let mimeType = uploadInput.mimeType || "image/png";
  if (uploadInput.type === "buffer") {
    const source = uploadInput.resource || {};
    let data2 = (source == null ? void 0 : source.data) ?? source;
    const isEmptyObject = (value) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
    if (data2 == null || isEmptyObject(data2)) {
      const token = typeof uploadInput.resource === "string" ? uploadInput.resource : uploadInput.resourceId ?? uploadInput.resource;
      if (token && typeof token === "string") {
        const resolved = await resolveResourceBuffer(token).catch(async () => {
          const legacy2 = await getImageHolder(token);
          if (!legacy2) {
            return void 0;
          }
          return {
            buffer: legacy2.file_buffer,
            mime: legacy2.file_mimetype
          };
        });
        if (!resolved) {
          throw new Error("Upload buffer data missing");
        }
        uint8Array = new Uint8Array(resolved.buffer);
        if (resolved.mime) {
          mimeType = uploadInput.mimeType || resolved.mime;
        }
      } else {
        throw new Error("Upload buffer data missing");
      }
    } else {
      if (typeof data2 === "string") {
        if (/^[A-Za-z0-9+/=]+$/.test(data2)) {
          uint8Array = new Uint8Array(Buffer.from(data2, "base64"));
        } else {
          uint8Array = new TextEncoder().encode(data2);
        }
      } else if (data2 instanceof ArrayBuffer) {
        uint8Array = new Uint8Array(data2);
      } else if (ArrayBuffer.isView(data2)) {
        const view = data2;
        uint8Array = new Uint8Array(view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
      } else {
        uint8Array = new Uint8Array(data2);
      }
    }
    const sourceMime = (source == null ? void 0 : source.mimeType) ?? uploadInput.mimeType;
    if (sourceMime) {
      mimeType = sourceMime;
    }
  } else {
    const token = typeof uploadInput.resource === "string" ? uploadInput.resource : uploadInput.resourceId ?? uploadInput.resource;
    if (!token || typeof token !== "string") {
      throw new Error("Upload resource token missing");
    }
    try {
      const resolved = await resolveResourceBuffer(token);
      uint8Array = new Uint8Array(resolved.buffer);
      if (resolved.mime) {
        mimeType = uploadInput.mimeType || resolved.mime;
      }
    } catch {
      const legacy2 = await getImageHolder(token);
      if (!legacy2) {
        throw new Error("Image not found: " + token);
      }
      uint8Array = new Uint8Array(legacy2.file_buffer);
      if (legacy2.file_mimetype) {
        mimeType = uploadInput.mimeType || legacy2.file_mimetype;
      }
    }
  }
  if (!uint8Array) {
    throw new Error("Upload buffer data missing");
  }
  return { uint8Array, mimeType };
};
mcpMesh.implementAction("uploadComfyImage", async (request, extra, signal) => {
  var _a3, _b2, _c2;
  const { uploadInput, overwrite } = request;
  const { uint8Array, mimeType } = await resolveUploadContent(uploadInput);
  const comfyStore = (_b2 = (_a3 = mcpMesh.store) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3);
  const comfyURL = typeof (comfyStore == null ? void 0 : comfyStore.comfyURL) === "string" ? comfyStore.comfyURL.split("?")[0] : "";
  const uploadURL = comfyURL ? comfyURL.endsWith("/") ? `${comfyURL}sdppp_upload2` : `${comfyURL}/sdppp_upload2` : "";
  const attemptDirectUpload = async () => {
    if (!uploadURL) {
      return null;
    }
    try {
      const headResp = await fetch(uploadURL, { method: "HEAD", signal });
      if (!headResp.ok) {
        return null;
      }
    } catch (error) {
      try {
        console.warn("[uploadComfyImage] HEAD probe failed, fallback to action", error instanceof Error ? error.message : error);
      } catch {
      }
      return null;
    }
    try {
      const blob = new Blob([uint8Array], { type: mimeType || "image/png" });
      const formData = new FormData();
      const payload2 = FormData.prototype.get ? blob : await blob.arrayBuffer();
      formData.append("image", payload2);
      formData.append("filename", uploadInput.fileName);
      formData.append("overwrite", overwrite ? "true" : "false");
      const response = await fetch(uploadURL, {
        method: "POST",
        body: formData,
        signal
      });
      if (!response.ok) {
        throw new Error(response.statusText || `HTTP ${response.status}`);
      }
      const result = await response.json();
      return {
        name: `${result.subfolder}/${result.name}`
      };
    } catch (error) {
      try {
        console.warn("[uploadComfyImage] direct upload failed, fallback to action", error instanceof Error ? error.message : error);
      } catch {
      }
      return null;
    }
  };
  const directResult = await attemptDirectUpload();
  if (directResult) {
    return directResult;
  }
  const comfyActions = (_c2 = mcpMesh.getNode("comfy")) == null ? void 0 : _c2.actions;
  if (!(comfyActions == null ? void 0 : comfyActions.uploadComfyImageFromUXP)) {
    throw new Error("Comfy uploader is not available");
  }
  const base64Data = Buffer.from(uint8Array).toString("base64");
  const payload = {
    fileName: uploadInput.fileName,
    overwrite,
    mimeType: mimeType || "image/png",
    dataBase64: base64Data
  };
  return await comfyActions.uploadComfyImageFromUXP(payload, extra, signal);
});
mcpMesh.implementAction("openaiImageEdit", async (params, _extra, signal) => {
  var _a3;
  const apiStartTime = Date.now();
  try {
    if (signal == null ? void 0 : signal.aborted) {
      throw new DOMException("Request aborted", "AbortError");
    }
    const imageHolderResult = await getImageHolder(params.imageToken);
    if (!imageHolderResult) {
      return {
        success: false,
        apiTime: Date.now() - apiStartTime,
        error: "Invalid image token"
      };
    }
    const { file_buffer, file_mimetype } = imageHolderResult;
    const imageBuffer = Buffer.from(file_buffer);
    const base2 = params.baseURL.replace(/\/$/, "");
    const url = `${base2}/images/edits`;
    const form = new FormData();
    const blob = new Blob([imageBuffer], { type: "image/png" });
    form.append("image", blob, "image.png");
    form.append("prompt", params.prompt);
    form.append("model", params.model || "gpt-image-1");
    form.append("n", "1");
    form.append("size", "1024x1024");
    const res = await fetch(url, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${params.apiKey}`
      },
      body: form,
      signal
    });
    if (!res.ok) {
      const text = await res.text();
      return {
        success: false,
        apiTime: Date.now() - apiStartTime,
        error: `HTTP ${res.status}: ${text}`
      };
    }
    const json = await res.json();
    const apiTime = Date.now() - apiStartTime;
    const item = (_a3 = json == null ? void 0 : json.data) == null ? void 0 : _a3[0];
    let imageUrl;
    if (item == null ? void 0 : item.url) {
      imageUrl = item.url;
    } else if (item == null ? void 0 : item.b64_json) {
      imageUrl = `data:image/png;base64,${item.b64_json}`;
    }
    if (imageUrl) {
      return { success: true, imageUrl, apiTime };
    }
    return { success: false, apiTime, error: "No image returned" };
  } catch (error) {
    const apiTime = Date.now() - apiStartTime;
    return {
      success: false,
      apiTime,
      error: (error == null ? void 0 : error.message) || "OpenAI API error"
    };
  }
});
mcpMesh.implementAction("geminiImageGenerate", async (params, _extra, signal) => {
  const apiStartTime = Date.now();
  try {
    if (signal == null ? void 0 : signal.aborted) {
      throw new DOMException("Request aborted", "AbortError");
    }
    const inputsArray = Array.isArray(params.imageInputs) && params.imageInputs.length > 0 ? params.imageInputs : params.imageInput ? [params.imageInput] : [];
    if (inputsArray.length === 0) {
      return {
        success: false,
        apiTime: Date.now() - apiStartTime,
        error: "No image input provided"
      };
    }
    const inlineParts = [];
    for (const input of inputsArray) {
      let imageBuffer;
      if (params.imageInputType === "token") {
        const imageHolderResult = await getImageHolder(input);
        if (!imageHolderResult) {
          return {
            success: false,
            apiTime: Date.now() - apiStartTime,
            error: "Invalid image token"
          };
        }
        imageBuffer = Buffer.from(imageHolderResult.file_buffer);
      } else {
        if (input.startsWith("data:")) {
          const base64Data = input.split(",")[1];
          imageBuffer = Buffer.from(base64Data, "base64");
        } else {
          imageBuffer = Buffer.from(input, "base64");
        }
      }
      inlineParts.push({
        inlineData: {
          mimeType: "image/png",
          data: imageBuffer.toString("base64")
        }
      });
    }
    const options2 = { apiKey: params.apiKey };
    if (params.baseURL) {
      options2.httpOptions = { baseUrl: params.baseURL };
    }
    const genAI = new GoogleGenAI(options2);
    const requestPromise = genAI.models.generateContent({
      model: "gemini-2.5-flash-image-preview",
      contents: [
        {
          role: "user",
          parts: [
            ...inlineParts,
            { text: params.prompt }
          ]
        }
      ],
      config: {
        temperature: 1,
        topP: 0.95,
        maxOutputTokens: 32768,
        responseModalities: ["TEXT", "IMAGE"],
        safetySettings: [
          { category: HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold: HarmBlockThreshold.BLOCK_NONE },
          { category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold.BLOCK_NONE },
          { category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold: HarmBlockThreshold.BLOCK_NONE },
          { category: HarmCategory.HARM_CATEGORY_HARASSMENT, threshold: HarmBlockThreshold.BLOCK_NONE }
        ]
      }
    });
    const response = await (signal ? new Promise((resolve2, reject2) => {
      const onAbort = () => reject2(new DOMException("Request aborted", "AbortError"));
      signal.addEventListener("abort", onAbort, { once: true });
      requestPromise.then((res) => {
        signal.removeEventListener("abort", onAbort);
        resolve2(res);
      }).catch((err) => {
        signal.removeEventListener("abort", onAbort);
        reject2(err);
      });
    }) : requestPromise);
    const apiTime = Date.now() - apiStartTime;
    if (response && response.candidates && response.candidates.length > 0) {
      for (const candidate of response.candidates) {
        if (candidate.content && candidate.content.parts) {
          for (const part of candidate.content.parts) {
            if (part.inlineData && part.inlineData.data) {
              const mimeType = part.inlineData.mimeType || "image/png";
              const imageUrl = `data:${mimeType};base64,${part.inlineData.data}`;
              return {
                success: true,
                imageUrl,
                apiTime
              };
            }
          }
        }
      }
    }
    return {
      success: false,
      apiTime,
      error: "No image data found in Gemini response"
    };
  } catch (error) {
    const apiTime = Date.now() - apiStartTime;
    return {
      success: false,
      apiTime,
      error: (error == null ? void 0 : error.message) || "Gemini API error"
    };
  }
});
var commonjsGlobal = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {};
function getDefaultExportFromCjs(e4) {
  return e4 && e4.__esModule && Object.prototype.hasOwnProperty.call(e4, "default") ? e4.default : e4;
}
function getAugmentedNamespace(e4) {
  if (e4.__esModule) return e4;
  var t2 = e4.default;
  if ("function" == typeof t2) {
    var i2 = function e5() {
      return this instanceof e5 ? Reflect.construct(t2, arguments, this.constructor) : t2.apply(this, arguments);
    };
    i2.prototype = t2.prototype;
  } else i2 = {};
  return Object.defineProperty(i2, "__esModule", { value: true }), Object.keys(e4).forEach(function(t3) {
    var r2 = Object.getOwnPropertyDescriptor(e4, t3);
    Object.defineProperty(i2, t3, r2.get ? r2 : { enumerable: true, get: function() {
      return e4[t3];
    } });
  }), i2;
}
"undefined" == typeof self && "object" == typeof commonjsGlobal && (commonjsGlobal.self = commonjsGlobal);
var global$1 = "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, lookup = [], revLookup = [], Arr = "undefined" != typeof Uint8Array ? Uint8Array : Array, inited = false;
function init() {
  inited = true;
  for (var e4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", t2 = 0; t2 < 64; ++t2) lookup[t2] = e4[t2], revLookup[e4.charCodeAt(t2)] = t2;
  revLookup["-".charCodeAt(0)] = 62, revLookup["_".charCodeAt(0)] = 63;
}
function toByteArray(e4) {
  var t2, i2, r2, n2, a2, o2;
  inited || init();
  var s2 = e4.length;
  if (s2 % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
  a2 = "=" === e4[s2 - 2] ? 2 : "=" === e4[s2 - 1] ? 1 : 0, o2 = new Arr(3 * s2 / 4 - a2), r2 = a2 > 0 ? s2 - 4 : s2;
  var l2 = 0;
  for (t2 = 0, i2 = 0; t2 < r2; t2 += 4, i2 += 3) n2 = revLookup[e4.charCodeAt(t2)] << 18 | revLookup[e4.charCodeAt(t2 + 1)] << 12 | revLookup[e4.charCodeAt(t2 + 2)] << 6 | revLookup[e4.charCodeAt(t2 + 3)], o2[l2++] = n2 >> 16 & 255, o2[l2++] = n2 >> 8 & 255, o2[l2++] = 255 & n2;
  return 2 === a2 ? (n2 = revLookup[e4.charCodeAt(t2)] << 2 | revLookup[e4.charCodeAt(t2 + 1)] >> 4, o2[l2++] = 255 & n2) : 1 === a2 && (n2 = revLookup[e4.charCodeAt(t2)] << 10 | revLookup[e4.charCodeAt(t2 + 1)] << 4 | revLookup[e4.charCodeAt(t2 + 2)] >> 2, o2[l2++] = n2 >> 8 & 255, o2[l2++] = 255 & n2), o2;
}
function tripletToBase64(e4) {
  return lookup[e4 >> 18 & 63] + lookup[e4 >> 12 & 63] + lookup[e4 >> 6 & 63] + lookup[63 & e4];
}
function encodeChunk(e4, t2, i2) {
  for (var r2, n2 = [], a2 = t2; a2 < i2; a2 += 3) r2 = (e4[a2] << 16) + (e4[a2 + 1] << 8) + e4[a2 + 2], n2.push(tripletToBase64(r2));
  return n2.join("");
}
function fromByteArray(e4) {
  var t2;
  inited || init();
  for (var i2 = e4.length, r2 = i2 % 3, n2 = "", a2 = [], o2 = 16383, s2 = 0, l2 = i2 - r2; s2 < l2; s2 += o2) a2.push(encodeChunk(e4, s2, s2 + o2 > l2 ? l2 : s2 + o2));
  return 1 === r2 ? (t2 = e4[i2 - 1], n2 += lookup[t2 >> 2], n2 += lookup[t2 << 4 & 63], n2 += "==") : 2 === r2 && (t2 = (e4[i2 - 2] << 8) + e4[i2 - 1], n2 += lookup[t2 >> 10], n2 += lookup[t2 >> 4 & 63], n2 += lookup[t2 << 2 & 63], n2 += "="), a2.push(n2), a2.join("");
}
function read(e4, t2, i2, r2, n2) {
  var a2, o2, s2 = 8 * n2 - r2 - 1, l2 = (1 << s2) - 1, u2 = l2 >> 1, h2 = -7, c2 = i2 ? n2 - 1 : 0, f2 = i2 ? -1 : 1, d = e4[t2 + c2];
  for (c2 += f2, a2 = d & (1 << -h2) - 1, d >>= -h2, h2 += s2; h2 > 0; a2 = 256 * a2 + e4[t2 + c2], c2 += f2, h2 -= 8) ;
  for (o2 = a2 & (1 << -h2) - 1, a2 >>= -h2, h2 += r2; h2 > 0; o2 = 256 * o2 + e4[t2 + c2], c2 += f2, h2 -= 8) ;
  if (0 === a2) a2 = 1 - u2;
  else {
    if (a2 === l2) return o2 ? NaN : 1 / 0 * (d ? -1 : 1);
    o2 += Math.pow(2, r2), a2 -= u2;
  }
  return (d ? -1 : 1) * o2 * Math.pow(2, a2 - r2);
}
function write(e4, t2, i2, r2, n2, a2) {
  var o2, s2, l2, u2 = 8 * a2 - n2 - 1, h2 = (1 << u2) - 1, c2 = h2 >> 1, f2 = 23 === n2 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = r2 ? 0 : a2 - 1, p2 = r2 ? 1 : -1, m = t2 < 0 || 0 === t2 && 1 / t2 < 0 ? 1 : 0;
  for (t2 = Math.abs(t2), isNaN(t2) || t2 === 1 / 0 ? (s2 = isNaN(t2) ? 1 : 0, o2 = h2) : (o2 = Math.floor(Math.log(t2) / Math.LN2), t2 * (l2 = Math.pow(2, -o2)) < 1 && (o2--, l2 *= 2), (t2 += o2 + c2 >= 1 ? f2 / l2 : f2 * Math.pow(2, 1 - c2)) * l2 >= 2 && (o2++, l2 /= 2), o2 + c2 >= h2 ? (s2 = 0, o2 = h2) : o2 + c2 >= 1 ? (s2 = (t2 * l2 - 1) * Math.pow(2, n2), o2 += c2) : (s2 = t2 * Math.pow(2, c2 - 1) * Math.pow(2, n2), o2 = 0)); n2 >= 8; e4[i2 + d] = 255 & s2, d += p2, s2 /= 256, n2 -= 8) ;
  for (o2 = o2 << n2 | s2, u2 += n2; u2 > 0; e4[i2 + d] = 255 & o2, d += p2, o2 /= 256, u2 -= 8) ;
  e4[i2 + d - p2] |= 128 * m;
}
var toString = {}.toString, isArray = Array.isArray || function(e4) {
  return "[object Array]" == toString.call(e4);
}, INSPECT_MAX_BYTES = 50;
function kMaxLength() {
  return Buffer$1.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(e4, t2) {
  if (kMaxLength() < t2) throw new RangeError("Invalid typed array length");
  return Buffer$1.TYPED_ARRAY_SUPPORT ? (e4 = new Uint8Array(t2)).__proto__ = Buffer$1.prototype : (null === e4 && (e4 = new Buffer$1(t2)), e4.length = t2), e4;
}
function Buffer$1(e4, t2, i2) {
  if (!(Buffer$1.TYPED_ARRAY_SUPPORT || this instanceof Buffer$1)) return new Buffer$1(e4, t2, i2);
  if ("number" == typeof e4) {
    if ("string" == typeof t2) throw new Error("If encoding is specified then the first argument must be a string");
    return allocUnsafe(this, e4);
  }
  return from(this, e4, t2, i2);
}
function from(e4, t2, i2, r2) {
  if ("number" == typeof t2) throw new TypeError('"value" argument must not be a number');
  return "undefined" != typeof ArrayBuffer && t2 instanceof ArrayBuffer ? fromArrayBuffer(e4, t2, i2, r2) : "string" == typeof t2 ? fromString(e4, t2, i2) : fromObject(e4, t2);
}
function assertSize(e4) {
  if ("number" != typeof e4) throw new TypeError('"size" argument must be a number');
  if (e4 < 0) throw new RangeError('"size" argument must not be negative');
}
function alloc(e4, t2, i2, r2) {
  return assertSize(t2), t2 <= 0 ? createBuffer(e4, t2) : void 0 !== i2 ? "string" == typeof r2 ? createBuffer(e4, t2).fill(i2, r2) : createBuffer(e4, t2).fill(i2) : createBuffer(e4, t2);
}
function allocUnsafe(e4, t2) {
  if (assertSize(t2), e4 = createBuffer(e4, t2 < 0 ? 0 : 0 | checked(t2)), !Buffer$1.TYPED_ARRAY_SUPPORT) for (var i2 = 0; i2 < t2; ++i2) e4[i2] = 0;
  return e4;
}
function fromString(e4, t2, i2) {
  if ("string" == typeof i2 && "" !== i2 || (i2 = "utf8"), !Buffer$1.isEncoding(i2)) throw new TypeError('"encoding" must be a valid string encoding');
  var r2 = 0 | byteLength(t2, i2), n2 = (e4 = createBuffer(e4, r2)).write(t2, i2);
  return n2 !== r2 && (e4 = e4.slice(0, n2)), e4;
}
function fromArrayLike(e4, t2) {
  var i2 = t2.length < 0 ? 0 : 0 | checked(t2.length);
  e4 = createBuffer(e4, i2);
  for (var r2 = 0; r2 < i2; r2 += 1) e4[r2] = 255 & t2[r2];
  return e4;
}
function fromArrayBuffer(e4, t2, i2, r2) {
  if (t2.byteLength, i2 < 0 || t2.byteLength < i2) throw new RangeError("'offset' is out of bounds");
  if (t2.byteLength < i2 + (r2 || 0)) throw new RangeError("'length' is out of bounds");
  return t2 = void 0 === i2 && void 0 === r2 ? new Uint8Array(t2) : void 0 === r2 ? new Uint8Array(t2, i2) : new Uint8Array(t2, i2, r2), Buffer$1.TYPED_ARRAY_SUPPORT ? (e4 = t2).__proto__ = Buffer$1.prototype : e4 = fromArrayLike(e4, t2), e4;
}
function fromObject(e4, t2) {
  if (internalIsBuffer(t2)) {
    var i2 = 0 | checked(t2.length);
    return 0 === (e4 = createBuffer(e4, i2)).length || t2.copy(e4, 0, 0, i2), e4;
  }
  if (t2) {
    if ("undefined" != typeof ArrayBuffer && t2.buffer instanceof ArrayBuffer || "length" in t2) return "number" != typeof t2.length || isnan(t2.length) ? createBuffer(e4, 0) : fromArrayLike(e4, t2);
    if ("Buffer" === t2.type && isArray(t2.data)) return fromArrayLike(e4, t2.data);
  }
  throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");
}
function checked(e4) {
  if (e4 >= kMaxLength()) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength().toString(16) + " bytes");
  return 0 | e4;
}
function internalIsBuffer(e4) {
  return !(null == e4 || !e4._isBuffer);
}
function byteLength(e4, t2) {
  if (internalIsBuffer(e4)) return e4.length;
  if ("undefined" != typeof ArrayBuffer && "function" == typeof ArrayBuffer.isView && (ArrayBuffer.isView(e4) || e4 instanceof ArrayBuffer)) return e4.byteLength;
  "string" != typeof e4 && (e4 = "" + e4);
  var i2 = e4.length;
  if (0 === i2) return 0;
  for (var r2 = false; ; ) switch (t2) {
    case "ascii":
    case "latin1":
    case "binary":
      return i2;
    case "utf8":
    case "utf-8":
    case void 0:
      return utf8ToBytes(e4).length;
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return 2 * i2;
    case "hex":
      return i2 >>> 1;
    case "base64":
      return base64ToBytes(e4).length;
    default:
      if (r2) return utf8ToBytes(e4).length;
      t2 = ("" + t2).toLowerCase(), r2 = true;
  }
}
function slowToString(e4, t2, i2) {
  var r2 = false;
  if ((void 0 === t2 || t2 < 0) && (t2 = 0), t2 > this.length) return "";
  if ((void 0 === i2 || i2 > this.length) && (i2 = this.length), i2 <= 0) return "";
  if ((i2 >>>= 0) <= (t2 >>>= 0)) return "";
  for (e4 || (e4 = "utf8"); ; ) switch (e4) {
    case "hex":
      return hexSlice(this, t2, i2);
    case "utf8":
    case "utf-8":
      return utf8Slice(this, t2, i2);
    case "ascii":
      return asciiSlice(this, t2, i2);
    case "latin1":
    case "binary":
      return latin1Slice(this, t2, i2);
    case "base64":
      return base64Slice(this, t2, i2);
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return utf16leSlice(this, t2, i2);
    default:
      if (r2) throw new TypeError("Unknown encoding: " + e4);
      e4 = (e4 + "").toLowerCase(), r2 = true;
  }
}
function swap(e4, t2, i2) {
  var r2 = e4[t2];
  e4[t2] = e4[i2], e4[i2] = r2;
}
function bidirectionalIndexOf(e4, t2, i2, r2, n2) {
  if (0 === e4.length) return -1;
  if ("string" == typeof i2 ? (r2 = i2, i2 = 0) : i2 > 2147483647 ? i2 = 2147483647 : i2 < -2147483648 && (i2 = -2147483648), i2 = +i2, isNaN(i2) && (i2 = n2 ? 0 : e4.length - 1), i2 < 0 && (i2 = e4.length + i2), i2 >= e4.length) {
    if (n2) return -1;
    i2 = e4.length - 1;
  } else if (i2 < 0) {
    if (!n2) return -1;
    i2 = 0;
  }
  if ("string" == typeof t2 && (t2 = Buffer$1.from(t2, r2)), internalIsBuffer(t2)) return 0 === t2.length ? -1 : arrayIndexOf(e4, t2, i2, r2, n2);
  if ("number" == typeof t2) return t2 &= 255, Buffer$1.TYPED_ARRAY_SUPPORT && "function" == typeof Uint8Array.prototype.indexOf ? n2 ? Uint8Array.prototype.indexOf.call(e4, t2, i2) : Uint8Array.prototype.lastIndexOf.call(e4, t2, i2) : arrayIndexOf(e4, [t2], i2, r2, n2);
  throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(e4, t2, i2, r2, n2) {
  var a2, o2 = 1, s2 = e4.length, l2 = t2.length;
  if (void 0 !== r2 && ("ucs2" === (r2 = String(r2).toLowerCase()) || "ucs-2" === r2 || "utf16le" === r2 || "utf-16le" === r2)) {
    if (e4.length < 2 || t2.length < 2) return -1;
    o2 = 2, s2 /= 2, l2 /= 2, i2 /= 2;
  }
  function u2(e5, t3) {
    return 1 === o2 ? e5[t3] : e5.readUInt16BE(t3 * o2);
  }
  if (n2) {
    var h2 = -1;
    for (a2 = i2; a2 < s2; a2++) if (u2(e4, a2) === u2(t2, -1 === h2 ? 0 : a2 - h2)) {
      if (-1 === h2 && (h2 = a2), a2 - h2 + 1 === l2) return h2 * o2;
    } else -1 !== h2 && (a2 -= a2 - h2), h2 = -1;
  } else for (i2 + l2 > s2 && (i2 = s2 - l2), a2 = i2; a2 >= 0; a2--) {
    for (var c2 = true, f2 = 0; f2 < l2; f2++) if (u2(e4, a2 + f2) !== u2(t2, f2)) {
      c2 = false;
      break;
    }
    if (c2) return a2;
  }
  return -1;
}
function hexWrite(e4, t2, i2, r2) {
  i2 = Number(i2) || 0;
  var n2 = e4.length - i2;
  r2 ? (r2 = Number(r2)) > n2 && (r2 = n2) : r2 = n2;
  var a2 = t2.length;
  if (a2 % 2 != 0) throw new TypeError("Invalid hex string");
  r2 > a2 / 2 && (r2 = a2 / 2);
  for (var o2 = 0; o2 < r2; ++o2) {
    var s2 = parseInt(t2.substr(2 * o2, 2), 16);
    if (isNaN(s2)) return o2;
    e4[i2 + o2] = s2;
  }
  return o2;
}
function utf8Write(e4, t2, i2, r2) {
  return blitBuffer(utf8ToBytes(t2, e4.length - i2), e4, i2, r2);
}
function asciiWrite(e4, t2, i2, r2) {
  return blitBuffer(asciiToBytes(t2), e4, i2, r2);
}
function latin1Write(e4, t2, i2, r2) {
  return asciiWrite(e4, t2, i2, r2);
}
function base64Write(e4, t2, i2, r2) {
  return blitBuffer(base64ToBytes(t2), e4, i2, r2);
}
function ucs2Write(e4, t2, i2, r2) {
  return blitBuffer(utf16leToBytes(t2, e4.length - i2), e4, i2, r2);
}
function base64Slice(e4, t2, i2) {
  return 0 === t2 && i2 === e4.length ? fromByteArray(e4) : fromByteArray(e4.slice(t2, i2));
}
function utf8Slice(e4, t2, i2) {
  i2 = Math.min(e4.length, i2);
  for (var r2 = [], n2 = t2; n2 < i2; ) {
    var a2, o2, s2, l2, u2 = e4[n2], h2 = null, c2 = u2 > 239 ? 4 : u2 > 223 ? 3 : u2 > 191 ? 2 : 1;
    if (n2 + c2 <= i2) switch (c2) {
      case 1:
        u2 < 128 && (h2 = u2);
        break;
      case 2:
        128 == (192 & (a2 = e4[n2 + 1])) && (l2 = (31 & u2) << 6 | 63 & a2) > 127 && (h2 = l2);
        break;
      case 3:
        a2 = e4[n2 + 1], o2 = e4[n2 + 2], 128 == (192 & a2) && 128 == (192 & o2) && (l2 = (15 & u2) << 12 | (63 & a2) << 6 | 63 & o2) > 2047 && (l2 < 55296 || l2 > 57343) && (h2 = l2);
        break;
      case 4:
        a2 = e4[n2 + 1], o2 = e4[n2 + 2], s2 = e4[n2 + 3], 128 == (192 & a2) && 128 == (192 & o2) && 128 == (192 & s2) && (l2 = (15 & u2) << 18 | (63 & a2) << 12 | (63 & o2) << 6 | 63 & s2) > 65535 && l2 < 1114112 && (h2 = l2);
    }
    null === h2 ? (h2 = 65533, c2 = 1) : h2 > 65535 && (h2 -= 65536, r2.push(h2 >>> 10 & 1023 | 55296), h2 = 56320 | 1023 & h2), r2.push(h2), n2 += c2;
  }
  return decodeCodePointsArray(r2);
}
Buffer$1.TYPED_ARRAY_SUPPORT = void 0 === global$1.TYPED_ARRAY_SUPPORT || global$1.TYPED_ARRAY_SUPPORT, kMaxLength(), Buffer$1.poolSize = 8192, Buffer$1._augment = function(e4) {
  return e4.__proto__ = Buffer$1.prototype, e4;
}, Buffer$1.from = function(e4, t2, i2) {
  return from(null, e4, t2, i2);
}, Buffer$1.TYPED_ARRAY_SUPPORT && (Buffer$1.prototype.__proto__ = Uint8Array.prototype, Buffer$1.__proto__ = Uint8Array, "undefined" != typeof Symbol && Symbol.species && Buffer$1[Symbol.species]), Buffer$1.alloc = function(e4, t2, i2) {
  return alloc(null, e4, t2, i2);
}, Buffer$1.allocUnsafe = function(e4) {
  return allocUnsafe(null, e4);
}, Buffer$1.allocUnsafeSlow = function(e4) {
  return allocUnsafe(null, e4);
}, Buffer$1.isBuffer = isBuffer, Buffer$1.compare = function(e4, t2) {
  if (!internalIsBuffer(e4) || !internalIsBuffer(t2)) throw new TypeError("Arguments must be Buffers");
  if (e4 === t2) return 0;
  for (var i2 = e4.length, r2 = t2.length, n2 = 0, a2 = Math.min(i2, r2); n2 < a2; ++n2) if (e4[n2] !== t2[n2]) {
    i2 = e4[n2], r2 = t2[n2];
    break;
  }
  return i2 < r2 ? -1 : r2 < i2 ? 1 : 0;
}, Buffer$1.isEncoding = function(e4) {
  switch (String(e4).toLowerCase()) {
    case "hex":
    case "utf8":
    case "utf-8":
    case "ascii":
    case "latin1":
    case "binary":
    case "base64":
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return true;
    default:
      return false;
  }
}, Buffer$1.concat = function(e4, t2) {
  if (!isArray(e4)) throw new TypeError('"list" argument must be an Array of Buffers');
  if (0 === e4.length) return Buffer$1.alloc(0);
  var i2;
  if (void 0 === t2) for (t2 = 0, i2 = 0; i2 < e4.length; ++i2) t2 += e4[i2].length;
  var r2 = Buffer$1.allocUnsafe(t2), n2 = 0;
  for (i2 = 0; i2 < e4.length; ++i2) {
    var a2 = e4[i2];
    if (!internalIsBuffer(a2)) throw new TypeError('"list" argument must be an Array of Buffers');
    a2.copy(r2, n2), n2 += a2.length;
  }
  return r2;
}, Buffer$1.byteLength = byteLength, Buffer$1.prototype._isBuffer = true, Buffer$1.prototype.swap16 = function() {
  var e4 = this.length;
  if (e4 % 2 != 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
  for (var t2 = 0; t2 < e4; t2 += 2) swap(this, t2, t2 + 1);
  return this;
}, Buffer$1.prototype.swap32 = function() {
  var e4 = this.length;
  if (e4 % 4 != 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
  for (var t2 = 0; t2 < e4; t2 += 4) swap(this, t2, t2 + 3), swap(this, t2 + 1, t2 + 2);
  return this;
}, Buffer$1.prototype.swap64 = function() {
  var e4 = this.length;
  if (e4 % 8 != 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
  for (var t2 = 0; t2 < e4; t2 += 8) swap(this, t2, t2 + 7), swap(this, t2 + 1, t2 + 6), swap(this, t2 + 2, t2 + 5), swap(this, t2 + 3, t2 + 4);
  return this;
}, Buffer$1.prototype.toString = function() {
  var e4 = 0 | this.length;
  return 0 === e4 ? "" : 0 === arguments.length ? utf8Slice(this, 0, e4) : slowToString.apply(this, arguments);
}, Buffer$1.prototype.equals = function(e4) {
  if (!internalIsBuffer(e4)) throw new TypeError("Argument must be a Buffer");
  return this === e4 || 0 === Buffer$1.compare(this, e4);
}, Buffer$1.prototype.inspect = function() {
  var e4 = "", t2 = INSPECT_MAX_BYTES;
  return this.length > 0 && (e4 = this.toString("hex", 0, t2).match(/.{2}/g).join(" "), this.length > t2 && (e4 += " ... ")), "<Buffer " + e4 + ">";
}, Buffer$1.prototype.compare = function(e4, t2, i2, r2, n2) {
  if (!internalIsBuffer(e4)) throw new TypeError("Argument must be a Buffer");
  if (void 0 === t2 && (t2 = 0), void 0 === i2 && (i2 = e4 ? e4.length : 0), void 0 === r2 && (r2 = 0), void 0 === n2 && (n2 = this.length), t2 < 0 || i2 > e4.length || r2 < 0 || n2 > this.length) throw new RangeError("out of range index");
  if (r2 >= n2 && t2 >= i2) return 0;
  if (r2 >= n2) return -1;
  if (t2 >= i2) return 1;
  if (this === e4) return 0;
  for (var a2 = (n2 >>>= 0) - (r2 >>>= 0), o2 = (i2 >>>= 0) - (t2 >>>= 0), s2 = Math.min(a2, o2), l2 = this.slice(r2, n2), u2 = e4.slice(t2, i2), h2 = 0; h2 < s2; ++h2) if (l2[h2] !== u2[h2]) {
    a2 = l2[h2], o2 = u2[h2];
    break;
  }
  return a2 < o2 ? -1 : o2 < a2 ? 1 : 0;
}, Buffer$1.prototype.includes = function(e4, t2, i2) {
  return -1 !== this.indexOf(e4, t2, i2);
}, Buffer$1.prototype.indexOf = function(e4, t2, i2) {
  return bidirectionalIndexOf(this, e4, t2, i2, true);
}, Buffer$1.prototype.lastIndexOf = function(e4, t2, i2) {
  return bidirectionalIndexOf(this, e4, t2, i2, false);
}, Buffer$1.prototype.write = function(e4, t2, i2, r2) {
  if (void 0 === t2) r2 = "utf8", i2 = this.length, t2 = 0;
  else if (void 0 === i2 && "string" == typeof t2) r2 = t2, i2 = this.length, t2 = 0;
  else {
    if (!isFinite(t2)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    t2 |= 0, isFinite(i2) ? (i2 |= 0, void 0 === r2 && (r2 = "utf8")) : (r2 = i2, i2 = void 0);
  }
  var n2 = this.length - t2;
  if ((void 0 === i2 || i2 > n2) && (i2 = n2), e4.length > 0 && (i2 < 0 || t2 < 0) || t2 > this.length) throw new RangeError("Attempt to write outside buffer bounds");
  r2 || (r2 = "utf8");
  for (var a2 = false; ; ) switch (r2) {
    case "hex":
      return hexWrite(this, e4, t2, i2);
    case "utf8":
    case "utf-8":
      return utf8Write(this, e4, t2, i2);
    case "ascii":
      return asciiWrite(this, e4, t2, i2);
    case "latin1":
    case "binary":
      return latin1Write(this, e4, t2, i2);
    case "base64":
      return base64Write(this, e4, t2, i2);
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return ucs2Write(this, e4, t2, i2);
    default:
      if (a2) throw new TypeError("Unknown encoding: " + r2);
      r2 = ("" + r2).toLowerCase(), a2 = true;
  }
}, Buffer$1.prototype.toJSON = function() {
  return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
};
var MAX_ARGUMENTS_LENGTH = 4096;
function decodeCodePointsArray(e4) {
  var t2 = e4.length;
  if (t2 <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode.apply(String, e4);
  for (var i2 = "", r2 = 0; r2 < t2; ) i2 += String.fromCharCode.apply(String, e4.slice(r2, r2 += MAX_ARGUMENTS_LENGTH));
  return i2;
}
function asciiSlice(e4, t2, i2) {
  var r2 = "";
  i2 = Math.min(e4.length, i2);
  for (var n2 = t2; n2 < i2; ++n2) r2 += String.fromCharCode(127 & e4[n2]);
  return r2;
}
function latin1Slice(e4, t2, i2) {
  var r2 = "";
  i2 = Math.min(e4.length, i2);
  for (var n2 = t2; n2 < i2; ++n2) r2 += String.fromCharCode(e4[n2]);
  return r2;
}
function hexSlice(e4, t2, i2) {
  var r2 = e4.length;
  (!t2 || t2 < 0) && (t2 = 0), (!i2 || i2 < 0 || i2 > r2) && (i2 = r2);
  for (var n2 = "", a2 = t2; a2 < i2; ++a2) n2 += toHex(e4[a2]);
  return n2;
}
function utf16leSlice(e4, t2, i2) {
  for (var r2 = e4.slice(t2, i2), n2 = "", a2 = 0; a2 < r2.length; a2 += 2) n2 += String.fromCharCode(r2[a2] + 256 * r2[a2 + 1]);
  return n2;
}
function checkOffset(e4, t2, i2) {
  if (e4 % 1 != 0 || e4 < 0) throw new RangeError("offset is not uint");
  if (e4 + t2 > i2) throw new RangeError("Trying to access beyond buffer length");
}
function checkInt(e4, t2, i2, r2, n2, a2) {
  if (!internalIsBuffer(e4)) throw new TypeError('"buffer" argument must be a Buffer instance');
  if (t2 > n2 || t2 < a2) throw new RangeError('"value" argument is out of bounds');
  if (i2 + r2 > e4.length) throw new RangeError("Index out of range");
}
function objectWriteUInt16(e4, t2, i2, r2) {
  t2 < 0 && (t2 = 65535 + t2 + 1);
  for (var n2 = 0, a2 = Math.min(e4.length - i2, 2); n2 < a2; ++n2) e4[i2 + n2] = (t2 & 255 << 8 * (r2 ? n2 : 1 - n2)) >>> 8 * (r2 ? n2 : 1 - n2);
}
function objectWriteUInt32(e4, t2, i2, r2) {
  t2 < 0 && (t2 = 4294967295 + t2 + 1);
  for (var n2 = 0, a2 = Math.min(e4.length - i2, 4); n2 < a2; ++n2) e4[i2 + n2] = t2 >>> 8 * (r2 ? n2 : 3 - n2) & 255;
}
function checkIEEE754(e4, t2, i2, r2, n2, a2) {
  if (i2 + r2 > e4.length) throw new RangeError("Index out of range");
  if (i2 < 0) throw new RangeError("Index out of range");
}
function writeFloat(e4, t2, i2, r2, n2) {
  return n2 || checkIEEE754(e4, t2, i2, 4), write(e4, t2, i2, r2, 23, 4), i2 + 4;
}
function writeDouble(e4, t2, i2, r2, n2) {
  return n2 || checkIEEE754(e4, t2, i2, 8), write(e4, t2, i2, r2, 52, 8), i2 + 8;
}
Buffer$1.prototype.slice = function(e4, t2) {
  var i2, r2 = this.length;
  if ((e4 = ~~e4) < 0 ? (e4 += r2) < 0 && (e4 = 0) : e4 > r2 && (e4 = r2), (t2 = void 0 === t2 ? r2 : ~~t2) < 0 ? (t2 += r2) < 0 && (t2 = 0) : t2 > r2 && (t2 = r2), t2 < e4 && (t2 = e4), Buffer$1.TYPED_ARRAY_SUPPORT) (i2 = this.subarray(e4, t2)).__proto__ = Buffer$1.prototype;
  else {
    var n2 = t2 - e4;
    i2 = new Buffer$1(n2, void 0);
    for (var a2 = 0; a2 < n2; ++a2) i2[a2] = this[a2 + e4];
  }
  return i2;
}, Buffer$1.prototype.readUIntLE = function(e4, t2, i2) {
  e4 |= 0, t2 |= 0, i2 || checkOffset(e4, t2, this.length);
  for (var r2 = this[e4], n2 = 1, a2 = 0; ++a2 < t2 && (n2 *= 256); ) r2 += this[e4 + a2] * n2;
  return r2;
}, Buffer$1.prototype.readUIntBE = function(e4, t2, i2) {
  e4 |= 0, t2 |= 0, i2 || checkOffset(e4, t2, this.length);
  for (var r2 = this[e4 + --t2], n2 = 1; t2 > 0 && (n2 *= 256); ) r2 += this[e4 + --t2] * n2;
  return r2;
}, Buffer$1.prototype.readUInt8 = function(e4, t2) {
  return t2 || checkOffset(e4, 1, this.length), this[e4];
}, Buffer$1.prototype.readUInt16LE = function(e4, t2) {
  return t2 || checkOffset(e4, 2, this.length), this[e4] | this[e4 + 1] << 8;
}, Buffer$1.prototype.readUInt16BE = function(e4, t2) {
  return t2 || checkOffset(e4, 2, this.length), this[e4] << 8 | this[e4 + 1];
}, Buffer$1.prototype.readUInt32LE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), (this[e4] | this[e4 + 1] << 8 | this[e4 + 2] << 16) + 16777216 * this[e4 + 3];
}, Buffer$1.prototype.readUInt32BE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), 16777216 * this[e4] + (this[e4 + 1] << 16 | this[e4 + 2] << 8 | this[e4 + 3]);
}, Buffer$1.prototype.readIntLE = function(e4, t2, i2) {
  e4 |= 0, t2 |= 0, i2 || checkOffset(e4, t2, this.length);
  for (var r2 = this[e4], n2 = 1, a2 = 0; ++a2 < t2 && (n2 *= 256); ) r2 += this[e4 + a2] * n2;
  return r2 >= (n2 *= 128) && (r2 -= Math.pow(2, 8 * t2)), r2;
}, Buffer$1.prototype.readIntBE = function(e4, t2, i2) {
  e4 |= 0, t2 |= 0, i2 || checkOffset(e4, t2, this.length);
  for (var r2 = t2, n2 = 1, a2 = this[e4 + --r2]; r2 > 0 && (n2 *= 256); ) a2 += this[e4 + --r2] * n2;
  return a2 >= (n2 *= 128) && (a2 -= Math.pow(2, 8 * t2)), a2;
}, Buffer$1.prototype.readInt8 = function(e4, t2) {
  return t2 || checkOffset(e4, 1, this.length), 128 & this[e4] ? -1 * (255 - this[e4] + 1) : this[e4];
}, Buffer$1.prototype.readInt16LE = function(e4, t2) {
  t2 || checkOffset(e4, 2, this.length);
  var i2 = this[e4] | this[e4 + 1] << 8;
  return 32768 & i2 ? 4294901760 | i2 : i2;
}, Buffer$1.prototype.readInt16BE = function(e4, t2) {
  t2 || checkOffset(e4, 2, this.length);
  var i2 = this[e4 + 1] | this[e4] << 8;
  return 32768 & i2 ? 4294901760 | i2 : i2;
}, Buffer$1.prototype.readInt32LE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), this[e4] | this[e4 + 1] << 8 | this[e4 + 2] << 16 | this[e4 + 3] << 24;
}, Buffer$1.prototype.readInt32BE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), this[e4] << 24 | this[e4 + 1] << 16 | this[e4 + 2] << 8 | this[e4 + 3];
}, Buffer$1.prototype.readFloatLE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), read(this, e4, true, 23, 4);
}, Buffer$1.prototype.readFloatBE = function(e4, t2) {
  return t2 || checkOffset(e4, 4, this.length), read(this, e4, false, 23, 4);
}, Buffer$1.prototype.readDoubleLE = function(e4, t2) {
  return t2 || checkOffset(e4, 8, this.length), read(this, e4, true, 52, 8);
}, Buffer$1.prototype.readDoubleBE = function(e4, t2) {
  return t2 || checkOffset(e4, 8, this.length), read(this, e4, false, 52, 8);
}, Buffer$1.prototype.writeUIntLE = function(e4, t2, i2, r2) {
  (e4 = +e4, t2 |= 0, i2 |= 0, r2) || checkInt(this, e4, t2, i2, Math.pow(2, 8 * i2) - 1, 0);
  var n2 = 1, a2 = 0;
  for (this[t2] = 255 & e4; ++a2 < i2 && (n2 *= 256); ) this[t2 + a2] = e4 / n2 & 255;
  return t2 + i2;
}, Buffer$1.prototype.writeUIntBE = function(e4, t2, i2, r2) {
  (e4 = +e4, t2 |= 0, i2 |= 0, r2) || checkInt(this, e4, t2, i2, Math.pow(2, 8 * i2) - 1, 0);
  var n2 = i2 - 1, a2 = 1;
  for (this[t2 + n2] = 255 & e4; --n2 >= 0 && (a2 *= 256); ) this[t2 + n2] = e4 / a2 & 255;
  return t2 + i2;
}, Buffer$1.prototype.writeUInt8 = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 1, 255, 0), Buffer$1.TYPED_ARRAY_SUPPORT || (e4 = Math.floor(e4)), this[t2] = 255 & e4, t2 + 1;
}, Buffer$1.prototype.writeUInt16LE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 2, 65535, 0), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = 255 & e4, this[t2 + 1] = e4 >>> 8) : objectWriteUInt16(this, e4, t2, true), t2 + 2;
}, Buffer$1.prototype.writeUInt16BE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 2, 65535, 0), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = e4 >>> 8, this[t2 + 1] = 255 & e4) : objectWriteUInt16(this, e4, t2, false), t2 + 2;
}, Buffer$1.prototype.writeUInt32LE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 4, 4294967295, 0), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2 + 3] = e4 >>> 24, this[t2 + 2] = e4 >>> 16, this[t2 + 1] = e4 >>> 8, this[t2] = 255 & e4) : objectWriteUInt32(this, e4, t2, true), t2 + 4;
}, Buffer$1.prototype.writeUInt32BE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 4, 4294967295, 0), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = e4 >>> 24, this[t2 + 1] = e4 >>> 16, this[t2 + 2] = e4 >>> 8, this[t2 + 3] = 255 & e4) : objectWriteUInt32(this, e4, t2, false), t2 + 4;
}, Buffer$1.prototype.writeIntLE = function(e4, t2, i2, r2) {
  if (e4 = +e4, t2 |= 0, !r2) {
    var n2 = Math.pow(2, 8 * i2 - 1);
    checkInt(this, e4, t2, i2, n2 - 1, -n2);
  }
  var a2 = 0, o2 = 1, s2 = 0;
  for (this[t2] = 255 & e4; ++a2 < i2 && (o2 *= 256); ) e4 < 0 && 0 === s2 && 0 !== this[t2 + a2 - 1] && (s2 = 1), this[t2 + a2] = (e4 / o2 | 0) - s2 & 255;
  return t2 + i2;
}, Buffer$1.prototype.writeIntBE = function(e4, t2, i2, r2) {
  if (e4 = +e4, t2 |= 0, !r2) {
    var n2 = Math.pow(2, 8 * i2 - 1);
    checkInt(this, e4, t2, i2, n2 - 1, -n2);
  }
  var a2 = i2 - 1, o2 = 1, s2 = 0;
  for (this[t2 + a2] = 255 & e4; --a2 >= 0 && (o2 *= 256); ) e4 < 0 && 0 === s2 && 0 !== this[t2 + a2 + 1] && (s2 = 1), this[t2 + a2] = (e4 / o2 | 0) - s2 & 255;
  return t2 + i2;
}, Buffer$1.prototype.writeInt8 = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 1, 127, -128), Buffer$1.TYPED_ARRAY_SUPPORT || (e4 = Math.floor(e4)), e4 < 0 && (e4 = 255 + e4 + 1), this[t2] = 255 & e4, t2 + 1;
}, Buffer$1.prototype.writeInt16LE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 2, 32767, -32768), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = 255 & e4, this[t2 + 1] = e4 >>> 8) : objectWriteUInt16(this, e4, t2, true), t2 + 2;
}, Buffer$1.prototype.writeInt16BE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 2, 32767, -32768), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = e4 >>> 8, this[t2 + 1] = 255 & e4) : objectWriteUInt16(this, e4, t2, false), t2 + 2;
}, Buffer$1.prototype.writeInt32LE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 4, 2147483647, -2147483648), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = 255 & e4, this[t2 + 1] = e4 >>> 8, this[t2 + 2] = e4 >>> 16, this[t2 + 3] = e4 >>> 24) : objectWriteUInt32(this, e4, t2, true), t2 + 4;
}, Buffer$1.prototype.writeInt32BE = function(e4, t2, i2) {
  return e4 = +e4, t2 |= 0, i2 || checkInt(this, e4, t2, 4, 2147483647, -2147483648), e4 < 0 && (e4 = 4294967295 + e4 + 1), Buffer$1.TYPED_ARRAY_SUPPORT ? (this[t2] = e4 >>> 24, this[t2 + 1] = e4 >>> 16, this[t2 + 2] = e4 >>> 8, this[t2 + 3] = 255 & e4) : objectWriteUInt32(this, e4, t2, false), t2 + 4;
}, Buffer$1.prototype.writeFloatLE = function(e4, t2, i2) {
  return writeFloat(this, e4, t2, true, i2);
}, Buffer$1.prototype.writeFloatBE = function(e4, t2, i2) {
  return writeFloat(this, e4, t2, false, i2);
}, Buffer$1.prototype.writeDoubleLE = function(e4, t2, i2) {
  return writeDouble(this, e4, t2, true, i2);
}, Buffer$1.prototype.writeDoubleBE = function(e4, t2, i2) {
  return writeDouble(this, e4, t2, false, i2);
}, Buffer$1.prototype.copy = function(e4, t2, i2, r2) {
  if (i2 || (i2 = 0), r2 || 0 === r2 || (r2 = this.length), t2 >= e4.length && (t2 = e4.length), t2 || (t2 = 0), r2 > 0 && r2 < i2 && (r2 = i2), r2 === i2) return 0;
  if (0 === e4.length || 0 === this.length) return 0;
  if (t2 < 0) throw new RangeError("targetStart out of bounds");
  if (i2 < 0 || i2 >= this.length) throw new RangeError("sourceStart out of bounds");
  if (r2 < 0) throw new RangeError("sourceEnd out of bounds");
  r2 > this.length && (r2 = this.length), e4.length - t2 < r2 - i2 && (r2 = e4.length - t2 + i2);
  var n2, a2 = r2 - i2;
  if (this === e4 && i2 < t2 && t2 < r2) for (n2 = a2 - 1; n2 >= 0; --n2) e4[n2 + t2] = this[n2 + i2];
  else if (a2 < 1e3 || !Buffer$1.TYPED_ARRAY_SUPPORT) for (n2 = 0; n2 < a2; ++n2) e4[n2 + t2] = this[n2 + i2];
  else Uint8Array.prototype.set.call(e4, this.subarray(i2, i2 + a2), t2);
  return a2;
}, Buffer$1.prototype.fill = function(e4, t2, i2, r2) {
  if ("string" == typeof e4) {
    if ("string" == typeof t2 ? (r2 = t2, t2 = 0, i2 = this.length) : "string" == typeof i2 && (r2 = i2, i2 = this.length), 1 === e4.length) {
      var n2 = e4.charCodeAt(0);
      n2 < 256 && (e4 = n2);
    }
    if (void 0 !== r2 && "string" != typeof r2) throw new TypeError("encoding must be a string");
    if ("string" == typeof r2 && !Buffer$1.isEncoding(r2)) throw new TypeError("Unknown encoding: " + r2);
  } else "number" == typeof e4 && (e4 &= 255);
  if (t2 < 0 || this.length < t2 || this.length < i2) throw new RangeError("Out of range index");
  if (i2 <= t2) return this;
  var a2;
  if (t2 >>>= 0, i2 = void 0 === i2 ? this.length : i2 >>> 0, e4 || (e4 = 0), "number" == typeof e4) for (a2 = t2; a2 < i2; ++a2) this[a2] = e4;
  else {
    var o2 = internalIsBuffer(e4) ? e4 : utf8ToBytes(new Buffer$1(e4, r2).toString()), s2 = o2.length;
    for (a2 = 0; a2 < i2 - t2; ++a2) this[a2 + t2] = o2[a2 % s2];
  }
  return this;
};
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g, HeaderTypes;
function base64clean(e4) {
  if ((e4 = stringtrim(e4).replace(INVALID_BASE64_RE, "")).length < 2) return "";
  for (; e4.length % 4 != 0; ) e4 += "=";
  return e4;
}
function stringtrim(e4) {
  return e4.trim ? e4.trim() : e4.replace(/^\s+|\s+$/g, "");
}
function toHex(e4) {
  return e4 < 16 ? "0" + e4.toString(16) : e4.toString(16);
}
function utf8ToBytes(e4, t2) {
  var i2;
  t2 = t2 || 1 / 0;
  for (var r2 = e4.length, n2 = null, a2 = [], o2 = 0; o2 < r2; ++o2) {
    if ((i2 = e4.charCodeAt(o2)) > 55295 && i2 < 57344) {
      if (!n2) {
        if (i2 > 56319) {
          (t2 -= 3) > -1 && a2.push(239, 191, 189);
          continue;
        }
        if (o2 + 1 === r2) {
          (t2 -= 3) > -1 && a2.push(239, 191, 189);
          continue;
        }
        n2 = i2;
        continue;
      }
      if (i2 < 56320) {
        (t2 -= 3) > -1 && a2.push(239, 191, 189), n2 = i2;
        continue;
      }
      i2 = 65536 + (n2 - 55296 << 10 | i2 - 56320);
    } else n2 && (t2 -= 3) > -1 && a2.push(239, 191, 189);
    if (n2 = null, i2 < 128) {
      if ((t2 -= 1) < 0) break;
      a2.push(i2);
    } else if (i2 < 2048) {
      if ((t2 -= 2) < 0) break;
      a2.push(i2 >> 6 | 192, 63 & i2 | 128);
    } else if (i2 < 65536) {
      if ((t2 -= 3) < 0) break;
      a2.push(i2 >> 12 | 224, i2 >> 6 & 63 | 128, 63 & i2 | 128);
    } else {
      if (!(i2 < 1114112)) throw new Error("Invalid code point");
      if ((t2 -= 4) < 0) break;
      a2.push(i2 >> 18 | 240, i2 >> 12 & 63 | 128, i2 >> 6 & 63 | 128, 63 & i2 | 128);
    }
  }
  return a2;
}
function asciiToBytes(e4) {
  for (var t2 = [], i2 = 0; i2 < e4.length; ++i2) t2.push(255 & e4.charCodeAt(i2));
  return t2;
}
function utf16leToBytes(e4, t2) {
  for (var i2, r2, n2, a2 = [], o2 = 0; o2 < e4.length && !((t2 -= 2) < 0); ++o2) r2 = (i2 = e4.charCodeAt(o2)) >> 8, n2 = i2 % 256, a2.push(n2), a2.push(r2);
  return a2;
}
function base64ToBytes(e4) {
  return toByteArray(base64clean(e4));
}
function blitBuffer(e4, t2, i2, r2) {
  for (var n2 = 0; n2 < r2 && !(n2 + i2 >= t2.length || n2 >= e4.length); ++n2) t2[n2 + i2] = e4[n2];
  return n2;
}
function isnan(e4) {
  return e4 != e4;
}
function isBuffer(e4) {
  return null != e4 && (!!e4._isBuffer || isFastBuffer(e4) || isSlowBuffer(e4));
}
function isFastBuffer(e4) {
  return !!e4.constructor && "function" == typeof e4.constructor.isBuffer && e4.constructor.isBuffer(e4);
}
function isSlowBuffer(e4) {
  return "function" == typeof e4.readFloatLE && "function" == typeof e4.slice && isFastBuffer(e4.slice(0, 0));
}
!function(e4) {
  e4[e4.BITMAP_INFO_HEADER = 40] = "BITMAP_INFO_HEADER", e4[e4.BITMAP_V2_INFO_HEADER = 52] = "BITMAP_V2_INFO_HEADER", e4[e4.BITMAP_V3_INFO_HEADER = 56] = "BITMAP_V3_INFO_HEADER", e4[e4.BITMAP_V4_HEADER = 108] = "BITMAP_V4_HEADER", e4[e4.BITMAP_V5_HEADER = 124] = "BITMAP_V5_HEADER";
}(HeaderTypes || (HeaderTypes = {}));
var HeaderTypes$1 = HeaderTypes, BmpCompression;
function maskColor(e4, t2, i2, r2) {
  const n2 = 1 + ~e4 & e4, a2 = 1 + ~t2 & t2, o2 = 1 + ~i2 & i2, s2 = 1 + ~r2 & r2, l2 = e4 / n2 + 1, u2 = t2 / a2 + 1, h2 = i2 / o2 + 1, c2 = r2 / s2 + 1;
  return { shiftRed: (t3) => (t3 & e4) / n2 * 256 / l2, shiftGreen: (e5) => (e5 & t2) / a2 * 256 / u2, shiftBlue: (e5) => (e5 & i2) / o2 * 256 / h2, shiftAlpha: 0 !== r2 ? (e5) => (e5 & r2) / s2 * 256 / c2 : () => 255 };
}
!function(e4) {
  e4[e4.NONE = 0] = "NONE", e4[e4.BI_RLE8 = 1] = "BI_RLE8", e4[e4.BI_RLE4 = 2] = "BI_RLE4", e4[e4.BI_BIT_FIELDS = 3] = "BI_BIT_FIELDS", e4[e4.BI_ALPHA_BIT_FIELDS = 6] = "BI_ALPHA_BIT_FIELDS";
}(BmpCompression || (BmpCompression = {}));
class BmpDecoder {
  constructor(e4, { toRGBA: t2 } = { toRGBA: false }) {
    __publicField2(this, "flag");
    __publicField2(this, "fileSize");
    __publicField2(this, "reserved1");
    __publicField2(this, "reserved2");
    __publicField2(this, "offset");
    __publicField2(this, "headerSize");
    __publicField2(this, "width");
    __publicField2(this, "height");
    __publicField2(this, "planes");
    __publicField2(this, "bitPP");
    __publicField2(this, "compression");
    __publicField2(this, "rawSize");
    __publicField2(this, "hr");
    __publicField2(this, "vr");
    __publicField2(this, "colors");
    __publicField2(this, "importantColors");
    __publicField2(this, "palette");
    __publicField2(this, "data");
    __publicField2(this, "maskRed");
    __publicField2(this, "maskGreen");
    __publicField2(this, "maskBlue");
    __publicField2(this, "maskAlpha");
    __publicField2(this, "toRGBA");
    __publicField2(this, "pos");
    __publicField2(this, "bottomUp");
    __publicField2(this, "buffer");
    __publicField2(this, "locRed");
    __publicField2(this, "locGreen");
    __publicField2(this, "locBlue");
    __publicField2(this, "locAlpha");
    __publicField2(this, "shiftRed");
    __publicField2(this, "shiftGreen");
    __publicField2(this, "shiftBlue");
    __publicField2(this, "shiftAlpha");
    if (this.buffer = e4, this.toRGBA = !!t2, this.pos = 0, this.bottomUp = true, this.flag = this.buffer.toString("utf-8", 0, this.pos += 2), "BM" !== this.flag) throw new Error("Invalid BMP File");
    this.locRed = this.toRGBA ? 0 : 3, this.locGreen = this.toRGBA ? 1 : 2, this.locBlue = this.toRGBA ? 2 : 1, this.locAlpha = this.toRGBA ? 3 : 0, this.parseHeader(), this.parseRGBA();
  }
  parseHeader() {
    if (this.fileSize = this.readUInt32LE(), this.reserved1 = this.buffer.readUInt16LE(this.pos), this.pos += 2, this.reserved2 = this.buffer.readUInt16LE(this.pos), this.pos += 2, this.offset = this.readUInt32LE(), this.headerSize = this.readUInt32LE(), !(this.headerSize in HeaderTypes$1)) throw new Error(`Unsupported BMP header size ${this.headerSize}`);
    if (this.width = this.readUInt32LE(), this.height = this.readUInt32LE(), this.height = this.height > 2147483647 ? this.height - 4294967296 : this.height, this.planes = this.buffer.readUInt16LE(this.pos), this.pos += 2, this.bitPP = this.buffer.readUInt16LE(this.pos), this.pos += 2, this.compression = this.readUInt32LE(), this.rawSize = this.readUInt32LE(), this.hr = this.readUInt32LE(), this.vr = this.readUInt32LE(), this.colors = this.readUInt32LE(), this.importantColors = this.readUInt32LE(), 32 === this.bitPP ? (this.maskAlpha = 0, this.maskRed = 16711680, this.maskGreen = 65280, this.maskBlue = 255) : 16 === this.bitPP && (this.maskAlpha = 0, this.maskRed = 31744, this.maskGreen = 992, this.maskBlue = 31), (this.headerSize > HeaderTypes$1.BITMAP_INFO_HEADER || this.compression === BmpCompression.BI_BIT_FIELDS || this.compression === BmpCompression.BI_ALPHA_BIT_FIELDS) && (this.maskRed = this.readUInt32LE(), this.maskGreen = this.readUInt32LE(), this.maskBlue = this.readUInt32LE()), (this.headerSize > HeaderTypes$1.BITMAP_V2_INFO_HEADER || this.compression === BmpCompression.BI_ALPHA_BIT_FIELDS) && (this.maskAlpha = this.readUInt32LE()), this.headerSize > HeaderTypes$1.BITMAP_V3_INFO_HEADER && (this.pos += HeaderTypes$1.BITMAP_V4_HEADER - HeaderTypes$1.BITMAP_V3_INFO_HEADER), this.headerSize > HeaderTypes$1.BITMAP_V4_HEADER && (this.pos += HeaderTypes$1.BITMAP_V5_HEADER - HeaderTypes$1.BITMAP_V4_HEADER), this.bitPP <= 8 || this.colors > 0) {
      const e5 = 0 === this.colors ? 1 << this.bitPP : this.colors;
      this.palette = new Array(e5);
      for (let t2 = 0; t2 < e5; t2++) {
        const e6 = this.buffer.readUInt8(this.pos++), i2 = this.buffer.readUInt8(this.pos++), r2 = this.buffer.readUInt8(this.pos++), n2 = this.buffer.readUInt8(this.pos++);
        this.palette[t2] = { red: r2, green: i2, blue: e6, quad: n2 };
      }
    }
    this.height < 0 && (this.height *= -1, this.bottomUp = false);
    const e4 = maskColor(this.maskRed, this.maskGreen, this.maskBlue, this.maskAlpha);
    this.shiftRed = e4.shiftRed, this.shiftGreen = e4.shiftGreen, this.shiftBlue = e4.shiftBlue, this.shiftAlpha = e4.shiftAlpha;
  }
  parseRGBA() {
    switch (this.data = Buffer$1.alloc(this.width * this.height * 4), this.bitPP) {
      case 1:
        this.bit1();
        break;
      case 4:
        this.bit4();
        break;
      case 8:
        this.bit8();
        break;
      case 16:
        this.bit16();
        break;
      case 24:
        this.bit24();
        break;
      default:
        this.bit32();
    }
  }
  bit1() {
    const e4 = Math.ceil(this.width / 8), t2 = e4 % 4, i2 = 0 !== t2 ? 4 - t2 : 0;
    this.scanImage(i2, e4, (e5, t3) => {
      const i3 = this.buffer.readUInt8(this.pos++), r2 = t3 * this.width * 4 + 8 * e5 * 4;
      for (let t4 = 0; t4 < 8 && 8 * e5 + t4 < this.width; t4++) {
        const e6 = this.palette[i3 >> 7 - t4 & 1];
        this.data[r2 + t4 * this.locAlpha] = 0, this.data[r2 + 4 * t4 + this.locBlue] = e6.blue, this.data[r2 + 4 * t4 + this.locGreen] = e6.green, this.data[r2 + 4 * t4 + this.locRed] = e6.red;
      }
    });
  }
  bit4() {
    if (this.compression === BmpCompression.BI_RLE4) {
      this.data.fill(0);
      let e4 = false, t2 = this.bottomUp ? this.height - 1 : 0, i2 = 0;
      for (; i2 < this.data.length; ) {
        const r2 = this.buffer.readUInt8(this.pos++), n2 = this.buffer.readUInt8(this.pos++);
        if (0 === r2) {
          if (0 === n2) {
            t2 += this.bottomUp ? -1 : 1, i2 = t2 * this.width * 4, e4 = false;
            continue;
          }
          if (1 === n2) break;
          if (2 === n2) {
            const e5 = this.buffer.readUInt8(this.pos++), r3 = this.buffer.readUInt8(this.pos++);
            t2 += this.bottomUp ? -r3 : r3, i2 += r3 * this.width * 4 + 4 * e5;
          } else {
            let t3 = this.buffer.readUInt8(this.pos++);
            for (let r3 = 0; r3 < n2; r3++) i2 = this.setPixelData(i2, e4 ? 15 & t3 : (240 & t3) >> 4), 1 & r3 && r3 + 1 < n2 && (t3 = this.buffer.readUInt8(this.pos++)), e4 = !e4;
            1 == (n2 + 1 >> 1 & 1) && this.pos++;
          }
        } else for (let t3 = 0; t3 < r2; t3++) i2 = this.setPixelData(i2, e4 ? 15 & n2 : (240 & n2) >> 4), e4 = !e4;
      }
    } else {
      const e4 = Math.ceil(this.width / 2), t2 = e4 % 4, i2 = 0 !== t2 ? 4 - t2 : 0;
      this.scanImage(i2, e4, (e5, t3) => {
        const i3 = this.buffer.readUInt8(this.pos++), r2 = t3 * this.width * 4 + 2 * e5 * 4, n2 = i3 >> 4;
        let a2 = this.palette[n2];
        if (this.data[r2] = 0, this.data[r2 + 1] = a2.blue, this.data[r2 + 2] = a2.green, this.data[r2 + 3] = a2.red, 2 * e5 + 1 >= this.width) return false;
        const o2 = 15 & i3;
        a2 = this.palette[o2], this.data[r2 + 4] = 0, this.data[r2 + 4 + 1] = a2.blue, this.data[r2 + 4 + 2] = a2.green, this.data[r2 + 4 + 3] = a2.red;
      });
    }
  }
  bit8() {
    if (this.compression === BmpCompression.BI_RLE8) {
      this.data.fill(0);
      let e4 = this.bottomUp ? this.height - 1 : 0, t2 = 0;
      for (; t2 < this.data.length; ) {
        const i2 = this.buffer.readUInt8(this.pos++), r2 = this.buffer.readUInt8(this.pos++);
        if (0 === i2) {
          if (0 === r2) {
            e4 += this.bottomUp ? -1 : 1, t2 = e4 * this.width * 4;
            continue;
          }
          if (1 === r2) break;
          if (2 === r2) {
            const i3 = this.buffer.readUInt8(this.pos++), r3 = this.buffer.readUInt8(this.pos++);
            e4 += this.bottomUp ? -r3 : r3, t2 += r3 * this.width * 4 + 4 * i3;
          } else {
            for (let e5 = 0; e5 < r2; e5++) {
              const e6 = this.buffer.readUInt8(this.pos++);
              t2 = this.setPixelData(t2, e6);
            }
            true & r2 && this.pos++;
          }
        } else for (let e5 = 0; e5 < i2; e5++) t2 = this.setPixelData(t2, r2);
      }
    } else {
      const e4 = this.width % 4, t2 = 0 !== e4 ? 4 - e4 : 0;
      this.scanImage(t2, this.width, (e5, t3) => {
        const i2 = this.buffer.readUInt8(this.pos++), r2 = t3 * this.width * 4 + 4 * e5;
        if (i2 < this.palette.length) {
          const e6 = this.palette[i2];
          this.data[r2] = 0, this.data[r2 + 1] = e6.blue, this.data[r2 + 2] = e6.green, this.data[r2 + 3] = e6.red;
        } else this.data[r2] = 0, this.data[r2 + 1] = 255, this.data[r2 + 2] = 255, this.data[r2 + 3] = 255;
      });
    }
  }
  bit16() {
    const e4 = this.width % 2 * 2;
    this.scanImage(e4, this.width, (e5, t2) => {
      const i2 = t2 * this.width * 4 + 4 * e5, r2 = this.buffer.readUInt16LE(this.pos);
      this.pos += 2, this.data[i2 + this.locRed] = this.shiftRed(r2), this.data[i2 + this.locGreen] = this.shiftGreen(r2), this.data[i2 + this.locBlue] = this.shiftBlue(r2), this.data[i2 + this.locAlpha] = this.shiftAlpha(r2);
    });
  }
  bit24() {
    const e4 = this.width % 4;
    this.scanImage(e4, this.width, (e5, t2) => {
      const i2 = t2 * this.width * 4 + 4 * e5, r2 = this.buffer.readUInt8(this.pos++), n2 = this.buffer.readUInt8(this.pos++), a2 = this.buffer.readUInt8(this.pos++);
      this.data[i2 + this.locRed] = a2, this.data[i2 + this.locGreen] = n2, this.data[i2 + this.locBlue] = r2, this.data[i2 + this.locAlpha] = 0;
    });
  }
  bit32() {
    this.scanImage(0, this.width, (e4, t2) => {
      const i2 = t2 * this.width * 4 + 4 * e4, r2 = this.readUInt32LE();
      this.data[i2 + this.locRed] = this.shiftRed(r2), this.data[i2 + this.locGreen] = this.shiftGreen(r2), this.data[i2 + this.locBlue] = this.shiftBlue(r2), this.data[i2 + this.locAlpha] = this.shiftAlpha(r2);
    });
  }
  scanImage(e4 = 0, t2 = this.width, i2) {
    for (let r2 = this.height - 1; r2 >= 0; r2--) {
      const n2 = this.bottomUp ? r2 : this.height - 1 - r2;
      for (let e5 = 0; e5 < t2; e5++) {
        if (false === i2.call(this, e5, n2)) return;
      }
      this.pos += e4;
    }
  }
  readUInt32LE() {
    const e4 = this.buffer.readUInt32LE(this.pos);
    return this.pos += 4, e4;
  }
  setPixelData(e4, t2) {
    const { blue: i2, green: r2, red: n2 } = this.palette[t2];
    return this.data[e4 + this.locAlpha] = 0, this.data[e4 + 1 + this.locBlue] = i2, this.data[e4 + 2 + this.locGreen] = r2, this.data[e4 + 3 + this.locRed] = n2, e4 + 4;
  }
}
function createInteger(e4) {
  return e4.reduce((e5, t2) => e5 << 1 | t2, 0);
}
function createColor(e4) {
  return e4.quad << 24 | e4.red << 16 | e4.green << 8 | e4.blue;
}
class BmpEncoder {
  constructor(e4) {
    __publicField2(this, "fileSize");
    __publicField2(this, "reserved1");
    __publicField2(this, "reserved2");
    __publicField2(this, "offset");
    __publicField2(this, "width");
    __publicField2(this, "flag");
    __publicField2(this, "height");
    __publicField2(this, "planes");
    __publicField2(this, "bitPP");
    __publicField2(this, "compress");
    __publicField2(this, "hr");
    __publicField2(this, "vr");
    __publicField2(this, "colors");
    __publicField2(this, "importantColors");
    __publicField2(this, "rawSize");
    __publicField2(this, "headerSize");
    __publicField2(this, "data");
    __publicField2(this, "palette");
    __publicField2(this, "extraBytes");
    __publicField2(this, "buffer");
    __publicField2(this, "bytesInColor");
    __publicField2(this, "pos");
    switch (this.buffer = e4.data, this.width = e4.width, this.height = e4.height, this.headerSize = HeaderTypes$1.BITMAP_INFO_HEADER, this.flag = "BM", this.bitPP = e4.bitPP || 24, this.offset = 54, this.reserved1 = e4.reserved1 || 0, this.reserved2 = e4.reserved2 || 0, this.planes = 1, this.compress = 0, this.hr = e4.hr || 0, this.vr = e4.vr || 0, this.importantColors = e4.importantColors || 0, this.colors = Math.min(2 ** (this.bitPP - 1 || 1), e4.colors || 1 / 0), this.palette = e4.palette || [], this.colors && this.bitPP < 16 ? this.offset += 4 * this.colors : this.colors = 0, this.bitPP) {
      case 32:
        this.bytesInColor = 4;
        break;
      case 16:
        this.bytesInColor = 2;
        break;
      case 8:
        this.bytesInColor = 1;
        break;
      case 4:
        this.bytesInColor = 0.5;
        break;
      case 1:
        this.bytesInColor = 1 / 8;
        break;
      default:
        this.bytesInColor = 3, this.bitPP = 24;
    }
    const t2 = this.width * this.bitPP / 32, i2 = Math.ceil(t2);
    this.extraBytes = 4 * (i2 - t2), this.rawSize = this.height * i2 * 4 + 2, this.fileSize = this.rawSize + this.offset, this.data = Buffer$1.alloc(this.fileSize, 1), this.pos = 0, this.encode();
  }
  encode() {
    switch (this.pos = 0, this.writeHeader(), this.bitPP) {
      case 32:
        this.bit32();
        break;
      case 16:
        this.bit16();
        break;
      case 8:
        this.bit8();
        break;
      case 4:
        this.bit4();
        break;
      case 1:
        this.bit1();
        break;
      default:
        this.bit24();
    }
  }
  writeHeader() {
    this.data.write(this.flag, this.pos, 2), this.pos += 2, this.writeUInt32LE(this.fileSize), this.writeUInt32LE(this.reserved1 << 16 | this.reserved2), this.writeUInt32LE(this.offset), this.writeUInt32LE(this.headerSize), this.writeUInt32LE(this.width), this.writeUInt32LE(this.height), this.data.writeUInt16LE(this.planes, this.pos), this.pos += 2, this.data.writeUInt16LE(this.bitPP, this.pos), this.pos += 2, this.writeUInt32LE(this.compress), this.writeUInt32LE(this.rawSize), this.writeUInt32LE(this.hr), this.writeUInt32LE(this.vr), this.writeUInt32LE(this.colors), this.writeUInt32LE(this.importantColors);
  }
  bit1() {
    this.palette.length && 2 === this.colors ? this.initColors(1) : (this.writeUInt32LE(16777215), this.writeUInt32LE(0)), this.pos += 1;
    let e4 = [];
    this.writeImage((t2, i2, r2) => {
      let n2 = i2;
      n2++;
      const a2 = this.buffer[n2++], o2 = this.buffer[n2++], s2 = 0.2126 * this.buffer[n2++] + 0.7152 * o2 + 0.0722 * a2;
      return e4.push(s2 > 127 ? 0 : 1), (r2 + 1) % 8 == 0 ? (this.data[t2 - 1] = createInteger(e4), e4 = []) : r2 === this.width - 1 && e4.length > 0 && (this.data[t2 - 1] = createInteger(e4) << 4, e4 = []), n2;
    });
  }
  bit4() {
    const e4 = this.initColors(4);
    let t2 = [];
    this.writeImage((i2, r2, n2) => {
      let a2 = r2;
      const o2 = createColor({ quad: this.buffer[a2++], blue: this.buffer[a2++], green: this.buffer[a2++], red: this.buffer[a2++] }), s2 = e4.findIndex((e5) => e5 === o2);
      return -1 !== s2 ? t2.push(s2) : t2.push(0), (n2 + 1) % 2 == 0 && (this.data[i2] = t2[0] << 4 | t2[1], t2 = []), a2;
    });
  }
  bit8() {
    const e4 = this.initColors(8);
    this.writeImage((t2, i2) => {
      let r2 = i2;
      const n2 = createColor({ quad: this.buffer[r2++], blue: this.buffer[r2++], green: this.buffer[r2++], red: this.buffer[r2++] }), a2 = e4.findIndex((e5) => e5 === n2);
      return this.data[t2] = -1 !== a2 ? a2 : 0, r2;
    });
  }
  bit16() {
    this.writeImage((e4, t2) => {
      let i2 = t2 + 1;
      const r2 = this.buffer[i2++] / 8, n2 = this.buffer[i2++] / 8, a2 = this.buffer[i2++] / 8 << 10 | n2 << 5 | r2;
      return this.data[e4] = 255 & a2, this.data[e4 + 1] = (65280 & a2) >> 8, i2;
    });
  }
  bit24() {
    this.writeImage((e4, t2) => {
      let i2 = t2 + 1;
      return this.data[e4] = this.buffer[i2++], this.data[e4 + 1] = this.buffer[i2++], this.data[e4 + 2] = this.buffer[i2++], i2;
    });
  }
  bit32() {
    this.writeImage((e4, t2) => {
      let i2 = t2;
      return this.data[e4 + 3] = this.buffer[i2++], this.data[e4] = this.buffer[i2++], this.data[e4 + 1] = this.buffer[i2++], this.data[e4 + 2] = this.buffer[i2++], i2;
    });
  }
  writeImage(e4) {
    const t2 = this.extraBytes + this.width * this.bytesInColor;
    let i2 = 0;
    for (let r2 = 0; r2 < this.height; r2++) for (let n2 = 0; n2 < this.width; n2++) {
      const a2 = Math.floor(this.pos + (this.height - 1 - r2) * t2 + n2 * this.bytesInColor);
      i2 = e4.call(this, a2, i2, n2, r2);
    }
  }
  initColors(e4) {
    const t2 = [];
    if (!this.palette.length) throw new Error(`To encode ${e4}-bit BMPs a pallette is needed. Please choose up to ${this.colors} colors. Colors must be 32-bit integers.`);
    for (let e5 = 0; e5 < this.colors; e5++) {
      const i2 = createColor(this.palette[e5]);
      this.writeUInt32LE(i2), t2.push(i2);
    }
    return t2;
  }
  writeUInt32LE(e4) {
    this.data.writeUInt32LE(e4, this.pos), this.pos += 4;
  }
}
function decode$2(e4, t2) {
  return new BmpDecoder(e4, t2);
}
function encode$2(e4) {
  return new BmpEncoder(e4);
}
function _typeof(e4) {
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e5) {
    return typeof e5;
  } : function(e5) {
    return e5 && "function" == typeof Symbol && e5.constructor === Symbol && e5 !== Symbol.prototype ? "symbol" : typeof e5;
  }, _typeof(e4);
}
var trimLeft = /^\s+/, trimRight = /\s+$/;
function tinycolor(e4, t2) {
  if (t2 = t2 || {}, (e4 = e4 || "") instanceof tinycolor) return e4;
  if (!(this instanceof tinycolor)) return new tinycolor(e4, t2);
  var i2 = inputToRGB(e4);
  this._originalInput = e4, this._r = i2.r, this._g = i2.g, this._b = i2.b, this._a = i2.a, this._roundA = Math.round(100 * this._a) / 100, this._format = t2.format || i2.format, this._gradientType = t2.gradientType, this._r < 1 && (this._r = Math.round(this._r)), this._g < 1 && (this._g = Math.round(this._g)), this._b < 1 && (this._b = Math.round(this._b)), this._ok = i2.ok;
}
function inputToRGB(e4) {
  var t2 = { r: 0, g: 0, b: 0 }, i2 = 1, r2 = null, n2 = null, a2 = null, o2 = false, s2 = false;
  return "string" == typeof e4 && (e4 = stringInputToObject(e4)), "object" == _typeof(e4) && (isValidCSSUnit(e4.r) && isValidCSSUnit(e4.g) && isValidCSSUnit(e4.b) ? (t2 = rgbToRgb(e4.r, e4.g, e4.b), o2 = true, s2 = "%" === String(e4.r).substr(-1) ? "prgb" : "rgb") : isValidCSSUnit(e4.h) && isValidCSSUnit(e4.s) && isValidCSSUnit(e4.v) ? (r2 = convertToPercentage(e4.s), n2 = convertToPercentage(e4.v), t2 = hsvToRgb(e4.h, r2, n2), o2 = true, s2 = "hsv") : isValidCSSUnit(e4.h) && isValidCSSUnit(e4.s) && isValidCSSUnit(e4.l) && (r2 = convertToPercentage(e4.s), a2 = convertToPercentage(e4.l), t2 = hslToRgb(e4.h, r2, a2), o2 = true, s2 = "hsl"), e4.hasOwnProperty("a") && (i2 = e4.a)), i2 = boundAlpha(i2), { ok: o2, format: e4.format || s2, r: Math.min(255, Math.max(t2.r, 0)), g: Math.min(255, Math.max(t2.g, 0)), b: Math.min(255, Math.max(t2.b, 0)), a: i2 };
}
function rgbToRgb(e4, t2, i2) {
  return { r: 255 * bound01(e4, 255), g: 255 * bound01(t2, 255), b: 255 * bound01(i2, 255) };
}
function rgbToHsl(e4, t2, i2) {
  e4 = bound01(e4, 255), t2 = bound01(t2, 255), i2 = bound01(i2, 255);
  var r2, n2, a2 = Math.max(e4, t2, i2), o2 = Math.min(e4, t2, i2), s2 = (a2 + o2) / 2;
  if (a2 == o2) r2 = n2 = 0;
  else {
    var l2 = a2 - o2;
    switch (n2 = s2 > 0.5 ? l2 / (2 - a2 - o2) : l2 / (a2 + o2), a2) {
      case e4:
        r2 = (t2 - i2) / l2 + (t2 < i2 ? 6 : 0);
        break;
      case t2:
        r2 = (i2 - e4) / l2 + 2;
        break;
      case i2:
        r2 = (e4 - t2) / l2 + 4;
    }
    r2 /= 6;
  }
  return { h: r2, s: n2, l: s2 };
}
function hslToRgb(e4, t2, i2) {
  var r2, n2, a2;
  function o2(e5, t3, i3) {
    return i3 < 0 && (i3 += 1), i3 > 1 && (i3 -= 1), i3 < 1 / 6 ? e5 + 6 * (t3 - e5) * i3 : i3 < 0.5 ? t3 : i3 < 2 / 3 ? e5 + (t3 - e5) * (2 / 3 - i3) * 6 : e5;
  }
  if (e4 = bound01(e4, 360), t2 = bound01(t2, 100), i2 = bound01(i2, 100), 0 === t2) r2 = n2 = a2 = i2;
  else {
    var s2 = i2 < 0.5 ? i2 * (1 + t2) : i2 + t2 - i2 * t2, l2 = 2 * i2 - s2;
    r2 = o2(l2, s2, e4 + 1 / 3), n2 = o2(l2, s2, e4), a2 = o2(l2, s2, e4 - 1 / 3);
  }
  return { r: 255 * r2, g: 255 * n2, b: 255 * a2 };
}
function rgbToHsv(e4, t2, i2) {
  e4 = bound01(e4, 255), t2 = bound01(t2, 255), i2 = bound01(i2, 255);
  var r2, n2, a2 = Math.max(e4, t2, i2), o2 = Math.min(e4, t2, i2), s2 = a2, l2 = a2 - o2;
  if (n2 = 0 === a2 ? 0 : l2 / a2, a2 == o2) r2 = 0;
  else {
    switch (a2) {
      case e4:
        r2 = (t2 - i2) / l2 + (t2 < i2 ? 6 : 0);
        break;
      case t2:
        r2 = (i2 - e4) / l2 + 2;
        break;
      case i2:
        r2 = (e4 - t2) / l2 + 4;
    }
    r2 /= 6;
  }
  return { h: r2, s: n2, v: s2 };
}
function hsvToRgb(e4, t2, i2) {
  e4 = 6 * bound01(e4, 360), t2 = bound01(t2, 100), i2 = bound01(i2, 100);
  var r2 = Math.floor(e4), n2 = e4 - r2, a2 = i2 * (1 - t2), o2 = i2 * (1 - n2 * t2), s2 = i2 * (1 - (1 - n2) * t2), l2 = r2 % 6;
  return { r: 255 * [i2, o2, a2, a2, s2, i2][l2], g: 255 * [s2, i2, i2, o2, a2, a2][l2], b: 255 * [a2, a2, s2, i2, i2, o2][l2] };
}
function rgbToHex(e4, t2, i2, r2) {
  var n2 = [pad2(Math.round(e4).toString(16)), pad2(Math.round(t2).toString(16)), pad2(Math.round(i2).toString(16))];
  return r2 && n2[0].charAt(0) == n2[0].charAt(1) && n2[1].charAt(0) == n2[1].charAt(1) && n2[2].charAt(0) == n2[2].charAt(1) ? n2[0].charAt(0) + n2[1].charAt(0) + n2[2].charAt(0) : n2.join("");
}
function rgbaToHex(e4, t2, i2, r2, n2) {
  var a2 = [pad2(Math.round(e4).toString(16)), pad2(Math.round(t2).toString(16)), pad2(Math.round(i2).toString(16)), pad2(convertDecimalToHex(r2))];
  return n2 && a2[0].charAt(0) == a2[0].charAt(1) && a2[1].charAt(0) == a2[1].charAt(1) && a2[2].charAt(0) == a2[2].charAt(1) && a2[3].charAt(0) == a2[3].charAt(1) ? a2[0].charAt(0) + a2[1].charAt(0) + a2[2].charAt(0) + a2[3].charAt(0) : a2.join("");
}
function rgbaToArgbHex(e4, t2, i2, r2) {
  return [pad2(convertDecimalToHex(r2)), pad2(Math.round(e4).toString(16)), pad2(Math.round(t2).toString(16)), pad2(Math.round(i2).toString(16))].join("");
}
function _desaturate(e4, t2) {
  t2 = 0 === t2 ? 0 : t2 || 10;
  var i2 = tinycolor(e4).toHsl();
  return i2.s -= t2 / 100, i2.s = clamp01(i2.s), tinycolor(i2);
}
function _saturate(e4, t2) {
  t2 = 0 === t2 ? 0 : t2 || 10;
  var i2 = tinycolor(e4).toHsl();
  return i2.s += t2 / 100, i2.s = clamp01(i2.s), tinycolor(i2);
}
function _greyscale(e4) {
  return tinycolor(e4).desaturate(100);
}
function _lighten(e4, t2) {
  t2 = 0 === t2 ? 0 : t2 || 10;
  var i2 = tinycolor(e4).toHsl();
  return i2.l += t2 / 100, i2.l = clamp01(i2.l), tinycolor(i2);
}
function _brighten(e4, t2) {
  t2 = 0 === t2 ? 0 : t2 || 10;
  var i2 = tinycolor(e4).toRgb();
  return i2.r = Math.max(0, Math.min(255, i2.r - Math.round(-t2 / 100 * 255))), i2.g = Math.max(0, Math.min(255, i2.g - Math.round(-t2 / 100 * 255))), i2.b = Math.max(0, Math.min(255, i2.b - Math.round(-t2 / 100 * 255))), tinycolor(i2);
}
function _darken(e4, t2) {
  t2 = 0 === t2 ? 0 : t2 || 10;
  var i2 = tinycolor(e4).toHsl();
  return i2.l -= t2 / 100, i2.l = clamp01(i2.l), tinycolor(i2);
}
function _spin(e4, t2) {
  var i2 = tinycolor(e4).toHsl(), r2 = (i2.h + t2) % 360;
  return i2.h = r2 < 0 ? 360 + r2 : r2, tinycolor(i2);
}
function _complement(e4) {
  var t2 = tinycolor(e4).toHsl();
  return t2.h = (t2.h + 180) % 360, tinycolor(t2);
}
function polyad(e4, t2) {
  if (isNaN(t2) || t2 <= 0) throw new Error("Argument to polyad must be a positive number");
  for (var i2 = tinycolor(e4).toHsl(), r2 = [tinycolor(e4)], n2 = 360 / t2, a2 = 1; a2 < t2; a2++) r2.push(tinycolor({ h: (i2.h + a2 * n2) % 360, s: i2.s, l: i2.l }));
  return r2;
}
function _splitcomplement(e4) {
  var t2 = tinycolor(e4).toHsl(), i2 = t2.h;
  return [tinycolor(e4), tinycolor({ h: (i2 + 72) % 360, s: t2.s, l: t2.l }), tinycolor({ h: (i2 + 216) % 360, s: t2.s, l: t2.l })];
}
function _analogous(e4, t2, i2) {
  t2 = t2 || 6, i2 = i2 || 30;
  var r2 = tinycolor(e4).toHsl(), n2 = 360 / i2, a2 = [tinycolor(e4)];
  for (r2.h = (r2.h - (n2 * t2 >> 1) + 720) % 360; --t2; ) r2.h = (r2.h + n2) % 360, a2.push(tinycolor(r2));
  return a2;
}
function _monochromatic(e4, t2) {
  t2 = t2 || 6;
  for (var i2 = tinycolor(e4).toHsv(), r2 = i2.h, n2 = i2.s, a2 = i2.v, o2 = [], s2 = 1 / t2; t2--; ) o2.push(tinycolor({ h: r2, s: n2, v: a2 })), a2 = (a2 + s2) % 1;
  return o2;
}
tinycolor.prototype = { isDark: function() {
  return this.getBrightness() < 128;
}, isLight: function() {
  return !this.isDark();
}, isValid: function() {
  return this._ok;
}, getOriginalInput: function() {
  return this._originalInput;
}, getFormat: function() {
  return this._format;
}, getAlpha: function() {
  return this._a;
}, getBrightness: function() {
  var e4 = this.toRgb();
  return (299 * e4.r + 587 * e4.g + 114 * e4.b) / 1e3;
}, getLuminance: function() {
  var e4, t2, i2, r2 = this.toRgb();
  return e4 = r2.r / 255, t2 = r2.g / 255, i2 = r2.b / 255, 0.2126 * (e4 <= 0.03928 ? e4 / 12.92 : Math.pow((e4 + 0.055) / 1.055, 2.4)) + 0.7152 * (t2 <= 0.03928 ? t2 / 12.92 : Math.pow((t2 + 0.055) / 1.055, 2.4)) + 0.0722 * (i2 <= 0.03928 ? i2 / 12.92 : Math.pow((i2 + 0.055) / 1.055, 2.4));
}, setAlpha: function(e4) {
  return this._a = boundAlpha(e4), this._roundA = Math.round(100 * this._a) / 100, this;
}, toHsv: function() {
  var e4 = rgbToHsv(this._r, this._g, this._b);
  return { h: 360 * e4.h, s: e4.s, v: e4.v, a: this._a };
}, toHsvString: function() {
  var e4 = rgbToHsv(this._r, this._g, this._b), t2 = Math.round(360 * e4.h), i2 = Math.round(100 * e4.s), r2 = Math.round(100 * e4.v);
  return 1 == this._a ? "hsv(" + t2 + ", " + i2 + "%, " + r2 + "%)" : "hsva(" + t2 + ", " + i2 + "%, " + r2 + "%, " + this._roundA + ")";
}, toHsl: function() {
  var e4 = rgbToHsl(this._r, this._g, this._b);
  return { h: 360 * e4.h, s: e4.s, l: e4.l, a: this._a };
}, toHslString: function() {
  var e4 = rgbToHsl(this._r, this._g, this._b), t2 = Math.round(360 * e4.h), i2 = Math.round(100 * e4.s), r2 = Math.round(100 * e4.l);
  return 1 == this._a ? "hsl(" + t2 + ", " + i2 + "%, " + r2 + "%)" : "hsla(" + t2 + ", " + i2 + "%, " + r2 + "%, " + this._roundA + ")";
}, toHex: function(e4) {
  return rgbToHex(this._r, this._g, this._b, e4);
}, toHexString: function(e4) {
  return "#" + this.toHex(e4);
}, toHex8: function(e4) {
  return rgbaToHex(this._r, this._g, this._b, this._a, e4);
}, toHex8String: function(e4) {
  return "#" + this.toHex8(e4);
}, toRgb: function() {
  return { r: Math.round(this._r), g: Math.round(this._g), b: Math.round(this._b), a: this._a };
}, toRgbString: function() {
  return 1 == this._a ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")";
}, toPercentageRgb: function() {
  return { r: Math.round(100 * bound01(this._r, 255)) + "%", g: Math.round(100 * bound01(this._g, 255)) + "%", b: Math.round(100 * bound01(this._b, 255)) + "%", a: this._a };
}, toPercentageRgbString: function() {
  return 1 == this._a ? "rgb(" + Math.round(100 * bound01(this._r, 255)) + "%, " + Math.round(100 * bound01(this._g, 255)) + "%, " + Math.round(100 * bound01(this._b, 255)) + "%)" : "rgba(" + Math.round(100 * bound01(this._r, 255)) + "%, " + Math.round(100 * bound01(this._g, 255)) + "%, " + Math.round(100 * bound01(this._b, 255)) + "%, " + this._roundA + ")";
}, toName: function() {
  return 0 === this._a ? "transparent" : !(this._a < 1) && (hexNames[rgbToHex(this._r, this._g, this._b, true)] || false);
}, toFilter: function(e4) {
  var t2 = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a), i2 = t2, r2 = this._gradientType ? "GradientType = 1, " : "";
  if (e4) {
    var n2 = tinycolor(e4);
    i2 = "#" + rgbaToArgbHex(n2._r, n2._g, n2._b, n2._a);
  }
  return "progid:DXImageTransform.Microsoft.gradient(" + r2 + "startColorstr=" + t2 + ",endColorstr=" + i2 + ")";
}, toString: function(e4) {
  var t2 = !!e4;
  e4 = e4 || this._format;
  var i2 = false, r2 = this._a < 1 && this._a >= 0;
  return t2 || !r2 || "hex" !== e4 && "hex6" !== e4 && "hex3" !== e4 && "hex4" !== e4 && "hex8" !== e4 && "name" !== e4 ? ("rgb" === e4 && (i2 = this.toRgbString()), "prgb" === e4 && (i2 = this.toPercentageRgbString()), "hex" !== e4 && "hex6" !== e4 || (i2 = this.toHexString()), "hex3" === e4 && (i2 = this.toHexString(true)), "hex4" === e4 && (i2 = this.toHex8String(true)), "hex8" === e4 && (i2 = this.toHex8String()), "name" === e4 && (i2 = this.toName()), "hsl" === e4 && (i2 = this.toHslString()), "hsv" === e4 && (i2 = this.toHsvString()), i2 || this.toHexString()) : "name" === e4 && 0 === this._a ? this.toName() : this.toRgbString();
}, clone: function() {
  return tinycolor(this.toString());
}, _applyModification: function(e4, t2) {
  var i2 = e4.apply(null, [this].concat([].slice.call(t2)));
  return this._r = i2._r, this._g = i2._g, this._b = i2._b, this.setAlpha(i2._a), this;
}, lighten: function() {
  return this._applyModification(_lighten, arguments);
}, brighten: function() {
  return this._applyModification(_brighten, arguments);
}, darken: function() {
  return this._applyModification(_darken, arguments);
}, desaturate: function() {
  return this._applyModification(_desaturate, arguments);
}, saturate: function() {
  return this._applyModification(_saturate, arguments);
}, greyscale: function() {
  return this._applyModification(_greyscale, arguments);
}, spin: function() {
  return this._applyModification(_spin, arguments);
}, _applyCombination: function(e4, t2) {
  return e4.apply(null, [this].concat([].slice.call(t2)));
}, analogous: function() {
  return this._applyCombination(_analogous, arguments);
}, complement: function() {
  return this._applyCombination(_complement, arguments);
}, monochromatic: function() {
  return this._applyCombination(_monochromatic, arguments);
}, splitcomplement: function() {
  return this._applyCombination(_splitcomplement, arguments);
}, triad: function() {
  return this._applyCombination(polyad, [3]);
}, tetrad: function() {
  return this._applyCombination(polyad, [4]);
} }, tinycolor.fromRatio = function(e4, t2) {
  if ("object" == _typeof(e4)) {
    var i2 = {};
    for (var r2 in e4) e4.hasOwnProperty(r2) && (i2[r2] = "a" === r2 ? e4[r2] : convertToPercentage(e4[r2]));
    e4 = i2;
  }
  return tinycolor(e4, t2);
}, tinycolor.equals = function(e4, t2) {
  return !(!e4 || !t2) && tinycolor(e4).toRgbString() == tinycolor(t2).toRgbString();
}, tinycolor.random = function() {
  return tinycolor.fromRatio({ r: Math.random(), g: Math.random(), b: Math.random() });
}, tinycolor.mix = function(e4, t2, i2) {
  i2 = 0 === i2 ? 0 : i2 || 50;
  var r2 = tinycolor(e4).toRgb(), n2 = tinycolor(t2).toRgb(), a2 = i2 / 100;
  return tinycolor({ r: (n2.r - r2.r) * a2 + r2.r, g: (n2.g - r2.g) * a2 + r2.g, b: (n2.b - r2.b) * a2 + r2.b, a: (n2.a - r2.a) * a2 + r2.a });
}, tinycolor.readability = function(e4, t2) {
  var i2 = tinycolor(e4), r2 = tinycolor(t2);
  return (Math.max(i2.getLuminance(), r2.getLuminance()) + 0.05) / (Math.min(i2.getLuminance(), r2.getLuminance()) + 0.05);
}, tinycolor.isReadable = function(e4, t2, i2) {
  var r2, n2, a2 = tinycolor.readability(e4, t2);
  switch (n2 = false, (r2 = validateWCAG2Parms(i2)).level + r2.size) {
    case "AAsmall":
    case "AAAlarge":
      n2 = a2 >= 4.5;
      break;
    case "AAlarge":
      n2 = a2 >= 3;
      break;
    case "AAAsmall":
      n2 = a2 >= 7;
  }
  return n2;
}, tinycolor.mostReadable = function(e4, t2, i2) {
  var r2, n2, a2, o2, s2 = null, l2 = 0;
  n2 = (i2 = i2 || {}).includeFallbackColors, a2 = i2.level, o2 = i2.size;
  for (var u2 = 0; u2 < t2.length; u2++) (r2 = tinycolor.readability(e4, t2[u2])) > l2 && (l2 = r2, s2 = tinycolor(t2[u2]));
  return tinycolor.isReadable(e4, s2, { level: a2, size: o2 }) || !n2 ? s2 : (i2.includeFallbackColors = false, tinycolor.mostReadable(e4, ["#fff", "#000"], i2));
};
var names$1 = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }, hexNames = tinycolor.hexNames = flip(names$1);
function flip(e4) {
  var t2 = {};
  for (var i2 in e4) e4.hasOwnProperty(i2) && (t2[e4[i2]] = i2);
  return t2;
}
function boundAlpha(e4) {
  return e4 = parseFloat(e4), (isNaN(e4) || e4 < 0 || e4 > 1) && (e4 = 1), e4;
}
function bound01(e4, t2) {
  isOnePointZero(e4) && (e4 = "100%");
  var i2 = isPercentage(e4);
  return e4 = Math.min(t2, Math.max(0, parseFloat(e4))), i2 && (e4 = parseInt(e4 * t2, 10) / 100), Math.abs(e4 - t2) < 1e-6 ? 1 : e4 % t2 / parseFloat(t2);
}
function clamp01(e4) {
  return Math.min(1, Math.max(0, e4));
}
function parseIntFromHex(e4) {
  return parseInt(e4, 16);
}
function isOnePointZero(e4) {
  return "string" == typeof e4 && -1 != e4.indexOf(".") && 1 === parseFloat(e4);
}
function isPercentage(e4) {
  return "string" == typeof e4 && -1 != e4.indexOf("%");
}
function pad2(e4) {
  return 1 == e4.length ? "0" + e4 : "" + e4;
}
function convertToPercentage(e4) {
  return e4 <= 1 && (e4 = 100 * e4 + "%"), e4;
}
function convertDecimalToHex(e4) {
  return Math.round(255 * parseFloat(e4)).toString(16);
}
function convertHexToDecimal(e4) {
  return parseIntFromHex(e4) / 255;
}
var matchers = (CSS_UNIT = "(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)", PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?", PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?", { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }), CSS_UNIT, PERMISSIVE_MATCH3, PERMISSIVE_MATCH4;
function isValidCSSUnit(e4) {
  return !!matchers.CSS_UNIT.exec(e4);
}
function stringInputToObject(e4) {
  e4 = e4.replace(trimLeft, "").replace(trimRight, "").toLowerCase();
  var t2, i2 = false;
  if (names$1[e4]) e4 = names$1[e4], i2 = true;
  else if ("transparent" == e4) return { r: 0, g: 0, b: 0, a: 0, format: "name" };
  return (t2 = matchers.rgb.exec(e4)) ? { r: t2[1], g: t2[2], b: t2[3] } : (t2 = matchers.rgba.exec(e4)) ? { r: t2[1], g: t2[2], b: t2[3], a: t2[4] } : (t2 = matchers.hsl.exec(e4)) ? { h: t2[1], s: t2[2], l: t2[3] } : (t2 = matchers.hsla.exec(e4)) ? { h: t2[1], s: t2[2], l: t2[3], a: t2[4] } : (t2 = matchers.hsv.exec(e4)) ? { h: t2[1], s: t2[2], v: t2[3] } : (t2 = matchers.hsva.exec(e4)) ? { h: t2[1], s: t2[2], v: t2[3], a: t2[4] } : (t2 = matchers.hex8.exec(e4)) ? { r: parseIntFromHex(t2[1]), g: parseIntFromHex(t2[2]), b: parseIntFromHex(t2[3]), a: convertHexToDecimal(t2[4]), format: i2 ? "name" : "hex8" } : (t2 = matchers.hex6.exec(e4)) ? { r: parseIntFromHex(t2[1]), g: parseIntFromHex(t2[2]), b: parseIntFromHex(t2[3]), format: i2 ? "name" : "hex" } : (t2 = matchers.hex4.exec(e4)) ? { r: parseIntFromHex(t2[1] + "" + t2[1]), g: parseIntFromHex(t2[2] + "" + t2[2]), b: parseIntFromHex(t2[3] + "" + t2[3]), a: convertHexToDecimal(t2[4] + "" + t2[4]), format: i2 ? "name" : "hex8" } : !!(t2 = matchers.hex3.exec(e4)) && { r: parseIntFromHex(t2[1] + "" + t2[1]), g: parseIntFromHex(t2[2] + "" + t2[2]), b: parseIntFromHex(t2[3] + "" + t2[3]), format: i2 ? "name" : "hex" };
}
function validateWCAG2Parms(e4) {
  var t2, i2;
  return "AA" !== (t2 = ((e4 = e4 || { level: "AA", size: "small" }).level || "AA").toUpperCase()) && "AAA" !== t2 && (t2 = "AA"), "small" !== (i2 = (e4.size || "small").toLowerCase()) && "large" !== i2 && (i2 = "small"), { level: t2, size: i2 };
}
function clone(e4) {
  const t2 = { width: e4.bitmap.width, height: e4.bitmap.height, data: Buffer$1.from(e4.bitmap.data) };
  return new e4.constructor(t2);
}
function scan(e4, t2, i2, r2, n2, a2) {
  let o2, s2, l2, u2, h2;
  if ("function" == typeof t2) h2 = t2, o2 = 0, s2 = 0, l2 = e4.bitmap.width, u2 = e4.bitmap.height;
  else {
    if (o2 = t2, "number" != typeof i2) throw new Error("y must be a number");
    if (s2 = i2, "number" != typeof r2) throw new Error("w must be a number");
    if (l2 = r2, "number" != typeof n2) throw new Error("h must be a number");
    if (u2 = n2, "function" != typeof a2) throw new Error("cb must be a function");
    h2 = a2;
  }
  o2 = Math.round(o2), s2 = Math.round(s2), l2 = Math.round(l2), u2 = Math.round(u2);
  const c2 = h2.bind(e4);
  for (let t3 = s2; t3 < s2 + u2; t3++) for (let i3 = o2; i3 < o2 + l2; i3++) {
    c2(i3, t3, e4.bitmap.width * t3 + i3 << 2);
  }
  return e4;
}
function* scanIterator(e4, t2, i2, r2, n2) {
  t2 = Math.round(t2), i2 = Math.round(i2), r2 = Math.round(r2), n2 = Math.round(n2);
  for (let a2 = i2; a2 < i2 + n2; a2++) for (let i3 = t2; i3 < t2 + r2; i3++) {
    const t3 = e4.bitmap.width * a2 + i3 << 2;
    yield { x: i3, y: a2, idx: t3, image: e4 };
  }
}
function intToRGBA$1(e4) {
  if ("number" != typeof e4) throw new Error("i must be a number");
  const t2 = { r: 0, g: 0, b: 0, a: 0 };
  return t2.r = Math.floor(e4 / Math.pow(256, 3)), t2.g = Math.floor((e4 - t2.r * Math.pow(256, 3)) / Math.pow(256, 2)), t2.b = Math.floor((e4 - t2.r * Math.pow(256, 3) - t2.g * Math.pow(256, 2)) / Math.pow(256, 1)), t2.a = Math.floor((e4 - t2.r * Math.pow(256, 3) - t2.g * Math.pow(256, 2) - t2.b * Math.pow(256, 1)) / Math.pow(256, 0)), t2;
}
function colorDiff(e4, t2) {
  const i2 = (e5) => Math.pow(e5, 2), { max: r2 } = Math, n2 = "a" in e4 ? e4.a : 255, a2 = "a" in t2 ? t2.a : 255;
  return (r2(i2(e4.r - t2.r), i2(e4.r - t2.r - n2 + a2)) + r2(i2(e4.g - t2.g), i2(e4.g - t2.g - n2 + a2)) + r2(i2(e4.b - t2.b), i2(e4.b - t2.b - n2 + a2))) / 195075;
}
function limit255(e4) {
  return e4 = Math.max(e4, 0), e4 = Math.min(e4, 255);
}
function cssColorToHex(e4) {
  return "number" == typeof e4 ? e4 : parseInt(tinycolor(e4).toHex8(), 16);
}
function encode$1(e4, t2 = {}) {
  return scan({ bitmap: e4 }, 0, 0, e4.width, e4.height, function(t3, i2, r2) {
    const n2 = e4.data[r2 + 0], a2 = e4.data[r2 + 1], o2 = e4.data[r2 + 2], s2 = e4.data[r2 + 3];
    e4.data[r2 + 0] = s2, e4.data[r2 + 1] = o2, e4.data[r2 + 2] = a2, e4.data[r2 + 3] = n2;
  }), encode$2({ ...e4, ...t2 }).data;
}
function decode$1(e4, t2) {
  const i2 = decode$2(e4, t2);
  return scan({ bitmap: i2 }, 0, 0, i2.width, i2.height, function(e5, t3, r2) {
    const n2 = i2.data[r2 + 1], a2 = i2.data[r2 + 2], o2 = i2.data[r2 + 3];
    i2.data[r2 + 0] = o2, i2.data[r2 + 1] = a2, i2.data[r2 + 2] = n2, i2.data[r2 + 3] = 255;
  }), i2;
}
function msBmp() {
  return { mime: "image/x-ms-bmp", encode: encode$1, decode: decode$1 };
}
function bmp() {
  return { mime: "image/bmp", encode: encode$1, decode: decode$1 };
}
var omggif = {}, GifReader_1, GifWriter_1;
function GifWriter(e4, t2, i2, r2) {
  var n2 = 0, a2 = void 0 === (r2 = void 0 === r2 ? {} : r2).loop ? null : r2.loop, o2 = void 0 === r2.palette ? null : r2.palette;
  if (t2 <= 0 || i2 <= 0 || t2 > 65535 || i2 > 65535) throw new Error("Width/Height invalid.");
  function s2(e5) {
    var t3 = e5.length;
    if (t3 < 2 || t3 > 256 || t3 & t3 - 1) throw new Error("Invalid code/color length, must be power of 2 and 2 .. 256.");
    return t3;
  }
  e4[n2++] = 71, e4[n2++] = 73, e4[n2++] = 70, e4[n2++] = 56, e4[n2++] = 57, e4[n2++] = 97;
  var l2 = 0, u2 = 0;
  if (null !== o2) {
    for (var h2 = s2(o2); h2 >>= 1; ) ++l2;
    if (h2 = 1 << l2, --l2, void 0 !== r2.background) {
      if ((u2 = r2.background) >= h2) throw new Error("Background index out of range.");
      if (0 === u2) throw new Error("Background index explicitly passed as 0.");
    }
  }
  if (e4[n2++] = 255 & t2, e4[n2++] = t2 >> 8 & 255, e4[n2++] = 255 & i2, e4[n2++] = i2 >> 8 & 255, e4[n2++] = (null !== o2 ? 128 : 0) | l2, e4[n2++] = u2, e4[n2++] = 0, null !== o2) for (var c2 = 0, f2 = o2.length; c2 < f2; ++c2) {
    var d = o2[c2];
    e4[n2++] = d >> 16 & 255, e4[n2++] = d >> 8 & 255, e4[n2++] = 255 & d;
  }
  if (null !== a2) {
    if (a2 < 0 || a2 > 65535) throw new Error("Loop count invalid.");
    e4[n2++] = 33, e4[n2++] = 255, e4[n2++] = 11, e4[n2++] = 78, e4[n2++] = 69, e4[n2++] = 84, e4[n2++] = 83, e4[n2++] = 67, e4[n2++] = 65, e4[n2++] = 80, e4[n2++] = 69, e4[n2++] = 50, e4[n2++] = 46, e4[n2++] = 48, e4[n2++] = 3, e4[n2++] = 1, e4[n2++] = 255 & a2, e4[n2++] = a2 >> 8 & 255, e4[n2++] = 0;
  }
  var p2 = false;
  this.addFrame = function(t3, i3, r3, a3, l3, u3) {
    if (true === p2 && (--n2, p2 = false), u3 = void 0 === u3 ? {} : u3, t3 < 0 || i3 < 0 || t3 > 65535 || i3 > 65535) throw new Error("x/y invalid.");
    if (r3 <= 0 || a3 <= 0 || r3 > 65535 || a3 > 65535) throw new Error("Width/Height invalid.");
    if (l3.length < r3 * a3) throw new Error("Not enough pixels for the frame size.");
    var h3 = true, c3 = u3.palette;
    if (null == c3 && (h3 = false, c3 = o2), null == c3) throw new Error("Must supply either a local or global palette.");
    for (var f3 = s2(c3), d2 = 0; f3 >>= 1; ) ++d2;
    f3 = 1 << d2;
    var m = void 0 === u3.delay ? 0 : u3.delay, _2 = void 0 === u3.disposal ? 0 : u3.disposal;
    if (_2 < 0 || _2 > 3) throw new Error("Disposal out of range.");
    var g = false, b2 = 0;
    if (void 0 !== u3.transparent && null !== u3.transparent && (g = true, (b2 = u3.transparent) < 0 || b2 >= f3)) throw new Error("Transparent color index.");
    if ((0 !== _2 || g || 0 !== m) && (e4[n2++] = 33, e4[n2++] = 249, e4[n2++] = 4, e4[n2++] = _2 << 2 | (true === g ? 1 : 0), e4[n2++] = 255 & m, e4[n2++] = m >> 8 & 255, e4[n2++] = b2, e4[n2++] = 0), e4[n2++] = 44, e4[n2++] = 255 & t3, e4[n2++] = t3 >> 8 & 255, e4[n2++] = 255 & i3, e4[n2++] = i3 >> 8 & 255, e4[n2++] = 255 & r3, e4[n2++] = r3 >> 8 & 255, e4[n2++] = 255 & a3, e4[n2++] = a3 >> 8 & 255, e4[n2++] = true === h3 ? 128 | d2 - 1 : 0, true === h3) for (var y2 = 0, w = c3.length; y2 < w; ++y2) {
      var v2 = c3[y2];
      e4[n2++] = v2 >> 16 & 255, e4[n2++] = v2 >> 8 & 255, e4[n2++] = 255 & v2;
    }
    return n2 = GifWriterOutputLZWCodeStream(e4, n2, d2 < 2 ? 2 : d2, l3);
  }, this.end = function() {
    return false === p2 && (e4[n2++] = 59, p2 = true), n2;
  }, this.getOutputBuffer = function() {
    return e4;
  }, this.setOutputBuffer = function(t3) {
    e4 = t3;
  }, this.getOutputBufferPosition = function() {
    return n2;
  }, this.setOutputBufferPosition = function(e5) {
    n2 = e5;
  };
}
function GifWriterOutputLZWCodeStream(e4, t2, i2, r2) {
  e4[t2++] = i2;
  var n2 = t2++, a2 = 1 << i2, o2 = a2 - 1, s2 = a2 + 1, l2 = s2 + 1, u2 = i2 + 1, h2 = 0, c2 = 0;
  function f2(i3) {
    for (; h2 >= i3; ) e4[t2++] = 255 & c2, c2 >>= 8, h2 -= 8, t2 === n2 + 256 && (e4[n2] = 255, n2 = t2++);
  }
  function d(e5) {
    c2 |= e5 << h2, h2 += u2, f2(8);
  }
  var p2 = r2[0] & o2, m = {};
  d(a2);
  for (var _2 = 1, g = r2.length; _2 < g; ++_2) {
    var b2 = r2[_2] & o2, y2 = p2 << 8 | b2, w = m[y2];
    if (void 0 === w) {
      for (c2 |= p2 << h2, h2 += u2; h2 >= 8; ) e4[t2++] = 255 & c2, c2 >>= 8, h2 -= 8, t2 === n2 + 256 && (e4[n2] = 255, n2 = t2++);
      4096 === l2 ? (d(a2), l2 = s2 + 1, u2 = i2 + 1, m = {}) : (l2 >= 1 << u2 && ++u2, m[y2] = l2++), p2 = b2;
    } else p2 = w;
  }
  return d(p2), d(s2), f2(1), n2 + 1 === t2 ? e4[n2] = 0 : (e4[n2] = t2 - n2 - 1, e4[t2++] = 0), t2;
}
function GifReader(e4) {
  var t2 = 0;
  if (71 !== e4[t2++] || 73 !== e4[t2++] || 70 !== e4[t2++] || 56 !== e4[t2++] || 56 != (e4[t2++] + 1 & 253) || 97 !== e4[t2++]) throw new Error("Invalid GIF 87a/89a header.");
  var i2 = e4[t2++] | e4[t2++] << 8, r2 = e4[t2++] | e4[t2++] << 8, n2 = e4[t2++], a2 = n2 >> 7, o2 = 1 << (7 & n2) + 1;
  e4[t2++], e4[t2++];
  var s2 = null, l2 = null;
  a2 && (s2 = t2, l2 = o2, t2 += 3 * o2);
  var u2 = true, h2 = [], c2 = 0, f2 = null, d = 0, p2 = null;
  for (this.width = i2, this.height = r2; u2 && t2 < e4.length; ) switch (e4[t2++]) {
    case 33:
      switch (e4[t2++]) {
        case 255:
          if (11 !== e4[t2] || 78 == e4[t2 + 1] && 69 == e4[t2 + 2] && 84 == e4[t2 + 3] && 83 == e4[t2 + 4] && 67 == e4[t2 + 5] && 65 == e4[t2 + 6] && 80 == e4[t2 + 7] && 69 == e4[t2 + 8] && 50 == e4[t2 + 9] && 46 == e4[t2 + 10] && 48 == e4[t2 + 11] && 3 == e4[t2 + 12] && 1 == e4[t2 + 13] && 0 == e4[t2 + 16]) t2 += 14, p2 = e4[t2++] | e4[t2++] << 8, t2++;
          else for (t2 += 12; ; ) {
            if (!((I = e4[t2++]) >= 0)) throw Error("Invalid block size");
            if (0 === I) break;
            t2 += I;
          }
          break;
        case 249:
          if (4 !== e4[t2++] || 0 !== e4[t2 + 4]) throw new Error("Invalid graphics extension block.");
          var m = e4[t2++];
          c2 = e4[t2++] | e4[t2++] << 8, f2 = e4[t2++], 1 & m || (f2 = null), d = m >> 2 & 7, t2++;
          break;
        case 254:
          for (; ; ) {
            if (!((I = e4[t2++]) >= 0)) throw Error("Invalid block size");
            if (0 === I) break;
            t2 += I;
          }
          break;
        default:
          throw new Error("Unknown graphic control label: 0x" + e4[t2 - 1].toString(16));
      }
      break;
    case 44:
      var _2 = e4[t2++] | e4[t2++] << 8, g = e4[t2++] | e4[t2++] << 8, b2 = e4[t2++] | e4[t2++] << 8, y2 = e4[t2++] | e4[t2++] << 8, w = e4[t2++], v2 = w >> 6 & 1, x2 = 1 << (7 & w) + 1, E2 = s2, k2 = l2, S2 = false;
      if (w >> 7) {
        S2 = true;
        E2 = t2, k2 = x2, t2 += 3 * x2;
      }
      var A2 = t2;
      for (t2++; ; ) {
        var I;
        if (!((I = e4[t2++]) >= 0)) throw Error("Invalid block size");
        if (0 === I) break;
        t2 += I;
      }
      h2.push({ x: _2, y: g, width: b2, height: y2, has_local_palette: S2, palette_offset: E2, palette_size: k2, data_offset: A2, data_length: t2 - A2, transparent_index: f2, interlaced: !!v2, delay: c2, disposal: d });
      break;
    case 59:
      u2 = false;
      break;
    default:
      throw new Error("Unknown gif block: 0x" + e4[t2 - 1].toString(16));
  }
  this.numFrames = function() {
    return h2.length;
  }, this.loopCount = function() {
    return p2;
  }, this.frameInfo = function(e5) {
    if (e5 < 0 || e5 >= h2.length) throw new Error("Frame index out of range.");
    return h2[e5];
  }, this.decodeAndBlitFrameBGRA = function(t3, r3) {
    var n3 = this.frameInfo(t3), a3 = n3.width * n3.height, o3 = new Uint8Array(a3);
    GifReaderLZWOutputIndexStream(e4, n3.data_offset, o3, a3);
    var s3 = n3.palette_offset, l3 = n3.transparent_index;
    null === l3 && (l3 = 256);
    var u3 = n3.width, h3 = i2 - u3, c3 = u3, f3 = 4 * (n3.y * i2 + n3.x), d2 = 4 * ((n3.y + n3.height) * i2 + n3.x), p3 = f3, m2 = 4 * h3;
    true === n3.interlaced && (m2 += 4 * i2 * 7);
    for (var _3 = 8, g2 = 0, b3 = o3.length; g2 < b3; ++g2) {
      var y3 = o3[g2];
      if (0 === c3 && (c3 = u3, (p3 += m2) >= d2 && (m2 = 4 * h3 + 4 * i2 * (_3 - 1), p3 = f3 + (u3 + h3) * (_3 << 1), _3 >>= 1)), y3 === l3) p3 += 4;
      else {
        var w2 = e4[s3 + 3 * y3], v3 = e4[s3 + 3 * y3 + 1], x3 = e4[s3 + 3 * y3 + 2];
        r3[p3++] = x3, r3[p3++] = v3, r3[p3++] = w2, r3[p3++] = 255;
      }
      --c3;
    }
  }, this.decodeAndBlitFrameRGBA = function(t3, r3) {
    var n3 = this.frameInfo(t3), a3 = n3.width * n3.height, o3 = new Uint8Array(a3);
    GifReaderLZWOutputIndexStream(e4, n3.data_offset, o3, a3);
    var s3 = n3.palette_offset, l3 = n3.transparent_index;
    null === l3 && (l3 = 256);
    var u3 = n3.width, h3 = i2 - u3, c3 = u3, f3 = 4 * (n3.y * i2 + n3.x), d2 = 4 * ((n3.y + n3.height) * i2 + n3.x), p3 = f3, m2 = 4 * h3;
    true === n3.interlaced && (m2 += 4 * i2 * 7);
    for (var _3 = 8, g2 = 0, b3 = o3.length; g2 < b3; ++g2) {
      var y3 = o3[g2];
      if (0 === c3 && (c3 = u3, (p3 += m2) >= d2 && (m2 = 4 * h3 + 4 * i2 * (_3 - 1), p3 = f3 + (u3 + h3) * (_3 << 1), _3 >>= 1)), y3 === l3) p3 += 4;
      else {
        var w2 = e4[s3 + 3 * y3], v3 = e4[s3 + 3 * y3 + 1], x3 = e4[s3 + 3 * y3 + 2];
        r3[p3++] = w2, r3[p3++] = v3, r3[p3++] = x3, r3[p3++] = 255;
      }
      --c3;
    }
  };
}
function GifReaderLZWOutputIndexStream(e4, t2, i2, r2) {
  for (var n2 = e4[t2++], a2 = 1 << n2, o2 = a2 + 1, s2 = o2 + 1, l2 = n2 + 1, u2 = (1 << l2) - 1, h2 = 0, c2 = 0, f2 = 0, d = e4[t2++], p2 = new Int32Array(4096), m = null; ; ) {
    for (; h2 < 16 && 0 !== d; ) c2 |= e4[t2++] << h2, h2 += 8, 1 === d ? d = e4[t2++] : --d;
    if (h2 < l2) break;
    var _2 = c2 & u2;
    if (c2 >>= l2, h2 -= l2, _2 !== a2) {
      if (_2 === o2) break;
      for (var g = _2 < s2 ? _2 : m, b2 = 0, y2 = g; y2 > a2; ) y2 = p2[y2] >> 8, ++b2;
      var w = y2;
      if (f2 + b2 + (g !== _2 ? 1 : 0) > r2) return void console.log("Warning, gif stream longer than expected.");
      i2[f2++] = w;
      var v2 = f2 += b2;
      for (g !== _2 && (i2[f2++] = w), y2 = g; b2--; ) y2 = p2[y2], i2[--v2] = 255 & y2, y2 >>= 8;
      null !== m && s2 < 4096 && (p2[s2++] = m << 8 | w, s2 >= u2 + 1 && l2 < 12 && (++l2, u2 = u2 << 1 | 1)), m = _2;
    } else s2 = o2 + 1, u2 = (1 << (l2 = n2 + 1)) - 1, m = null;
  }
  return f2 !== r2 && console.log("Warning, gif stream shorter than expected."), i2;
}
try {
  GifWriter_1 = omggif.GifWriter = GifWriter, GifReader_1 = omggif.GifReader = GifReader;
} catch (e4) {
}
let BitmapImage$2 = class e2 {
  constructor(...t2) {
    if (0 === t2.length) throw new Error("constructor requires parameters");
    const i2 = t2[0];
    if (null !== i2 && "object" == typeof i2) if (i2 instanceof e2) {
      const e4 = i2.bitmap;
      this.bitmap = { width: e4.width, height: e4.height, data: new Buffer$1(e4.width * e4.height * 4) }, e4.data.copy(this.bitmap.data);
    } else {
      if (!(i2.width && i2.height && i2.data)) throw new Error("unrecognized constructor parameters");
      this.bitmap = i2;
    }
    else {
      if ("number" != typeof i2 || "number" != typeof t2[1]) throw new Error("unrecognized constructor parameters");
      {
        const e4 = i2, r2 = t2[1], n2 = t2[2];
        this.bitmap = { width: e4, height: r2 }, Buffer$1.isBuffer(n2) ? this.bitmap.data = n2 : (this.bitmap.data = new Buffer$1(e4 * r2 * 4), "number" == typeof n2 && this.fillRGBA(n2));
      }
    }
  }
  blit(e4, t2, i2, r2, n2, a2, o2) {
    if (r2 + a2 > this.bitmap.width) throw new Error("copy exceeds width of source bitmap");
    if (t2 + a2 > e4.bitmap.width) throw new Error("copy exceeds width of target bitmap");
    if (n2 + o2 > this.bitmap.height) throw new Error("copy exceeds height of source bitmap");
    if (i2 + o2 > e4.bitmap.height) throw new Erro("copy exceeds height of target bitmap");
    const s2 = this.bitmap.data, l2 = e4.bitmap.data, u2 = 4 * this.bitmap.width, h2 = 4 * e4.bitmap.width, c2 = 4 * a2;
    let f2 = n2 * u2 + 4 * r2, d = i2 * h2 + 4 * t2;
    for (; --o2 >= 0; ) s2.copy(l2, d, f2, f2 + c2), f2 += u2, d += h2;
    return this;
  }
  fillRGBA(e4) {
    const t2 = this.bitmap.data, i2 = 4 * this.bitmap.height;
    let r2 = 0;
    for (; r2 < i2; ) t2.writeUInt32BE(e4, r2), r2 += 4;
    for (; r2 < t2.length; ) t2.copy(t2, r2, 0, i2), r2 += i2;
    return this;
  }
  getRGBA(e4, t2) {
    const i2 = 4 * (t2 * this.bitmap.width + e4);
    return this.bitmap.data.readUInt32BE(i2);
  }
  getRGBASet() {
    const e4 = /* @__PURE__ */ new Set(), t2 = this.bitmap.data;
    for (let i2 = 0; i2 < t2.length; i2 += 4) e4.add(t2.readUInt32BE(i2, true));
    return e4;
  }
  greyscale() {
    const e4 = this.bitmap.data;
    return this.scan(0, 0, this.bitmap.width, this.bitmap.height, (t2, i2, r2) => {
      const n2 = Math.round(0.299 * e4[r2] + 0.587 * e4[r2 + 1] + 0.114 * e4[r2 + 2]);
      e4[r2] = n2, e4[r2 + 1] = n2, e4[r2 + 2] = n2;
    }), this;
  }
  reframe(t2, i2, r2, n2, a2) {
    const o2 = t2 < 0 ? 0 : t2, s2 = i2 < 0 ? 0 : i2, l2 = r2 + o2 > this.bitmap.width ? this.bitmap.width - o2 : r2, u2 = n2 + s2 > this.bitmap.height ? this.bitmap.height - s2 : n2, h2 = t2 < 0 ? -t2 : 0, c2 = i2 < 0 ? -i2 : 0;
    let f2;
    if (void 0 === a2) {
      if (o2 !== t2 || s2 != i2 || l2 !== r2 || u2 !== n2) throw new GifError("fillRGBA required for this reframing");
      f2 = new e2(r2, n2);
    } else f2 = new e2(r2, n2, a2);
    return this.blit(f2, h2, c2, o2, s2, l2, u2), this.bitmap = f2.bitmap, this;
  }
  scale(e4) {
    if (1 === e4) return;
    if (!Number.isInteger(e4) || e4 < 1) throw new Error("the scale must be an integer >= 1");
    const t2 = this.bitmap.width, i2 = this.bitmap.height, r2 = t2 * e4 * 4, n2 = this.bitmap.data, a2 = new Buffer$1(i2 * r2 * e4);
    let o2, s2 = 0, l2 = 0;
    for (let u2 = 0; u2 < i2; ++u2) {
      o2 = l2;
      for (let i3 = 0; i3 < t2; ++i3) {
        const t3 = n2.readUInt32BE(s2, true);
        for (let i4 = 0; i4 < e4; ++i4) a2.writeUInt32BE(t3, l2), l2 += 4;
        s2 += 4;
      }
      for (let t3 = 1; t3 < e4; ++t3) a2.copy(a2, l2, o2, l2), l2 += r2, o2 += r2;
    }
    return this.bitmap = { width: t2 * e4, height: i2 * e4, data: a2 }, this;
  }
  scanAllCoords(e4) {
    const t2 = this.bitmap.width, i2 = this.bitmap.data.length;
    let r2 = 0, n2 = 0;
    for (let a2 = 0; a2 < i2; a2 += 4) e4(r2, n2, a2), ++r2 === t2 && (r2 = 0, ++n2);
  }
  scanAllIndexes(e4) {
    const t2 = this.bitmap.data.length;
    for (let i2 = 0; i2 < t2; i2 += 4) e4(i2);
  }
};
var bitmapimage = BitmapImage$2, gif$1 = {};
let Gif$1 = class {
  constructor(e4, t2, i2) {
    this.width = i2.width, this.height = i2.height, this.loops = i2.loops, this.usesTransparency = i2.usesTransparency, this.colorScope = i2.colorScope, this.frames = t2, this.buffer = e4;
  }
};
Gif$1.GlobalColorsPreferred = 0, Gif$1.GlobalColorsOnly = 1, Gif$1.LocalColorsOnly = 2;
let GifError$2 = class extends Error {
  constructor(e4) {
    super(e4), e4 instanceof Error && (this.stack = "Gif" + e4.stack);
  }
};
gif$1.Gif = Gif$1, gif$1.GifError = GifError$2;
var gifcodec = {}, gifutil = {}, _polyfillNode_fs = {}, _polyfillNode_fs$1 = Object.freeze({ __proto__: null, default: _polyfillNode_fs }), require$$0 = getAugmentedNamespace(_polyfillNode_fs$1), __defProp$3 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __hasOwnProp = Object.prototype.hasOwnProperty, __defNormalProp$3 = (e4, t2, i2) => t2 in e4 ? __defProp$3(e4, t2, { enumerable: true, configurable: true, writable: true, value: i2 }) : e4[t2] = i2, __markAsModule = (e4) => __defProp$3(e4, "__esModule", { value: true }), __export$1 = (e4, t2) => {
  for (var i2 in t2) __defProp$3(e4, i2, { get: t2[i2], enumerable: true });
}, __reExport = (e4, t2, i2, r2) => {
  if (t2 && "object" == typeof t2 || "function" == typeof t2) for (let n2 of __getOwnPropNames(t2)) !__hasOwnProp.call(e4, n2) && i2 && __defProp$3(e4, n2, { get: () => t2[n2], enumerable: !(r2 = __getOwnPropDesc(t2, n2)) || r2.enumerable });
  return e4;
}, __toCommonJS = /* @__PURE__ */ ((e4) => (t2, i2) => e4 && e4.get(t2) || (i2 = __reExport(__markAsModule({}), t2, 1), e4 && e4.set(t2, i2), i2))("undefined" != typeof WeakMap ? /* @__PURE__ */ new WeakMap() : 0), __publicField$3 = (e4, t2, i2) => (__defNormalProp$3(e4, "symbol" != typeof t2 ? t2 + "" : t2, i2), i2), src_exports = {};
__export$1(src_exports, { applyPalette: () => applyPalette, applyPaletteSync: () => applyPaletteSync$1, buildPalette: () => buildPalette, buildPaletteSync: () => buildPaletteSync$1, constants: () => constants_exports$1, conversion: () => conversion_exports$1, distance: () => distance_exports$1, image: () => image_exports$1, palette: () => palette_exports$1, quality: () => quality_exports$1, utils: () => utils_exports$1 });
var constants_exports$1 = {};
__export$1(constants_exports$1, { bt709: () => bt709_exports$1 });
var bt709_exports$1 = {};
__export$1(bt709_exports$1, { Y: () => Y$1, x: () => x$2, y: () => y$2 });
var Y$1 = ((e4) => (e4[e4.RED = 0.2126] = "RED", e4[e4.GREEN = 0.7152] = "GREEN", e4[e4.BLUE = 0.0722] = "BLUE", e4[e4.WHITE = 1] = "WHITE", e4))(Y$1 || {}), x$2 = ((e4) => (e4[e4.RED = 0.64] = "RED", e4[e4.GREEN = 0.3] = "GREEN", e4[e4.BLUE = 0.15] = "BLUE", e4[e4.WHITE = 0.3127] = "WHITE", e4))(x$2 || {}), y$2 = ((e4) => (e4[e4.RED = 0.33] = "RED", e4[e4.GREEN = 0.6] = "GREEN", e4[e4.BLUE = 0.06] = "BLUE", e4[e4.WHITE = 0.329] = "WHITE", e4))(y$2 || {}), conversion_exports$1 = {};
function correctGamma$1(e4) {
  return e4 > 0.04045 ? ((e4 + 0.055) / 1.055) ** 2.4 : e4 / 12.92;
}
function rgb2xyz$1(e4, t2, i2) {
  return { x: 0.4124 * (e4 = correctGamma$1(e4 / 255)) + 0.3576 * (t2 = correctGamma$1(t2 / 255)) + 0.1805 * (i2 = correctGamma$1(i2 / 255)), y: 0.2126 * e4 + 0.7152 * t2 + 0.0722 * i2, z: 0.0193 * e4 + 0.1192 * t2 + 0.9505 * i2 };
}
__export$1(conversion_exports$1, { lab2rgb: () => lab2rgb$1, lab2xyz: () => lab2xyz$1, rgb2hsl: () => rgb2hsl$1, rgb2lab: () => rgb2lab$1, rgb2xyz: () => rgb2xyz$1, xyz2lab: () => xyz2lab$1, xyz2rgb: () => xyz2rgb$1 });
var arithmetic_exports$1 = {};
function degrees2radians$1(e4) {
  return e4 * (Math.PI / 180);
}
function max3$1(e4, t2, i2) {
  let r2 = e4;
  return r2 < t2 && (r2 = t2), r2 < i2 && (r2 = i2), r2;
}
function min3$1(e4, t2, i2) {
  let r2 = e4;
  return r2 > t2 && (r2 = t2), r2 > i2 && (r2 = i2), r2;
}
function intInRange$1(e4, t2, i2) {
  return e4 > i2 && (e4 = i2), e4 < t2 && (e4 = t2), 0 | e4;
}
function inRange0to255Rounded$1(e4) {
  return (e4 = Math.round(e4)) > 255 ? e4 = 255 : e4 < 0 && (e4 = 0), e4;
}
function inRange0to255$1(e4) {
  return e4 > 255 ? e4 = 255 : e4 < 0 && (e4 = 0), e4;
}
function stableSort$1(e4, t2) {
  const i2 = typeof e4[0];
  let r2;
  if ("number" === i2 || "string" === i2) {
    const i3 = /* @__PURE__ */ Object.create(null);
    for (let t3 = 0, r3 = e4.length; t3 < r3; t3++) {
      const r4 = e4[t3];
      i3[r4] || 0 === i3[r4] || (i3[r4] = t3);
    }
    r2 = e4.sort((e5, r3) => t2(e5, r3) || i3[e5] - i3[r3]);
  } else {
    const i3 = e4.slice(0);
    r2 = e4.sort((e5, r3) => t2(e5, r3) || i3.indexOf(e5) - i3.indexOf(r3));
  }
  return r2;
}
function rgb2hsl$1(e4, t2, i2) {
  const r2 = min3$1(e4, t2, i2), n2 = max3$1(e4, t2, i2), a2 = n2 - r2, o2 = (r2 + n2) / 510;
  let s2 = 0;
  o2 > 0 && o2 < 1 && (s2 = a2 / (o2 < 0.5 ? n2 + r2 : 510 - n2 - r2));
  let l2 = 0;
  return a2 > 0 && (l2 = n2 === e4 ? (t2 - i2) / a2 : n2 === t2 ? 2 + (i2 - e4) / a2 : 4 + (e4 - t2) / a2, l2 *= 60, l2 < 0 && (l2 += 360)), { h: l2, s: s2, l: o2 };
}
__export$1(arithmetic_exports$1, { degrees2radians: () => degrees2radians$1, inRange0to255: () => inRange0to255$1, inRange0to255Rounded: () => inRange0to255Rounded$1, intInRange: () => intInRange$1, max3: () => max3$1, min3: () => min3$1, stableSort: () => stableSort$1 });
var refX$1 = 0.95047, refY$1 = 1, refZ$1 = 1.08883;
function pivot$1(e4) {
  return e4 > 8856e-6 ? e4 ** (1 / 3) : 7.787 * e4 + 16 / 116;
}
function xyz2lab$1(e4, t2, i2) {
  if (e4 = pivot$1(e4 / refX$1), t2 = pivot$1(t2 / refY$1), i2 = pivot$1(i2 / refZ$1), 116 * t2 - 16 < 0) throw new Error("xxx");
  return { L: Math.max(0, 116 * t2 - 16), a: 500 * (e4 - t2), b: 200 * (t2 - i2) };
}
function rgb2lab$1(e4, t2, i2) {
  const r2 = rgb2xyz$1(e4, t2, i2);
  return xyz2lab$1(r2.x, r2.y, r2.z);
}
var refX2$1 = 0.95047, refY2$1 = 1, refZ2$1 = 1.08883;
function pivot2$1(e4) {
  return e4 > 0.206893034 ? e4 ** 3 : (e4 - 16 / 116) / 7.787;
}
function lab2xyz$1(e4, t2, i2) {
  const r2 = (e4 + 16) / 116, n2 = r2 - i2 / 200;
  return { x: refX2$1 * pivot2$1(t2 / 500 + r2), y: refY2$1 * pivot2$1(r2), z: refZ2$1 * pivot2$1(n2) };
}
function correctGamma2$1(e4) {
  return e4 > 31308e-7 ? 1.055 * e4 ** (1 / 2.4) - 0.055 : 12.92 * e4;
}
function xyz2rgb$1(e4, t2, i2) {
  const r2 = correctGamma2$1(3.2406 * e4 + -1.5372 * t2 + -0.4986 * i2), n2 = correctGamma2$1(-0.9689 * e4 + 1.8758 * t2 + 0.0415 * i2), a2 = correctGamma2$1(0.0557 * e4 + -0.204 * t2 + 1.057 * i2);
  return { r: inRange0to255Rounded$1(255 * r2), g: inRange0to255Rounded$1(255 * n2), b: inRange0to255Rounded$1(255 * a2) };
}
function lab2rgb$1(e4, t2, i2) {
  const r2 = lab2xyz$1(e4, t2, i2);
  return xyz2rgb$1(r2.x, r2.y, r2.z);
}
var distance_exports$1 = {};
__export$1(distance_exports$1, { AbstractDistanceCalculator: () => AbstractDistanceCalculator$1, AbstractEuclidean: () => AbstractEuclidean$1, AbstractManhattan: () => AbstractManhattan$1, CIE94GraphicArts: () => CIE94GraphicArts$1, CIE94Textiles: () => CIE94Textiles$1, CIEDE2000: () => CIEDE2000$1, CMetric: () => CMetric$1, Euclidean: () => Euclidean$1, EuclideanBT709: () => EuclideanBT709$1, EuclideanBT709NoAlpha: () => EuclideanBT709NoAlpha$1, Manhattan: () => Manhattan$1, ManhattanBT709: () => ManhattanBT709$1, ManhattanNommyde: () => ManhattanNommyde$1, PNGQuant: () => PNGQuant$1 });
var AbstractDistanceCalculator$1 = class {
  constructor() {
    __publicField$3(this, "_maxDistance"), __publicField$3(this, "_whitePoint"), this._setDefaults(), this.setWhitePoint(255, 255, 255, 255);
  }
  setWhitePoint(e4, t2, i2, r2) {
    this._whitePoint = { r: e4 > 0 ? 255 / e4 : 0, g: t2 > 0 ? 255 / t2 : 0, b: i2 > 0 ? 255 / i2 : 0, a: r2 > 0 ? 255 / r2 : 0 }, this._maxDistance = this.calculateRaw(e4, t2, i2, r2, 0, 0, 0, 0);
  }
  calculateNormalized(e4, t2) {
    return this.calculateRaw(e4.r, e4.g, e4.b, e4.a, t2.r, t2.g, t2.b, t2.a) / this._maxDistance;
  }
}, AbstractCIE94$1 = class extends AbstractDistanceCalculator$1 {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = rgb2lab$1(inRange0to255$1(e4 * this._whitePoint.r), inRange0to255$1(t2 * this._whitePoint.g), inRange0to255$1(i2 * this._whitePoint.b)), u2 = rgb2lab$1(inRange0to255$1(n2 * this._whitePoint.r), inRange0to255$1(a2 * this._whitePoint.g), inRange0to255$1(o2 * this._whitePoint.b)), h2 = l2.L - u2.L, c2 = l2.a - u2.a, f2 = l2.b - u2.b, d = Math.sqrt(l2.a * l2.a + l2.b * l2.b), p2 = d - Math.sqrt(u2.a * u2.a + u2.b * u2.b);
    let m = c2 * c2 + f2 * f2 - p2 * p2;
    m = m < 0 ? 0 : Math.sqrt(m);
    const _2 = (s2 - r2) * this._whitePoint.a * this._kA;
    return Math.sqrt((h2 / this._Kl) ** 2 + (p2 / (1 + this._K1 * d)) ** 2 + (m / (1 + this._K2 * d)) ** 2 + _2 ** 2);
  }
}, CIE94Textiles$1 = class extends AbstractCIE94$1 {
  _setDefaults() {
    this._Kl = 2, this._K1 = 0.048, this._K2 = 0.014, this._kA = 12.5 / 255;
  }
}, CIE94GraphicArts$1 = class extends AbstractCIE94$1 {
  _setDefaults() {
    this._Kl = 1, this._K1 = 0.045, this._K2 = 0.015, this._kA = 25 / 255;
  }
}, _CIEDE2000$1 = class extends AbstractDistanceCalculator$1 {
  _setDefaults() {
  }
  static _calculatehp(e4, t2) {
    const i2 = Math.atan2(e4, t2);
    return i2 >= 0 ? i2 : i2 + _CIEDE2000$1._deg360InRad;
  }
  static _calculateRT(e4, t2) {
    const i2 = t2 ** 7, r2 = 2 * Math.sqrt(i2 / (i2 + _CIEDE2000$1._pow25to7)), n2 = _CIEDE2000$1._deg30InRad * Math.exp(-(((e4 - _CIEDE2000$1._deg275InRad) / _CIEDE2000$1._deg25InRad) ** 2));
    return -Math.sin(2 * n2) * r2;
  }
  static _calculateT(e4) {
    return 1 - 0.17 * Math.cos(e4 - _CIEDE2000$1._deg30InRad) + 0.24 * Math.cos(2 * e4) + 0.32 * Math.cos(3 * e4 + _CIEDE2000$1._deg6InRad) - 0.2 * Math.cos(4 * e4 - _CIEDE2000$1._deg63InRad);
  }
  static _calculate_ahp(e4, t2, i2, r2) {
    const n2 = i2 + r2;
    return 0 === e4 ? n2 : t2 <= _CIEDE2000$1._deg180InRad ? n2 / 2 : n2 < _CIEDE2000$1._deg360InRad ? (n2 + _CIEDE2000$1._deg360InRad) / 2 : (n2 - _CIEDE2000$1._deg360InRad) / 2;
  }
  static _calculate_dHp(e4, t2, i2, r2) {
    let n2;
    return n2 = 0 === e4 ? 0 : t2 <= _CIEDE2000$1._deg180InRad ? i2 - r2 : i2 <= r2 ? i2 - r2 + _CIEDE2000$1._deg360InRad : i2 - r2 - _CIEDE2000$1._deg360InRad, 2 * Math.sqrt(e4) * Math.sin(n2 / 2);
  }
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = rgb2lab$1(inRange0to255$1(e4 * this._whitePoint.r), inRange0to255$1(t2 * this._whitePoint.g), inRange0to255$1(i2 * this._whitePoint.b)), u2 = rgb2lab$1(inRange0to255$1(n2 * this._whitePoint.r), inRange0to255$1(a2 * this._whitePoint.g), inRange0to255$1(o2 * this._whitePoint.b)), h2 = (s2 - r2) * this._whitePoint.a * _CIEDE2000$1._kA, c2 = this.calculateRawInLab(l2, u2);
    return Math.sqrt(c2 + h2 * h2);
  }
  calculateRawInLab(e4, t2) {
    const i2 = e4.L, r2 = e4.a, n2 = e4.b, a2 = t2.L, o2 = t2.a, s2 = t2.b, l2 = ((Math.sqrt(r2 * r2 + n2 * n2) + Math.sqrt(o2 * o2 + s2 * s2)) / 2) ** 7, u2 = 0.5 * (1 - Math.sqrt(l2 / (l2 + _CIEDE2000$1._pow25to7))), h2 = (1 + u2) * r2, c2 = (1 + u2) * o2, f2 = Math.sqrt(h2 * h2 + n2 * n2), d = Math.sqrt(c2 * c2 + s2 * s2), p2 = f2 * d, m = _CIEDE2000$1._calculatehp(n2, h2), _2 = _CIEDE2000$1._calculatehp(s2, c2), g = Math.abs(m - _2), b2 = a2 - i2, y2 = d - f2, w = _CIEDE2000$1._calculate_dHp(p2, g, _2, m), v2 = _CIEDE2000$1._calculate_ahp(p2, g, m, _2), x2 = (f2 + d) / 2, E2 = ((i2 + a2) / 2 - 50) ** 2, k2 = y2 / (1 + 0.045 * x2), S2 = w / (1 + 0.015 * _CIEDE2000$1._calculateT(v2) * x2);
    return (b2 / (1 + 0.015 * E2 / Math.sqrt(20 + E2))) ** 2 + k2 ** 2 + S2 ** 2 + _CIEDE2000$1._calculateRT(v2, x2) * k2 * S2;
  }
}, CIEDE2000$1 = _CIEDE2000$1;
__publicField$3(CIEDE2000$1, "_kA", 25 / 255), __publicField$3(CIEDE2000$1, "_pow25to7", 25 ** 7), __publicField$3(CIEDE2000$1, "_deg360InRad", degrees2radians$1(360)), __publicField$3(CIEDE2000$1, "_deg180InRad", degrees2radians$1(180)), __publicField$3(CIEDE2000$1, "_deg30InRad", degrees2radians$1(30)), __publicField$3(CIEDE2000$1, "_deg6InRad", degrees2radians$1(6)), __publicField$3(CIEDE2000$1, "_deg63InRad", degrees2radians$1(63)), __publicField$3(CIEDE2000$1, "_deg275InRad", degrees2radians$1(275)), __publicField$3(CIEDE2000$1, "_deg25InRad", degrees2radians$1(25));
var CMetric$1 = class extends AbstractDistanceCalculator$1 {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = (e4 + n2) / 2 * this._whitePoint.r, u2 = (e4 - n2) * this._whitePoint.r, h2 = (t2 - a2) * this._whitePoint.g, c2 = (i2 - o2) * this._whitePoint.b, f2 = ((512 + l2) * u2 * u2 >> 8) + 4 * h2 * h2 + ((767 - l2) * c2 * c2 >> 8), d = (s2 - r2) * this._whitePoint.a;
    return Math.sqrt(f2 + d * d);
  }
  _setDefaults() {
  }
}, AbstractEuclidean$1 = class extends AbstractDistanceCalculator$1 {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = n2 - e4, u2 = a2 - t2, h2 = o2 - i2, c2 = s2 - r2;
    return Math.sqrt(this._kR * l2 * l2 + this._kG * u2 * u2 + this._kB * h2 * h2 + this._kA * c2 * c2);
  }
}, Euclidean$1 = class extends AbstractEuclidean$1 {
  _setDefaults() {
    this._kR = 1, this._kG = 1, this._kB = 1, this._kA = 1;
  }
}, EuclideanBT709$1 = class extends AbstractEuclidean$1 {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 1;
  }
}, EuclideanBT709NoAlpha$1 = class extends AbstractEuclidean$1 {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 0;
  }
}, AbstractManhattan$1 = class extends AbstractDistanceCalculator$1 {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    let l2 = n2 - e4, u2 = a2 - t2, h2 = o2 - i2, c2 = s2 - r2;
    return l2 < 0 && (l2 = 0 - l2), u2 < 0 && (u2 = 0 - u2), h2 < 0 && (h2 = 0 - h2), c2 < 0 && (c2 = 0 - c2), this._kR * l2 + this._kG * u2 + this._kB * h2 + this._kA * c2;
  }
}, Manhattan$1 = class extends AbstractManhattan$1 {
  _setDefaults() {
    this._kR = 1, this._kG = 1, this._kB = 1, this._kA = 1;
  }
}, ManhattanNommyde$1 = class extends AbstractManhattan$1 {
  _setDefaults() {
    this._kR = 0.4984, this._kG = 0.8625, this._kB = 0.2979, this._kA = 1;
  }
}, ManhattanBT709$1 = class extends AbstractManhattan$1 {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 1;
  }
}, PNGQuant$1 = class extends AbstractDistanceCalculator$1 {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = (s2 - r2) * this._whitePoint.a;
    return this._colordifferenceCh(e4 * this._whitePoint.r, n2 * this._whitePoint.r, l2) + this._colordifferenceCh(t2 * this._whitePoint.g, a2 * this._whitePoint.g, l2) + this._colordifferenceCh(i2 * this._whitePoint.b, o2 * this._whitePoint.b, l2);
  }
  _colordifferenceCh(e4, t2, i2) {
    const r2 = e4 - t2, n2 = r2 + i2;
    return r2 * r2 + n2 * n2;
  }
  _setDefaults() {
  }
}, palette_exports$1 = {};
__export$1(palette_exports$1, { AbstractPaletteQuantizer: () => AbstractPaletteQuantizer$1, ColorHistogram: () => ColorHistogram$1, NeuQuant: () => NeuQuant$1, NeuQuantFloat: () => NeuQuantFloat$1, RGBQuant: () => RGBQuant$1, WuColorCube: () => WuColorCube$1, WuQuant: () => WuQuant$1 });
var AbstractPaletteQuantizer$1 = class {
  quantizeSync() {
    for (const e4 of this.quantize()) if (e4.palette) return e4.palette;
    throw new Error("unreachable");
  }
}, Point$1 = class {
  constructor() {
    __publicField$3(this, "r"), __publicField$3(this, "g"), __publicField$3(this, "b"), __publicField$3(this, "a"), __publicField$3(this, "uint32"), __publicField$3(this, "rgba"), this.uint32 = -1 >>> 0, this.r = this.g = this.b = this.a = 0, this.rgba = new Array(4), this.rgba[0] = 0, this.rgba[1] = 0, this.rgba[2] = 0, this.rgba[3] = 0;
  }
  static createByQuadruplet(e4) {
    const t2 = new Point$1();
    return t2.r = 0 | e4[0], t2.g = 0 | e4[1], t2.b = 0 | e4[2], t2.a = 0 | e4[3], t2._loadUINT32(), t2._loadQuadruplet(), t2;
  }
  static createByRGBA(e4, t2, i2, r2) {
    const n2 = new Point$1();
    return n2.r = 0 | e4, n2.g = 0 | t2, n2.b = 0 | i2, n2.a = 0 | r2, n2._loadUINT32(), n2._loadQuadruplet(), n2;
  }
  static createByUint32(e4) {
    const t2 = new Point$1();
    return t2.uint32 = e4 >>> 0, t2._loadRGBA(), t2._loadQuadruplet(), t2;
  }
  from(e4) {
    this.r = e4.r, this.g = e4.g, this.b = e4.b, this.a = e4.a, this.uint32 = e4.uint32, this.rgba[0] = e4.r, this.rgba[1] = e4.g, this.rgba[2] = e4.b, this.rgba[3] = e4.a;
  }
  getLuminosity(e4) {
    let t2 = this.r, i2 = this.g, r2 = this.b;
    return e4 && (t2 = Math.min(255, 255 - this.a + this.a * t2 / 255), i2 = Math.min(255, 255 - this.a + this.a * i2 / 255), r2 = Math.min(255, 255 - this.a + this.a * r2 / 255)), 0.2126 * t2 + 0.7152 * i2 + 0.0722 * r2;
  }
  _loadUINT32() {
    this.uint32 = (this.a << 24 | this.b << 16 | this.g << 8 | this.r) >>> 0;
  }
  _loadRGBA() {
    this.r = 255 & this.uint32, this.g = this.uint32 >>> 8 & 255, this.b = this.uint32 >>> 16 & 255, this.a = this.uint32 >>> 24 & 255;
  }
  _loadQuadruplet() {
    this.rgba[0] = this.r, this.rgba[1] = this.g, this.rgba[2] = this.b, this.rgba[3] = this.a;
  }
}, PointContainer$1 = class {
  constructor() {
    __publicField$3(this, "_pointArray"), __publicField$3(this, "_width"), __publicField$3(this, "_height"), this._width = 0, this._height = 0, this._pointArray = [];
  }
  getWidth() {
    return this._width;
  }
  getHeight() {
    return this._height;
  }
  setWidth(e4) {
    this._width = e4;
  }
  setHeight(e4) {
    this._height = e4;
  }
  getPointArray() {
    return this._pointArray;
  }
  clone() {
    const e4 = new PointContainer$1();
    e4._width = this._width, e4._height = this._height;
    for (let t2 = 0, i2 = this._pointArray.length; t2 < i2; t2++) e4._pointArray[t2] = Point$1.createByUint32(0 | this._pointArray[t2].uint32);
    return e4;
  }
  toUint32Array() {
    const e4 = this._pointArray.length, t2 = new Uint32Array(e4);
    for (let i2 = 0; i2 < e4; i2++) t2[i2] = this._pointArray[i2].uint32;
    return t2;
  }
  toUint8Array() {
    return new Uint8Array(this.toUint32Array().buffer);
  }
  static fromHTMLImageElement(e4) {
    const t2 = e4.naturalWidth, i2 = e4.naturalHeight, r2 = document.createElement("canvas");
    r2.width = t2, r2.height = i2;
    return r2.getContext("2d").drawImage(e4, 0, 0, t2, i2, 0, 0, t2, i2), PointContainer$1.fromHTMLCanvasElement(r2);
  }
  static fromHTMLCanvasElement(e4) {
    const t2 = e4.width, i2 = e4.height, r2 = e4.getContext("2d").getImageData(0, 0, t2, i2);
    return PointContainer$1.fromImageData(r2);
  }
  static fromImageData(e4) {
    const t2 = e4.width, i2 = e4.height;
    return PointContainer$1.fromUint8Array(e4.data, t2, i2);
  }
  static fromUint8Array(e4, t2, i2) {
    switch (Object.prototype.toString.call(e4)) {
      case "[object Uint8ClampedArray]":
      case "[object Uint8Array]":
        break;
      default:
        e4 = new Uint8Array(e4);
    }
    const r2 = new Uint32Array(e4.buffer);
    return PointContainer$1.fromUint32Array(r2, t2, i2);
  }
  static fromUint32Array(e4, t2, i2) {
    const r2 = new PointContainer$1();
    r2._width = t2, r2._height = i2;
    for (let t3 = 0, i3 = e4.length; t3 < i3; t3++) r2._pointArray[t3] = Point$1.createByUint32(0 | e4[t3]);
    return r2;
  }
  static fromBuffer(e4, t2, i2) {
    const r2 = new Uint32Array(e4.buffer, e4.byteOffset, e4.byteLength / Uint32Array.BYTES_PER_ELEMENT);
    return PointContainer$1.fromUint32Array(r2, t2, i2);
  }
}, hueGroups$1 = 10;
function hueGroup$1(e4, t2) {
  const i2 = 360 / t2;
  for (let r2 = 1, n2 = i2 - i2 / 2; r2 < t2; r2++, n2 += i2) if (e4 >= n2 && e4 < n2 + i2) return r2;
  return 0;
}
var Palette$1 = class {
  constructor() {
    __publicField$3(this, "_pointContainer"), __publicField$3(this, "_pointArray", []), __publicField$3(this, "_i32idx", {}), this._pointContainer = new PointContainer$1(), this._pointContainer.setHeight(1), this._pointArray = this._pointContainer.getPointArray();
  }
  add(e4) {
    this._pointArray.push(e4), this._pointContainer.setWidth(this._pointArray.length);
  }
  has(e4) {
    for (let t2 = this._pointArray.length - 1; t2 >= 0; t2--) if (e4.uint32 === this._pointArray[t2].uint32) return true;
    return false;
  }
  getNearestColor(e4, t2) {
    return this._pointArray[0 | this._getNearestIndex(e4, t2)];
  }
  getPointContainer() {
    return this._pointContainer;
  }
  _nearestPointFromCache(e4) {
    return "number" == typeof this._i32idx[e4] ? this._i32idx[e4] : -1;
  }
  _getNearestIndex(e4, t2) {
    let i2 = this._nearestPointFromCache("" + t2.uint32);
    if (i2 >= 0) return i2;
    let r2 = Number.MAX_VALUE;
    i2 = 0;
    for (let n2 = 0, a2 = this._pointArray.length; n2 < a2; n2++) {
      const a3 = this._pointArray[n2], o2 = e4.calculateRaw(t2.r, t2.g, t2.b, t2.a, a3.r, a3.g, a3.b, a3.a);
      o2 < r2 && (r2 = o2, i2 = n2);
    }
    return this._i32idx[t2.uint32] = i2, i2;
  }
  sort() {
    this._i32idx = {}, this._pointArray.sort((e4, t2) => {
      const i2 = rgb2hsl$1(e4.r, e4.g, e4.b), r2 = rgb2hsl$1(t2.r, t2.g, t2.b), n2 = e4.r === e4.g && e4.g === e4.b ? 0 : 1 + hueGroup$1(i2.h, hueGroups$1), a2 = (t2.r === t2.g && t2.g === t2.b ? 0 : 1 + hueGroup$1(r2.h, hueGroups$1)) - n2;
      if (a2) return -a2;
      const o2 = e4.getLuminosity(true), s2 = t2.getLuminosity(true);
      if (s2 - o2 != 0) return s2 - o2;
      const l2 = (100 * r2.s | 0) - (100 * i2.s | 0);
      return l2 ? -l2 : 0;
    });
  }
}, utils_exports$1 = {};
__export$1(utils_exports$1, { HueStatistics: () => HueStatistics$1, Palette: () => Palette$1, Point: () => Point$1, PointContainer: () => PointContainer$1, ProgressTracker: () => ProgressTracker$1, arithmetic: () => arithmetic_exports$1 });
var HueGroup$1 = class {
  constructor() {
    __publicField$3(this, "num", 0), __publicField$3(this, "cols", []);
  }
}, HueStatistics$1 = class {
  constructor(e4, t2) {
    __publicField$3(this, "_numGroups"), __publicField$3(this, "_minCols"), __publicField$3(this, "_stats"), __publicField$3(this, "_groupsFull"), this._numGroups = e4, this._minCols = t2, this._stats = [];
    for (let t3 = 0; t3 <= e4; t3++) this._stats[t3] = new HueGroup$1();
    this._groupsFull = 0;
  }
  check(e4) {
    this._groupsFull === this._numGroups + 1 && (this.check = () => {
    });
    const t2 = 255 & e4, i2 = e4 >>> 8 & 255, r2 = e4 >>> 16 & 255, n2 = t2 === i2 && i2 === r2 ? 0 : 1 + hueGroup$1(rgb2hsl$1(t2, i2, r2).h, this._numGroups), a2 = this._stats[n2], o2 = this._minCols;
    a2.num++, a2.num > o2 || (a2.num === o2 && this._groupsFull++, a2.num <= o2 && this._stats[n2].cols.push(e4));
  }
  injectIntoDictionary(e4) {
    for (let t2 = 0; t2 <= this._numGroups; t2++) this._stats[t2].num <= this._minCols && this._stats[t2].cols.forEach((t3) => {
      e4[t3] ? e4[t3]++ : e4[t3] = 1;
    });
  }
  injectIntoArray(e4) {
    for (let t2 = 0; t2 <= this._numGroups; t2++) this._stats[t2].num <= this._minCols && this._stats[t2].cols.forEach((t3) => {
      -1 === e4.indexOf(t3) && e4.push(t3);
    });
  }
}, _ProgressTracker$1 = class {
  constructor(e4, t2) {
    __publicField$3(this, "progress"), __publicField$3(this, "_step"), __publicField$3(this, "_range"), __publicField$3(this, "_last"), __publicField$3(this, "_progressRange"), this._range = e4, this._progressRange = t2, this._step = Math.max(1, this._range / (_ProgressTracker$1.steps + 1) | 0), this._last = -this._step, this.progress = 0;
  }
  shouldNotify(e4) {
    return e4 - this._last >= this._step && (this._last = e4, this.progress = Math.min(this._progressRange * this._last / this._range, this._progressRange), true);
  }
}, ProgressTracker$1 = _ProgressTracker$1;
__publicField$3(ProgressTracker$1, "steps", 100);
var networkBiasShift$1 = 3, Neuron$1 = class {
  constructor(e4) {
    __publicField$3(this, "r"), __publicField$3(this, "g"), __publicField$3(this, "b"), __publicField$3(this, "a"), this.r = this.g = this.b = this.a = e4;
  }
  toPoint() {
    return Point$1.createByRGBA(this.r >> networkBiasShift$1, this.g >> networkBiasShift$1, this.b >> networkBiasShift$1, this.a >> networkBiasShift$1);
  }
  subtract(e4, t2, i2, r2) {
    this.r -= 0 | e4, this.g -= 0 | t2, this.b -= 0 | i2, this.a -= 0 | r2;
  }
}, _NeuQuant$1 = class extends AbstractPaletteQuantizer$1 {
  constructor(e4, t2 = 256) {
    super(), __publicField$3(this, "_pointArray"), __publicField$3(this, "_networkSize"), __publicField$3(this, "_network"), __publicField$3(this, "_sampleFactor"), __publicField$3(this, "_radPower"), __publicField$3(this, "_freq"), __publicField$3(this, "_bias"), __publicField$3(this, "_distance"), this._distance = e4, this._pointArray = [], this._sampleFactor = 1, this._networkSize = t2, this._distance.setWhitePoint(255 << networkBiasShift$1, 255 << networkBiasShift$1, 255 << networkBiasShift$1, 255 << networkBiasShift$1);
  }
  sample(e4) {
    this._pointArray = this._pointArray.concat(e4.getPointArray());
  }
  *quantize() {
    this._init(), yield* this._learn(), yield { palette: this._buildPalette(), progress: 100 };
  }
  _init() {
    this._freq = [], this._bias = [], this._radPower = [], this._network = [];
    for (let e4 = 0; e4 < this._networkSize; e4++) this._network[e4] = new Neuron$1((e4 << networkBiasShift$1 + 8) / this._networkSize | 0), this._freq[e4] = _NeuQuant$1._initialBias / this._networkSize | 0, this._bias[e4] = 0;
  }
  *_learn() {
    let e4 = this._sampleFactor;
    const t2 = this._pointArray.length;
    t2 < _NeuQuant$1._minpicturebytes && (e4 = 1);
    const i2 = 30 + (e4 - 1) / 3 | 0, r2 = t2 / e4 | 0;
    let n2, a2 = r2 / _NeuQuant$1._nCycles | 0, o2 = _NeuQuant$1._initAlpha, s2 = (this._networkSize >> 3) * _NeuQuant$1._radiusBias, l2 = s2 >> _NeuQuant$1._radiusBiasShift;
    l2 <= 1 && (l2 = 0);
    for (let e5 = 0; e5 < l2; e5++) this._radPower[e5] = o2 * ((l2 * l2 - e5 * e5) * _NeuQuant$1._radBias / (l2 * l2)) >>> 0;
    n2 = t2 < _NeuQuant$1._minpicturebytes ? 1 : t2 % _NeuQuant$1._prime1 != 0 ? _NeuQuant$1._prime1 : t2 % _NeuQuant$1._prime2 != 0 ? _NeuQuant$1._prime2 : t2 % _NeuQuant$1._prime3 != 0 ? _NeuQuant$1._prime3 : _NeuQuant$1._prime4;
    const u2 = new ProgressTracker$1(r2, 99);
    for (let e5 = 0, h2 = 0; e5 < r2; ) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress });
      const r3 = this._pointArray[h2], c2 = r3.b << networkBiasShift$1, f2 = r3.g << networkBiasShift$1, d = r3.r << networkBiasShift$1, p2 = r3.a << networkBiasShift$1, m = this._contest(c2, f2, d, p2);
      if (this._alterSingle(o2, m, c2, f2, d, p2), 0 !== l2 && this._alterNeighbour(l2, m, c2, f2, d, p2), h2 += n2, h2 >= t2 && (h2 -= t2), e5++, 0 === a2 && (a2 = 1), e5 % a2 == 0) {
        o2 -= o2 / i2 | 0, s2 -= s2 / _NeuQuant$1._radiusDecrease | 0, l2 = s2 >> _NeuQuant$1._radiusBiasShift, l2 <= 1 && (l2 = 0);
        for (let e6 = 0; e6 < l2; e6++) this._radPower[e6] = o2 * ((l2 * l2 - e6 * e6) * _NeuQuant$1._radBias / (l2 * l2)) >>> 0;
      }
    }
  }
  _buildPalette() {
    const e4 = new Palette$1();
    return this._network.forEach((t2) => {
      e4.add(t2.toPoint());
    }), e4.sort(), e4;
  }
  _alterNeighbour(e4, t2, i2, r2, n2, a2) {
    let o2 = t2 - e4;
    o2 < -1 && (o2 = -1);
    let s2 = t2 + e4;
    s2 > this._networkSize && (s2 = this._networkSize);
    let l2 = t2 + 1, u2 = t2 - 1, h2 = 1;
    for (; l2 < s2 || u2 > o2; ) {
      const e5 = this._radPower[h2++] / _NeuQuant$1._alphaRadBias;
      if (l2 < s2) {
        const t3 = this._network[l2++];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
      if (u2 > o2) {
        const t3 = this._network[u2--];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
    }
  }
  _alterSingle(e4, t2, i2, r2, n2, a2) {
    e4 /= _NeuQuant$1._initAlpha;
    const o2 = this._network[t2];
    o2.subtract(e4 * (o2.r - n2), e4 * (o2.g - r2), e4 * (o2.b - i2), e4 * (o2.a - a2));
  }
  _contest(e4, t2, i2, r2) {
    const n2 = 1020 << networkBiasShift$1;
    let a2 = 2147483647, o2 = a2, s2 = -1, l2 = s2;
    for (let u2 = 0; u2 < this._networkSize; u2++) {
      const h2 = this._network[u2], c2 = this._distance.calculateNormalized(h2, { r: i2, g: t2, b: e4, a: r2 }) * n2 | 0;
      c2 < a2 && (a2 = c2, s2 = u2);
      const f2 = c2 - (this._bias[u2] >> _NeuQuant$1._initialBiasShift - networkBiasShift$1);
      f2 < o2 && (o2 = f2, l2 = u2);
      const d = this._freq[u2] >> _NeuQuant$1._betaShift;
      this._freq[u2] -= d, this._bias[u2] += d << _NeuQuant$1._gammaShift;
    }
    return this._freq[s2] += _NeuQuant$1._beta, this._bias[s2] -= _NeuQuant$1._betaGamma, l2;
  }
}, NeuQuant$1 = _NeuQuant$1;
__publicField$3(NeuQuant$1, "_prime1", 499), __publicField$3(NeuQuant$1, "_prime2", 491), __publicField$3(NeuQuant$1, "_prime3", 487), __publicField$3(NeuQuant$1, "_prime4", 503), __publicField$3(NeuQuant$1, "_minpicturebytes", _NeuQuant$1._prime4), __publicField$3(NeuQuant$1, "_nCycles", 100), __publicField$3(NeuQuant$1, "_initialBiasShift", 16), __publicField$3(NeuQuant$1, "_initialBias", 1 << _NeuQuant$1._initialBiasShift), __publicField$3(NeuQuant$1, "_gammaShift", 10), __publicField$3(NeuQuant$1, "_betaShift", 10), __publicField$3(NeuQuant$1, "_beta", _NeuQuant$1._initialBias >> _NeuQuant$1._betaShift), __publicField$3(NeuQuant$1, "_betaGamma", _NeuQuant$1._initialBias << _NeuQuant$1._gammaShift - _NeuQuant$1._betaShift), __publicField$3(NeuQuant$1, "_radiusBiasShift", 6), __publicField$3(NeuQuant$1, "_radiusBias", 1 << _NeuQuant$1._radiusBiasShift), __publicField$3(NeuQuant$1, "_radiusDecrease", 30), __publicField$3(NeuQuant$1, "_alphaBiasShift", 10), __publicField$3(NeuQuant$1, "_initAlpha", 1 << _NeuQuant$1._alphaBiasShift), __publicField$3(NeuQuant$1, "_radBiasShift", 8), __publicField$3(NeuQuant$1, "_radBias", 1 << _NeuQuant$1._radBiasShift), __publicField$3(NeuQuant$1, "_alphaRadBiasShift", _NeuQuant$1._alphaBiasShift + _NeuQuant$1._radBiasShift), __publicField$3(NeuQuant$1, "_alphaRadBias", 1 << _NeuQuant$1._alphaRadBiasShift);
var networkBiasShift2$1 = 3, NeuronFloat$1 = class {
  constructor(e4) {
    __publicField$3(this, "r"), __publicField$3(this, "g"), __publicField$3(this, "b"), __publicField$3(this, "a"), this.r = this.g = this.b = this.a = e4;
  }
  toPoint() {
    return Point$1.createByRGBA(this.r >> networkBiasShift2$1, this.g >> networkBiasShift2$1, this.b >> networkBiasShift2$1, this.a >> networkBiasShift2$1);
  }
  subtract(e4, t2, i2, r2) {
    this.r -= e4, this.g -= t2, this.b -= i2, this.a -= r2;
  }
}, _NeuQuantFloat$1 = class extends AbstractPaletteQuantizer$1 {
  constructor(e4, t2 = 256) {
    super(), __publicField$3(this, "_pointArray"), __publicField$3(this, "_networkSize"), __publicField$3(this, "_network"), __publicField$3(this, "_sampleFactor"), __publicField$3(this, "_radPower"), __publicField$3(this, "_freq"), __publicField$3(this, "_bias"), __publicField$3(this, "_distance"), this._distance = e4, this._pointArray = [], this._sampleFactor = 1, this._networkSize = t2, this._distance.setWhitePoint(255 << networkBiasShift2$1, 255 << networkBiasShift2$1, 255 << networkBiasShift2$1, 255 << networkBiasShift2$1);
  }
  sample(e4) {
    this._pointArray = this._pointArray.concat(e4.getPointArray());
  }
  *quantize() {
    this._init(), yield* this._learn(), yield { palette: this._buildPalette(), progress: 100 };
  }
  _init() {
    this._freq = [], this._bias = [], this._radPower = [], this._network = [];
    for (let e4 = 0; e4 < this._networkSize; e4++) this._network[e4] = new NeuronFloat$1((e4 << networkBiasShift2$1 + 8) / this._networkSize), this._freq[e4] = _NeuQuantFloat$1._initialBias / this._networkSize, this._bias[e4] = 0;
  }
  *_learn() {
    let e4 = this._sampleFactor;
    const t2 = this._pointArray.length;
    t2 < _NeuQuantFloat$1._minpicturebytes && (e4 = 1);
    const i2 = 30 + (e4 - 1) / 3, r2 = t2 / e4;
    let n2, a2 = r2 / _NeuQuantFloat$1._nCycles | 0, o2 = _NeuQuantFloat$1._initAlpha, s2 = (this._networkSize >> 3) * _NeuQuantFloat$1._radiusBias, l2 = s2 >> _NeuQuantFloat$1._radiusBiasShift;
    l2 <= 1 && (l2 = 0);
    for (let e5 = 0; e5 < l2; e5++) this._radPower[e5] = o2 * ((l2 * l2 - e5 * e5) * _NeuQuantFloat$1._radBias / (l2 * l2));
    n2 = t2 < _NeuQuantFloat$1._minpicturebytes ? 1 : t2 % _NeuQuantFloat$1._prime1 != 0 ? _NeuQuantFloat$1._prime1 : t2 % _NeuQuantFloat$1._prime2 != 0 ? _NeuQuantFloat$1._prime2 : t2 % _NeuQuantFloat$1._prime3 != 0 ? _NeuQuantFloat$1._prime3 : _NeuQuantFloat$1._prime4;
    const u2 = new ProgressTracker$1(r2, 99);
    for (let e5 = 0, h2 = 0; e5 < r2; ) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress });
      const r3 = this._pointArray[h2], c2 = r3.b << networkBiasShift2$1, f2 = r3.g << networkBiasShift2$1, d = r3.r << networkBiasShift2$1, p2 = r3.a << networkBiasShift2$1, m = this._contest(c2, f2, d, p2);
      if (this._alterSingle(o2, m, c2, f2, d, p2), 0 !== l2 && this._alterNeighbour(l2, m, c2, f2, d, p2), h2 += n2, h2 >= t2 && (h2 -= t2), e5++, 0 === a2 && (a2 = 1), e5 % a2 == 0) {
        o2 -= o2 / i2, s2 -= s2 / _NeuQuantFloat$1._radiusDecrease, l2 = s2 >> _NeuQuantFloat$1._radiusBiasShift, l2 <= 1 && (l2 = 0);
        for (let e6 = 0; e6 < l2; e6++) this._radPower[e6] = o2 * ((l2 * l2 - e6 * e6) * _NeuQuantFloat$1._radBias / (l2 * l2));
      }
    }
  }
  _buildPalette() {
    const e4 = new Palette$1();
    return this._network.forEach((t2) => {
      e4.add(t2.toPoint());
    }), e4.sort(), e4;
  }
  _alterNeighbour(e4, t2, i2, r2, n2, a2) {
    let o2 = t2 - e4;
    o2 < -1 && (o2 = -1);
    let s2 = t2 + e4;
    s2 > this._networkSize && (s2 = this._networkSize);
    let l2 = t2 + 1, u2 = t2 - 1, h2 = 1;
    for (; l2 < s2 || u2 > o2; ) {
      const e5 = this._radPower[h2++] / _NeuQuantFloat$1._alphaRadBias;
      if (l2 < s2) {
        const t3 = this._network[l2++];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
      if (u2 > o2) {
        const t3 = this._network[u2--];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
    }
  }
  _alterSingle(e4, t2, i2, r2, n2, a2) {
    e4 /= _NeuQuantFloat$1._initAlpha;
    const o2 = this._network[t2];
    o2.subtract(e4 * (o2.r - n2), e4 * (o2.g - r2), e4 * (o2.b - i2), e4 * (o2.a - a2));
  }
  _contest(e4, t2, i2, r2) {
    const n2 = 1020 << networkBiasShift2$1;
    let a2 = 2147483647, o2 = a2, s2 = -1, l2 = s2;
    for (let u2 = 0; u2 < this._networkSize; u2++) {
      const h2 = this._network[u2], c2 = this._distance.calculateNormalized(h2, { r: i2, g: t2, b: e4, a: r2 }) * n2;
      c2 < a2 && (a2 = c2, s2 = u2);
      const f2 = c2 - (this._bias[u2] >> _NeuQuantFloat$1._initialBiasShift - networkBiasShift2$1);
      f2 < o2 && (o2 = f2, l2 = u2);
      const d = this._freq[u2] >> _NeuQuantFloat$1._betaShift;
      this._freq[u2] -= d, this._bias[u2] += d << _NeuQuantFloat$1._gammaShift;
    }
    return this._freq[s2] += _NeuQuantFloat$1._beta, this._bias[s2] -= _NeuQuantFloat$1._betaGamma, l2;
  }
}, NeuQuantFloat$1 = _NeuQuantFloat$1;
__publicField$3(NeuQuantFloat$1, "_prime1", 499), __publicField$3(NeuQuantFloat$1, "_prime2", 491), __publicField$3(NeuQuantFloat$1, "_prime3", 487), __publicField$3(NeuQuantFloat$1, "_prime4", 503), __publicField$3(NeuQuantFloat$1, "_minpicturebytes", _NeuQuantFloat$1._prime4), __publicField$3(NeuQuantFloat$1, "_nCycles", 100), __publicField$3(NeuQuantFloat$1, "_initialBiasShift", 16), __publicField$3(NeuQuantFloat$1, "_initialBias", 1 << _NeuQuantFloat$1._initialBiasShift), __publicField$3(NeuQuantFloat$1, "_gammaShift", 10), __publicField$3(NeuQuantFloat$1, "_betaShift", 10), __publicField$3(NeuQuantFloat$1, "_beta", _NeuQuantFloat$1._initialBias >> _NeuQuantFloat$1._betaShift), __publicField$3(NeuQuantFloat$1, "_betaGamma", _NeuQuantFloat$1._initialBias << _NeuQuantFloat$1._gammaShift - _NeuQuantFloat$1._betaShift), __publicField$3(NeuQuantFloat$1, "_radiusBiasShift", 6), __publicField$3(NeuQuantFloat$1, "_radiusBias", 1 << _NeuQuantFloat$1._radiusBiasShift), __publicField$3(NeuQuantFloat$1, "_radiusDecrease", 30), __publicField$3(NeuQuantFloat$1, "_alphaBiasShift", 10), __publicField$3(NeuQuantFloat$1, "_initAlpha", 1 << _NeuQuantFloat$1._alphaBiasShift), __publicField$3(NeuQuantFloat$1, "_radBiasShift", 8), __publicField$3(NeuQuantFloat$1, "_radBias", 1 << _NeuQuantFloat$1._radBiasShift), __publicField$3(NeuQuantFloat$1, "_alphaRadBiasShift", _NeuQuantFloat$1._alphaBiasShift + _NeuQuantFloat$1._radBiasShift), __publicField$3(NeuQuantFloat$1, "_alphaRadBias", 1 << _NeuQuantFloat$1._alphaRadBiasShift);
var _ColorHistogram$1 = class {
  constructor(e4, t2) {
    __publicField$3(this, "_method"), __publicField$3(this, "_hueStats"), __publicField$3(this, "_histogram"), __publicField$3(this, "_initColors"), __publicField$3(this, "_minHueCols"), this._method = e4, this._minHueCols = t2 << 2, this._initColors = t2 << 2, this._hueStats = new HueStatistics$1(_ColorHistogram$1._hueGroups, this._minHueCols), this._histogram = /* @__PURE__ */ Object.create(null);
  }
  sample(e4) {
    switch (this._method) {
      case 1:
        this._colorStats1D(e4);
        break;
      case 2:
        this._colorStats2D(e4);
    }
  }
  getImportanceSortedColorsIDXI32() {
    const e4 = stableSort$1(Object.keys(this._histogram), (e5, t3) => this._histogram[t3] - this._histogram[e5]);
    if (0 === e4.length) return [];
    let t2;
    switch (this._method) {
      case 1:
        const i2 = Math.min(e4.length, this._initColors), r2 = e4[i2 - 1], n2 = this._histogram[r2];
        t2 = e4.slice(0, i2);
        let a2 = i2;
        const o2 = e4.length;
        for (; a2 < o2 && this._histogram[e4[a2]] === n2; ) t2.push(e4[a2++]);
        this._hueStats.injectIntoArray(t2);
        break;
      case 2:
        t2 = e4;
        break;
      default:
        throw new Error("Incorrect method");
    }
    return t2.map((e5) => +e5);
  }
  _colorStats1D(e4) {
    const t2 = this._histogram, i2 = e4.getPointArray(), r2 = i2.length;
    for (let e5 = 0; e5 < r2; e5++) {
      const r3 = i2[e5].uint32;
      this._hueStats.check(r3), r3 in t2 ? t2[r3]++ : t2[r3] = 1;
    }
  }
  _colorStats2D(e4) {
    const t2 = e4.getWidth(), i2 = e4.getHeight(), r2 = e4.getPointArray(), n2 = _ColorHistogram$1._boxSize[0], a2 = _ColorHistogram$1._boxSize[1], o2 = n2 * a2, s2 = this._makeBoxes(t2, i2, n2, a2), l2 = this._histogram;
    s2.forEach((e5) => {
      let i3 = Math.round(e5.w * e5.h / o2) * _ColorHistogram$1._boxPixels;
      i3 < 2 && (i3 = 2);
      const n3 = {};
      this._iterateBox(e5, t2, (e6) => {
        const t3 = r2[e6].uint32;
        this._hueStats.check(t3), t3 in l2 ? l2[t3]++ : t3 in n3 ? ++n3[t3] >= i3 && (l2[t3] = n3[t3]) : n3[t3] = 1;
      });
    }), this._hueStats.injectIntoDictionary(l2);
  }
  _iterateBox(e4, t2, i2) {
    const r2 = e4, n2 = r2.y * t2 + r2.x, a2 = (r2.y + r2.h - 1) * t2 + (r2.x + r2.w - 1), o2 = t2 - r2.w + 1;
    let s2 = 0, l2 = n2;
    do {
      i2.call(this, l2), l2 += ++s2 % r2.w == 0 ? o2 : 1;
    } while (l2 <= a2);
  }
  _makeBoxes(e4, t2, i2, r2) {
    const n2 = e4 % i2, a2 = t2 % r2, o2 = e4 - n2, s2 = t2 - a2, l2 = [];
    for (let u2 = 0; u2 < t2; u2 += r2) for (let t3 = 0; t3 < e4; t3 += i2) l2.push({ x: t3, y: u2, w: t3 === o2 ? n2 : i2, h: u2 === s2 ? a2 : r2 });
    return l2;
  }
}, ColorHistogram$1 = _ColorHistogram$1;
__publicField$3(ColorHistogram$1, "_boxSize", [64, 64]), __publicField$3(ColorHistogram$1, "_boxPixels", 2), __publicField$3(ColorHistogram$1, "_hueGroups", 10);
var RemovedColor$1 = class {
  constructor(e4, t2, i2) {
    __publicField$3(this, "index"), __publicField$3(this, "color"), __publicField$3(this, "distance"), this.index = e4, this.color = t2, this.distance = i2;
  }
}, RGBQuant$1 = class extends AbstractPaletteQuantizer$1 {
  constructor(e4, t2 = 256, i2 = 2) {
    super(), __publicField$3(this, "_colors"), __publicField$3(this, "_initialDistance"), __publicField$3(this, "_distanceIncrement"), __publicField$3(this, "_histogram"), __publicField$3(this, "_distance"), this._distance = e4, this._colors = t2, this._histogram = new ColorHistogram$1(i2, t2), this._initialDistance = 0.01, this._distanceIncrement = 5e-3;
  }
  sample(e4) {
    this._histogram.sample(e4);
  }
  *quantize() {
    const e4 = this._histogram.getImportanceSortedColorsIDXI32();
    if (0 === e4.length) throw new Error("No colors in image");
    yield* this._buildPalette(e4);
  }
  *_buildPalette(e4) {
    const t2 = new Palette$1(), i2 = t2.getPointContainer().getPointArray(), r2 = new Array(e4.length);
    for (let t3 = 0; t3 < e4.length; t3++) i2.push(Point$1.createByUint32(e4[t3])), r2[t3] = 1;
    const n2 = i2.length, a2 = [];
    let o2 = n2, s2 = this._initialDistance;
    const l2 = new ProgressTracker$1(o2 - this._colors, 99);
    for (; o2 > this._colors; ) {
      a2.length = 0;
      for (let e5 = 0; e5 < n2; e5++) {
        if (l2.shouldNotify(n2 - o2) && (yield { progress: l2.progress }), 0 === r2[e5]) continue;
        const t3 = i2[e5];
        for (let l3 = e5 + 1; l3 < n2; l3++) {
          if (0 === r2[l3]) continue;
          const e6 = i2[l3], n3 = this._distance.calculateNormalized(t3, e6);
          n3 < s2 && (a2.push(new RemovedColor$1(l3, e6, n3)), r2[l3] = 0, o2--);
        }
      }
      s2 += o2 > 3 * this._colors ? this._initialDistance : this._distanceIncrement;
    }
    if (o2 < this._colors) {
      stableSort$1(a2, (e6, t3) => t3.distance - e6.distance);
      let e5 = 0;
      for (; o2 < this._colors && e5 < a2.length; ) {
        r2[a2[e5].index] = 1, o2++, e5++;
      }
    }
    let u2 = i2.length;
    for (let e5 = u2 - 1; e5 >= 0; e5--) 0 === r2[e5] && (e5 !== u2 - 1 && (i2[e5] = i2[u2 - 1]), --u2);
    i2.length = u2, t2.sort(), yield { palette: t2, progress: 100 };
  }
};
function createArray1D$1(e4) {
  const t2 = [];
  for (let i2 = 0; i2 < e4; i2++) t2[i2] = 0;
  return t2;
}
function createArray4D$1(e4, t2, i2, r2) {
  const n2 = new Array(e4);
  for (let a2 = 0; a2 < e4; a2++) {
    n2[a2] = new Array(t2);
    for (let e5 = 0; e5 < t2; e5++) {
      n2[a2][e5] = new Array(i2);
      for (let t3 = 0; t3 < i2; t3++) {
        n2[a2][e5][t3] = new Array(r2);
        for (let i3 = 0; i3 < r2; i3++) n2[a2][e5][t3][i3] = 0;
      }
    }
  }
  return n2;
}
function createArray3D$1(e4, t2, i2) {
  const r2 = new Array(e4);
  for (let n2 = 0; n2 < e4; n2++) {
    r2[n2] = new Array(t2);
    for (let e5 = 0; e5 < t2; e5++) {
      r2[n2][e5] = new Array(i2);
      for (let t3 = 0; t3 < i2; t3++) r2[n2][e5][t3] = 0;
    }
  }
  return r2;
}
function fillArray3D$1(e4, t2, i2, r2, n2) {
  for (let a2 = 0; a2 < t2; a2++) {
    e4[a2] = [];
    for (let t3 = 0; t3 < i2; t3++) {
      e4[a2][t3] = [];
      for (let i3 = 0; i3 < r2; i3++) e4[a2][t3][i3] = n2;
    }
  }
}
function fillArray1D$1(e4, t2, i2) {
  for (let r2 = 0; r2 < t2; r2++) e4[r2] = i2;
}
var WuColorCube$1 = class {
  constructor() {
    __publicField$3(this, "redMinimum"), __publicField$3(this, "redMaximum"), __publicField$3(this, "greenMinimum"), __publicField$3(this, "greenMaximum"), __publicField$3(this, "blueMinimum"), __publicField$3(this, "blueMaximum"), __publicField$3(this, "volume"), __publicField$3(this, "alphaMinimum"), __publicField$3(this, "alphaMaximum");
  }
}, _WuQuant$1 = class extends AbstractPaletteQuantizer$1 {
  constructor(e4, t2 = 256, i2 = 5) {
    super(), __publicField$3(this, "_reds"), __publicField$3(this, "_greens"), __publicField$3(this, "_blues"), __publicField$3(this, "_alphas"), __publicField$3(this, "_sums"), __publicField$3(this, "_weights"), __publicField$3(this, "_momentsRed"), __publicField$3(this, "_momentsGreen"), __publicField$3(this, "_momentsBlue"), __publicField$3(this, "_momentsAlpha"), __publicField$3(this, "_moments"), __publicField$3(this, "_table"), __publicField$3(this, "_pixels"), __publicField$3(this, "_cubes"), __publicField$3(this, "_colors"), __publicField$3(this, "_significantBitsPerChannel"), __publicField$3(this, "_maxSideIndex"), __publicField$3(this, "_alphaMaxSideIndex"), __publicField$3(this, "_sideSize"), __publicField$3(this, "_alphaSideSize"), __publicField$3(this, "_distance"), this._distance = e4, this._setQuality(i2), this._initialize(t2);
  }
  sample(e4) {
    const t2 = e4.getPointArray();
    for (let e5 = 0, i2 = t2.length; e5 < i2; e5++) this._addColor(t2[e5]);
    this._pixels = this._pixels.concat(t2);
  }
  *quantize() {
    yield* this._preparePalette();
    const e4 = new Palette$1();
    for (let t2 = 0; t2 < this._colors; t2++) if (this._sums[t2] > 0) {
      const i2 = this._sums[t2], r2 = this._reds[t2] / i2, n2 = this._greens[t2] / i2, a2 = this._blues[t2] / i2, o2 = this._alphas[t2] / i2, s2 = Point$1.createByRGBA(0 | r2, 0 | n2, 0 | a2, 0 | o2);
      e4.add(s2);
    }
    e4.sort(), yield { palette: e4, progress: 100 };
  }
  *_preparePalette() {
    yield* this._calculateMoments();
    let e4 = 0;
    const t2 = createArray1D$1(this._colors);
    for (let i3 = 1; i3 < this._colors; ++i3) {
      this._cut(this._cubes[e4], this._cubes[i3]) ? (t2[e4] = this._cubes[e4].volume > 1 ? this._calculateVariance(this._cubes[e4]) : 0, t2[i3] = this._cubes[i3].volume > 1 ? this._calculateVariance(this._cubes[i3]) : 0) : (t2[e4] = 0, i3--), e4 = 0;
      let r3 = t2[0];
      for (let n3 = 1; n3 <= i3; ++n3) t2[n3] > r3 && (r3 = t2[n3], e4 = n3);
      if (r3 <= 0) {
        this._colors = i3 + 1;
        break;
      }
    }
    const i2 = [], r2 = [], n2 = [], a2 = [];
    for (let e5 = 0; e5 < this._colors; ++e5) {
      const t3 = _WuQuant$1._volume(this._cubes[e5], this._weights);
      t3 > 0 ? (i2[e5] = _WuQuant$1._volume(this._cubes[e5], this._momentsRed) / t3 | 0, r2[e5] = _WuQuant$1._volume(this._cubes[e5], this._momentsGreen) / t3 | 0, n2[e5] = _WuQuant$1._volume(this._cubes[e5], this._momentsBlue) / t3 | 0, a2[e5] = _WuQuant$1._volume(this._cubes[e5], this._momentsAlpha) / t3 | 0) : (i2[e5] = 0, r2[e5] = 0, n2[e5] = 0, a2[e5] = 0);
    }
    this._reds = createArray1D$1(this._colors + 1), this._greens = createArray1D$1(this._colors + 1), this._blues = createArray1D$1(this._colors + 1), this._alphas = createArray1D$1(this._colors + 1), this._sums = createArray1D$1(this._colors + 1);
    for (let e5 = 0, t3 = this._pixels.length; e5 < t3; e5++) {
      const t4 = this._pixels[e5];
      let o2 = -1, s2 = Number.MAX_VALUE;
      for (let e6 = 0; e6 < this._colors; e6++) {
        const l2 = i2[e6], u2 = r2[e6], h2 = n2[e6], c2 = a2[e6], f2 = this._distance.calculateRaw(l2, u2, h2, c2, t4.r, t4.g, t4.b, t4.a);
        f2 < s2 && (s2 = f2, o2 = e6);
      }
      this._reds[o2] += t4.r, this._greens[o2] += t4.g, this._blues[o2] += t4.b, this._alphas[o2] += t4.a, this._sums[o2]++;
    }
  }
  _addColor(e4) {
    const t2 = 8 - this._significantBitsPerChannel, i2 = 1 + (e4.r >> t2), r2 = 1 + (e4.g >> t2), n2 = 1 + (e4.b >> t2), a2 = 1 + (e4.a >> t2);
    this._weights[a2][i2][r2][n2]++, this._momentsRed[a2][i2][r2][n2] += e4.r, this._momentsGreen[a2][i2][r2][n2] += e4.g, this._momentsBlue[a2][i2][r2][n2] += e4.b, this._momentsAlpha[a2][i2][r2][n2] += e4.a, this._moments[a2][i2][r2][n2] += this._table[e4.r] + this._table[e4.g] + this._table[e4.b] + this._table[e4.a];
  }
  *_calculateMoments() {
    const e4 = [], t2 = [], i2 = [], r2 = [], n2 = [], a2 = [], o2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize), s2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize), l2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize), u2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize), h2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize), c2 = createArray3D$1(this._sideSize, this._sideSize, this._sideSize);
    let f2 = 0;
    const d = new ProgressTracker$1(this._alphaMaxSideIndex * this._maxSideIndex, 99);
    for (let p2 = 1; p2 <= this._alphaMaxSideIndex; ++p2) {
      fillArray3D$1(o2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D$1(s2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D$1(l2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D$1(u2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D$1(h2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D$1(c2, this._sideSize, this._sideSize, this._sideSize, 0);
      for (let m = 1; m <= this._maxSideIndex; ++m, ++f2) {
        d.shouldNotify(f2) && (yield { progress: d.progress }), fillArray1D$1(e4, this._sideSize, 0), fillArray1D$1(t2, this._sideSize, 0), fillArray1D$1(i2, this._sideSize, 0), fillArray1D$1(r2, this._sideSize, 0), fillArray1D$1(n2, this._sideSize, 0), fillArray1D$1(a2, this._sideSize, 0);
        for (let f3 = 1; f3 <= this._maxSideIndex; ++f3) {
          let d2 = 0, _2 = 0, g = 0, b2 = 0, y2 = 0, w = 0;
          for (let v2 = 1; v2 <= this._maxSideIndex; ++v2) d2 += this._weights[p2][m][f3][v2], _2 += this._momentsRed[p2][m][f3][v2], g += this._momentsGreen[p2][m][f3][v2], b2 += this._momentsBlue[p2][m][f3][v2], y2 += this._momentsAlpha[p2][m][f3][v2], w += this._moments[p2][m][f3][v2], e4[v2] += d2, t2[v2] += _2, i2[v2] += g, r2[v2] += b2, n2[v2] += y2, a2[v2] += w, o2[m][f3][v2] = o2[m - 1][f3][v2] + e4[v2], s2[m][f3][v2] = s2[m - 1][f3][v2] + t2[v2], l2[m][f3][v2] = l2[m - 1][f3][v2] + i2[v2], u2[m][f3][v2] = u2[m - 1][f3][v2] + r2[v2], h2[m][f3][v2] = h2[m - 1][f3][v2] + n2[v2], c2[m][f3][v2] = c2[m - 1][f3][v2] + a2[v2], this._weights[p2][m][f3][v2] = this._weights[p2 - 1][m][f3][v2] + o2[m][f3][v2], this._momentsRed[p2][m][f3][v2] = this._momentsRed[p2 - 1][m][f3][v2] + s2[m][f3][v2], this._momentsGreen[p2][m][f3][v2] = this._momentsGreen[p2 - 1][m][f3][v2] + l2[m][f3][v2], this._momentsBlue[p2][m][f3][v2] = this._momentsBlue[p2 - 1][m][f3][v2] + u2[m][f3][v2], this._momentsAlpha[p2][m][f3][v2] = this._momentsAlpha[p2 - 1][m][f3][v2] + h2[m][f3][v2], this._moments[p2][m][f3][v2] = this._moments[p2 - 1][m][f3][v2] + c2[m][f3][v2];
        }
      }
    }
  }
  static _volumeFloat(e4, t2) {
    return t2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] - t2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - t2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + t2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - t2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] + t2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + t2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - t2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (t2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - t2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - t2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + t2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - t2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + t2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + t2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] - t2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
  }
  static _volume(e4, t2) {
    return 0 | _WuQuant$1._volumeFloat(e4, t2);
  }
  static _top(e4, t2, i2, r2) {
    let n2;
    switch (t2) {
      case _WuQuant$1._alpha:
        n2 = r2[i2][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] - r2[i2][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - r2[i2][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + r2[i2][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (r2[i2][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - r2[i2][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - r2[i2][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + r2[i2][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
        break;
      case _WuQuant$1._red:
        n2 = r2[e4.alphaMaximum][i2][e4.greenMaximum][e4.blueMaximum] - r2[e4.alphaMaximum][i2][e4.greenMinimum][e4.blueMaximum] - r2[e4.alphaMinimum][i2][e4.greenMaximum][e4.blueMaximum] + r2[e4.alphaMinimum][i2][e4.greenMinimum][e4.blueMaximum] - (r2[e4.alphaMaximum][i2][e4.greenMaximum][e4.blueMinimum] - r2[e4.alphaMaximum][i2][e4.greenMinimum][e4.blueMinimum] - r2[e4.alphaMinimum][i2][e4.greenMaximum][e4.blueMinimum] + r2[e4.alphaMinimum][i2][e4.greenMinimum][e4.blueMinimum]);
        break;
      case _WuQuant$1._green:
        n2 = r2[e4.alphaMaximum][e4.redMaximum][i2][e4.blueMaximum] - r2[e4.alphaMaximum][e4.redMinimum][i2][e4.blueMaximum] - r2[e4.alphaMinimum][e4.redMaximum][i2][e4.blueMaximum] + r2[e4.alphaMinimum][e4.redMinimum][i2][e4.blueMaximum] - (r2[e4.alphaMaximum][e4.redMaximum][i2][e4.blueMinimum] - r2[e4.alphaMaximum][e4.redMinimum][i2][e4.blueMinimum] - r2[e4.alphaMinimum][e4.redMaximum][i2][e4.blueMinimum] + r2[e4.alphaMinimum][e4.redMinimum][i2][e4.blueMinimum]);
        break;
      case _WuQuant$1._blue:
        n2 = r2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][i2] - r2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][i2] - r2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][i2] + r2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][i2] - (r2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][i2] - r2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][i2] - r2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][i2] + r2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][i2]);
        break;
      default:
        throw new Error("impossible");
    }
    return 0 | n2;
  }
  static _bottom(e4, t2, i2) {
    switch (t2) {
      case _WuQuant$1._alpha:
        return -i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant$1._red:
        return -i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant$1._green:
        return -i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant$1._blue:
        return -i2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] - (-i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      default:
        return 0;
    }
  }
  _calculateVariance(e4) {
    const t2 = _WuQuant$1._volume(e4, this._momentsRed), i2 = _WuQuant$1._volume(e4, this._momentsGreen), r2 = _WuQuant$1._volume(e4, this._momentsBlue), n2 = _WuQuant$1._volume(e4, this._momentsAlpha);
    return _WuQuant$1._volumeFloat(e4, this._moments) - (t2 * t2 + i2 * i2 + r2 * r2 + n2 * n2) / _WuQuant$1._volume(e4, this._weights);
  }
  _maximize(e4, t2, i2, r2, n2, a2, o2, s2, l2) {
    const u2 = 0 | _WuQuant$1._bottom(e4, t2, this._momentsRed), h2 = 0 | _WuQuant$1._bottom(e4, t2, this._momentsGreen), c2 = 0 | _WuQuant$1._bottom(e4, t2, this._momentsBlue), f2 = 0 | _WuQuant$1._bottom(e4, t2, this._momentsAlpha), d = 0 | _WuQuant$1._bottom(e4, t2, this._weights);
    let p2 = 0, m = -1;
    for (let _2 = i2; _2 < r2; ++_2) {
      let i3 = u2 + _WuQuant$1._top(e4, t2, _2, this._momentsRed), r3 = h2 + _WuQuant$1._top(e4, t2, _2, this._momentsGreen), g = c2 + _WuQuant$1._top(e4, t2, _2, this._momentsBlue), b2 = f2 + _WuQuant$1._top(e4, t2, _2, this._momentsAlpha), y2 = d + _WuQuant$1._top(e4, t2, _2, this._weights);
      if (0 !== y2) {
        let e5 = i3 * i3 + r3 * r3 + g * g + b2 * b2, t3 = e5 / y2;
        i3 = n2 - i3, r3 = a2 - r3, g = o2 - g, b2 = s2 - b2, y2 = l2 - y2, 0 !== y2 && (e5 = i3 * i3 + r3 * r3 + g * g + b2 * b2, t3 += e5 / y2, t3 > p2 && (p2 = t3, m = _2));
      }
    }
    return { max: p2, position: m };
  }
  _cut(e4, t2) {
    let i2;
    const r2 = _WuQuant$1._volume(e4, this._momentsRed), n2 = _WuQuant$1._volume(e4, this._momentsGreen), a2 = _WuQuant$1._volume(e4, this._momentsBlue), o2 = _WuQuant$1._volume(e4, this._momentsAlpha), s2 = _WuQuant$1._volume(e4, this._weights), l2 = this._maximize(e4, _WuQuant$1._red, e4.redMinimum + 1, e4.redMaximum, r2, n2, a2, o2, s2), u2 = this._maximize(e4, _WuQuant$1._green, e4.greenMinimum + 1, e4.greenMaximum, r2, n2, a2, o2, s2), h2 = this._maximize(e4, _WuQuant$1._blue, e4.blueMinimum + 1, e4.blueMaximum, r2, n2, a2, o2, s2), c2 = this._maximize(e4, _WuQuant$1._alpha, e4.alphaMinimum + 1, e4.alphaMaximum, r2, n2, a2, o2, s2);
    if (c2.max >= l2.max && c2.max >= u2.max && c2.max >= h2.max) {
      if (i2 = _WuQuant$1._alpha, c2.position < 0) return false;
    } else i2 = l2.max >= c2.max && l2.max >= u2.max && l2.max >= h2.max ? _WuQuant$1._red : u2.max >= c2.max && u2.max >= l2.max && u2.max >= h2.max ? _WuQuant$1._green : _WuQuant$1._blue;
    switch (t2.redMaximum = e4.redMaximum, t2.greenMaximum = e4.greenMaximum, t2.blueMaximum = e4.blueMaximum, t2.alphaMaximum = e4.alphaMaximum, i2) {
      case _WuQuant$1._red:
        t2.redMinimum = e4.redMaximum = l2.position, t2.greenMinimum = e4.greenMinimum, t2.blueMinimum = e4.blueMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant$1._green:
        t2.greenMinimum = e4.greenMaximum = u2.position, t2.redMinimum = e4.redMinimum, t2.blueMinimum = e4.blueMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant$1._blue:
        t2.blueMinimum = e4.blueMaximum = h2.position, t2.redMinimum = e4.redMinimum, t2.greenMinimum = e4.greenMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant$1._alpha:
        t2.alphaMinimum = e4.alphaMaximum = c2.position, t2.blueMinimum = e4.blueMinimum, t2.redMinimum = e4.redMinimum, t2.greenMinimum = e4.greenMinimum;
    }
    return e4.volume = (e4.redMaximum - e4.redMinimum) * (e4.greenMaximum - e4.greenMinimum) * (e4.blueMaximum - e4.blueMinimum) * (e4.alphaMaximum - e4.alphaMinimum), t2.volume = (t2.redMaximum - t2.redMinimum) * (t2.greenMaximum - t2.greenMinimum) * (t2.blueMaximum - t2.blueMinimum) * (t2.alphaMaximum - t2.alphaMinimum), true;
  }
  _initialize(e4) {
    this._colors = e4, this._cubes = [];
    for (let t2 = 0; t2 < e4; t2++) this._cubes[t2] = new WuColorCube$1();
    this._cubes[0].redMinimum = 0, this._cubes[0].greenMinimum = 0, this._cubes[0].blueMinimum = 0, this._cubes[0].alphaMinimum = 0, this._cubes[0].redMaximum = this._maxSideIndex, this._cubes[0].greenMaximum = this._maxSideIndex, this._cubes[0].blueMaximum = this._maxSideIndex, this._cubes[0].alphaMaximum = this._alphaMaxSideIndex, this._weights = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsRed = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsGreen = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsBlue = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsAlpha = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._moments = createArray4D$1(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._table = [];
    for (let e5 = 0; e5 < 256; ++e5) this._table[e5] = e5 * e5;
    this._pixels = [];
  }
  _setQuality(e4 = 5) {
    this._significantBitsPerChannel = e4, this._maxSideIndex = 1 << this._significantBitsPerChannel, this._alphaMaxSideIndex = this._maxSideIndex, this._sideSize = this._maxSideIndex + 1, this._alphaSideSize = this._alphaMaxSideIndex + 1;
  }
}, WuQuant$1 = _WuQuant$1;
__publicField$3(WuQuant$1, "_alpha", 3), __publicField$3(WuQuant$1, "_red", 2), __publicField$3(WuQuant$1, "_green", 1), __publicField$3(WuQuant$1, "_blue", 0);
var image_exports$1 = {};
__export$1(image_exports$1, { AbstractImageQuantizer: () => AbstractImageQuantizer$1, ErrorDiffusionArray: () => ErrorDiffusionArray$1, ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel$1, ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma$1, NearestColor: () => NearestColor$1 });
var AbstractImageQuantizer$1 = class {
  quantizeSync(e4, t2) {
    for (const i2 of this.quantize(e4, t2)) if (i2.pointContainer) return i2.pointContainer;
    throw new Error("unreachable");
  }
}, NearestColor$1 = class extends AbstractImageQuantizer$1 {
  constructor(e4) {
    super(), __publicField$3(this, "_distance"), this._distance = e4;
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = e4.getWidth(), n2 = e4.getHeight(), a2 = new ProgressTracker$1(n2, 99);
    for (let e5 = 0; e5 < n2; e5++) {
      a2.shouldNotify(e5) && (yield { progress: a2.progress });
      for (let n3 = 0, a3 = e5 * r2; n3 < r2; n3++, a3++) {
        const e6 = i2[a3];
        e6.from(t2.getNearestColor(this._distance, e6));
      }
    }
    yield { pointContainer: e4, progress: 100 };
  }
}, ErrorDiffusionArrayKernel$1 = ((e4) => (e4[e4.FloydSteinberg = 0] = "FloydSteinberg", e4[e4.FalseFloydSteinberg = 1] = "FalseFloydSteinberg", e4[e4.Stucki = 2] = "Stucki", e4[e4.Atkinson = 3] = "Atkinson", e4[e4.Jarvis = 4] = "Jarvis", e4[e4.Burkes = 5] = "Burkes", e4[e4.Sierra = 6] = "Sierra", e4[e4.TwoSierra = 7] = "TwoSierra", e4[e4.SierraLite = 8] = "SierraLite", e4))(ErrorDiffusionArrayKernel$1 || {}), ErrorDiffusionArray$1 = class extends AbstractImageQuantizer$1 {
  constructor(e4, t2, i2 = true, r2 = 0, n2 = false) {
    super(), __publicField$3(this, "_minColorDistance"), __publicField$3(this, "_serpentine"), __publicField$3(this, "_kernel"), __publicField$3(this, "_calculateErrorLikeGIMP"), __publicField$3(this, "_distance"), this._setKernel(t2), this._distance = e4, this._minColorDistance = r2, this._serpentine = i2, this._calculateErrorLikeGIMP = n2;
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = new Point$1(), n2 = e4.getWidth(), a2 = e4.getHeight(), o2 = [];
    let s2 = 1, l2 = 1;
    for (const e5 of this._kernel) {
      const t3 = e5[2] + 1;
      l2 < t3 && (l2 = t3);
    }
    for (let e5 = 0; e5 < l2; e5++) this._fillErrorLine(o2[e5] = [], n2);
    const u2 = new ProgressTracker$1(a2, 99);
    for (let e5 = 0; e5 < a2; e5++) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress }), this._serpentine && (s2 *= -1);
      const l3 = e5 * n2, h2 = 1 === s2 ? 0 : n2 - 1, c2 = 1 === s2 ? n2 : -1;
      this._fillErrorLine(o2[0], n2), o2.push(o2.shift());
      const f2 = o2[0];
      for (let u3 = h2, d = l3 + h2; u3 !== c2; u3 += s2, d += s2) {
        const l4 = i2[d], h3 = f2[u3];
        r2.from(l4);
        const c3 = Point$1.createByRGBA(inRange0to255Rounded$1(l4.r + h3[0]), inRange0to255Rounded$1(l4.g + h3[1]), inRange0to255Rounded$1(l4.b + h3[2]), inRange0to255Rounded$1(l4.a + h3[3])), p2 = t2.getNearestColor(this._distance, c3);
        if (l4.from(p2), this._minColorDistance) {
          if (this._distance.calculateNormalized(r2, p2) < this._minColorDistance) continue;
        }
        let m, _2, g, b2;
        this._calculateErrorLikeGIMP ? (m = c3.r - p2.r, _2 = c3.g - p2.g, g = c3.b - p2.b, b2 = c3.a - p2.a) : (m = r2.r - p2.r, _2 = r2.g - p2.g, g = r2.b - p2.b, b2 = r2.a - p2.a);
        const y2 = 1 === s2 ? 0 : this._kernel.length - 1, w = 1 === s2 ? this._kernel.length : -1;
        for (let t3 = y2; t3 !== w; t3 += s2) {
          const i3 = this._kernel[t3][1] * s2, r3 = this._kernel[t3][2];
          if (i3 + u3 >= 0 && i3 + u3 < n2 && r3 + e5 >= 0 && r3 + e5 < a2) {
            const e6 = this._kernel[t3][0], n3 = o2[r3][i3 + u3];
            n3[0] += m * e6, n3[1] += _2 * e6, n3[2] += g * e6, n3[3] += b2 * e6;
          }
        }
      }
    }
    yield { pointContainer: e4, progress: 100 };
  }
  _fillErrorLine(e4, t2) {
    e4.length > t2 && (e4.length = t2);
    const i2 = e4.length;
    for (let t3 = 0; t3 < i2; t3++) {
      const i3 = e4[t3];
      i3[0] = i3[1] = i3[2] = i3[3] = 0;
    }
    for (let r2 = i2; r2 < t2; r2++) e4[r2] = [0, 0, 0, 0];
  }
  _setKernel(e4) {
    switch (e4) {
      case 0:
        this._kernel = [[7 / 16, 1, 0], [3 / 16, -1, 1], [5 / 16, 0, 1], [1 / 16, 1, 1]];
        break;
      case 1:
        this._kernel = [[3 / 8, 1, 0], [3 / 8, 0, 1], [2 / 8, 1, 1]];
        break;
      case 2:
        this._kernel = [[8 / 42, 1, 0], [4 / 42, 2, 0], [2 / 42, -2, 1], [4 / 42, -1, 1], [8 / 42, 0, 1], [4 / 42, 1, 1], [2 / 42, 2, 1], [1 / 42, -2, 2], [2 / 42, -1, 2], [4 / 42, 0, 2], [2 / 42, 1, 2], [1 / 42, 2, 2]];
        break;
      case 3:
        this._kernel = [[1 / 8, 1, 0], [1 / 8, 2, 0], [1 / 8, -1, 1], [1 / 8, 0, 1], [1 / 8, 1, 1], [1 / 8, 0, 2]];
        break;
      case 4:
        this._kernel = [[7 / 48, 1, 0], [5 / 48, 2, 0], [3 / 48, -2, 1], [5 / 48, -1, 1], [7 / 48, 0, 1], [5 / 48, 1, 1], [3 / 48, 2, 1], [1 / 48, -2, 2], [3 / 48, -1, 2], [5 / 48, 0, 2], [3 / 48, 1, 2], [1 / 48, 2, 2]];
        break;
      case 5:
        this._kernel = [[0.25, 1, 0], [4 / 32, 2, 0], [2 / 32, -2, 1], [4 / 32, -1, 1], [0.25, 0, 1], [4 / 32, 1, 1], [2 / 32, 2, 1]];
        break;
      case 6:
        this._kernel = [[5 / 32, 1, 0], [3 / 32, 2, 0], [2 / 32, -2, 1], [4 / 32, -1, 1], [5 / 32, 0, 1], [4 / 32, 1, 1], [2 / 32, 2, 1], [2 / 32, -1, 2], [3 / 32, 0, 2], [2 / 32, 1, 2]];
        break;
      case 7:
        this._kernel = [[0.25, 1, 0], [3 / 16, 2, 0], [1 / 16, -2, 1], [2 / 16, -1, 1], [3 / 16, 0, 1], [2 / 16, 1, 1], [1 / 16, 2, 1]];
        break;
      case 8:
        this._kernel = [[0.5, 1, 0], [1 / 4, -1, 1], [1 / 4, 0, 1]];
        break;
      default:
        throw new Error(`ErrorDiffusionArray: unknown kernel = ${e4}`);
    }
  }
};
function* hilbertCurve$1(e4, t2, i2) {
  const r2 = Math.max(e4, t2), n2 = { width: e4, height: t2, level: Math.floor(Math.log(r2) / Math.log(2) + 1), callback: i2, tracker: new ProgressTracker$1(e4 * t2, 99), index: 0, x: 0, y: 0 };
  yield* walkHilbert$1(n2, 1), visit$1(n2, 0);
}
function* walkHilbert$1(e4, t2) {
  if (!(e4.level < 1)) {
    switch (e4.tracker.shouldNotify(e4.index) && (yield { progress: e4.tracker.progress }), e4.level--, t2) {
      case 2:
        yield* walkHilbert$1(e4, 1), visit$1(e4, 3), yield* walkHilbert$1(e4, 2), visit$1(e4, 4), yield* walkHilbert$1(e4, 2), visit$1(e4, 2), yield* walkHilbert$1(e4, 4);
        break;
      case 3:
        yield* walkHilbert$1(e4, 4), visit$1(e4, 2), yield* walkHilbert$1(e4, 3), visit$1(e4, 1), yield* walkHilbert$1(e4, 3), visit$1(e4, 3), yield* walkHilbert$1(e4, 1);
        break;
      case 1:
        yield* walkHilbert$1(e4, 2), visit$1(e4, 4), yield* walkHilbert$1(e4, 1), visit$1(e4, 3), yield* walkHilbert$1(e4, 1), visit$1(e4, 1), yield* walkHilbert$1(e4, 3);
        break;
      case 4:
        yield* walkHilbert$1(e4, 3), visit$1(e4, 1), yield* walkHilbert$1(e4, 4), visit$1(e4, 2), yield* walkHilbert$1(e4, 4), visit$1(e4, 4), yield* walkHilbert$1(e4, 2);
    }
    e4.level++;
  }
}
function visit$1(e4, t2) {
  switch (e4.x >= 0 && e4.x < e4.width && e4.y >= 0 && e4.y < e4.height && (e4.callback(e4.x, e4.y), e4.index++), t2) {
    case 2:
      e4.x--;
      break;
    case 3:
      e4.x++;
      break;
    case 1:
      e4.y--;
      break;
    case 4:
      e4.y++;
  }
}
var ErrorDiffusionRiemersma$1 = class extends AbstractImageQuantizer$1 {
  constructor(e4, t2 = 16, i2 = 1) {
    super(), __publicField$3(this, "_distance"), __publicField$3(this, "_weights"), __publicField$3(this, "_errorQueueSize"), this._distance = e4, this._errorQueueSize = t2, this._weights = ErrorDiffusionRiemersma$1._createWeights(i2, t2);
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = e4.getWidth(), n2 = e4.getHeight(), a2 = [];
    let o2 = 0;
    for (let e5 = 0; e5 < this._errorQueueSize; e5++) a2[e5] = { r: 0, g: 0, b: 0, a: 0 };
    yield* hilbertCurve$1(r2, n2, (e5, n3) => {
      const s2 = i2[e5 + n3 * r2];
      let { r: l2, g: u2, b: h2, a: c2 } = s2;
      for (let e6 = 0; e6 < this._errorQueueSize; e6++) {
        const t3 = this._weights[e6], i3 = a2[(e6 + o2) % this._errorQueueSize];
        l2 += i3.r * t3, u2 += i3.g * t3, h2 += i3.b * t3, c2 += i3.a * t3;
      }
      const f2 = Point$1.createByRGBA(inRange0to255Rounded$1(l2), inRange0to255Rounded$1(u2), inRange0to255Rounded$1(h2), inRange0to255Rounded$1(c2)), d = t2.getNearestColor(this._distance, f2);
      o2 = (o2 + 1) % this._errorQueueSize;
      const p2 = (o2 + this._errorQueueSize - 1) % this._errorQueueSize;
      a2[p2].r = s2.r - d.r, a2[p2].g = s2.g - d.g, a2[p2].b = s2.b - d.b, a2[p2].a = s2.a - d.a, s2.from(d);
    }), yield { pointContainer: e4, progress: 100 };
  }
  static _createWeights(e4, t2) {
    const i2 = [], r2 = Math.exp(Math.log(t2) / (t2 - 1));
    for (let n2 = 0, a2 = 1; n2 < t2; n2++) i2[n2] = (a2 + 0.5 | 0) / t2 * e4, a2 *= r2;
    return i2;
  }
}, quality_exports$1 = {};
__export$1(quality_exports$1, { ssim: () => ssim$1 });
var K1$1 = 0.01, K2$1 = 0.03;
function ssim$1(e4, t2) {
  if (e4.getHeight() !== t2.getHeight() || e4.getWidth() !== t2.getWidth()) throw new Error("Images have different sizes!");
  const i2 = (255 * K1$1) ** 2, r2 = (255 * K2$1) ** 2;
  let n2 = 0, a2 = 0;
  return iterate$1(e4, t2, (e5, t3, o2, s2) => {
    let l2 = 0, u2 = 0, h2 = 0;
    for (let i3 = 0; i3 < e5.length; i3++) u2 += (e5[i3] - o2) ** 2, h2 += (t3[i3] - s2) ** 2, l2 += (e5[i3] - o2) * (t3[i3] - s2);
    const c2 = e5.length - 1;
    u2 /= c2, h2 /= c2, l2 /= c2;
    a2 += (2 * o2 * s2 + i2) * (2 * l2 + r2) / ((o2 ** 2 + s2 ** 2 + i2) * (u2 + h2 + r2)), n2++;
  }), a2 / n2;
}
function iterate$1(e4, t2, i2) {
  const r2 = e4.getWidth(), n2 = e4.getHeight();
  for (let a2 = 0; a2 < n2; a2 += 8) for (let o2 = 0; o2 < r2; o2 += 8) {
    const s2 = Math.min(8, r2 - o2), l2 = Math.min(8, n2 - a2), u2 = calculateLumaValuesForWindow$1(e4, o2, a2, s2, l2), h2 = calculateLumaValuesForWindow$1(t2, o2, a2, s2, l2);
    i2(u2, h2, calculateAverageLuma$1(u2), calculateAverageLuma$1(h2));
  }
}
function calculateLumaValuesForWindow$1(e4, t2, i2, r2, n2) {
  const a2 = e4.getPointArray(), o2 = [];
  let s2 = 0;
  for (let l2 = i2; l2 < i2 + n2; l2++) {
    const i3 = l2 * e4.getWidth();
    for (let e5 = t2; e5 < t2 + r2; e5++) {
      const t3 = a2[i3 + e5];
      o2[s2] = 0.2126 * t3.r + 0.7152 * t3.g + 0.0722 * t3.b, s2++;
    }
  }
  return o2;
}
function calculateAverageLuma$1(e4) {
  let t2 = 0;
  for (const i2 of e4) t2 += i2;
  return t2 / e4.length;
}
var setImmediateImpl = "function" == typeof setImmediate ? setImmediate : "undefined" != typeof process && "function" == typeof (null == process ? void 0 : process.nextTick) ? (e4) => process.nextTick(e4) : (e4) => setTimeout(e4, 0);
function buildPaletteSync$1(e4, { colorDistanceFormula: t2, paletteQuantization: i2, colors: r2 } = {}) {
  const n2 = paletteQuantizationToPaletteQuantizer$1(colorDistanceFormulaToColorDistance$1(t2), i2, r2);
  return e4.forEach((e5) => n2.sample(e5)), n2.quantizeSync();
}
async function buildPalette(e4, { colorDistanceFormula: t2, paletteQuantization: i2, colors: r2, onProgress: n2 } = {}) {
  return new Promise((a2, o2) => {
    const s2 = paletteQuantizationToPaletteQuantizer$1(colorDistanceFormulaToColorDistance$1(t2), i2, r2);
    let l2;
    e4.forEach((e5) => s2.sample(e5));
    const u2 = s2.quantize(), h2 = () => {
      try {
        const e5 = u2.next();
        e5.done ? a2(l2) : (e5.value.palette && (l2 = e5.value.palette), n2 && n2(e5.value.progress), setImmediateImpl(h2));
      } catch (e5) {
        o2(e5);
      }
    };
    setImmediateImpl(h2);
  });
}
function applyPaletteSync$1(e4, t2, { colorDistanceFormula: i2, imageQuantization: r2 } = {}) {
  return imageQuantizationToImageQuantizer$1(colorDistanceFormulaToColorDistance$1(i2), r2).quantizeSync(e4, t2);
}
async function applyPalette(e4, t2, { colorDistanceFormula: i2, imageQuantization: r2, onProgress: n2 } = {}) {
  return new Promise((a2, o2) => {
    let s2;
    const l2 = imageQuantizationToImageQuantizer$1(colorDistanceFormulaToColorDistance$1(i2), r2).quantize(e4, t2), u2 = () => {
      try {
        const e5 = l2.next();
        e5.done ? a2(s2) : (e5.value.pointContainer && (s2 = e5.value.pointContainer), n2 && n2(e5.value.progress), setImmediateImpl(u2));
      } catch (e5) {
        o2(e5);
      }
    };
    setImmediateImpl(u2);
  });
}
function colorDistanceFormulaToColorDistance$1(e4 = "euclidean-bt709") {
  switch (e4) {
    case "cie94-graphic-arts":
      return new CIE94GraphicArts$1();
    case "cie94-textiles":
      return new CIE94Textiles$1();
    case "ciede2000":
      return new CIEDE2000$1();
    case "color-metric":
      return new CMetric$1();
    case "euclidean":
      return new Euclidean$1();
    case "euclidean-bt709":
      return new EuclideanBT709$1();
    case "euclidean-bt709-noalpha":
      return new EuclideanBT709NoAlpha$1();
    case "manhattan":
      return new Manhattan$1();
    case "manhattan-bt709":
      return new ManhattanBT709$1();
    case "manhattan-nommyde":
      return new ManhattanNommyde$1();
    case "pngquant":
      return new PNGQuant$1();
    default:
      throw new Error(`Unknown colorDistanceFormula ${e4}`);
  }
}
function imageQuantizationToImageQuantizer$1(e4, t2 = "floyd-steinberg") {
  switch (t2) {
    case "nearest":
      return new NearestColor$1(e4);
    case "riemersma":
      return new ErrorDiffusionRiemersma$1(e4);
    case "floyd-steinberg":
      return new ErrorDiffusionArray$1(e4, 0);
    case "false-floyd-steinberg":
      return new ErrorDiffusionArray$1(e4, 1);
    case "stucki":
      return new ErrorDiffusionArray$1(e4, 2);
    case "atkinson":
      return new ErrorDiffusionArray$1(e4, 3);
    case "jarvis":
      return new ErrorDiffusionArray$1(e4, 4);
    case "burkes":
      return new ErrorDiffusionArray$1(e4, 5);
    case "sierra":
      return new ErrorDiffusionArray$1(e4, 6);
    case "two-sierra":
      return new ErrorDiffusionArray$1(e4, 7);
    case "sierra-lite":
      return new ErrorDiffusionArray$1(e4, 8);
    default:
      throw new Error(`Unknown imageQuantization ${t2}`);
  }
}
function paletteQuantizationToPaletteQuantizer$1(e4, t2 = "wuquant", i2 = 256) {
  switch (t2) {
    case "neuquant":
      return new NeuQuant$1(e4, i2);
    case "rgbquant":
      return new RGBQuant$1(e4, i2);
    case "wuquant":
      return new WuQuant$1(e4, i2);
    case "neuquant-float":
      return new NeuQuantFloat$1(e4, i2);
    default:
      throw new Error(`Unknown paletteQuantization ${t2}`);
  }
}
var imageQ = __toCommonJS(src_exports), gifframe = {};
const BitmapImage$1 = bitmapimage;
let GifFrame$1 = class e3 extends BitmapImage$1 {
  constructor(...t2) {
    if (super(...t2), t2[0] instanceof e3) {
      const e4 = t2[0];
      this.xOffset = e4.xOffset, this.yOffset = e4.yOffset, this.disposalMethod = e4.disposalMethod, this.delayCentisecs = e4.delayCentisecs, this.interlaced = e4.interlaced;
    } else {
      const i2 = t2[t2.length - 1];
      let r2 = {};
      "object" != typeof i2 || i2 instanceof BitmapImage$1 || (r2 = i2), this.xOffset = r2.xOffset || 0, this.yOffset = r2.yOffset || 0, this.disposalMethod = void 0 !== r2.disposalMethod ? r2.disposalMethod : e3.DisposeToBackgroundColor, this.delayCentisecs = r2.delayCentisecs || 8, this.interlaced = r2.interlaced || false;
    }
  }
  getPalette() {
    const e4 = /* @__PURE__ */ new Set(), t2 = this.bitmap.data;
    let i2 = 0, r2 = false;
    for (; i2 < t2.length; ) {
      if (0 === t2[i2 + 3]) r2 = true;
      else {
        const r3 = t2.readUInt32BE(i2, true) >> 8 & 16777215;
        e4.add(r3);
      }
      i2 += 4;
    }
    const n2 = new Array(e4.size), a2 = e4.values();
    for (i2 = 0; i2 < n2.length; ++i2) n2[i2] = a2.next().value;
    n2.sort((e5, t3) => e5 - t3);
    let o2 = n2.length;
    return r2 && ++o2, { colors: n2, usesTransparency: r2, indexCount: o2 };
  }
};
var hasRequiredGifutil, hasRequiredGifcodec;
function requireGifutil() {
  return hasRequiredGifutil || (hasRequiredGifutil = 1, function(e4) {
    const t2 = require$$0, i2 = imageQ, r2 = bitmapimage, { GifFrame: n2 } = gifframe, { GifError: a2 } = gif$1, { GifCodec: o2 } = requireGifcodec(), s2 = [".jpg", ".jpeg", ".png", ".bmp"], l2 = new o2();
    function u2(e5, t3, r3, n3, a3) {
      const o3 = Array.isArray(e5) ? e5 : [e5];
      if (a3) {
        if (["FloydSteinberg", "FalseFloydSteinberg", "Stucki", "Atkinson", "Jarvis", "Burkes", "Sierra", "TwoSierra", "SierraLite"].indexOf(a3.ditherAlgorithm) < 0) throw new Error(`Invalid ditherAlgorithm '${a3.ditherAlgorithm}'`);
        void 0 === a3.serpentine && (a3.serpentine = true), void 0 === a3.minimumColorDistanceToDither && (a3.minimumColorDistanceToDither = 0), void 0 === a3.calculateErrorLikeGIMP && (a3.calculateErrorLikeGIMP = false);
      }
      const s3 = new i2.distance.Euclidean(), l3 = new i2.palette[t3](s3, r3, n3);
      let u3;
      u3 = a3 ? new i2.image.ErrorDiffusionArray(s3, i2.image.ErrorDiffusionArrayKernel[a3.ditherAlgorithm], a3.serpentine, a3.minimumColorDistanceToDither, a3.calculateErrorLikeGIMP) : new i2.image.NearestColor(s3);
      const h2 = [];
      o3.forEach((e6) => {
        const t4 = e6.bitmap.data, r4 = new ArrayBuffer(t4.length), n4 = new Uint32Array(r4);
        for (let e7 = 0, i3 = 0; e7 < t4.length; e7 += 4, ++i3) n4[i3] = t4.readUInt32LE(e7, true);
        const a4 = i2.utils.PointContainer.fromUint32Array(n4, e6.bitmap.width, e6.bitmap.height);
        l3.sample(a4), h2.push(a4);
      });
      const c2 = l3.quantizeSync();
      for (let e6 = 0; e6 < o3.length; ++e6) {
        const t4 = o3[e6].bitmap.data, i3 = u3.quantizeSync(h2[e6], c2).toUint32Array();
        for (let e7 = 0, r4 = 0; e7 < t4.length; e7 += 4, ++r4) t4.writeUInt32LE(i3[r4], e7);
      }
    }
    e4.cloneFrames = function(e5) {
      let t3 = [];
      return e5.forEach((e6) => {
        t3.push(new n2(e6));
      }), t3;
    }, e4.getColorInfo = function(e5, t3) {
      let i3 = false;
      const r3 = [];
      for (let t4 = 0; t4 < e5.length; ++t4) {
        let n4 = e5[t4].getPalette();
        if (n4.usesTransparency && (i3 = true), n4.indexCount > 256) throw new a2(`Frame ${t4} uses more than 256 color indexes`);
        r3.push(n4);
      }
      if (0 === t3) return { usesTransparency: i3, palettes: r3 };
      const n3 = /* @__PURE__ */ new Set();
      r3.forEach((e6) => {
        e6.colors.forEach((e7) => {
          n3.add(e7);
        });
      });
      let o3 = n3.size;
      if (i3 && ++o3, t3 && o3 > t3) return { usesTransparency: i3, palettes: r3 };
      const s3 = new Array(n3.size), l3 = n3.values();
      for (let e6 = 0; e6 < s3.length; ++e6) s3[e6] = l3.next().value;
      return s3.sort((e6, t4) => e6 - t4), { colors: s3, indexCount: o3, usesTransparency: i3, palettes: r3 };
    }, e4.copyAsJimp = function(t3, i3) {
      return e4.shareAsJimp(t3, new r2(i3));
    }, e4.getMaxDimensions = function(e5) {
      let t3 = 0, i3 = 0;
      return e5.forEach((e6) => {
        const r3 = e6.xOffset + e6.bitmap.width;
        r3 > t3 && (t3 = r3);
        const n3 = e6.yOffset + e6.bitmap.height;
        n3 > i3 && (i3 = n3);
      }), { maxWidth: t3, maxHeight: i3 };
    }, e4.quantizeDekker = function(e5, t3, i3) {
      u2(e5, "NeuQuantFloat", t3 = t3 || 256, 0, i3);
    }, e4.quantizeSorokin = function(e5, t3, i3, r3) {
      let n3;
      switch (t3 = t3 || 256, i3 = i3 || "min-pop") {
        case "min-pop":
          n3 = 2;
          break;
        case "top-pop":
          n3 = 1;
          break;
        default:
          throw new Error(`Invalid quantizeSorokin histogram '${i3}'`);
      }
      u2(e5, "RGBQuant", t3, n3, r3);
    }, e4.quantizeWu = function(e5, t3, i3, r3) {
      if (t3 = t3 || 256, (i3 = i3 || 5) < 1 || i3 > 8) throw new Error("Invalid quantization quality");
      u2(e5, "WuQuant", t3, i3, r3);
    }, e4.read = function(e5, i3) {
      return i3 = i3 || l2, Buffer$1.isBuffer(e5) ? i3.decodeGif(e5) : function(e6) {
        return new Promise((i4, r3) => {
          t2.readFile(e6, (e7, t3) => e7 ? r3(e7) : i4(t3));
        });
      }(e5).then((e6) => i3.decodeGif(e6));
    }, e4.shareAsJimp = function(e5, t3) {
      const i3 = new e5(t3.bitmap.width, t3.bitmap.height, 0);
      return i3.bitmap.data = t3.bitmap.data, i3;
    }, e4.write = function(e5, i3, r3, n3) {
      n3 = n3 || l2;
      const a3 = e5.match(/\.[a-zA-Z]+$/);
      if (null !== a3 && s2.includes(a3[0].toLowerCase())) throw new Error(`GIF '${e5}' has an unexpected suffix`);
      return n3.encodeGif(i3, r3).then((i4) => function(e6, i5) {
        return new Promise((r4, n4) => {
          t2.writeFile(e6, i5, (e7) => e7 ? n4(e7) : r4());
        });
      }(e5, i4.buffer).then(() => i4));
    };
  }(gifutil)), gifutil;
}
function requireGifcodec() {
  if (hasRequiredGifcodec) return gifcodec;
  hasRequiredGifcodec = 1;
  const e4 = omggif, { Gif: t2, GifError: i2 } = gif$1;
  function r2() {
    const e5 = requireGifutil();
    return r2 = function() {
      return e5;
    }, e5;
  }
  const { GifFrame: n2 } = gifframe;
  function a2(e5, t3) {
    const i3 = e5.indexOf(t3);
    return -1 === i3 ? null : i3;
  }
  function o2(e5, t3) {
    for (var i3, r3 = 0, n3 = e5.length - 1; r3 <= n3; ) if (e5[i3 = Math.floor((r3 + n3) / 2)] > t3) n3 = i3 - 1;
    else {
      if (!(e5[i3] < t3)) return i3;
      r3 = i3 + 1;
    }
    return null;
  }
  function s2(e5) {
    const t3 = e5.colors;
    e5.usesTransparency && t3.push(0);
    const i3 = t3.length;
    let r3 = 2;
    for (; i3 > r3; ) r3 <<= 1;
    t3.length = r3, t3.fill(0, i3);
  }
  function l2(e5, t3) {
    let i3 = e5.bitmap.width * e5.bitmap.height;
    return i3 = Math.ceil(i3 * t3 / 8), i3 += Math.ceil(i3 / 255), 100 + i3 + 768;
  }
  function u2(e5) {
    let t3 = e5.indexCount, i3 = 0;
    for (--t3; t3; ) ++i3, t3 >>= 1;
    return i3 > 0 ? i3 : 1;
  }
  function h2(e5, t3, r3, n3, l3) {
    if (r3.interlaced) throw new i2("writing interlaced GIFs is not supported");
    const u3 = function(e6, t4, r4) {
      const n4 = r4.colors, s3 = n4.length <= 8 ? a2 : o2, l4 = t4.bitmap.data, u4 = new Buffer$1(l4.length / 4);
      let h4 = n4.length, c2 = 0, f2 = 0;
      for (; c2 < l4.length; ) {
        if (0 !== l4[c2 + 3]) {
          const e7 = l4.readUInt32BE(c2, true) >> 8 & 16777215;
          u4[f2] = s3(n4, e7);
        } else u4[f2] = h4;
        c2 += 4, ++f2;
      }
      if (r4.usesTransparency) {
        if (256 === h4) throw new i2(`Frame ${e6} already has 256 colorsand so can't use transparency`);
      } else h4 = null;
      return { buffer: u4, transparentIndex: h4 };
    }(t3, r3, n3), h3 = { delay: r3.delayCentisecs, disposal: r3.disposalMethod, transparent: u3.transparentIndex };
    l3 && (s2(n3), h3.palette = n3.colors);
    try {
      let t4, i3 = e5.getOutputBuffer(), n4 = e5.getOutputBufferPosition(), a3 = true;
      for (; a3; ) if (t4 = e5.addFrame(r3.xOffset, r3.yOffset, r3.bitmap.width, r3.bitmap.height, u3.buffer, h3), a3 = false, t4 >= i3.length - 1) {
        const t5 = new Buffer$1(1.5 * i3.length);
        i3.copy(t5), e5.setOutputBuffer(t5), e5.setOutputBufferPosition(n4), i3 = t5, a3 = true;
      }
      return i3;
    } catch (e6) {
      throw new i2(e6);
    }
  }
  return gifcodec.GifCodec = class {
    constructor(e5 = {}) {
      this._transparentRGB = null, "number" == typeof e5.transparentRGB && 0 !== e5.transparentRGB && (this._transparentRGBA = 256 * e5.transparentRGB), this._testInitialBufferSize = 0;
    }
    decodeGif(r3) {
      try {
        let n3;
        try {
          n3 = new e4.GifReader(r3);
        } catch (e5) {
          throw new i2(e5);
        }
        const a3 = n3.numFrames(), o3 = [], s3 = { width: n3.width, height: n3.height, loops: n3.loopCount(), usesTransparency: false };
        for (let e5 = 0; e5 < a3; ++e5) {
          const t3 = this._decodeFrame(n3, e5, s3.usesTransparency);
          o3.push(t3.frame), t3.usesTransparency && (s3.usesTransparency = true);
        }
        return Promise.resolve(new t2(r3, o3, s3));
      } catch (e5) {
        return Promise.reject(e5);
      }
    }
    encodeGif(e5, n3 = {}) {
      try {
        if (null === e5 || 0 === e5.length) throw new i2("there are no frames");
        const a3 = r2().getMaxDimensions(e5);
        return (n3 = Object.assign({}, n3)).width = a3.maxWidth, n3.height = a3.maxHeight, void 0 === n3.loops && (n3.loops = 0), n3.colorScope = n3.colorScope || t2.GlobalColorsPreferred, Promise.resolve(this._encodeGif(e5, n3));
      } catch (e6) {
        return Promise.reject(e6);
      }
    }
    _decodeFrame(e5, t3, r3) {
      let a3, o3;
      try {
        if (a3 = e5.frameInfo(t3), o3 = new Buffer$1(e5.width * e5.height * 4), e5.decodeAndBlitFrameRGBA(t3, o3), a3.width !== e5.width || a3.height !== e5.height) {
          if (a3.y && (o3 = o3.slice(a3.y * e5.width * 4)), e5.width > a3.width) for (let t4 = 0; t4 < a3.height; ++t4) o3.copy(o3, t4 * a3.width * 4, 4 * (a3.x + t4 * e5.width), 4 * (a3.x + t4 * e5.width) + 4 * a3.width);
          o3 = o3.slice(0, a3.width * a3.height * 4);
        }
      } catch (e6) {
        throw new i2(e6);
      }
      let s3 = false;
      if (null === this._transparentRGBA) {
        if (!r3) for (let e6 = 3; e6 < o3.length; e6 += 4) 0 === o3[e6] && (s3 = true, e6 = o3.length);
      } else for (let e6 = 3; e6 < o3.length; e6 += 4) 0 === o3[e6] && (o3.writeUInt32BE(this._transparentRGBA, e6 - 3), s3 = true);
      return { frame: new n2(a3.width, a3.height, o3, { xOffset: a3.x, yOffset: a3.y, disposalMethod: a3.disposal, interlaced: a3.interlaced, delayCentisecs: a3.delay }), usesTransparency: s3 };
    }
    _encodeGif(n3, a3) {
      let o3;
      if (a3.colorScope === t2.LocalColorsOnly) o3 = r2().getColorInfo(n3, 0);
      else if (o3 = r2().getColorInfo(n3, 256), !o3.colors) {
        if (a3.colorScope === t2.GlobalColorsOnly) throw new i2("Too many color indexes for global color table");
        a3.colorScope = t2.LocalColorsOnly;
      }
      a3.usesTransparency = o3.usesTransparency;
      const l3 = o3.palettes;
      if (a3.colorScope === t2.LocalColorsOnly) {
        return function(r3, n4, a4, o4) {
          const s3 = { loop: n4.loops };
          let l4, u3 = new Buffer$1(a4);
          try {
            l4 = new e4.GifWriter(u3, n4.width, n4.height, s3);
          } catch (e5) {
            throw new i2(e5);
          }
          for (let e5 = 0; e5 < r3.length; ++e5) u3 = h2(l4, e5, r3[e5], o4[e5], true);
          return new t2(u3.slice(0, l4.end()), r3, n4);
        }(n3, a3, 2e3, l3);
      }
      return function(r3, n4, a4, o4) {
        const l4 = { colors: o4.colors.slice(), usesTransparency: o4.usesTransparency };
        s2(l4);
        const u3 = { palette: l4.colors, loop: n4.loops };
        let c2, f2 = new Buffer$1(a4);
        try {
          c2 = new e4.GifWriter(f2, n4.width, n4.height, u3);
        } catch (e5) {
          throw new i2(e5);
        }
        for (let e5 = 0; e5 < r3.length; ++e5) f2 = h2(c2, e5, r3[e5], o4, false);
        return new t2(f2.slice(0, c2.end()), r3, n4);
      }(n3, a3, 2e3, o3);
    }
    _getSizeEstimateGlobal(e5, t3) {
      if (this._testInitialBufferSize > 0) return this._testInitialBufferSize;
      let i3 = 968;
      const r3 = u2(e5);
      return t3.forEach((e6) => {
        i3 += l2(e6, r3);
      }), i3;
    }
    _getSizeEstimateLocal(e5, t3) {
      if (this._testInitialBufferSize > 0) return this._testInitialBufferSize;
      let i3 = 200;
      for (let r3 = 0; r3 < t3.length; ++r3) {
        const n3 = u2(e5[r3]);
        i3 += l2(t3[r3], n3);
      }
      return i3;
    }
  }, gifcodec;
}
GifFrame$1.DisposeToAnything = 0, GifFrame$1.DisposeNothing = 1, GifFrame$1.DisposeToBackgroundColor = 2, GifFrame$1.DisposeToPrevious = 3, gifframe.GifFrame = GifFrame$1;
const BitmapImage = bitmapimage, { GifCodec } = requireGifcodec(), { GifFrame } = gifframe, GifUtil = requireGifutil();
var src = { BitmapImage, GifCodec, GifFrame, GifUtil };
function gif() {
  return { mime: "image/gif", encode: async (e4) => {
    const t2 = new src.BitmapImage(e4);
    src.GifUtil.quantizeDekker(t2, 256);
    const i2 = new src.GifFrame(e4), r2 = new src.GifCodec();
    return (await r2.encodeGif([i2], {})).buffer;
  }, decode: (e4) => {
    const t2 = new omggif.GifReader(e4), i2 = Buffer$1.alloc(t2.width * t2.height * 4);
    return t2.decodeAndBlitFrameRGBA(0, i2), { data: i2, width: t2.width, height: t2.height };
  } };
}
var encoder = { exports: {} };
!function(e4) {
  function t2(e5) {
    var t3, i2, r2, n2, a2, o2 = Math.floor, s2 = new Array(64), l2 = new Array(64), u2 = new Array(64), h2 = new Array(64), c2 = new Array(65535), f2 = new Array(65535), d = new Array(64), p2 = new Array(64), m = [], _2 = 0, g = 7, b2 = new Array(64), y2 = new Array(64), w = new Array(64), v2 = new Array(256), x2 = new Array(2048), E2 = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63], k2 = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], S2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], A2 = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 125], I = [1, 2, 3, 0, 4, 17, 5, 18, 33, 49, 65, 6, 19, 81, 97, 7, 34, 113, 20, 50, 129, 145, 161, 8, 35, 66, 177, 193, 21, 82, 209, 240, 36, 51, 98, 114, 130, 9, 10, 22, 23, 24, 25, 26, 37, 38, 39, 40, 41, 42, 52, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250], M2 = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], T2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], P = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 119], B2 = [0, 1, 2, 3, 17, 4, 5, 33, 49, 6, 18, 65, 81, 7, 97, 113, 19, 34, 50, 129, 8, 20, 66, 145, 161, 177, 193, 9, 35, 51, 82, 240, 21, 98, 114, 209, 10, 22, 36, 52, 225, 37, 241, 23, 24, 25, 26, 38, 39, 40, 41, 42, 53, 54, 55, 56, 57, 58, 67, 68, 69, 70, 71, 72, 73, 74, 83, 84, 85, 86, 87, 88, 89, 90, 99, 100, 101, 102, 103, 104, 105, 106, 115, 116, 117, 118, 119, 120, 121, 122, 130, 131, 132, 133, 134, 135, 136, 137, 138, 146, 147, 148, 149, 150, 151, 152, 153, 154, 162, 163, 164, 165, 166, 167, 168, 169, 170, 178, 179, 180, 181, 182, 183, 184, 185, 186, 194, 195, 196, 197, 198, 199, 200, 201, 202, 210, 211, 212, 213, 214, 215, 216, 217, 218, 226, 227, 228, 229, 230, 231, 232, 233, 234, 242, 243, 244, 245, 246, 247, 248, 249, 250];
    function C2(e6, t4) {
      for (var i3 = 0, r3 = 0, n3 = new Array(), a3 = 1; a3 <= 16; a3++) {
        for (var o3 = 1; o3 <= e6[a3]; o3++) n3[t4[r3]] = [], n3[t4[r3]][0] = i3, n3[t4[r3]][1] = a3, r3++, i3++;
        i3 *= 2;
      }
      return n3;
    }
    function R2(e6) {
      for (var t4 = e6[0], i3 = e6[1] - 1; i3 >= 0; ) t4 & 1 << i3 && (_2 |= 1 << g), i3--, --g < 0 && (255 == _2 ? (z2(255), z2(0)) : z2(_2), g = 7, _2 = 0);
    }
    function z2(e6) {
      m.push(e6);
    }
    function F(e6) {
      z2(e6 >> 8 & 255), z2(255 & e6);
    }
    function N2(e6, t4, i3, r3, n3) {
      for (var a3, o3 = n3[0], s3 = n3[240], l3 = function(e7, t5) {
        var i4, r4, n4, a4, o4, s4, l4, u4, h4, c3, f3 = 0;
        for (h4 = 0; h4 < 8; ++h4) {
          i4 = e7[f3], r4 = e7[f3 + 1], n4 = e7[f3 + 2], a4 = e7[f3 + 3], o4 = e7[f3 + 4], s4 = e7[f3 + 5], l4 = e7[f3 + 6];
          var p3 = i4 + (u4 = e7[f3 + 7]), m3 = i4 - u4, _4 = r4 + l4, g3 = r4 - l4, b4 = n4 + s4, y4 = n4 - s4, w3 = a4 + o4, v3 = a4 - o4, x3 = p3 + w3, E3 = p3 - w3, k3 = _4 + b4, S3 = _4 - b4;
          e7[f3] = x3 + k3, e7[f3 + 4] = x3 - k3;
          var A3 = 0.707106781 * (S3 + E3);
          e7[f3 + 2] = E3 + A3, e7[f3 + 6] = E3 - A3;
          var I2 = 0.382683433 * ((x3 = v3 + y4) - (S3 = g3 + m3)), M3 = 0.5411961 * x3 + I2, T3 = 1.306562965 * S3 + I2, P2 = 0.707106781 * (k3 = y4 + g3), B3 = m3 + P2, C3 = m3 - P2;
          e7[f3 + 5] = C3 + M3, e7[f3 + 3] = C3 - M3, e7[f3 + 1] = B3 + T3, e7[f3 + 7] = B3 - T3, f3 += 8;
        }
        for (f3 = 0, h4 = 0; h4 < 8; ++h4) {
          i4 = e7[f3], r4 = e7[f3 + 8], n4 = e7[f3 + 16], a4 = e7[f3 + 24], o4 = e7[f3 + 32], s4 = e7[f3 + 40], l4 = e7[f3 + 48];
          var R3 = i4 + (u4 = e7[f3 + 56]), z3 = i4 - u4, F2 = r4 + l4, N3 = r4 - l4, O3 = n4 + s4, D = n4 - s4, $ = a4 + o4, L2 = a4 - o4, U = R3 + $, Z = R3 - $, j = F2 + O3, G2 = F2 - O3;
          e7[f3] = U + j, e7[f3 + 32] = U - j;
          var H = 0.707106781 * (G2 + Z);
          e7[f3 + 16] = Z + H, e7[f3 + 48] = Z - H;
          var Q = 0.382683433 * ((U = L2 + D) - (G2 = N3 + z3)), W = 0.5411961 * U + Q, q = 1.306562965 * G2 + Q, V = 0.707106781 * (j = D + N3), Y2 = z3 + V, K = z3 - V;
          e7[f3 + 40] = K + W, e7[f3 + 24] = K - W, e7[f3 + 8] = Y2 + q, e7[f3 + 56] = Y2 - q, f3++;
        }
        for (h4 = 0; h4 < 64; ++h4) c3 = e7[h4] * t5[h4], d[h4] = c3 > 0 ? c3 + 0.5 | 0 : c3 - 0.5 | 0;
        return d;
      }(e6, t4), u3 = 0; u3 < 64; ++u3) p2[E2[u3]] = l3[u3];
      var h3 = p2[0] - i3;
      i3 = p2[0], 0 == h3 ? R2(r3[0]) : (R2(r3[f2[a3 = 32767 + h3]]), R2(c2[a3]));
      for (var m2 = 63; m2 > 0 && 0 == p2[m2]; m2--) ;
      if (0 == m2) return R2(o3), i3;
      for (var _3, g2 = 1; g2 <= m2; ) {
        for (var b3 = g2; 0 == p2[g2] && g2 <= m2; ++g2) ;
        var y3 = g2 - b3;
        if (y3 >= 16) {
          _3 = y3 >> 4;
          for (var w2 = 1; w2 <= _3; ++w2) R2(s3);
          y3 &= 15;
        }
        a3 = 32767 + p2[g2], R2(n3[(y3 << 4) + f2[a3]]), R2(c2[a3]), g2++;
      }
      return 63 != m2 && R2(o3), i3;
    }
    function O2(e6) {
      if (e6 <= 0 && (e6 = 1), e6 > 100 && (e6 = 100), a2 != e6) {
        (function(e7) {
          for (var t4 = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99], i3 = 0; i3 < 64; i3++) {
            var r3 = o2((t4[i3] * e7 + 50) / 100);
            r3 < 1 ? r3 = 1 : r3 > 255 && (r3 = 255), s2[E2[i3]] = r3;
          }
          for (var n3 = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99], a3 = 0; a3 < 64; a3++) {
            var c3 = o2((n3[a3] * e7 + 50) / 100);
            c3 < 1 ? c3 = 1 : c3 > 255 && (c3 = 255), l2[E2[a3]] = c3;
          }
          for (var f3 = [1, 1.387039845, 1.306562965, 1.175875602, 1, 0.785694958, 0.5411961, 0.275899379], d2 = 0, p3 = 0; p3 < 8; p3++) for (var m2 = 0; m2 < 8; m2++) u2[d2] = 1 / (s2[E2[d2]] * f3[p3] * f3[m2] * 8), h2[d2] = 1 / (l2[E2[d2]] * f3[p3] * f3[m2] * 8), d2++;
        })(e6 < 50 ? Math.floor(5e3 / e6) : Math.floor(200 - 2 * e6)), a2 = e6;
      }
    }
    this.encode = function(e6, a3) {
      var o3;
      (/* @__PURE__ */ new Date()).getTime(), a3 && O2(a3), m = new Array(), _2 = 0, g = 7, F(65496), F(65504), F(16), z2(74), z2(70), z2(73), z2(70), z2(0), z2(1), z2(1), z2(0), F(1), F(1), z2(0), z2(0), void 0 !== (o3 = e6.comments) && o3.constructor === Array && o3.forEach((e7) => {
        if ("string" == typeof e7) {
          F(65534);
          var t4, i3 = e7.length;
          for (F(i3 + 2), t4 = 0; t4 < i3; t4++) z2(e7.charCodeAt(t4));
        }
      }), function(e7) {
        if (e7) {
          F(65505), 69 === e7[0] && 120 === e7[1] && 105 === e7[2] && 102 === e7[3] ? F(e7.length + 2) : (F(e7.length + 5 + 2), z2(69), z2(120), z2(105), z2(102), z2(0));
          for (var t4 = 0; t4 < e7.length; t4++) z2(e7[t4]);
        }
      }(e6.exifBuffer), function() {
        F(65499), F(132), z2(0);
        for (var e7 = 0; e7 < 64; e7++) z2(s2[e7]);
        z2(1);
        for (var t4 = 0; t4 < 64; t4++) z2(l2[t4]);
      }(), function(e7, t4) {
        F(65472), F(17), z2(8), F(t4), F(e7), z2(3), z2(1), z2(17), z2(0), z2(2), z2(17), z2(1), z2(3), z2(17), z2(1);
      }(e6.width, e6.height), function() {
        F(65476), F(418), z2(0);
        for (var e7 = 0; e7 < 16; e7++) z2(k2[e7 + 1]);
        for (var t4 = 0; t4 <= 11; t4++) z2(S2[t4]);
        z2(16);
        for (var i3 = 0; i3 < 16; i3++) z2(A2[i3 + 1]);
        for (var r3 = 0; r3 <= 161; r3++) z2(I[r3]);
        z2(1);
        for (var n3 = 0; n3 < 16; n3++) z2(M2[n3 + 1]);
        for (var a4 = 0; a4 <= 11; a4++) z2(T2[a4]);
        z2(17);
        for (var o4 = 0; o4 < 16; o4++) z2(P[o4 + 1]);
        for (var s3 = 0; s3 <= 161; s3++) z2(B2[s3]);
      }(), F(65498), F(12), z2(3), z2(1), z2(0), z2(2), z2(17), z2(3), z2(17), z2(0), z2(63), z2(0);
      var c3 = 0, f3 = 0, d2 = 0;
      _2 = 0, g = 7, this.encode.displayName = "_encode_";
      for (var p3, v3, E3, C3, D, $, L2, U, Z, j = e6.data, G2 = e6.width, H = e6.height, Q = 4 * G2, W = 0; W < H; ) {
        for (p3 = 0; p3 < Q; ) {
          for ($ = D = Q * W + p3, L2 = -1, U = 0, Z = 0; Z < 64; Z++) $ = D + (U = Z >> 3) * Q + (L2 = 4 * (7 & Z)), W + U >= H && ($ -= Q * (W + 1 + U - H)), p3 + L2 >= Q && ($ -= p3 + L2 - Q + 4), v3 = j[$++], E3 = j[$++], C3 = j[$++], b2[Z] = (x2[v3] + x2[E3 + 256 | 0] + x2[C3 + 512 | 0] >> 16) - 128, y2[Z] = (x2[v3 + 768 | 0] + x2[E3 + 1024 | 0] + x2[C3 + 1280 | 0] >> 16) - 128, w[Z] = (x2[v3 + 1280 | 0] + x2[E3 + 1536 | 0] + x2[C3 + 1792 | 0] >> 16) - 128;
          c3 = N2(b2, u2, c3, t3, r2), f3 = N2(y2, h2, f3, i2, n2), d2 = N2(w, h2, d2, i2, n2), p3 += 32;
        }
        W += 8;
      }
      if (g >= 0) {
        var q = [];
        q[1] = g + 1, q[0] = (1 << g + 1) - 1, R2(q);
      }
      return F(65497), Buffer$1.from(m);
    }, (/* @__PURE__ */ new Date()).getTime(), e5 || (e5 = 50), function() {
      for (var e6 = String.fromCharCode, t4 = 0; t4 < 256; t4++) v2[t4] = e6(t4);
    }(), t3 = C2(k2, S2), i2 = C2(M2, T2), r2 = C2(A2, I), n2 = C2(P, B2), function() {
      for (var e6 = 1, t4 = 2, i3 = 1; i3 <= 15; i3++) {
        for (var r3 = e6; r3 < t4; r3++) f2[32767 + r3] = i3, c2[32767 + r3] = [], c2[32767 + r3][1] = i3, c2[32767 + r3][0] = r3;
        for (var n3 = -(t4 - 1); n3 <= -e6; n3++) f2[32767 + n3] = i3, c2[32767 + n3] = [], c2[32767 + n3][1] = i3, c2[32767 + n3][0] = t4 - 1 + n3;
        e6 <<= 1, t4 <<= 1;
      }
    }(), function() {
      for (var e6 = 0; e6 < 256; e6++) x2[e6] = 19595 * e6, x2[e6 + 256 | 0] = 38470 * e6, x2[e6 + 512 | 0] = 7471 * e6 + 32768, x2[e6 + 768 | 0] = -11059 * e6, x2[e6 + 1024 | 0] = -21709 * e6, x2[e6 + 1280 | 0] = 32768 * e6 + 8421375, x2[e6 + 1536 | 0] = -27439 * e6, x2[e6 + 1792 | 0] = -5329 * e6;
    }(), O2(e5), (/* @__PURE__ */ new Date()).getTime();
  }
  encoder.exports = function(e5, i2) {
    void 0 === i2 && (i2 = 50);
    var r2 = new t2(i2), n2 = r2.encode(e5, i2);
    return { data: n2, width: e5.width, height: e5.height };
  };
}();
var encoderExports = encoder.exports, decoder = { exports: {} }, module$1, JpegImage;
module$1 = decoder, JpegImage = function() {
  var e4 = new Int32Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t2 = 4017, i2 = 799, r2 = 3406, n2 = 2276, a2 = 1567, o2 = 3784, s2 = 5793, l2 = 2896;
  function u2() {
  }
  function h2(e5, t3) {
    for (var i3, r3, n3 = 0, a3 = [], o3 = 16; o3 > 0 && !e5[o3 - 1]; ) o3--;
    a3.push({ children: [], index: 0 });
    var s3, l3 = a3[0];
    for (i3 = 0; i3 < o3; i3++) {
      for (r3 = 0; r3 < e5[i3]; r3++) {
        for ((l3 = a3.pop()).children[l3.index] = t3[n3]; l3.index > 0; ) {
          if (0 === a3.length) throw new Error("Could not recreate Huffman Table");
          l3 = a3.pop();
        }
        for (l3.index++, a3.push(l3); a3.length <= i3; ) a3.push(s3 = { children: [], index: 0 }), l3.children[l3.index] = s3.children, l3 = s3;
        n3++;
      }
      i3 + 1 < o3 && (a3.push(s3 = { children: [], index: 0 }), l3.children[l3.index] = s3.children, l3 = s3);
    }
    return a3[0].children;
  }
  function c2(t3, i3, r3, n3, a3, o3, s3, l3, u3, h3) {
    r3.precision, r3.samplesPerLine, r3.scanLines;
    var c3 = r3.mcusPerLine, f3 = r3.progressive;
    r3.maxH, r3.maxV;
    var d2 = i3, p3 = 0, m2 = 0;
    function _3() {
      if (m2 > 0) return m2--, p3 >> m2 & 1;
      if (255 == (p3 = t3[i3++])) {
        var e5 = t3[i3++];
        if (e5) throw new Error("unexpected marker: " + (p3 << 8 | e5).toString(16));
      }
      return m2 = 7, p3 >>> 7;
    }
    function g(e5) {
      for (var t4, i4 = e5; null !== (t4 = _3()); ) {
        if ("number" == typeof (i4 = i4[t4])) return i4;
        if ("object" != typeof i4) throw new Error("invalid huffman sequence");
      }
      return null;
    }
    function b2(e5) {
      for (var t4 = 0; e5 > 0; ) {
        var i4 = _3();
        if (null === i4) return;
        t4 = t4 << 1 | i4, e5--;
      }
      return t4;
    }
    function y2(e5) {
      var t4 = b2(e5);
      return t4 >= 1 << e5 - 1 ? t4 : t4 + (-1 << e5) + 1;
    }
    var w, v2 = 0, x2 = 0;
    function E2(e5, t4, i4, r4, n4) {
      var a4 = i4 % c3, o4 = (i4 / c3 | 0) * e5.v + r4, s4 = a4 * e5.h + n4;
      void 0 === e5.blocks[o4] && h3.tolerantDecoding || t4(e5, e5.blocks[o4][s4]);
    }
    function k2(e5, t4, i4) {
      var r4 = i4 / e5.blocksPerLine | 0, n4 = i4 % e5.blocksPerLine;
      void 0 === e5.blocks[r4] && h3.tolerantDecoding || t4(e5, e5.blocks[r4][n4]);
    }
    var S2, A2, I, M2, T2, P, B2 = n3.length;
    P = f3 ? 0 === o3 ? 0 === l3 ? function(e5, t4) {
      var i4 = g(e5.huffmanTableDC), r4 = 0 === i4 ? 0 : y2(i4) << u3;
      t4[0] = e5.pred += r4;
    } : function(e5, t4) {
      t4[0] |= _3() << u3;
    } : 0 === l3 ? function(t4, i4) {
      if (v2 > 0) v2--;
      else for (var r4 = o3, n4 = s3; r4 <= n4; ) {
        var a4 = g(t4.huffmanTableAC), l4 = 15 & a4, h4 = a4 >> 4;
        if (0 !== l4) i4[e4[r4 += h4]] = y2(l4) * (1 << u3), r4++;
        else {
          if (h4 < 15) {
            v2 = b2(h4) + (1 << h4) - 1;
            break;
          }
          r4 += 16;
        }
      }
    } : function(t4, i4) {
      for (var r4 = o3, n4 = s3, a4 = 0; r4 <= n4; ) {
        var l4 = e4[r4], h4 = i4[l4] < 0 ? -1 : 1;
        switch (x2) {
          case 0:
            var c4 = g(t4.huffmanTableAC), f4 = 15 & c4;
            if (a4 = c4 >> 4, 0 === f4) a4 < 15 ? (v2 = b2(a4) + (1 << a4), x2 = 4) : (a4 = 16, x2 = 1);
            else {
              if (1 !== f4) throw new Error("invalid ACn encoding");
              w = y2(f4), x2 = a4 ? 2 : 3;
            }
            continue;
          case 1:
          case 2:
            i4[l4] ? i4[l4] += (_3() << u3) * h4 : 0 == --a4 && (x2 = 2 == x2 ? 3 : 0);
            break;
          case 3:
            i4[l4] ? i4[l4] += (_3() << u3) * h4 : (i4[l4] = w << u3, x2 = 0);
            break;
          case 4:
            i4[l4] && (i4[l4] += (_3() << u3) * h4);
        }
        r4++;
      }
      4 === x2 && 0 == --v2 && (x2 = 0);
    } : function(t4, i4) {
      var r4 = g(t4.huffmanTableDC), n4 = 0 === r4 ? 0 : y2(r4);
      i4[0] = t4.pred += n4;
      for (var a4 = 1; a4 < 64; ) {
        var o4 = g(t4.huffmanTableAC), s4 = 15 & o4, l4 = o4 >> 4;
        if (0 !== s4) i4[e4[a4 += l4]] = y2(s4), a4++;
        else {
          if (l4 < 15) break;
          a4 += 16;
        }
      }
    };
    var C2, R2, z2, F, N2 = 0;
    for (R2 = 1 == B2 ? n3[0].blocksPerLine * n3[0].blocksPerColumn : c3 * r3.mcusPerColumn, a3 || (a3 = R2); N2 < R2; ) {
      for (A2 = 0; A2 < B2; A2++) n3[A2].pred = 0;
      if (v2 = 0, 1 == B2) for (S2 = n3[0], T2 = 0; T2 < a3; T2++) k2(S2, P, N2), N2++;
      else for (T2 = 0; T2 < a3; T2++) {
        for (A2 = 0; A2 < B2; A2++) for (z2 = (S2 = n3[A2]).h, F = S2.v, I = 0; I < F; I++) for (M2 = 0; M2 < z2; M2++) E2(S2, P, N2, I, M2);
        if (++N2 === R2) break;
      }
      if (N2 === R2) do {
        if (255 === t3[i3] && 0 !== t3[i3 + 1]) break;
        i3 += 1;
      } while (i3 < t3.length - 2);
      if (m2 = 0, (C2 = t3[i3] << 8 | t3[i3 + 1]) < 65280) throw new Error("marker was not found");
      if (!(C2 >= 65488 && C2 <= 65495)) break;
      i3 += 2;
    }
    return i3 - d2;
  }
  function f2(e5, u3) {
    var h3, c3, f3 = [], d2 = u3.blocksPerLine, p3 = u3.blocksPerColumn, m2 = d2 << 3, g = new Int32Array(64), b2 = new Uint8Array(64);
    function y2(e6, h4, c4) {
      var f4, d3, p4, m3, _3, g2, b3, y3, w2, v3, x3 = u3.quantizationTable, E3 = c4;
      for (v3 = 0; v3 < 64; v3++) E3[v3] = e6[v3] * x3[v3];
      for (v3 = 0; v3 < 8; ++v3) {
        var k3 = 8 * v3;
        0 != E3[1 + k3] || 0 != E3[2 + k3] || 0 != E3[3 + k3] || 0 != E3[4 + k3] || 0 != E3[5 + k3] || 0 != E3[6 + k3] || 0 != E3[7 + k3] ? (f4 = s2 * E3[0 + k3] + 128 >> 8, d3 = s2 * E3[4 + k3] + 128 >> 8, p4 = E3[2 + k3], m3 = E3[6 + k3], _3 = l2 * (E3[1 + k3] - E3[7 + k3]) + 128 >> 8, y3 = l2 * (E3[1 + k3] + E3[7 + k3]) + 128 >> 8, g2 = E3[3 + k3] << 4, b3 = E3[5 + k3] << 4, w2 = f4 - d3 + 1 >> 1, f4 = f4 + d3 + 1 >> 1, d3 = w2, w2 = p4 * o2 + m3 * a2 + 128 >> 8, p4 = p4 * a2 - m3 * o2 + 128 >> 8, m3 = w2, w2 = _3 - b3 + 1 >> 1, _3 = _3 + b3 + 1 >> 1, b3 = w2, w2 = y3 + g2 + 1 >> 1, g2 = y3 - g2 + 1 >> 1, y3 = w2, w2 = f4 - m3 + 1 >> 1, f4 = f4 + m3 + 1 >> 1, m3 = w2, w2 = d3 - p4 + 1 >> 1, d3 = d3 + p4 + 1 >> 1, p4 = w2, w2 = _3 * n2 + y3 * r2 + 2048 >> 12, _3 = _3 * r2 - y3 * n2 + 2048 >> 12, y3 = w2, w2 = g2 * i2 + b3 * t2 + 2048 >> 12, g2 = g2 * t2 - b3 * i2 + 2048 >> 12, b3 = w2, E3[0 + k3] = f4 + y3, E3[7 + k3] = f4 - y3, E3[1 + k3] = d3 + b3, E3[6 + k3] = d3 - b3, E3[2 + k3] = p4 + g2, E3[5 + k3] = p4 - g2, E3[3 + k3] = m3 + _3, E3[4 + k3] = m3 - _3) : (w2 = s2 * E3[0 + k3] + 512 >> 10, E3[0 + k3] = w2, E3[1 + k3] = w2, E3[2 + k3] = w2, E3[3 + k3] = w2, E3[4 + k3] = w2, E3[5 + k3] = w2, E3[6 + k3] = w2, E3[7 + k3] = w2);
      }
      for (v3 = 0; v3 < 8; ++v3) {
        var S3 = v3;
        0 != E3[8 + S3] || 0 != E3[16 + S3] || 0 != E3[24 + S3] || 0 != E3[32 + S3] || 0 != E3[40 + S3] || 0 != E3[48 + S3] || 0 != E3[56 + S3] ? (f4 = s2 * E3[0 + S3] + 2048 >> 12, d3 = s2 * E3[32 + S3] + 2048 >> 12, p4 = E3[16 + S3], m3 = E3[48 + S3], _3 = l2 * (E3[8 + S3] - E3[56 + S3]) + 2048 >> 12, y3 = l2 * (E3[8 + S3] + E3[56 + S3]) + 2048 >> 12, g2 = E3[24 + S3], b3 = E3[40 + S3], w2 = f4 - d3 + 1 >> 1, f4 = f4 + d3 + 1 >> 1, d3 = w2, w2 = p4 * o2 + m3 * a2 + 2048 >> 12, p4 = p4 * a2 - m3 * o2 + 2048 >> 12, m3 = w2, w2 = _3 - b3 + 1 >> 1, _3 = _3 + b3 + 1 >> 1, b3 = w2, w2 = y3 + g2 + 1 >> 1, g2 = y3 - g2 + 1 >> 1, y3 = w2, w2 = f4 - m3 + 1 >> 1, f4 = f4 + m3 + 1 >> 1, m3 = w2, w2 = d3 - p4 + 1 >> 1, d3 = d3 + p4 + 1 >> 1, p4 = w2, w2 = _3 * n2 + y3 * r2 + 2048 >> 12, _3 = _3 * r2 - y3 * n2 + 2048 >> 12, y3 = w2, w2 = g2 * i2 + b3 * t2 + 2048 >> 12, g2 = g2 * t2 - b3 * i2 + 2048 >> 12, b3 = w2, E3[0 + S3] = f4 + y3, E3[56 + S3] = f4 - y3, E3[8 + S3] = d3 + b3, E3[48 + S3] = d3 - b3, E3[16 + S3] = p4 + g2, E3[40 + S3] = p4 - g2, E3[24 + S3] = m3 + _3, E3[32 + S3] = m3 - _3) : (w2 = s2 * c4[v3 + 0] + 8192 >> 14, E3[0 + S3] = w2, E3[8 + S3] = w2, E3[16 + S3] = w2, E3[24 + S3] = w2, E3[32 + S3] = w2, E3[40 + S3] = w2, E3[48 + S3] = w2, E3[56 + S3] = w2);
      }
      for (v3 = 0; v3 < 64; ++v3) {
        var A2 = 128 + (E3[v3] + 8 >> 4);
        h4[v3] = A2 < 0 ? 0 : A2 > 255 ? 255 : A2;
      }
    }
    _2(m2 * p3 * 8);
    for (var w = 0; w < p3; w++) {
      var v2 = w << 3;
      for (h3 = 0; h3 < 8; h3++) f3.push(new Uint8Array(m2));
      for (var x2 = 0; x2 < d2; x2++) {
        y2(u3.blocks[w][x2], b2, g);
        var E2 = 0, k2 = x2 << 3;
        for (c3 = 0; c3 < 8; c3++) {
          var S2 = f3[v2 + c3];
          for (h3 = 0; h3 < 8; h3++) S2[k2 + h3] = b2[E2++];
        }
      }
    }
    return f3;
  }
  function d(e5) {
    return e5 < 0 ? 0 : e5 > 255 ? 255 : e5;
  }
  u2.prototype = { load: function(e5) {
    var t3 = new XMLHttpRequest();
    t3.open("GET", e5, true), t3.responseType = "arraybuffer", t3.onload = (function() {
      var e6 = new Uint8Array(t3.response || t3.mozResponseArrayBuffer);
      this.parse(e6), this.onload && this.onload();
    }).bind(this), t3.send(null);
  }, parse: function(t3) {
    var i3 = 1e3 * this.opts.maxResolutionInMP * 1e3, r3 = 0;
    function n3() {
      var e5 = t3[r3] << 8 | t3[r3 + 1];
      return r3 += 2, e5;
    }
    function a3(e5) {
      var t4, i4, r4 = 1, n4 = 1;
      for (i4 in e5.components) e5.components.hasOwnProperty(i4) && (r4 < (t4 = e5.components[i4]).h && (r4 = t4.h), n4 < t4.v && (n4 = t4.v));
      var a4 = Math.ceil(e5.samplesPerLine / 8 / r4), o4 = Math.ceil(e5.scanLines / 8 / n4);
      for (i4 in e5.components) if (e5.components.hasOwnProperty(i4)) {
        t4 = e5.components[i4];
        var s4 = Math.ceil(Math.ceil(e5.samplesPerLine / 8) * t4.h / r4), l4 = Math.ceil(Math.ceil(e5.scanLines / 8) * t4.v / n4), u4 = a4 * t4.h, h3 = o4 * t4.v, c3 = [];
        _2(h3 * u4 * 256);
        for (var f3 = 0; f3 < h3; f3++) {
          for (var d3 = [], p4 = 0; p4 < u4; p4++) d3.push(new Int32Array(64));
          c3.push(d3);
        }
        t4.blocksPerLine = s4, t4.blocksPerColumn = l4, t4.blocks = c3;
      }
      e5.maxH = r4, e5.maxV = n4, e5.mcusPerLine = a4, e5.mcusPerColumn = o4;
    }
    t3.length;
    var o3, s3, l3, u3, d2 = null, p3 = null, m2 = [], g = [], b2 = [], y2 = [], w = n3(), v2 = -1;
    if (this.comments = [], 65496 != w) throw new Error("SOI not found");
    for (w = n3(); 65497 != w; ) {
      switch (w) {
        case 65280:
          break;
        case 65504:
        case 65505:
        case 65506:
        case 65507:
        case 65508:
        case 65509:
        case 65510:
        case 65511:
        case 65512:
        case 65513:
        case 65514:
        case 65515:
        case 65516:
        case 65517:
        case 65518:
        case 65519:
        case 65534:
          var x2 = (l3 = void 0, u3 = void 0, l3 = n3(), u3 = t3.subarray(r3, r3 + l3 - 2), r3 += u3.length, u3);
          if (65534 === w) {
            var E2 = String.fromCharCode.apply(null, x2);
            this.comments.push(E2);
          }
          65504 === w && 74 === x2[0] && 70 === x2[1] && 73 === x2[2] && 70 === x2[3] && 0 === x2[4] && (d2 = { version: { major: x2[5], minor: x2[6] }, densityUnits: x2[7], xDensity: x2[8] << 8 | x2[9], yDensity: x2[10] << 8 | x2[11], thumbWidth: x2[12], thumbHeight: x2[13], thumbData: x2.subarray(14, 14 + 3 * x2[12] * x2[13]) }), 65505 === w && 69 === x2[0] && 120 === x2[1] && 105 === x2[2] && 102 === x2[3] && 0 === x2[4] && (this.exifBuffer = x2.subarray(5, x2.length)), 65518 === w && 65 === x2[0] && 100 === x2[1] && 111 === x2[2] && 98 === x2[3] && 101 === x2[4] && 0 === x2[5] && (p3 = { version: x2[6], flags0: x2[7] << 8 | x2[8], flags1: x2[9] << 8 | x2[10], transformCode: x2[11] });
          break;
        case 65499:
          for (var k2 = n3() + r3 - 2; r3 < k2; ) {
            var S2 = t3[r3++];
            _2(256);
            var A2 = new Int32Array(64);
            if (S2 >> 4) {
              if (S2 >> 4 != 1) throw new Error("DQT: invalid table spec");
              for (q = 0; q < 64; q++) A2[e4[q]] = n3();
            } else for (q = 0; q < 64; q++) A2[e4[q]] = t3[r3++];
            m2[15 & S2] = A2;
          }
          break;
        case 65472:
        case 65473:
        case 65474:
          n3(), (o3 = {}).extended = 65473 === w, o3.progressive = 65474 === w, o3.precision = t3[r3++], o3.scanLines = n3(), o3.samplesPerLine = n3(), o3.components = {}, o3.componentsOrder = [];
          var I = o3.scanLines * o3.samplesPerLine;
          if (I > i3) {
            var M2 = Math.ceil((I - i3) / 1e6);
            throw new Error(`maxResolutionInMP limit exceeded by ${M2}MP`);
          }
          var T2, P = t3[r3++];
          for (Q = 0; Q < P; Q++) {
            T2 = t3[r3];
            var B2 = t3[r3 + 1] >> 4, C2 = 15 & t3[r3 + 1], R2 = t3[r3 + 2];
            if (B2 <= 0 || C2 <= 0) throw new Error("Invalid sampling factor, expected values above 0");
            o3.componentsOrder.push(T2), o3.components[T2] = { h: B2, v: C2, quantizationIdx: R2 }, r3 += 3;
          }
          a3(o3), g.push(o3);
          break;
        case 65476:
          var z2 = n3();
          for (Q = 2; Q < z2; ) {
            var F = t3[r3++], N2 = new Uint8Array(16), O2 = 0;
            for (q = 0; q < 16; q++, r3++) O2 += N2[q] = t3[r3];
            _2(16 + O2);
            var D = new Uint8Array(O2);
            for (q = 0; q < O2; q++, r3++) D[q] = t3[r3];
            Q += 17 + O2, (F >> 4 ? b2 : y2)[15 & F] = h2(N2, D);
          }
          break;
        case 65501:
          n3(), s3 = n3();
          break;
        case 65500:
          n3(), n3();
          break;
        case 65498:
          n3();
          var $ = t3[r3++], L2 = [];
          for (Q = 0; Q < $; Q++) {
            V = o3.components[t3[r3++]];
            var U = t3[r3++];
            V.huffmanTableDC = y2[U >> 4], V.huffmanTableAC = b2[15 & U], L2.push(V);
          }
          var Z = t3[r3++], j = t3[r3++], G2 = t3[r3++], H = c2(t3, r3, o3, L2, s3, Z, j, G2 >> 4, 15 & G2, this.opts);
          r3 += H;
          break;
        case 65535:
          255 !== t3[r3] && r3--;
          break;
        default:
          if (255 == t3[r3 - 3] && t3[r3 - 2] >= 192 && t3[r3 - 2] <= 254) {
            r3 -= 3;
            break;
          }
          if (224 === w || 225 == w) {
            if (-1 !== v2) throw new Error(`first unknown JPEG marker at offset ${v2.toString(16)}, second unknown JPEG marker ${w.toString(16)} at offset ${(r3 - 1).toString(16)}`);
            v2 = r3 - 1;
            const e5 = n3();
            if (255 === t3[r3 + e5 - 2]) {
              r3 += e5 - 2;
              break;
            }
          }
          throw new Error("unknown JPEG marker " + w.toString(16));
      }
      w = n3();
    }
    if (1 != g.length) throw new Error("only single frame JPEGs supported");
    for (var Q = 0; Q < g.length; Q++) {
      var W = g[Q].components;
      for (var q in W) W[q].quantizationTable = m2[W[q].quantizationIdx], delete W[q].quantizationIdx;
    }
    for (this.width = o3.samplesPerLine, this.height = o3.scanLines, this.jfif = d2, this.adobe = p3, this.components = [], Q = 0; Q < o3.componentsOrder.length; Q++) {
      var V = o3.components[o3.componentsOrder[Q]];
      this.components.push({ lines: f2(0, V), scaleX: V.h / o3.maxH, scaleY: V.v / o3.maxV });
    }
  }, getData: function(e5, t3) {
    var i3, r3, n3, a3, o3, s3, l3, u3, h3, c3, f3, p3, m2, g, b2, y2, w, v2, x2, E2, k2, S2 = this.width / e5, A2 = this.height / t3, I = 0, M2 = e5 * t3 * this.components.length;
    _2(M2);
    var T2 = new Uint8Array(M2);
    switch (this.components.length) {
      case 1:
        for (i3 = this.components[0], c3 = 0; c3 < t3; c3++) for (o3 = i3.lines[0 | c3 * i3.scaleY * A2], h3 = 0; h3 < e5; h3++) f3 = o3[0 | h3 * i3.scaleX * S2], T2[I++] = f3;
        break;
      case 2:
        for (i3 = this.components[0], r3 = this.components[1], c3 = 0; c3 < t3; c3++) for (o3 = i3.lines[0 | c3 * i3.scaleY * A2], s3 = r3.lines[0 | c3 * r3.scaleY * A2], h3 = 0; h3 < e5; h3++) f3 = o3[0 | h3 * i3.scaleX * S2], T2[I++] = f3, f3 = s3[0 | h3 * r3.scaleX * S2], T2[I++] = f3;
        break;
      case 3:
        for (k2 = true, this.adobe && this.adobe.transformCode ? k2 = true : void 0 !== this.opts.colorTransform && (k2 = !!this.opts.colorTransform), i3 = this.components[0], r3 = this.components[1], n3 = this.components[2], c3 = 0; c3 < t3; c3++) for (o3 = i3.lines[0 | c3 * i3.scaleY * A2], s3 = r3.lines[0 | c3 * r3.scaleY * A2], l3 = n3.lines[0 | c3 * n3.scaleY * A2], h3 = 0; h3 < e5; h3++) k2 ? (f3 = o3[0 | h3 * i3.scaleX * S2], p3 = s3[0 | h3 * r3.scaleX * S2], v2 = d(f3 + 1.402 * ((m2 = l3[0 | h3 * n3.scaleX * S2]) - 128)), x2 = d(f3 - 0.3441363 * (p3 - 128) - 0.71413636 * (m2 - 128)), E2 = d(f3 + 1.772 * (p3 - 128))) : (v2 = o3[0 | h3 * i3.scaleX * S2], x2 = s3[0 | h3 * r3.scaleX * S2], E2 = l3[0 | h3 * n3.scaleX * S2]), T2[I++] = v2, T2[I++] = x2, T2[I++] = E2;
        break;
      case 4:
        if (!this.adobe) throw new Error("Unsupported color mode (4 components)");
        for (k2 = false, this.adobe && this.adobe.transformCode ? k2 = true : void 0 !== this.opts.colorTransform && (k2 = !!this.opts.colorTransform), i3 = this.components[0], r3 = this.components[1], n3 = this.components[2], a3 = this.components[3], c3 = 0; c3 < t3; c3++) for (o3 = i3.lines[0 | c3 * i3.scaleY * A2], s3 = r3.lines[0 | c3 * r3.scaleY * A2], l3 = n3.lines[0 | c3 * n3.scaleY * A2], u3 = a3.lines[0 | c3 * a3.scaleY * A2], h3 = 0; h3 < e5; h3++) k2 ? (f3 = o3[0 | h3 * i3.scaleX * S2], p3 = s3[0 | h3 * r3.scaleX * S2], m2 = l3[0 | h3 * n3.scaleX * S2], g = u3[0 | h3 * a3.scaleX * S2], b2 = 255 - d(f3 + 1.402 * (m2 - 128)), y2 = 255 - d(f3 - 0.3441363 * (p3 - 128) - 0.71413636 * (m2 - 128)), w = 255 - d(f3 + 1.772 * (p3 - 128))) : (b2 = o3[0 | h3 * i3.scaleX * S2], y2 = s3[0 | h3 * r3.scaleX * S2], w = l3[0 | h3 * n3.scaleX * S2], g = u3[0 | h3 * a3.scaleX * S2]), T2[I++] = 255 - b2, T2[I++] = 255 - y2, T2[I++] = 255 - w, T2[I++] = 255 - g;
        break;
      default:
        throw new Error("Unsupported color mode");
    }
    return T2;
  }, copyToImageData: function(e5, t3) {
    var i3, r3, n3, a3, o3, s3, l3, u3, h3, c3 = e5.width, f3 = e5.height, p3 = e5.data, m2 = this.getData(c3, f3), _3 = 0, g = 0;
    switch (this.components.length) {
      case 1:
        for (r3 = 0; r3 < f3; r3++) for (i3 = 0; i3 < c3; i3++) n3 = m2[_3++], p3[g++] = n3, p3[g++] = n3, p3[g++] = n3, t3 && (p3[g++] = 255);
        break;
      case 3:
        for (r3 = 0; r3 < f3; r3++) for (i3 = 0; i3 < c3; i3++) l3 = m2[_3++], u3 = m2[_3++], h3 = m2[_3++], p3[g++] = l3, p3[g++] = u3, p3[g++] = h3, t3 && (p3[g++] = 255);
        break;
      case 4:
        for (r3 = 0; r3 < f3; r3++) for (i3 = 0; i3 < c3; i3++) o3 = m2[_3++], s3 = m2[_3++], n3 = m2[_3++], l3 = 255 - d(o3 * (1 - (a3 = m2[_3++]) / 255) + a3), u3 = 255 - d(s3 * (1 - a3 / 255) + a3), h3 = 255 - d(n3 * (1 - a3 / 255) + a3), p3[g++] = l3, p3[g++] = u3, p3[g++] = h3, t3 && (p3[g++] = 255);
        break;
      default:
        throw new Error("Unsupported color mode");
    }
  } };
  var p2 = 0, m = 0;
  function _2(e5 = 0) {
    var t3 = p2 + e5;
    if (t3 > m) {
      var i3 = Math.ceil((t3 - m) / 1024 / 1024);
      throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${i3}MB`);
    }
    p2 = t3;
  }
  return u2.resetMaxMemoryUsage = function(e5) {
    p2 = 0, m = e5;
  }, u2.getBytesAllocated = function() {
    return p2;
  }, u2.requestMemoryAllocation = _2, u2;
}(), module$1.exports = function(e4, t2 = {}) {
  var i2 = { colorTransform: void 0, useTArray: false, formatAsRGBA: true, tolerantDecoding: true, maxResolutionInMP: 100, maxMemoryUsageInMB: 512, ...t2 }, r2 = new Uint8Array(e4), n2 = new JpegImage();
  n2.opts = i2, JpegImage.resetMaxMemoryUsage(1024 * i2.maxMemoryUsageInMB * 1024), n2.parse(r2);
  var a2 = i2.formatAsRGBA ? 4 : 3, o2 = n2.width * n2.height * a2;
  try {
    JpegImage.requestMemoryAllocation(o2);
    var s2 = { width: n2.width, height: n2.height, exifBuffer: n2.exifBuffer, data: i2.useTArray ? new Uint8Array(o2) : Buffer$1.alloc(o2) };
    n2.comments.length > 0 && (s2.comments = n2.comments);
  } catch (e5) {
    if (e5 instanceof RangeError) throw new Error("Could not allocate enough memory for the image. Required: " + o2);
    if (e5 instanceof ReferenceError && "Buffer is not defined" === e5.message) throw new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true");
    throw e5;
  }
  return n2.copyToImageData(s2, i2.formatAsRGBA), s2;
};
var decoderExports = decoder.exports, encode = encoderExports, decode = decoderExports, jpegJs = { encode, decode }, JPEG = getDefaultExportFromCjs(jpegJs);
function jpeg$2() {
  return { mime: "image/jpeg", encode: (e4, { quality: t2 = 100 } = {}) => JPEG.encode(e4, t2).data, decode: (e4, t2) => JPEG.decode(e4, t2) };
}
function commonjsRequire(e4) {
  throw new Error('Could not dynamically require "' + e4 + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}
var browser$1 = { exports: {} };
browser$1.exports = (/* @__PURE__ */ function() {
  function e4(t2, i2, r2) {
    function n2(o3, s2) {
      if (!i2[o3]) {
        if (!t2[o3]) {
          var l2 = "function" == typeof commonjsRequire && commonjsRequire;
          if (!s2 && l2) return l2(o3, true);
          if (a2) return a2(o3, true);
          var u2 = new Error("Cannot find module '" + o3 + "'");
          throw u2.code = "MODULE_NOT_FOUND", u2;
        }
        var h2 = i2[o3] = { exports: {} };
        t2[o3][0].call(h2.exports, function(e5) {
          return n2(t2[o3][1][e5] || e5);
        }, h2, h2.exports, e4, t2, i2, r2);
      }
      return i2[o3].exports;
    }
    for (var a2 = "function" == typeof commonjsRequire && commonjsRequire, o2 = 0; o2 < r2.length; o2++) n2(r2[o2]);
    return n2;
  }
  return e4;
}())({ 1: [function(e4, t2, i2) {
  (function(t3) {
    (function() {
      let r2 = e4("./interlace"), n2 = [function() {
      }, function(e5, t4, i3, r3) {
        if (r3 === t4.length) throw new Error("Ran out of data");
        let n3 = t4[r3];
        e5[i3] = n3, e5[i3 + 1] = n3, e5[i3 + 2] = n3, e5[i3 + 3] = 255;
      }, function(e5, t4, i3, r3) {
        if (r3 + 1 >= t4.length) throw new Error("Ran out of data");
        let n3 = t4[r3];
        e5[i3] = n3, e5[i3 + 1] = n3, e5[i3 + 2] = n3, e5[i3 + 3] = t4[r3 + 1];
      }, function(e5, t4, i3, r3) {
        if (r3 + 2 >= t4.length) throw new Error("Ran out of data");
        e5[i3] = t4[r3], e5[i3 + 1] = t4[r3 + 1], e5[i3 + 2] = t4[r3 + 2], e5[i3 + 3] = 255;
      }, function(e5, t4, i3, r3) {
        if (r3 + 3 >= t4.length) throw new Error("Ran out of data");
        e5[i3] = t4[r3], e5[i3 + 1] = t4[r3 + 1], e5[i3 + 2] = t4[r3 + 2], e5[i3 + 3] = t4[r3 + 3];
      }], a2 = [function() {
      }, function(e5, t4, i3, r3) {
        let n3 = t4[0];
        e5[i3] = n3, e5[i3 + 1] = n3, e5[i3 + 2] = n3, e5[i3 + 3] = r3;
      }, function(e5, t4, i3) {
        let r3 = t4[0];
        e5[i3] = r3, e5[i3 + 1] = r3, e5[i3 + 2] = r3, e5[i3 + 3] = t4[1];
      }, function(e5, t4, i3, r3) {
        e5[i3] = t4[0], e5[i3 + 1] = t4[1], e5[i3 + 2] = t4[2], e5[i3 + 3] = r3;
      }, function(e5, t4, i3) {
        e5[i3] = t4[0], e5[i3 + 1] = t4[1], e5[i3 + 2] = t4[2], e5[i3 + 3] = t4[3];
      }];
      function o2(e5, t4) {
        let i3 = [], r3 = 0;
        function n3() {
          if (r3 === e5.length) throw new Error("Ran out of data");
          let n4, a3, o3, s3, l3, u2, h2, c2, f2 = e5[r3];
          switch (r3++, t4) {
            default:
              throw new Error("unrecognised depth");
            case 16:
              h2 = e5[r3], r3++, i3.push((f2 << 8) + h2);
              break;
            case 4:
              h2 = 15 & f2, c2 = f2 >> 4, i3.push(c2, h2);
              break;
            case 2:
              l3 = 3 & f2, u2 = f2 >> 2 & 3, h2 = f2 >> 4 & 3, c2 = f2 >> 6 & 3, i3.push(c2, h2, u2, l3);
              break;
            case 1:
              n4 = 1 & f2, a3 = f2 >> 1 & 1, o3 = f2 >> 2 & 1, s3 = f2 >> 3 & 1, l3 = f2 >> 4 & 1, u2 = f2 >> 5 & 1, h2 = f2 >> 6 & 1, c2 = f2 >> 7 & 1, i3.push(c2, h2, u2, l3, s3, o3, a3, n4);
          }
        }
        return { get: function(e6) {
          for (; i3.length < e6; ) n3();
          let t5 = i3.slice(0, e6);
          return i3 = i3.slice(e6), t5;
        }, resetAfterLine: function() {
          i3.length = 0;
        }, end: function() {
          if (r3 !== e5.length) throw new Error("extra data found");
        } };
      }
      function s2(e5, t4, i3, r3, a3, o3) {
        let s3 = e5.width, l3 = e5.height, u2 = e5.index;
        for (let e6 = 0; e6 < l3; e6++) for (let l4 = 0; l4 < s3; l4++) {
          let s4 = i3(l4, e6, u2);
          n2[r3](t4, a3, s4, o3), o3 += r3;
        }
        return o3;
      }
      function l2(e5, t4, i3, r3, n3, o3) {
        let s3 = e5.width, l3 = e5.height, u2 = e5.index;
        for (let e6 = 0; e6 < l3; e6++) {
          for (let l4 = 0; l4 < s3; l4++) {
            let s4 = n3.get(r3), h2 = i3(l4, e6, u2);
            a2[r3](t4, s4, h2, o3);
          }
          n3.resetAfterLine();
        }
      }
      i2.dataToBitMap = function(e5, i3) {
        let n3, a3, u2 = i3.width, h2 = i3.height, c2 = i3.depth, f2 = i3.bpp, d = i3.interlace;
        8 !== c2 && (n3 = o2(e5, c2)), a3 = c2 <= 8 ? t3.alloc(u2 * h2 * 4) : new Uint16Array(u2 * h2 * 4);
        let p2, m, _2 = Math.pow(2, c2) - 1, g = 0;
        if (d) p2 = r2.getImagePasses(u2, h2), m = r2.getInterlaceIterator(u2, h2);
        else {
          let e6 = 0;
          m = function() {
            let t4 = e6;
            return e6 += 4, t4;
          }, p2 = [{ width: u2, height: h2 }];
        }
        for (let t4 = 0; t4 < p2.length; t4++) 8 === c2 ? g = s2(p2[t4], a3, m, f2, e5, g) : l2(p2[t4], a3, m, f2, n3, _2);
        if (8 === c2) {
          if (g !== e5.length) throw new Error("extra data found");
        } else n3.end();
        return a3;
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./interlace": 11, buffer: 32 }], 2: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("./constants");
      t2.exports = function(e5, t3, n2, a2) {
        let o2 = -1 !== [r2.COLORTYPE_COLOR_ALPHA, r2.COLORTYPE_ALPHA].indexOf(a2.colorType);
        if (a2.colorType === a2.inputColorType) {
          let t4 = function() {
            let e6 = new ArrayBuffer(2);
            return new DataView(e6).setInt16(0, 256, true), 256 !== new Int16Array(e6)[0];
          }();
          if (8 === a2.bitDepth || 16 === a2.bitDepth && t4) return e5;
        }
        let s2 = 16 !== a2.bitDepth ? e5 : new Uint16Array(e5.buffer), l2 = 255, u2 = r2.COLORTYPE_TO_BPP_MAP[a2.inputColorType];
        4 !== u2 || a2.inputHasAlpha || (u2 = 3);
        let h2 = r2.COLORTYPE_TO_BPP_MAP[a2.colorType];
        16 === a2.bitDepth && (l2 = 65535, h2 *= 2);
        let c2 = i3.alloc(t3 * n2 * h2), f2 = 0, d = 0, p2 = a2.bgColor || {};
        function m() {
          let e6, t4, i4, n3 = l2;
          switch (a2.inputColorType) {
            case r2.COLORTYPE_COLOR_ALPHA:
              n3 = s2[f2 + 3], e6 = s2[f2], t4 = s2[f2 + 1], i4 = s2[f2 + 2];
              break;
            case r2.COLORTYPE_COLOR:
              e6 = s2[f2], t4 = s2[f2 + 1], i4 = s2[f2 + 2];
              break;
            case r2.COLORTYPE_ALPHA:
              n3 = s2[f2 + 1], e6 = s2[f2], t4 = e6, i4 = e6;
              break;
            case r2.COLORTYPE_GRAYSCALE:
              e6 = s2[f2], t4 = e6, i4 = e6;
              break;
            default:
              throw new Error("input color type:" + a2.inputColorType + " is not supported at present");
          }
          return a2.inputHasAlpha && (o2 || (n3 /= l2, e6 = Math.min(Math.max(Math.round((1 - n3) * p2.red + n3 * e6), 0), l2), t4 = Math.min(Math.max(Math.round((1 - n3) * p2.green + n3 * t4), 0), l2), i4 = Math.min(Math.max(Math.round((1 - n3) * p2.blue + n3 * i4), 0), l2))), { red: e6, green: t4, blue: i4, alpha: n3 };
        }
        void 0 === p2.red && (p2.red = l2), void 0 === p2.green && (p2.green = l2), void 0 === p2.blue && (p2.blue = l2);
        for (let e6 = 0; e6 < n2; e6++) for (let e7 = 0; e7 < t3; e7++) {
          let e8 = m();
          switch (a2.colorType) {
            case r2.COLORTYPE_COLOR_ALPHA:
            case r2.COLORTYPE_COLOR:
              8 === a2.bitDepth ? (c2[d] = e8.red, c2[d + 1] = e8.green, c2[d + 2] = e8.blue, o2 && (c2[d + 3] = e8.alpha)) : (c2.writeUInt16BE(e8.red, d), c2.writeUInt16BE(e8.green, d + 2), c2.writeUInt16BE(e8.blue, d + 4), o2 && c2.writeUInt16BE(e8.alpha, d + 6));
              break;
            case r2.COLORTYPE_ALPHA:
            case r2.COLORTYPE_GRAYSCALE: {
              let t4 = (e8.red + e8.green + e8.blue) / 3;
              8 === a2.bitDepth ? (c2[d] = t4, o2 && (c2[d + 1] = e8.alpha)) : (c2.writeUInt16BE(t4, d), o2 && c2.writeUInt16BE(e8.alpha, d + 2));
              break;
            }
            default:
              throw new Error("unrecognised color Type " + a2.colorType);
          }
          f2 += u2, d += h2;
        }
        return c2;
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./constants": 4, buffer: 32 }], 3: [function(e4, t2, i2) {
  (function(i3, r2) {
    (function() {
      let n2 = e4("util"), a2 = e4("stream"), o2 = t2.exports = function() {
        a2.call(this), this._buffers = [], this._buffered = 0, this._reads = [], this._paused = false, this._encoding = "utf8", this.writable = true;
      };
      n2.inherits(o2, a2), o2.prototype.read = function(e5, t3) {
        this._reads.push({ length: Math.abs(e5), allowLess: e5 < 0, func: t3 }), i3.nextTick((function() {
          this._process(), this._paused && this._reads && this._reads.length > 0 && (this._paused = false, this.emit("drain"));
        }).bind(this));
      }, o2.prototype.write = function(e5, t3) {
        if (!this.writable) return this.emit("error", new Error("Stream not writable")), false;
        let i4;
        return i4 = r2.isBuffer(e5) ? e5 : r2.from(e5, t3 || this._encoding), this._buffers.push(i4), this._buffered += i4.length, this._process(), this._reads && 0 === this._reads.length && (this._paused = true), this.writable && !this._paused;
      }, o2.prototype.end = function(e5, t3) {
        e5 && this.write(e5, t3), this.writable = false, this._buffers && (0 === this._buffers.length ? this._end() : (this._buffers.push(null), this._process()));
      }, o2.prototype.destroySoon = o2.prototype.end, o2.prototype._end = function() {
        this._reads.length > 0 && this.emit("error", new Error("Unexpected end of input")), this.destroy();
      }, o2.prototype.destroy = function() {
        this._buffers && (this.writable = false, this._reads = null, this._buffers = null, this.emit("close"));
      }, o2.prototype._processReadAllowingLess = function(e5) {
        this._reads.shift();
        let t3 = this._buffers[0];
        t3.length > e5.length ? (this._buffered -= e5.length, this._buffers[0] = t3.slice(e5.length), e5.func.call(this, t3.slice(0, e5.length))) : (this._buffered -= t3.length, this._buffers.shift(), e5.func.call(this, t3));
      }, o2.prototype._processRead = function(e5) {
        this._reads.shift();
        let t3 = 0, i4 = 0, n3 = r2.alloc(e5.length);
        for (; t3 < e5.length; ) {
          let r3 = this._buffers[i4++], a3 = Math.min(r3.length, e5.length - t3);
          r3.copy(n3, t3, 0, a3), t3 += a3, a3 !== r3.length && (this._buffers[--i4] = r3.slice(a3));
        }
        i4 > 0 && this._buffers.splice(0, i4), this._buffered -= e5.length, e5.func.call(this, n3);
      }, o2.prototype._process = function() {
        try {
          for (; this._buffered > 0 && this._reads && this._reads.length > 0; ) {
            let e5 = this._reads[0];
            if (e5.allowLess) this._processReadAllowingLess(e5);
            else {
              if (!(this._buffered >= e5.length)) break;
              this._processRead(e5);
            }
          }
          this._buffers && !this.writable && this._end();
        } catch (e5) {
          this.emit("error", e5);
        }
      };
    }).call(this);
  }).call(this, e4("_process"), e4("buffer").Buffer);
}, { _process: 63, buffer: 32, stream: 65, util: 84 }], 4: [function(e4, t2, i2) {
  t2.exports = { PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10], TYPE_IHDR: 1229472850, TYPE_IEND: 1229278788, TYPE_IDAT: 1229209940, TYPE_PLTE: 1347179589, TYPE_tRNS: 1951551059, TYPE_gAMA: 1732332865, COLORTYPE_GRAYSCALE: 0, COLORTYPE_PALETTE: 1, COLORTYPE_COLOR: 2, COLORTYPE_ALPHA: 4, COLORTYPE_PALETTE_COLOR: 3, COLORTYPE_COLOR_ALPHA: 6, COLORTYPE_TO_BPP_MAP: { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }, GAMMA_DIVISION: 1e5 };
}, {}], 5: [function(e4, t2, i2) {
  let r2 = [];
  !function() {
    for (let e5 = 0; e5 < 256; e5++) {
      let t3 = e5;
      for (let e6 = 0; e6 < 8; e6++) 1 & t3 ? t3 = 3988292384 ^ t3 >>> 1 : t3 >>>= 1;
      r2[e5] = t3;
    }
  }();
  let n2 = t2.exports = function() {
    this._crc = -1;
  };
  n2.prototype.write = function(e5) {
    for (let t3 = 0; t3 < e5.length; t3++) this._crc = r2[255 & (this._crc ^ e5[t3])] ^ this._crc >>> 8;
    return true;
  }, n2.prototype.crc32 = function() {
    return ~this._crc;
  }, n2.crc32 = function(e5) {
    let t3 = -1;
    for (let i3 = 0; i3 < e5.length; i3++) t3 = r2[255 & (t3 ^ e5[i3])] ^ t3 >>> 8;
    return ~t3;
  };
}, {}], 6: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("./paeth-predictor");
      function n2(e5, t3, i4, r3, n3) {
        for (let a3 = 0; a3 < i4; a3++) r3[n3 + a3] = e5[t3 + a3];
      }
      function a2(e5, t3, i4) {
        let r3 = 0, n3 = t3 + i4;
        for (let i5 = t3; i5 < n3; i5++) r3 += Math.abs(e5[i5]);
        return r3;
      }
      function o2(e5, t3, i4, r3, n3, a3) {
        for (let o3 = 0; o3 < i4; o3++) {
          let i5 = o3 >= a3 ? e5[t3 + o3 - a3] : 0, s3 = e5[t3 + o3] - i5;
          r3[n3 + o3] = s3;
        }
      }
      function s2(e5, t3, i4, r3) {
        let n3 = 0;
        for (let a3 = 0; a3 < i4; a3++) {
          let i5 = a3 >= r3 ? e5[t3 + a3 - r3] : 0, o3 = e5[t3 + a3] - i5;
          n3 += Math.abs(o3);
        }
        return n3;
      }
      function l2(e5, t3, i4, r3, n3) {
        for (let a3 = 0; a3 < i4; a3++) {
          let o3 = t3 > 0 ? e5[t3 + a3 - i4] : 0, s3 = e5[t3 + a3] - o3;
          r3[n3 + a3] = s3;
        }
      }
      function u2(e5, t3, i4) {
        let r3 = 0, n3 = t3 + i4;
        for (let a3 = t3; a3 < n3; a3++) {
          let n4 = t3 > 0 ? e5[a3 - i4] : 0, o3 = e5[a3] - n4;
          r3 += Math.abs(o3);
        }
        return r3;
      }
      function h2(e5, t3, i4, r3, n3, a3) {
        for (let o3 = 0; o3 < i4; o3++) {
          let s3 = o3 >= a3 ? e5[t3 + o3 - a3] : 0, l3 = t3 > 0 ? e5[t3 + o3 - i4] : 0, u3 = e5[t3 + o3] - (s3 + l3 >> 1);
          r3[n3 + o3] = u3;
        }
      }
      function c2(e5, t3, i4, r3) {
        let n3 = 0;
        for (let a3 = 0; a3 < i4; a3++) {
          let o3 = a3 >= r3 ? e5[t3 + a3 - r3] : 0, s3 = t3 > 0 ? e5[t3 + a3 - i4] : 0, l3 = e5[t3 + a3] - (o3 + s3 >> 1);
          n3 += Math.abs(l3);
        }
        return n3;
      }
      function f2(e5, t3, i4, n3, a3, o3) {
        for (let s3 = 0; s3 < i4; s3++) {
          let l3 = s3 >= o3 ? e5[t3 + s3 - o3] : 0, u3 = t3 > 0 ? e5[t3 + s3 - i4] : 0, h3 = t3 > 0 && s3 >= o3 ? e5[t3 + s3 - (i4 + o3)] : 0, c3 = e5[t3 + s3] - r2(l3, u3, h3);
          n3[a3 + s3] = c3;
        }
      }
      function d(e5, t3, i4, n3) {
        let a3 = 0;
        for (let o3 = 0; o3 < i4; o3++) {
          let s3 = o3 >= n3 ? e5[t3 + o3 - n3] : 0, l3 = t3 > 0 ? e5[t3 + o3 - i4] : 0, u3 = t3 > 0 && o3 >= n3 ? e5[t3 + o3 - (i4 + n3)] : 0, h3 = e5[t3 + o3] - r2(s3, l3, u3);
          a3 += Math.abs(h3);
        }
        return a3;
      }
      let p2 = { 0: n2, 1: o2, 2: l2, 3: h2, 4: f2 }, m = { 0: a2, 1: s2, 2: u2, 3: c2, 4: d };
      t2.exports = function(e5, t3, r3, n3, a3) {
        let o3;
        if ("filterType" in n3 && -1 !== n3.filterType) {
          if ("number" != typeof n3.filterType) throw new Error("unrecognised filter types");
          o3 = [n3.filterType];
        } else o3 = [0, 1, 2, 3, 4];
        16 === n3.bitDepth && (a3 *= 2);
        let s3 = t3 * a3, l3 = 0, u3 = 0, h3 = i3.alloc((s3 + 1) * r3), c3 = o3[0];
        for (let t4 = 0; t4 < r3; t4++) {
          if (o3.length > 1) {
            let t5 = 1 / 0;
            for (let i4 = 0; i4 < o3.length; i4++) {
              let r4 = m[o3[i4]](e5, u3, s3, a3);
              r4 < t5 && (c3 = o3[i4], t5 = r4);
            }
          }
          h3[l3] = c3, l3++, p2[c3](e5, u3, s3, h3, l3, a3), l3 += s3, u3 += s3;
        }
        return h3;
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./paeth-predictor": 15, buffer: 32 }], 7: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("util"), n2 = e4("./chunkstream"), a2 = e4("./filter-parse"), o2 = t2.exports = function(e5) {
        n2.call(this);
        let t3 = [], r3 = this;
        this._filter = new a2(e5, { read: this.read.bind(this), write: function(e6) {
          t3.push(e6);
        }, complete: function() {
          r3.emit("complete", i3.concat(t3));
        } }), this._filter.start();
      };
      r2.inherits(o2, n2);
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./chunkstream": 3, "./filter-parse": 9, buffer: 32, util: 84 }], 8: [function(e4, t2, i2) {
  (function(t3) {
    (function() {
      let r2 = e4("./sync-reader"), n2 = e4("./filter-parse");
      i2.process = function(e5, i3) {
        let a2 = [], o2 = new r2(e5);
        return new n2(i3, { read: o2.read.bind(o2), write: function(e6) {
          a2.push(e6);
        }, complete: function() {
        } }).start(), o2.process(), t3.concat(a2);
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./filter-parse": 9, "./sync-reader": 22, buffer: 32 }], 9: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("./interlace"), n2 = e4("./paeth-predictor");
      function a2(e5, t3, i4) {
        let r3 = e5 * t3;
        return 8 !== i4 && (r3 = Math.ceil(r3 / (8 / i4))), r3;
      }
      let o2 = t2.exports = function(e5, t3) {
        let i4 = e5.width, n3 = e5.height, o3 = e5.interlace, s2 = e5.bpp, l2 = e5.depth;
        if (this.read = t3.read, this.write = t3.write, this.complete = t3.complete, this._imageIndex = 0, this._images = [], o3) {
          let e6 = r2.getImagePasses(i4, n3);
          for (let t4 = 0; t4 < e6.length; t4++) this._images.push({ byteWidth: a2(e6[t4].width, s2, l2), height: e6[t4].height, lineIndex: 0 });
        } else this._images.push({ byteWidth: a2(i4, s2, l2), height: n3, lineIndex: 0 });
        this._xComparison = 8 === l2 ? s2 : 16 === l2 ? 2 * s2 : 1;
      };
      o2.prototype.start = function() {
        this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
      }, o2.prototype._unFilterType1 = function(e5, t3, i4) {
        let r3 = this._xComparison, n3 = r3 - 1;
        for (let a3 = 0; a3 < i4; a3++) {
          let i5 = e5[1 + a3], o3 = a3 > n3 ? t3[a3 - r3] : 0;
          t3[a3] = i5 + o3;
        }
      }, o2.prototype._unFilterType2 = function(e5, t3, i4) {
        let r3 = this._lastLine;
        for (let n3 = 0; n3 < i4; n3++) {
          let i5 = e5[1 + n3], a3 = r3 ? r3[n3] : 0;
          t3[n3] = i5 + a3;
        }
      }, o2.prototype._unFilterType3 = function(e5, t3, i4) {
        let r3 = this._xComparison, n3 = r3 - 1, a3 = this._lastLine;
        for (let o3 = 0; o3 < i4; o3++) {
          let i5 = e5[1 + o3], s2 = a3 ? a3[o3] : 0, l2 = o3 > n3 ? t3[o3 - r3] : 0, u2 = Math.floor((l2 + s2) / 2);
          t3[o3] = i5 + u2;
        }
      }, o2.prototype._unFilterType4 = function(e5, t3, i4) {
        let r3 = this._xComparison, a3 = r3 - 1, o3 = this._lastLine;
        for (let s2 = 0; s2 < i4; s2++) {
          let i5 = e5[1 + s2], l2 = o3 ? o3[s2] : 0, u2 = s2 > a3 ? t3[s2 - r3] : 0, h2 = s2 > a3 && o3 ? o3[s2 - r3] : 0, c2 = n2(u2, l2, h2);
          t3[s2] = i5 + c2;
        }
      }, o2.prototype._reverseFilterLine = function(e5) {
        let t3, r3 = e5[0], n3 = this._images[this._imageIndex], a3 = n3.byteWidth;
        if (0 === r3) t3 = e5.slice(1, a3 + 1);
        else switch (t3 = i3.alloc(a3), r3) {
          case 1:
            this._unFilterType1(e5, t3, a3);
            break;
          case 2:
            this._unFilterType2(e5, t3, a3);
            break;
          case 3:
            this._unFilterType3(e5, t3, a3);
            break;
          case 4:
            this._unFilterType4(e5, t3, a3);
            break;
          default:
            throw new Error("Unrecognised filter type - " + r3);
        }
        this.write(t3), n3.lineIndex++, n3.lineIndex >= n3.height ? (this._lastLine = null, this._imageIndex++, n3 = this._images[this._imageIndex]) : this._lastLine = t3, n3 ? this.read(n3.byteWidth + 1, this._reverseFilterLine.bind(this)) : (this._lastLine = null, this.complete());
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./interlace": 11, "./paeth-predictor": 15, buffer: 32 }], 10: [function(e4, t2, i2) {
  (function(e5) {
    (function() {
      function i3(e6, t3, i4, r3, n3) {
        let a2 = 0;
        for (let o2 = 0; o2 < r3; o2++) for (let r4 = 0; r4 < i4; r4++) {
          let i5 = n3[e6[a2]];
          if (!i5) throw new Error("index " + e6[a2] + " not in palette");
          for (let e7 = 0; e7 < 4; e7++) t3[a2 + e7] = i5[e7];
          a2 += 4;
        }
      }
      function r2(e6, t3, i4, r3, n3) {
        let a2 = 0;
        for (let o2 = 0; o2 < r3; o2++) for (let r4 = 0; r4 < i4; r4++) {
          let i5 = false;
          if (1 === n3.length ? n3[0] === e6[a2] && (i5 = true) : n3[0] === e6[a2] && n3[1] === e6[a2 + 1] && n3[2] === e6[a2 + 2] && (i5 = true), i5) for (let e7 = 0; e7 < 4; e7++) t3[a2 + e7] = 0;
          a2 += 4;
        }
      }
      function n2(e6, t3, i4, r3, n3) {
        let a2 = 255, o2 = Math.pow(2, n3) - 1, s2 = 0;
        for (let n4 = 0; n4 < r3; n4++) for (let r4 = 0; r4 < i4; r4++) {
          for (let i5 = 0; i5 < 4; i5++) t3[s2 + i5] = Math.floor(e6[s2 + i5] * a2 / o2 + 0.5);
          s2 += 4;
        }
      }
      t2.exports = function(t3, a2, o2 = false) {
        let s2 = a2.depth, l2 = a2.width, u2 = a2.height, h2 = a2.colorType, c2 = a2.transColor, f2 = a2.palette, d = t3;
        return 3 === h2 ? i3(t3, d, l2, u2, f2) : (c2 && r2(t3, d, l2, u2, c2), 8 === s2 || o2 || (16 === s2 && (d = e5.alloc(l2 * u2 * 4)), n2(t3, d, l2, u2, s2))), d;
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { buffer: 32 }], 11: [function(e4, t2, i2) {
  let r2 = [{ x: [0], y: [0] }, { x: [4], y: [0] }, { x: [0, 4], y: [4] }, { x: [2, 6], y: [0, 4] }, { x: [0, 2, 4, 6], y: [2, 6] }, { x: [1, 3, 5, 7], y: [0, 2, 4, 6] }, { x: [0, 1, 2, 3, 4, 5, 6, 7], y: [1, 3, 5, 7] }];
  i2.getImagePasses = function(e5, t3) {
    let i3 = [], n2 = e5 % 8, a2 = t3 % 8, o2 = (e5 - n2) / 8, s2 = (t3 - a2) / 8;
    for (let e6 = 0; e6 < r2.length; e6++) {
      let t4 = r2[e6], l2 = o2 * t4.x.length, u2 = s2 * t4.y.length;
      for (let e7 = 0; e7 < t4.x.length && t4.x[e7] < n2; e7++) l2++;
      for (let e7 = 0; e7 < t4.y.length && t4.y[e7] < a2; e7++) u2++;
      l2 > 0 && u2 > 0 && i3.push({ width: l2, height: u2, index: e6 });
    }
    return i3;
  }, i2.getInterlaceIterator = function(e5) {
    return function(t3, i3, n2) {
      let a2 = t3 % r2[n2].x.length, o2 = (t3 - a2) / r2[n2].x.length * 8 + r2[n2].x[a2], s2 = i3 % r2[n2].y.length;
      return 4 * o2 + ((i3 - s2) / r2[n2].y.length * 8 + r2[n2].y[s2]) * e5 * 4;
    };
  };
}, {}], 12: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("util"), n2 = e4("stream"), a2 = e4("./constants"), o2 = e4("./packer"), s2 = t2.exports = function(e5) {
        n2.call(this);
        let t3 = e5 || {};
        this._packer = new o2(t3), this._deflate = this._packer.createDeflate(), this.readable = true;
      };
      r2.inherits(s2, n2), s2.prototype.pack = function(e5, t3, r3, n3) {
        this.emit("data", i3.from(a2.PNG_SIGNATURE)), this.emit("data", this._packer.packIHDR(t3, r3)), n3 && this.emit("data", this._packer.packGAMA(n3));
        let o3 = this._packer.filterData(e5, t3, r3);
        this._deflate.on("error", this.emit.bind(this, "error")), this._deflate.on("data", (function(e6) {
          this.emit("data", this._packer.packIDAT(e6));
        }).bind(this)), this._deflate.on("end", (function() {
          this.emit("data", this._packer.packIEND()), this.emit("end");
        }).bind(this)), this._deflate.end(o3);
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./constants": 4, "./packer": 14, buffer: 32, stream: 65, util: 84 }], 13: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = true, n2 = e4("zlib");
      n2.deflateSync || (r2 = false);
      let a2 = e4("./constants"), o2 = e4("./packer");
      t2.exports = function(e5, t3) {
        if (!r2) throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");
        let s2 = new o2(t3 || {}), l2 = [];
        l2.push(i3.from(a2.PNG_SIGNATURE)), l2.push(s2.packIHDR(e5.width, e5.height)), e5.gamma && l2.push(s2.packGAMA(e5.gamma));
        let u2 = s2.filterData(e5.data, e5.width, e5.height), h2 = n2.deflateSync(u2, s2.getDeflateOptions());
        if (u2 = null, !h2 || !h2.length) throw new Error("bad png - invalid compressed data response");
        return l2.push(s2.packIDAT(h2)), l2.push(s2.packIEND()), i3.concat(l2);
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./constants": 4, "./packer": 14, buffer: 32, zlib: 31 }], 14: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("./constants"), n2 = e4("./crc"), a2 = e4("./bitpacker"), o2 = e4("./filter-pack"), s2 = e4("zlib"), l2 = t2.exports = function(e5) {
        if (this._options = e5, e5.deflateChunkSize = e5.deflateChunkSize || 32768, e5.deflateLevel = null != e5.deflateLevel ? e5.deflateLevel : 9, e5.deflateStrategy = null != e5.deflateStrategy ? e5.deflateStrategy : 3, e5.inputHasAlpha = null == e5.inputHasAlpha || e5.inputHasAlpha, e5.deflateFactory = e5.deflateFactory || s2.createDeflate, e5.bitDepth = e5.bitDepth || 8, e5.colorType = "number" == typeof e5.colorType ? e5.colorType : r2.COLORTYPE_COLOR_ALPHA, e5.inputColorType = "number" == typeof e5.inputColorType ? e5.inputColorType : r2.COLORTYPE_COLOR_ALPHA, -1 === [r2.COLORTYPE_GRAYSCALE, r2.COLORTYPE_COLOR, r2.COLORTYPE_COLOR_ALPHA, r2.COLORTYPE_ALPHA].indexOf(e5.colorType)) throw new Error("option color type:" + e5.colorType + " is not supported at present");
        if (-1 === [r2.COLORTYPE_GRAYSCALE, r2.COLORTYPE_COLOR, r2.COLORTYPE_COLOR_ALPHA, r2.COLORTYPE_ALPHA].indexOf(e5.inputColorType)) throw new Error("option input color type:" + e5.inputColorType + " is not supported at present");
        if (8 !== e5.bitDepth && 16 !== e5.bitDepth) throw new Error("option bit depth:" + e5.bitDepth + " is not supported at present");
      };
      l2.prototype.getDeflateOptions = function() {
        return { chunkSize: this._options.deflateChunkSize, level: this._options.deflateLevel, strategy: this._options.deflateStrategy };
      }, l2.prototype.createDeflate = function() {
        return this._options.deflateFactory(this.getDeflateOptions());
      }, l2.prototype.filterData = function(e5, t3, i4) {
        let n3 = a2(e5, t3, i4, this._options), s3 = r2.COLORTYPE_TO_BPP_MAP[this._options.colorType];
        return o2(n3, t3, i4, this._options, s3);
      }, l2.prototype._packChunk = function(e5, t3) {
        let r3 = t3 ? t3.length : 0, a3 = i3.alloc(r3 + 12);
        return a3.writeUInt32BE(r3, 0), a3.writeUInt32BE(e5, 4), t3 && t3.copy(a3, 8), a3.writeInt32BE(n2.crc32(a3.slice(4, a3.length - 4)), a3.length - 4), a3;
      }, l2.prototype.packGAMA = function(e5) {
        let t3 = i3.alloc(4);
        return t3.writeUInt32BE(Math.floor(e5 * r2.GAMMA_DIVISION), 0), this._packChunk(r2.TYPE_gAMA, t3);
      }, l2.prototype.packIHDR = function(e5, t3) {
        let n3 = i3.alloc(13);
        return n3.writeUInt32BE(e5, 0), n3.writeUInt32BE(t3, 4), n3[8] = this._options.bitDepth, n3[9] = this._options.colorType, n3[10] = 0, n3[11] = 0, n3[12] = 0, this._packChunk(r2.TYPE_IHDR, n3);
      }, l2.prototype.packIDAT = function(e5) {
        return this._packChunk(r2.TYPE_IDAT, e5);
      }, l2.prototype.packIEND = function() {
        return this._packChunk(r2.TYPE_IEND, null);
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./bitpacker": 2, "./constants": 4, "./crc": 5, "./filter-pack": 6, buffer: 32, zlib: 31 }], 15: [function(e4, t2, i2) {
  t2.exports = function(e5, t3, i3) {
    let r2 = e5 + t3 - i3, n2 = Math.abs(r2 - e5), a2 = Math.abs(r2 - t3), o2 = Math.abs(r2 - i3);
    return n2 <= a2 && n2 <= o2 ? e5 : a2 <= o2 ? t3 : i3;
  };
}, {}], 16: [function(e4, t2, i2) {
  let r2 = e4("util"), n2 = e4("zlib"), a2 = e4("./chunkstream"), o2 = e4("./filter-parse-async"), s2 = e4("./parser"), l2 = e4("./bitmapper"), u2 = e4("./format-normaliser"), h2 = t2.exports = function(e5) {
    a2.call(this), this._parser = new s2(e5, { read: this.read.bind(this), error: this._handleError.bind(this), metadata: this._handleMetaData.bind(this), gamma: this.emit.bind(this, "gamma"), palette: this._handlePalette.bind(this), transColor: this._handleTransColor.bind(this), finished: this._finished.bind(this), inflateData: this._inflateData.bind(this), simpleTransparency: this._simpleTransparency.bind(this), headersFinished: this._headersFinished.bind(this) }), this._options = e5, this.writable = true, this._parser.start();
  };
  r2.inherits(h2, a2), h2.prototype._handleError = function(e5) {
    this.emit("error", e5), this.writable = false, this.destroy(), this._inflate && this._inflate.destroy && this._inflate.destroy(), this._filter && (this._filter.destroy(), this._filter.on("error", function() {
    })), this.errord = true;
  }, h2.prototype._inflateData = function(e5) {
    if (!this._inflate) if (this._bitmapInfo.interlace) this._inflate = n2.createInflate(), this._inflate.on("error", this.emit.bind(this, "error")), this._filter.on("complete", this._complete.bind(this)), this._inflate.pipe(this._filter);
    else {
      let e6 = (1 + (this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7 >> 3)) * this._bitmapInfo.height, t3 = Math.max(e6, n2.Z_MIN_CHUNK);
      this._inflate = n2.createInflate({ chunkSize: t3 });
      let i3 = e6, r3 = this.emit.bind(this, "error");
      this._inflate.on("error", function(e7) {
        i3 && r3(e7);
      }), this._filter.on("complete", this._complete.bind(this));
      let a3 = this._filter.write.bind(this._filter);
      this._inflate.on("data", function(e7) {
        i3 && (e7.length > i3 && (e7 = e7.slice(0, i3)), i3 -= e7.length, a3(e7));
      }), this._inflate.on("end", this._filter.end.bind(this._filter));
    }
    this._inflate.write(e5);
  }, h2.prototype._handleMetaData = function(e5) {
    this._metaData = e5, this._bitmapInfo = Object.create(e5), this._filter = new o2(this._bitmapInfo);
  }, h2.prototype._handleTransColor = function(e5) {
    this._bitmapInfo.transColor = e5;
  }, h2.prototype._handlePalette = function(e5) {
    this._bitmapInfo.palette = e5;
  }, h2.prototype._simpleTransparency = function() {
    this._metaData.alpha = true;
  }, h2.prototype._headersFinished = function() {
    this.emit("metadata", this._metaData);
  }, h2.prototype._finished = function() {
    this.errord || (this._inflate ? this._inflate.end() : this.emit("error", "No Inflate block"));
  }, h2.prototype._complete = function(e5) {
    if (this.errord) return;
    let t3;
    try {
      let i3 = l2.dataToBitMap(e5, this._bitmapInfo);
      t3 = u2(i3, this._bitmapInfo, this._options.skipRescale), i3 = null;
    } catch (e6) {
      return void this._handleError(e6);
    }
    this.emit("parsed", t3);
  };
}, { "./bitmapper": 1, "./chunkstream": 3, "./filter-parse-async": 7, "./format-normaliser": 10, "./parser": 18, util: 84, zlib: 31 }], 17: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = true, n2 = e4("zlib"), a2 = e4("./sync-inflate");
      n2.deflateSync || (r2 = false);
      let o2 = e4("./sync-reader"), s2 = e4("./filter-parse-sync"), l2 = e4("./parser"), u2 = e4("./bitmapper"), h2 = e4("./format-normaliser");
      t2.exports = function(e5, t3) {
        if (!r2) throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");
        let c2, f2, d;
        function p2(e6) {
          c2 = e6;
        }
        function m(e6) {
          f2 = e6;
        }
        function _2(e6) {
          f2.transColor = e6;
        }
        function g(e6) {
          f2.palette = e6;
        }
        function b2() {
          f2.alpha = true;
        }
        function y2(e6) {
          d = e6;
        }
        let w = [];
        function v2(e6) {
          w.push(e6);
        }
        let x2 = new o2(e5);
        if (new l2(t3, { read: x2.read.bind(x2), error: p2, metadata: m, gamma: y2, palette: g, transColor: _2, inflateData: v2, simpleTransparency: b2 }).start(), x2.process(), c2) throw c2;
        let E2, k2 = i3.concat(w);
        if (w.length = 0, f2.interlace) E2 = n2.inflateSync(k2);
        else {
          let e6 = (1 + (f2.width * f2.bpp * f2.depth + 7 >> 3)) * f2.height;
          E2 = a2(k2, { chunkSize: e6, maxLength: e6 });
        }
        if (k2 = null, !E2 || !E2.length) throw new Error("bad png - invalid inflate data response");
        let S2 = s2.process(E2, f2);
        k2 = null;
        let A2 = u2.dataToBitMap(S2, f2);
        S2 = null;
        let I = h2(A2, f2, t3.skipRescale);
        return f2.data = I, f2.gamma = d || 0, f2;
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./bitmapper": 1, "./filter-parse-sync": 8, "./format-normaliser": 10, "./parser": 18, "./sync-inflate": 21, "./sync-reader": 22, buffer: 32, zlib: 31 }], 18: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      let r2 = e4("./constants"), n2 = e4("./crc"), a2 = t2.exports = function(e5, t3) {
        this._options = e5, e5.checkCRC = false !== e5.checkCRC, this._hasIHDR = false, this._hasIEND = false, this._emittedHeadersFinished = false, this._palette = [], this._colorType = 0, this._chunks = {}, this._chunks[r2.TYPE_IHDR] = this._handleIHDR.bind(this), this._chunks[r2.TYPE_IEND] = this._handleIEND.bind(this), this._chunks[r2.TYPE_IDAT] = this._handleIDAT.bind(this), this._chunks[r2.TYPE_PLTE] = this._handlePLTE.bind(this), this._chunks[r2.TYPE_tRNS] = this._handleTRNS.bind(this), this._chunks[r2.TYPE_gAMA] = this._handleGAMA.bind(this), this.read = t3.read, this.error = t3.error, this.metadata = t3.metadata, this.gamma = t3.gamma, this.transColor = t3.transColor, this.palette = t3.palette, this.parsed = t3.parsed, this.inflateData = t3.inflateData, this.finished = t3.finished, this.simpleTransparency = t3.simpleTransparency, this.headersFinished = t3.headersFinished || function() {
        };
      };
      a2.prototype.start = function() {
        this.read(r2.PNG_SIGNATURE.length, this._parseSignature.bind(this));
      }, a2.prototype._parseSignature = function(e5) {
        let t3 = r2.PNG_SIGNATURE;
        for (let i4 = 0; i4 < t3.length; i4++) if (e5[i4] !== t3[i4]) return void this.error(new Error("Invalid file signature"));
        this.read(8, this._parseChunkBegin.bind(this));
      }, a2.prototype._parseChunkBegin = function(e5) {
        let t3 = e5.readUInt32BE(0), a3 = e5.readUInt32BE(4), o2 = "";
        for (let t4 = 4; t4 < 8; t4++) o2 += String.fromCharCode(e5[t4]);
        let s2 = Boolean(32 & e5[4]);
        if (this._hasIHDR || a3 === r2.TYPE_IHDR) {
          if (this._crc = new n2(), this._crc.write(i3.from(o2)), this._chunks[a3]) return this._chunks[a3](t3);
          s2 ? this.read(t3 + 4, this._skipChunk.bind(this)) : this.error(new Error("Unsupported critical chunk type " + o2));
        } else this.error(new Error("Expected IHDR on beggining"));
      }, a2.prototype._skipChunk = function() {
        this.read(8, this._parseChunkBegin.bind(this));
      }, a2.prototype._handleChunkEnd = function() {
        this.read(4, this._parseChunkEnd.bind(this));
      }, a2.prototype._parseChunkEnd = function(e5) {
        let t3 = e5.readInt32BE(0), i4 = this._crc.crc32();
        this._options.checkCRC && i4 !== t3 ? this.error(new Error("Crc error - " + t3 + " - " + i4)) : this._hasIEND || this.read(8, this._parseChunkBegin.bind(this));
      }, a2.prototype._handleIHDR = function(e5) {
        this.read(e5, this._parseIHDR.bind(this));
      }, a2.prototype._parseIHDR = function(e5) {
        this._crc.write(e5);
        let t3 = e5.readUInt32BE(0), i4 = e5.readUInt32BE(4), n3 = e5[8], a3 = e5[9], o2 = e5[10], s2 = e5[11], l2 = e5[12];
        if (8 !== n3 && 4 !== n3 && 2 !== n3 && 1 !== n3 && 16 !== n3) return void this.error(new Error("Unsupported bit depth " + n3));
        if (!(a3 in r2.COLORTYPE_TO_BPP_MAP)) return void this.error(new Error("Unsupported color type"));
        if (0 !== o2) return void this.error(new Error("Unsupported compression method"));
        if (0 !== s2) return void this.error(new Error("Unsupported filter method"));
        if (0 !== l2 && 1 !== l2) return void this.error(new Error("Unsupported interlace method"));
        this._colorType = a3;
        let u2 = r2.COLORTYPE_TO_BPP_MAP[this._colorType];
        this._hasIHDR = true, this.metadata({ width: t3, height: i4, depth: n3, interlace: Boolean(l2), palette: Boolean(a3 & r2.COLORTYPE_PALETTE), color: Boolean(a3 & r2.COLORTYPE_COLOR), alpha: Boolean(a3 & r2.COLORTYPE_ALPHA), bpp: u2, colorType: a3 }), this._handleChunkEnd();
      }, a2.prototype._handlePLTE = function(e5) {
        this.read(e5, this._parsePLTE.bind(this));
      }, a2.prototype._parsePLTE = function(e5) {
        this._crc.write(e5);
        let t3 = Math.floor(e5.length / 3);
        for (let i4 = 0; i4 < t3; i4++) this._palette.push([e5[3 * i4], e5[3 * i4 + 1], e5[3 * i4 + 2], 255]);
        this.palette(this._palette), this._handleChunkEnd();
      }, a2.prototype._handleTRNS = function(e5) {
        this.simpleTransparency(), this.read(e5, this._parseTRNS.bind(this));
      }, a2.prototype._parseTRNS = function(e5) {
        if (this._crc.write(e5), this._colorType === r2.COLORTYPE_PALETTE_COLOR) {
          if (0 === this._palette.length) return void this.error(new Error("Transparency chunk must be after palette"));
          if (e5.length > this._palette.length) return void this.error(new Error("More transparent colors than palette size"));
          for (let t3 = 0; t3 < e5.length; t3++) this._palette[t3][3] = e5[t3];
          this.palette(this._palette);
        }
        this._colorType === r2.COLORTYPE_GRAYSCALE && this.transColor([e5.readUInt16BE(0)]), this._colorType === r2.COLORTYPE_COLOR && this.transColor([e5.readUInt16BE(0), e5.readUInt16BE(2), e5.readUInt16BE(4)]), this._handleChunkEnd();
      }, a2.prototype._handleGAMA = function(e5) {
        this.read(e5, this._parseGAMA.bind(this));
      }, a2.prototype._parseGAMA = function(e5) {
        this._crc.write(e5), this.gamma(e5.readUInt32BE(0) / r2.GAMMA_DIVISION), this._handleChunkEnd();
      }, a2.prototype._handleIDAT = function(e5) {
        this._emittedHeadersFinished || (this._emittedHeadersFinished = true, this.headersFinished()), this.read(-e5, this._parseIDAT.bind(this, e5));
      }, a2.prototype._parseIDAT = function(e5, t3) {
        if (this._crc.write(t3), this._colorType === r2.COLORTYPE_PALETTE_COLOR && 0 === this._palette.length) throw new Error("Expected palette not found");
        this.inflateData(t3);
        let i4 = e5 - t3.length;
        i4 > 0 ? this._handleIDAT(i4) : this._handleChunkEnd();
      }, a2.prototype._handleIEND = function(e5) {
        this.read(e5, this._parseIEND.bind(this));
      }, a2.prototype._parseIEND = function(e5) {
        this._crc.write(e5), this._hasIEND = true, this._handleChunkEnd(), this.finished && this.finished();
      };
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "./constants": 4, "./crc": 5, buffer: 32 }], 19: [function(e4, t2, i2) {
  let r2 = e4("./parser-sync"), n2 = e4("./packer-sync");
  i2.read = function(e5, t3) {
    return r2(e5, t3 || {});
  }, i2.write = function(e5, t3) {
    return n2(e5, t3);
  };
}, { "./packer-sync": 13, "./parser-sync": 17 }], 20: [function(e4, t2, i2) {
  (function(t3, r2) {
    (function() {
      let n2 = e4("util"), a2 = e4("stream"), o2 = e4("./parser-async"), s2 = e4("./packer-async"), l2 = e4("./png-sync"), u2 = i2.PNG = function(e5) {
        a2.call(this), e5 = e5 || {}, this.width = 0 | e5.width, this.height = 0 | e5.height, this.data = this.width > 0 && this.height > 0 ? r2.alloc(4 * this.width * this.height) : null, e5.fill && this.data && this.data.fill(0), this.gamma = 0, this.readable = this.writable = true, this._parser = new o2(e5), this._parser.on("error", this.emit.bind(this, "error")), this._parser.on("close", this._handleClose.bind(this)), this._parser.on("metadata", this._metadata.bind(this)), this._parser.on("gamma", this._gamma.bind(this)), this._parser.on("parsed", (function(e6) {
          this.data = e6, this.emit("parsed", e6);
        }).bind(this)), this._packer = new s2(e5), this._packer.on("data", this.emit.bind(this, "data")), this._packer.on("end", this.emit.bind(this, "end")), this._parser.on("close", this._handleClose.bind(this)), this._packer.on("error", this.emit.bind(this, "error"));
      };
      n2.inherits(u2, a2), u2.sync = l2, u2.prototype.pack = function() {
        return this.data && this.data.length ? (t3.nextTick((function() {
          this._packer.pack(this.data, this.width, this.height, this.gamma);
        }).bind(this)), this) : (this.emit("error", "No data provided"), this);
      }, u2.prototype.parse = function(e5, t4) {
        if (t4) {
          let e6, i3;
          e6 = (function(e7) {
            this.removeListener("error", i3), this.data = e7, t4(null, this);
          }).bind(this), i3 = (function(i4) {
            this.removeListener("parsed", e6), t4(i4, null);
          }).bind(this), this.once("parsed", e6), this.once("error", i3);
        }
        return this.end(e5), this;
      }, u2.prototype.write = function(e5) {
        return this._parser.write(e5), true;
      }, u2.prototype.end = function(e5) {
        this._parser.end(e5);
      }, u2.prototype._metadata = function(e5) {
        this.width = e5.width, this.height = e5.height, this.emit("metadata", e5);
      }, u2.prototype._gamma = function(e5) {
        this.gamma = e5;
      }, u2.prototype._handleClose = function() {
        this._parser.writable || this._packer.readable || this.emit("close");
      }, u2.bitblt = function(e5, t4, i3, r3, n3, a3, o3, s3) {
        if (r3 |= 0, n3 |= 0, a3 |= 0, o3 |= 0, s3 |= 0, (i3 |= 0) > e5.width || r3 > e5.height || i3 + n3 > e5.width || r3 + a3 > e5.height) throw new Error("bitblt reading outside image");
        if (o3 > t4.width || s3 > t4.height || o3 + n3 > t4.width || s3 + a3 > t4.height) throw new Error("bitblt writing outside image");
        for (let l3 = 0; l3 < a3; l3++) e5.data.copy(t4.data, (s3 + l3) * t4.width + o3 << 2, (r3 + l3) * e5.width + i3 << 2, (r3 + l3) * e5.width + i3 + n3 << 2);
      }, u2.prototype.bitblt = function(e5, t4, i3, r3, n3, a3, o3) {
        return u2.bitblt(this, e5, t4, i3, r3, n3, a3, o3), this;
      }, u2.adjustGamma = function(e5) {
        if (e5.gamma) {
          for (let t4 = 0; t4 < e5.height; t4++) for (let i3 = 0; i3 < e5.width; i3++) {
            let r3 = e5.width * t4 + i3 << 2;
            for (let t5 = 0; t5 < 3; t5++) {
              let i4 = e5.data[r3 + t5] / 255;
              i4 = Math.pow(i4, 1 / 2.2 / e5.gamma), e5.data[r3 + t5] = Math.round(255 * i4);
            }
          }
          e5.gamma = 0;
        }
      }, u2.prototype.adjustGamma = function() {
        u2.adjustGamma(this);
      };
    }).call(this);
  }).call(this, e4("_process"), e4("buffer").Buffer);
}, { "./packer-async": 12, "./parser-async": 16, "./png-sync": 19, _process: 63, buffer: 32, stream: 65, util: 84 }], 21: [function(e4, t2, i2) {
  (function(r2, n2) {
    (function() {
      let r3 = e4("assert").ok, a2 = e4("zlib"), o2 = e4("util"), s2 = e4("buffer").kMaxLength;
      function l2(e5) {
        if (!(this instanceof l2)) return new l2(e5);
        e5 && e5.chunkSize < a2.Z_MIN_CHUNK && (e5.chunkSize = a2.Z_MIN_CHUNK), a2.Inflate.call(this, e5), this._offset = void 0 === this._offset ? this._outOffset : this._offset, this._buffer = this._buffer || this._outBuffer, e5 && null != e5.maxLength && (this._maxLength = e5.maxLength);
      }
      function u2(e5) {
        return new l2(e5);
      }
      function h2(e5, t3) {
        e5._handle && (e5._handle.close(), e5._handle = null);
      }
      function c2(e5, t3) {
        if ("string" == typeof t3 && (t3 = n2.from(t3)), !(t3 instanceof n2)) throw new TypeError("Not a string or buffer");
        let i3 = e5._finishFlushFlag;
        return null == i3 && (i3 = a2.Z_FINISH), e5._processChunk(t3, i3);
      }
      function f2(e5, t3) {
        return c2(new l2(t3), e5);
      }
      l2.prototype._processChunk = function(e5, t3, i3) {
        if ("function" == typeof i3) return a2.Inflate._processChunk.call(this, e5, t3, i3);
        let o3, l3, u3 = this, c3 = e5 && e5.length, f3 = this._chunkSize - this._offset, d = this._maxLength, p2 = 0, m = [], _2 = 0;
        function g(e6, t4) {
          if (u3._hadError) return;
          let i4 = f3 - t4;
          if (r3(i4 >= 0, "have should not go down"), i4 > 0) {
            let e7 = u3._buffer.slice(u3._offset, u3._offset + i4);
            if (u3._offset += i4, e7.length > d && (e7 = e7.slice(0, d)), m.push(e7), _2 += e7.length, d -= e7.length, 0 === d) return false;
          }
          return (0 === t4 || u3._offset >= u3._chunkSize) && (f3 = u3._chunkSize, u3._offset = 0, u3._buffer = n2.allocUnsafe(u3._chunkSize)), 0 === t4 && (p2 += c3 - e6, c3 = e6, true);
        }
        this.on("error", function(e6) {
          o3 = e6;
        }), r3(this._handle, "zlib binding closed");
        do {
          l3 = this._handle.writeSync(t3, e5, p2, c3, this._buffer, this._offset, f3), l3 = l3 || this._writeState;
        } while (!this._hadError && g(l3[0], l3[1]));
        if (this._hadError) throw o3;
        if (_2 >= s2) throw h2(this), new RangeError("Cannot create final Buffer. It would be larger than 0x" + s2.toString(16) + " bytes");
        let b2 = n2.concat(m, _2);
        return h2(this), b2;
      }, o2.inherits(l2, a2.Inflate), t2.exports = i2 = f2, i2.Inflate = l2, i2.createInflate = u2, i2.inflateSync = f2;
    }).call(this);
  }).call(this, e4("_process"), e4("buffer").Buffer);
}, { _process: 63, assert: 23, buffer: 32, util: 84, zlib: 31 }], 22: [function(e4, t2, i2) {
  let r2 = t2.exports = function(e5) {
    this._buffer = e5, this._reads = [];
  };
  r2.prototype.read = function(e5, t3) {
    this._reads.push({ length: Math.abs(e5), allowLess: e5 < 0, func: t3 });
  }, r2.prototype.process = function() {
    for (; this._reads.length > 0 && this._buffer.length; ) {
      let e5 = this._reads[0];
      if (!this._buffer.length || !(this._buffer.length >= e5.length || e5.allowLess)) break;
      {
        this._reads.shift();
        let t3 = this._buffer;
        this._buffer = t3.slice(e5.length), e5.func.call(this, t3.slice(0, e5.length));
      }
    }
    if (this._reads.length > 0) throw new Error("There are some read requests waitng on finished stream");
    if (this._buffer.length > 0) throw new Error("unrecognised content at end of stream");
  };
}, {}], 23: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      var r2 = e4("object-assign");
      /*!
      	 * The buffer module from node.js, for the browser.
      	 *
      	 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
      	 * @license  MIT
      	 */
      function n2(e5, t3) {
        if (e5 === t3) return 0;
        for (var i4 = e5.length, r3 = t3.length, n3 = 0, a3 = Math.min(i4, r3); n3 < a3; ++n3) if (e5[n3] !== t3[n3]) {
          i4 = e5[n3], r3 = t3[n3];
          break;
        }
        return i4 < r3 ? -1 : r3 < i4 ? 1 : 0;
      }
      function a2(e5) {
        return i3.Buffer && "function" == typeof i3.Buffer.isBuffer ? i3.Buffer.isBuffer(e5) : !(null == e5 || !e5._isBuffer);
      }
      var o2 = e4("util/"), s2 = Object.prototype.hasOwnProperty, l2 = Array.prototype.slice, u2 = "foo" === (function() {
      }).name;
      function h2(e5) {
        return Object.prototype.toString.call(e5);
      }
      function c2(e5) {
        return !a2(e5) && "function" == typeof i3.ArrayBuffer && ("function" == typeof ArrayBuffer.isView ? ArrayBuffer.isView(e5) : !!e5 && (e5 instanceof DataView || !!(e5.buffer && e5.buffer instanceof ArrayBuffer)));
      }
      var f2 = t2.exports = y2, d = /\s*function\s+([^\(\s]*)\s*/;
      function p2(e5) {
        if (o2.isFunction(e5)) {
          if (u2) return e5.name;
          var t3 = e5.toString().match(d);
          return t3 && t3[1];
        }
      }
      function m(e5, t3) {
        return "string" == typeof e5 ? e5.length < t3 ? e5 : e5.slice(0, t3) : e5;
      }
      function _2(e5) {
        if (u2 || !o2.isFunction(e5)) return o2.inspect(e5);
        var t3 = p2(e5);
        return "[Function" + (t3 ? ": " + t3 : "") + "]";
      }
      function g(e5) {
        return m(_2(e5.actual), 128) + " " + e5.operator + " " + m(_2(e5.expected), 128);
      }
      function b2(e5, t3, i4, r3, n3) {
        throw new f2.AssertionError({ message: i4, actual: e5, expected: t3, operator: r3, stackStartFunction: n3 });
      }
      function y2(e5, t3) {
        e5 || b2(e5, true, t3, "==", f2.ok);
      }
      function w(e5, t3, i4, r3) {
        if (e5 === t3) return true;
        if (a2(e5) && a2(t3)) return 0 === n2(e5, t3);
        if (o2.isDate(e5) && o2.isDate(t3)) return e5.getTime() === t3.getTime();
        if (o2.isRegExp(e5) && o2.isRegExp(t3)) return e5.source === t3.source && e5.global === t3.global && e5.multiline === t3.multiline && e5.lastIndex === t3.lastIndex && e5.ignoreCase === t3.ignoreCase;
        if (null !== e5 && "object" == typeof e5 || null !== t3 && "object" == typeof t3) {
          if (c2(e5) && c2(t3) && h2(e5) === h2(t3) && !(e5 instanceof Float32Array || e5 instanceof Float64Array)) return 0 === n2(new Uint8Array(e5.buffer), new Uint8Array(t3.buffer));
          if (a2(e5) !== a2(t3)) return false;
          var s3 = (r3 = r3 || { actual: [], expected: [] }).actual.indexOf(e5);
          return -1 !== s3 && s3 === r3.expected.indexOf(t3) || (r3.actual.push(e5), r3.expected.push(t3), x2(e5, t3, i4, r3));
        }
        return i4 ? e5 === t3 : e5 == t3;
      }
      function v2(e5) {
        return "[object Arguments]" == Object.prototype.toString.call(e5);
      }
      function x2(e5, t3, i4, r3) {
        if (null == e5 || null == t3) return false;
        if (o2.isPrimitive(e5) || o2.isPrimitive(t3)) return e5 === t3;
        if (i4 && Object.getPrototypeOf(e5) !== Object.getPrototypeOf(t3)) return false;
        var n3 = v2(e5), a3 = v2(t3);
        if (n3 && !a3 || !n3 && a3) return false;
        if (n3) return w(e5 = l2.call(e5), t3 = l2.call(t3), i4);
        var s3, u3, h3 = M2(e5), c3 = M2(t3);
        if (h3.length !== c3.length) return false;
        for (h3.sort(), c3.sort(), u3 = h3.length - 1; u3 >= 0; u3--) if (h3[u3] !== c3[u3]) return false;
        for (u3 = h3.length - 1; u3 >= 0; u3--) if (!w(e5[s3 = h3[u3]], t3[s3], i4, r3)) return false;
        return true;
      }
      function E2(e5, t3, i4) {
        w(e5, t3, true) && b2(e5, t3, i4, "notDeepStrictEqual", E2);
      }
      function k2(e5, t3) {
        if (!e5 || !t3) return false;
        if ("[object RegExp]" == Object.prototype.toString.call(t3)) return t3.test(e5);
        try {
          if (e5 instanceof t3) return true;
        } catch (e6) {
        }
        return !Error.isPrototypeOf(t3) && true === t3.call({}, e5);
      }
      function S2(e5) {
        var t3;
        try {
          e5();
        } catch (e6) {
          t3 = e6;
        }
        return t3;
      }
      function A2(e5, t3, i4, r3) {
        var n3;
        if ("function" != typeof t3) throw new TypeError('"block" argument must be a function');
        "string" == typeof i4 && (r3 = i4, i4 = null), n3 = S2(t3), r3 = (i4 && i4.name ? " (" + i4.name + ")." : ".") + (r3 ? " " + r3 : "."), e5 && !n3 && b2(n3, i4, "Missing expected exception" + r3);
        var a3 = "string" == typeof r3, s3 = !e5 && n3 && !i4;
        if ((!e5 && o2.isError(n3) && a3 && k2(n3, i4) || s3) && b2(n3, i4, "Got unwanted exception" + r3), e5 && n3 && i4 && !k2(n3, i4) || !e5 && n3) throw n3;
      }
      function I(e5, t3) {
        e5 || b2(e5, true, t3, "==", I);
      }
      f2.AssertionError = function(e5) {
        this.name = "AssertionError", this.actual = e5.actual, this.expected = e5.expected, this.operator = e5.operator, e5.message ? (this.message = e5.message, this.generatedMessage = false) : (this.message = g(this), this.generatedMessage = true);
        var t3 = e5.stackStartFunction || b2;
        if (Error.captureStackTrace) Error.captureStackTrace(this, t3);
        else {
          var i4 = new Error();
          if (i4.stack) {
            var r3 = i4.stack, n3 = p2(t3), a3 = r3.indexOf("\n" + n3);
            if (a3 >= 0) {
              var o3 = r3.indexOf("\n", a3 + 1);
              r3 = r3.substring(o3 + 1);
            }
            this.stack = r3;
          }
        }
      }, o2.inherits(f2.AssertionError, Error), f2.fail = b2, f2.ok = y2, f2.equal = function(e5, t3, i4) {
        e5 != t3 && b2(e5, t3, i4, "==", f2.equal);
      }, f2.notEqual = function(e5, t3, i4) {
        e5 == t3 && b2(e5, t3, i4, "!=", f2.notEqual);
      }, f2.deepEqual = function(e5, t3, i4) {
        w(e5, t3, false) || b2(e5, t3, i4, "deepEqual", f2.deepEqual);
      }, f2.deepStrictEqual = function(e5, t3, i4) {
        w(e5, t3, true) || b2(e5, t3, i4, "deepStrictEqual", f2.deepStrictEqual);
      }, f2.notDeepEqual = function(e5, t3, i4) {
        w(e5, t3, false) && b2(e5, t3, i4, "notDeepEqual", f2.notDeepEqual);
      }, f2.notDeepStrictEqual = E2, f2.strictEqual = function(e5, t3, i4) {
        e5 !== t3 && b2(e5, t3, i4, "===", f2.strictEqual);
      }, f2.notStrictEqual = function(e5, t3, i4) {
        e5 === t3 && b2(e5, t3, i4, "!==", f2.notStrictEqual);
      }, f2.throws = function(e5, t3, i4) {
        A2(true, e5, t3, i4);
      }, f2.doesNotThrow = function(e5, t3, i4) {
        A2(false, e5, t3, i4);
      }, f2.ifError = function(e5) {
        if (e5) throw e5;
      }, f2.strict = r2(I, f2, { equal: f2.strictEqual, deepEqual: f2.deepStrictEqual, notEqual: f2.notStrictEqual, notDeepEqual: f2.notDeepStrictEqual }), f2.strict.strict = f2.strict;
      var M2 = Object.keys || function(e5) {
        var t3 = [];
        for (var i4 in e5) s2.call(e5, i4) && t3.push(i4);
        return t3;
      };
    }).call(this);
  }).call(this, void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "object-assign": 51, "util/": 26 }], 24: [function(e4, t2, i2) {
  "function" == typeof Object.create ? t2.exports = function(e5, t3) {
    e5.super_ = t3, e5.prototype = Object.create(t3.prototype, { constructor: { value: e5, enumerable: false, writable: true, configurable: true } });
  } : t2.exports = function(e5, t3) {
    e5.super_ = t3;
    var i3 = function() {
    };
    i3.prototype = t3.prototype, e5.prototype = new i3(), e5.prototype.constructor = e5;
  };
}, {}], 25: [function(e4, t2, i2) {
  t2.exports = function(e5) {
    return e5 && "object" == typeof e5 && "function" == typeof e5.copy && "function" == typeof e5.fill && "function" == typeof e5.readUInt8;
  };
}, {}], 26: [function(e4, t2, i2) {
  (function(t3, r2) {
    (function() {
      var n2 = /%[sdj%]/g;
      i2.format = function(e5) {
        if (!x2(e5)) {
          for (var t4 = [], i3 = 0; i3 < arguments.length; i3++) t4.push(s2(arguments[i3]));
          return t4.join(" ");
        }
        i3 = 1;
        for (var r3 = arguments, a3 = r3.length, o3 = String(e5).replace(n2, function(e6) {
          if ("%%" === e6) return "%";
          if (i3 >= a3) return e6;
          switch (e6) {
            case "%s":
              return String(r3[i3++]);
            case "%d":
              return Number(r3[i3++]);
            case "%j":
              try {
                return JSON.stringify(r3[i3++]);
              } catch (e7) {
                return "[Circular]";
              }
            default:
              return e6;
          }
        }), l3 = r3[i3]; i3 < a3; l3 = r3[++i3]) y2(l3) || !A2(l3) ? o3 += " " + l3 : o3 += " " + s2(l3);
        return o3;
      }, i2.deprecate = function(e5, n3) {
        if (k2(r2.process)) return function() {
          return i2.deprecate(e5, n3).apply(this, arguments);
        };
        if (true === t3.noDeprecation) return e5;
        var a3 = false;
        function o3() {
          if (!a3) {
            if (t3.throwDeprecation) throw new Error(n3);
            t3.traceDeprecation ? console.trace(n3) : console.error(n3), a3 = true;
          }
          return e5.apply(this, arguments);
        }
        return o3;
      };
      var a2, o2 = {};
      function s2(e5, t4) {
        var r3 = { seen: [], stylize: u2 };
        return arguments.length >= 3 && (r3.depth = arguments[2]), arguments.length >= 4 && (r3.colors = arguments[3]), b2(t4) ? r3.showHidden = t4 : t4 && i2._extend(r3, t4), k2(r3.showHidden) && (r3.showHidden = false), k2(r3.depth) && (r3.depth = 2), k2(r3.colors) && (r3.colors = false), k2(r3.customInspect) && (r3.customInspect = true), r3.colors && (r3.stylize = l2), c2(r3, e5, r3.depth);
      }
      function l2(e5, t4) {
        var i3 = s2.styles[t4];
        return i3 ? "\x1B[" + s2.colors[i3][0] + "m" + e5 + "\x1B[" + s2.colors[i3][1] + "m" : e5;
      }
      function u2(e5, t4) {
        return e5;
      }
      function h2(e5) {
        var t4 = {};
        return e5.forEach(function(e6, i3) {
          t4[e6] = true;
        }), t4;
      }
      function c2(e5, t4, r3) {
        if (e5.customInspect && t4 && T2(t4.inspect) && t4.inspect !== i2.inspect && (!t4.constructor || t4.constructor.prototype !== t4)) {
          var n3 = t4.inspect(r3, e5);
          return x2(n3) || (n3 = c2(e5, n3, r3)), n3;
        }
        var a3 = f2(e5, t4);
        if (a3) return a3;
        var o3 = Object.keys(t4), s3 = h2(o3);
        if (e5.showHidden && (o3 = Object.getOwnPropertyNames(t4)), M2(t4) && (o3.indexOf("message") >= 0 || o3.indexOf("description") >= 0)) return d(t4);
        if (0 === o3.length) {
          if (T2(t4)) {
            var l3 = t4.name ? ": " + t4.name : "";
            return e5.stylize("[Function" + l3 + "]", "special");
          }
          if (S2(t4)) return e5.stylize(RegExp.prototype.toString.call(t4), "regexp");
          if (I(t4)) return e5.stylize(Date.prototype.toString.call(t4), "date");
          if (M2(t4)) return d(t4);
        }
        var u3, b3 = "", y3 = false, w2 = ["{", "}"];
        return g(t4) && (y3 = true, w2 = ["[", "]"]), T2(t4) && (b3 = " [Function" + (t4.name ? ": " + t4.name : "") + "]"), S2(t4) && (b3 = " " + RegExp.prototype.toString.call(t4)), I(t4) && (b3 = " " + Date.prototype.toUTCString.call(t4)), M2(t4) && (b3 = " " + d(t4)), 0 !== o3.length || y3 && 0 != t4.length ? r3 < 0 ? S2(t4) ? e5.stylize(RegExp.prototype.toString.call(t4), "regexp") : e5.stylize("[Object]", "special") : (e5.seen.push(t4), u3 = y3 ? p2(e5, t4, r3, s3, o3) : o3.map(function(i3) {
          return m(e5, t4, r3, s3, i3, y3);
        }), e5.seen.pop(), _2(u3, b3, w2)) : w2[0] + b3 + w2[1];
      }
      function f2(e5, t4) {
        if (k2(t4)) return e5.stylize("undefined", "undefined");
        if (x2(t4)) {
          var i3 = "'" + JSON.stringify(t4).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
          return e5.stylize(i3, "string");
        }
        return v2(t4) ? e5.stylize("" + t4, "number") : b2(t4) ? e5.stylize("" + t4, "boolean") : y2(t4) ? e5.stylize("null", "null") : void 0;
      }
      function d(e5) {
        return "[" + Error.prototype.toString.call(e5) + "]";
      }
      function p2(e5, t4, i3, r3, n3) {
        for (var a3 = [], o3 = 0, s3 = t4.length; o3 < s3; ++o3) F(t4, String(o3)) ? a3.push(m(e5, t4, i3, r3, String(o3), true)) : a3.push("");
        return n3.forEach(function(n4) {
          n4.match(/^\d+$/) || a3.push(m(e5, t4, i3, r3, n4, true));
        }), a3;
      }
      function m(e5, t4, i3, r3, n3, a3) {
        var o3, s3, l3;
        if ((l3 = Object.getOwnPropertyDescriptor(t4, n3) || { value: t4[n3] }).get ? s3 = l3.set ? e5.stylize("[Getter/Setter]", "special") : e5.stylize("[Getter]", "special") : l3.set && (s3 = e5.stylize("[Setter]", "special")), F(r3, n3) || (o3 = "[" + n3 + "]"), s3 || (e5.seen.indexOf(l3.value) < 0 ? (s3 = y2(i3) ? c2(e5, l3.value, null) : c2(e5, l3.value, i3 - 1)).indexOf("\n") > -1 && (s3 = a3 ? s3.split("\n").map(function(e6) {
          return "  " + e6;
        }).join("\n").substr(2) : "\n" + s3.split("\n").map(function(e6) {
          return "   " + e6;
        }).join("\n")) : s3 = e5.stylize("[Circular]", "special")), k2(o3)) {
          if (a3 && n3.match(/^\d+$/)) return s3;
          (o3 = JSON.stringify("" + n3)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/) ? (o3 = o3.substr(1, o3.length - 2), o3 = e5.stylize(o3, "name")) : (o3 = o3.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), o3 = e5.stylize(o3, "string"));
        }
        return o3 + ": " + s3;
      }
      function _2(e5, t4, i3) {
        return e5.reduce(function(e6, t5) {
          return t5.indexOf("\n"), e6 + t5.replace(/\u001b\[\d\d?m/g, "").length + 1;
        }, 0) > 60 ? i3[0] + ("" === t4 ? "" : t4 + "\n ") + " " + e5.join(",\n  ") + " " + i3[1] : i3[0] + t4 + " " + e5.join(", ") + " " + i3[1];
      }
      function g(e5) {
        return Array.isArray(e5);
      }
      function b2(e5) {
        return "boolean" == typeof e5;
      }
      function y2(e5) {
        return null === e5;
      }
      function w(e5) {
        return null == e5;
      }
      function v2(e5) {
        return "number" == typeof e5;
      }
      function x2(e5) {
        return "string" == typeof e5;
      }
      function E2(e5) {
        return "symbol" == typeof e5;
      }
      function k2(e5) {
        return void 0 === e5;
      }
      function S2(e5) {
        return A2(e5) && "[object RegExp]" === B2(e5);
      }
      function A2(e5) {
        return "object" == typeof e5 && null !== e5;
      }
      function I(e5) {
        return A2(e5) && "[object Date]" === B2(e5);
      }
      function M2(e5) {
        return A2(e5) && ("[object Error]" === B2(e5) || e5 instanceof Error);
      }
      function T2(e5) {
        return "function" == typeof e5;
      }
      function P(e5) {
        return null === e5 || "boolean" == typeof e5 || "number" == typeof e5 || "string" == typeof e5 || "symbol" == typeof e5 || void 0 === e5;
      }
      function B2(e5) {
        return Object.prototype.toString.call(e5);
      }
      function C2(e5) {
        return e5 < 10 ? "0" + e5.toString(10) : e5.toString(10);
      }
      i2.debuglog = function(e5) {
        if (k2(a2) && (a2 = t3.env.NODE_DEBUG || ""), e5 = e5.toUpperCase(), !o2[e5]) if (new RegExp("\\b" + e5 + "\\b", "i").test(a2)) {
          var r3 = t3.pid;
          o2[e5] = function() {
            var t4 = i2.format.apply(i2, arguments);
            console.error("%s %d: %s", e5, r3, t4);
          };
        } else o2[e5] = function() {
        };
        return o2[e5];
      }, i2.inspect = s2, s2.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, s2.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, i2.isArray = g, i2.isBoolean = b2, i2.isNull = y2, i2.isNullOrUndefined = w, i2.isNumber = v2, i2.isString = x2, i2.isSymbol = E2, i2.isUndefined = k2, i2.isRegExp = S2, i2.isObject = A2, i2.isDate = I, i2.isError = M2, i2.isFunction = T2, i2.isPrimitive = P, i2.isBuffer = e4("./support/isBuffer");
      var R2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      function z2() {
        var e5 = /* @__PURE__ */ new Date(), t4 = [C2(e5.getHours()), C2(e5.getMinutes()), C2(e5.getSeconds())].join(":");
        return [e5.getDate(), R2[e5.getMonth()], t4].join(" ");
      }
      function F(e5, t4) {
        return Object.prototype.hasOwnProperty.call(e5, t4);
      }
      i2.log = function() {
        console.log("%s - %s", z2(), i2.format.apply(i2, arguments));
      }, i2.inherits = e4("inherits"), i2._extend = function(e5, t4) {
        if (!t4 || !A2(t4)) return e5;
        for (var i3 = Object.keys(t4), r3 = i3.length; r3--; ) e5[i3[r3]] = t4[i3[r3]];
        return e5;
      };
    }).call(this);
  }).call(this, e4("_process"), void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "./support/isBuffer": 25, _process: 63, inherits: 24 }], 27: [function(e4, t2, i2) {
  (function(e5) {
    (function() {
      var i3 = ["BigInt64Array", "BigUint64Array", "Float32Array", "Float64Array", "Int16Array", "Int32Array", "Int8Array", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray"], r2 = "undefined" == typeof globalThis ? e5 : globalThis;
      t2.exports = function() {
        for (var e6 = [], t3 = 0; t3 < i3.length; t3++) "function" == typeof r2[i3[t3]] && (e6[e6.length] = i3[t3]);
        return e6;
      };
    }).call(this);
  }).call(this, void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}], 28: [function(e4, t2, i2) {
  i2.byteLength = h2, i2.toByteArray = f2, i2.fromByteArray = m;
  for (var r2 = [], n2 = [], a2 = "undefined" != typeof Uint8Array ? Uint8Array : Array, o2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", s2 = 0, l2 = o2.length; s2 < l2; ++s2) r2[s2] = o2[s2], n2[o2.charCodeAt(s2)] = s2;
  function u2(e5) {
    var t3 = e5.length;
    if (t3 % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
    var i3 = e5.indexOf("=");
    return -1 === i3 && (i3 = t3), [i3, i3 === t3 ? 0 : 4 - i3 % 4];
  }
  function h2(e5) {
    var t3 = u2(e5), i3 = t3[0], r3 = t3[1];
    return 3 * (i3 + r3) / 4 - r3;
  }
  function c2(e5, t3, i3) {
    return 3 * (t3 + i3) / 4 - i3;
  }
  function f2(e5) {
    var t3, i3, r3 = u2(e5), o3 = r3[0], s3 = r3[1], l3 = new a2(c2(e5, o3, s3)), h3 = 0, f3 = s3 > 0 ? o3 - 4 : o3;
    for (i3 = 0; i3 < f3; i3 += 4) t3 = n2[e5.charCodeAt(i3)] << 18 | n2[e5.charCodeAt(i3 + 1)] << 12 | n2[e5.charCodeAt(i3 + 2)] << 6 | n2[e5.charCodeAt(i3 + 3)], l3[h3++] = t3 >> 16 & 255, l3[h3++] = t3 >> 8 & 255, l3[h3++] = 255 & t3;
    return 2 === s3 && (t3 = n2[e5.charCodeAt(i3)] << 2 | n2[e5.charCodeAt(i3 + 1)] >> 4, l3[h3++] = 255 & t3), 1 === s3 && (t3 = n2[e5.charCodeAt(i3)] << 10 | n2[e5.charCodeAt(i3 + 1)] << 4 | n2[e5.charCodeAt(i3 + 2)] >> 2, l3[h3++] = t3 >> 8 & 255, l3[h3++] = 255 & t3), l3;
  }
  function d(e5) {
    return r2[e5 >> 18 & 63] + r2[e5 >> 12 & 63] + r2[e5 >> 6 & 63] + r2[63 & e5];
  }
  function p2(e5, t3, i3) {
    for (var r3, n3 = [], a3 = t3; a3 < i3; a3 += 3) r3 = (e5[a3] << 16 & 16711680) + (e5[a3 + 1] << 8 & 65280) + (255 & e5[a3 + 2]), n3.push(d(r3));
    return n3.join("");
  }
  function m(e5) {
    for (var t3, i3 = e5.length, n3 = i3 % 3, a3 = [], o3 = 16383, s3 = 0, l3 = i3 - n3; s3 < l3; s3 += o3) a3.push(p2(e5, s3, s3 + o3 > l3 ? l3 : s3 + o3));
    return 1 === n3 ? (t3 = e5[i3 - 1], a3.push(r2[t3 >> 2] + r2[t3 << 4 & 63] + "==")) : 2 === n3 && (t3 = (e5[i3 - 2] << 8) + e5[i3 - 1], a3.push(r2[t3 >> 10] + r2[t3 >> 4 & 63] + r2[t3 << 2 & 63] + "=")), a3.join("");
  }
  n2["-".charCodeAt(0)] = 62, n2["_".charCodeAt(0)] = 63;
}, {}], 29: [function(e4, t2, i2) {
}, {}], 30: [function(e4, t2, i2) {
  (function(t3, r2) {
    (function() {
      var n2 = e4("assert"), a2 = e4("pako/lib/zlib/zstream"), o2 = e4("pako/lib/zlib/deflate.js"), s2 = e4("pako/lib/zlib/inflate.js"), l2 = e4("pako/lib/zlib/constants");
      for (var u2 in l2) i2[u2] = l2[u2];
      i2.NONE = 0, i2.DEFLATE = 1, i2.INFLATE = 2, i2.GZIP = 3, i2.GUNZIP = 4, i2.DEFLATERAW = 5, i2.INFLATERAW = 6, i2.UNZIP = 7;
      var h2 = 31, c2 = 139;
      function f2(e5) {
        if ("number" != typeof e5 || e5 < i2.DEFLATE || e5 > i2.UNZIP) throw new TypeError("Bad argument");
        this.dictionary = null, this.err = 0, this.flush = 0, this.init_done = false, this.level = 0, this.memLevel = 0, this.mode = e5, this.strategy = 0, this.windowBits = 0, this.write_in_progress = false, this.pending_close = false, this.gzip_id_bytes_read = 0;
      }
      f2.prototype.close = function() {
        this.write_in_progress ? this.pending_close = true : (this.pending_close = false, n2(this.init_done, "close before init"), n2(this.mode <= i2.UNZIP), this.mode === i2.DEFLATE || this.mode === i2.GZIP || this.mode === i2.DEFLATERAW ? o2.deflateEnd(this.strm) : this.mode !== i2.INFLATE && this.mode !== i2.GUNZIP && this.mode !== i2.INFLATERAW && this.mode !== i2.UNZIP || s2.inflateEnd(this.strm), this.mode = i2.NONE, this.dictionary = null);
      }, f2.prototype.write = function(e5, t4, i3, r3, n3, a3, o3) {
        return this._write(true, e5, t4, i3, r3, n3, a3, o3);
      }, f2.prototype.writeSync = function(e5, t4, i3, r3, n3, a3, o3) {
        return this._write(false, e5, t4, i3, r3, n3, a3, o3);
      }, f2.prototype._write = function(e5, a3, o3, s3, l3, u3, h3, c3) {
        if (n2.equal(arguments.length, 8), n2(this.init_done, "write before init"), n2(this.mode !== i2.NONE, "already finalized"), n2.equal(false, this.write_in_progress, "write already in progress"), n2.equal(false, this.pending_close, "close is pending"), this.write_in_progress = true, n2.equal(false, void 0 === a3, "must provide flush value"), this.write_in_progress = true, a3 !== i2.Z_NO_FLUSH && a3 !== i2.Z_PARTIAL_FLUSH && a3 !== i2.Z_SYNC_FLUSH && a3 !== i2.Z_FULL_FLUSH && a3 !== i2.Z_FINISH && a3 !== i2.Z_BLOCK) throw new Error("Invalid flush value");
        if (null == o3 && (o3 = r2.alloc(0), l3 = 0, s3 = 0), this.strm.avail_in = l3, this.strm.input = o3, this.strm.next_in = s3, this.strm.avail_out = c3, this.strm.output = u3, this.strm.next_out = h3, this.flush = a3, !e5) return this._process(), this._checkError() ? this._afterSync() : void 0;
        var f3 = this;
        return t3.nextTick(function() {
          f3._process(), f3._after();
        }), this;
      }, f2.prototype._afterSync = function() {
        var e5 = this.strm.avail_out, t4 = this.strm.avail_in;
        return this.write_in_progress = false, [t4, e5];
      }, f2.prototype._process = function() {
        var e5 = null;
        switch (this.mode) {
          case i2.DEFLATE:
          case i2.GZIP:
          case i2.DEFLATERAW:
            this.err = o2.deflate(this.strm, this.flush);
            break;
          case i2.UNZIP:
            switch (this.strm.avail_in > 0 && (e5 = this.strm.next_in), this.gzip_id_bytes_read) {
              case 0:
                if (null === e5) break;
                if (this.strm.input[e5] !== h2) {
                  this.mode = i2.INFLATE;
                  break;
                }
                if (this.gzip_id_bytes_read = 1, e5++, 1 === this.strm.avail_in) break;
              case 1:
                if (null === e5) break;
                this.strm.input[e5] === c2 ? (this.gzip_id_bytes_read = 2, this.mode = i2.GUNZIP) : this.mode = i2.INFLATE;
                break;
              default:
                throw new Error("invalid number of gzip magic number bytes read");
            }
          case i2.INFLATE:
          case i2.GUNZIP:
          case i2.INFLATERAW:
            for (this.err = s2.inflate(this.strm, this.flush), this.err === i2.Z_NEED_DICT && this.dictionary && (this.err = s2.inflateSetDictionary(this.strm, this.dictionary), this.err === i2.Z_OK ? this.err = s2.inflate(this.strm, this.flush) : this.err === i2.Z_DATA_ERROR && (this.err = i2.Z_NEED_DICT)); this.strm.avail_in > 0 && this.mode === i2.GUNZIP && this.err === i2.Z_STREAM_END && 0 !== this.strm.next_in[0]; ) this.reset(), this.err = s2.inflate(this.strm, this.flush);
            break;
          default:
            throw new Error("Unknown mode " + this.mode);
        }
      }, f2.prototype._checkError = function() {
        switch (this.err) {
          case i2.Z_OK:
          case i2.Z_BUF_ERROR:
            if (0 !== this.strm.avail_out && this.flush === i2.Z_FINISH) return this._error("unexpected end of file"), false;
            break;
          case i2.Z_STREAM_END:
            break;
          case i2.Z_NEED_DICT:
            return null == this.dictionary ? this._error("Missing dictionary") : this._error("Bad dictionary"), false;
          default:
            return this._error("Zlib error"), false;
        }
        return true;
      }, f2.prototype._after = function() {
        if (this._checkError()) {
          var e5 = this.strm.avail_out, t4 = this.strm.avail_in;
          this.write_in_progress = false, this.callback(t4, e5), this.pending_close && this.close();
        }
      }, f2.prototype._error = function(e5) {
        this.strm.msg && (e5 = this.strm.msg), this.onerror(e5, this.err), this.write_in_progress = false, this.pending_close && this.close();
      }, f2.prototype.init = function(e5, t4, r3, a3, o3) {
        n2(4 === arguments.length || 5 === arguments.length, "init(windowBits, level, memLevel, strategy, [dictionary])"), n2(e5 >= 8 && e5 <= 15, "invalid windowBits"), n2(t4 >= -1 && t4 <= 9, "invalid compression level"), n2(r3 >= 1 && r3 <= 9, "invalid memlevel"), n2(a3 === i2.Z_FILTERED || a3 === i2.Z_HUFFMAN_ONLY || a3 === i2.Z_RLE || a3 === i2.Z_FIXED || a3 === i2.Z_DEFAULT_STRATEGY, "invalid strategy"), this._init(t4, e5, r3, a3, o3), this._setDictionary();
      }, f2.prototype.params = function() {
        throw new Error("deflateParams Not supported");
      }, f2.prototype.reset = function() {
        this._reset(), this._setDictionary();
      }, f2.prototype._init = function(e5, t4, r3, n3, l3) {
        switch (this.level = e5, this.windowBits = t4, this.memLevel = r3, this.strategy = n3, this.flush = i2.Z_NO_FLUSH, this.err = i2.Z_OK, this.mode !== i2.GZIP && this.mode !== i2.GUNZIP || (this.windowBits += 16), this.mode === i2.UNZIP && (this.windowBits += 32), this.mode !== i2.DEFLATERAW && this.mode !== i2.INFLATERAW || (this.windowBits = -1 * this.windowBits), this.strm = new a2(), this.mode) {
          case i2.DEFLATE:
          case i2.GZIP:
          case i2.DEFLATERAW:
            this.err = o2.deflateInit2(this.strm, this.level, i2.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
            break;
          case i2.INFLATE:
          case i2.GUNZIP:
          case i2.INFLATERAW:
          case i2.UNZIP:
            this.err = s2.inflateInit2(this.strm, this.windowBits);
            break;
          default:
            throw new Error("Unknown mode " + this.mode);
        }
        this.err !== i2.Z_OK && this._error("Init error"), this.dictionary = l3, this.write_in_progress = false, this.init_done = true;
      }, f2.prototype._setDictionary = function() {
        if (null != this.dictionary) {
          switch (this.err = i2.Z_OK, this.mode) {
            case i2.DEFLATE:
            case i2.DEFLATERAW:
              this.err = o2.deflateSetDictionary(this.strm, this.dictionary);
          }
          this.err !== i2.Z_OK && this._error("Failed to set dictionary");
        }
      }, f2.prototype._reset = function() {
        switch (this.err = i2.Z_OK, this.mode) {
          case i2.DEFLATE:
          case i2.DEFLATERAW:
          case i2.GZIP:
            this.err = o2.deflateReset(this.strm);
            break;
          case i2.INFLATE:
          case i2.INFLATERAW:
          case i2.GUNZIP:
            this.err = s2.inflateReset(this.strm);
        }
        this.err !== i2.Z_OK && this._error("Failed to reset stream");
      }, i2.Zlib = f2;
    }).call(this);
  }).call(this, e4("_process"), e4("buffer").Buffer);
}, { _process: 63, assert: 23, buffer: 32, "pako/lib/zlib/constants": 54, "pako/lib/zlib/deflate.js": 56, "pako/lib/zlib/inflate.js": 58, "pako/lib/zlib/zstream": 62 }], 31: [function(e4, t2, i2) {
  (function(t3) {
    (function() {
      var r2 = e4("buffer").Buffer, n2 = e4("stream").Transform, a2 = e4("./binding"), o2 = e4("util"), s2 = e4("assert").ok, l2 = e4("buffer").kMaxLength, u2 = "Cannot create final Buffer. It would be larger than 0x" + l2.toString(16) + " bytes";
      a2.Z_MIN_WINDOWBITS = 8, a2.Z_MAX_WINDOWBITS = 15, a2.Z_DEFAULT_WINDOWBITS = 15, a2.Z_MIN_CHUNK = 64, a2.Z_MAX_CHUNK = 1 / 0, a2.Z_DEFAULT_CHUNK = 16384, a2.Z_MIN_MEMLEVEL = 1, a2.Z_MAX_MEMLEVEL = 9, a2.Z_DEFAULT_MEMLEVEL = 8, a2.Z_MIN_LEVEL = -1, a2.Z_MAX_LEVEL = 9, a2.Z_DEFAULT_LEVEL = a2.Z_DEFAULT_COMPRESSION;
      for (var h2 = Object.keys(a2), c2 = 0; c2 < h2.length; c2++) {
        var f2 = h2[c2];
        f2.match(/^Z/) && Object.defineProperty(i2, f2, { enumerable: true, value: a2[f2], writable: false });
      }
      for (var d = { Z_OK: a2.Z_OK, Z_STREAM_END: a2.Z_STREAM_END, Z_NEED_DICT: a2.Z_NEED_DICT, Z_ERRNO: a2.Z_ERRNO, Z_STREAM_ERROR: a2.Z_STREAM_ERROR, Z_DATA_ERROR: a2.Z_DATA_ERROR, Z_MEM_ERROR: a2.Z_MEM_ERROR, Z_BUF_ERROR: a2.Z_BUF_ERROR, Z_VERSION_ERROR: a2.Z_VERSION_ERROR }, p2 = Object.keys(d), m = 0; m < p2.length; m++) {
        var _2 = p2[m];
        d[d[_2]] = _2;
      }
      function g(e5, t4, i3) {
        var n3 = [], a3 = 0;
        function o3() {
          for (var t5; null !== (t5 = e5.read()); ) n3.push(t5), a3 += t5.length;
          e5.once("readable", o3);
        }
        function s3(t5) {
          e5.removeListener("end", h3), e5.removeListener("readable", o3), i3(t5);
        }
        function h3() {
          var t5, o4 = null;
          a3 >= l2 ? o4 = new RangeError(u2) : t5 = r2.concat(n3, a3), n3 = [], e5.close(), i3(o4, t5);
        }
        e5.on("error", s3), e5.on("end", h3), e5.end(t4), o3();
      }
      function b2(e5, t4) {
        if ("string" == typeof t4 && (t4 = r2.from(t4)), !r2.isBuffer(t4)) throw new TypeError("Not a string or buffer");
        var i3 = e5._finishFlushFlag;
        return e5._processChunk(t4, i3);
      }
      function y2(e5) {
        if (!(this instanceof y2)) return new y2(e5);
        I.call(this, e5, a2.DEFLATE);
      }
      function w(e5) {
        if (!(this instanceof w)) return new w(e5);
        I.call(this, e5, a2.INFLATE);
      }
      function v2(e5) {
        if (!(this instanceof v2)) return new v2(e5);
        I.call(this, e5, a2.GZIP);
      }
      function x2(e5) {
        if (!(this instanceof x2)) return new x2(e5);
        I.call(this, e5, a2.GUNZIP);
      }
      function E2(e5) {
        if (!(this instanceof E2)) return new E2(e5);
        I.call(this, e5, a2.DEFLATERAW);
      }
      function k2(e5) {
        if (!(this instanceof k2)) return new k2(e5);
        I.call(this, e5, a2.INFLATERAW);
      }
      function S2(e5) {
        if (!(this instanceof S2)) return new S2(e5);
        I.call(this, e5, a2.UNZIP);
      }
      function A2(e5) {
        return e5 === a2.Z_NO_FLUSH || e5 === a2.Z_PARTIAL_FLUSH || e5 === a2.Z_SYNC_FLUSH || e5 === a2.Z_FULL_FLUSH || e5 === a2.Z_FINISH || e5 === a2.Z_BLOCK;
      }
      function I(e5, t4) {
        var o3 = this;
        if (this._opts = e5 = e5 || {}, this._chunkSize = e5.chunkSize || i2.Z_DEFAULT_CHUNK, n2.call(this, e5), e5.flush && !A2(e5.flush)) throw new Error("Invalid flush flag: " + e5.flush);
        if (e5.finishFlush && !A2(e5.finishFlush)) throw new Error("Invalid flush flag: " + e5.finishFlush);
        if (this._flushFlag = e5.flush || a2.Z_NO_FLUSH, this._finishFlushFlag = void 0 !== e5.finishFlush ? e5.finishFlush : a2.Z_FINISH, e5.chunkSize && (e5.chunkSize < i2.Z_MIN_CHUNK || e5.chunkSize > i2.Z_MAX_CHUNK)) throw new Error("Invalid chunk size: " + e5.chunkSize);
        if (e5.windowBits && (e5.windowBits < i2.Z_MIN_WINDOWBITS || e5.windowBits > i2.Z_MAX_WINDOWBITS)) throw new Error("Invalid windowBits: " + e5.windowBits);
        if (e5.level && (e5.level < i2.Z_MIN_LEVEL || e5.level > i2.Z_MAX_LEVEL)) throw new Error("Invalid compression level: " + e5.level);
        if (e5.memLevel && (e5.memLevel < i2.Z_MIN_MEMLEVEL || e5.memLevel > i2.Z_MAX_MEMLEVEL)) throw new Error("Invalid memLevel: " + e5.memLevel);
        if (e5.strategy && e5.strategy != i2.Z_FILTERED && e5.strategy != i2.Z_HUFFMAN_ONLY && e5.strategy != i2.Z_RLE && e5.strategy != i2.Z_FIXED && e5.strategy != i2.Z_DEFAULT_STRATEGY) throw new Error("Invalid strategy: " + e5.strategy);
        if (e5.dictionary && !r2.isBuffer(e5.dictionary)) throw new Error("Invalid dictionary: it should be a Buffer instance");
        this._handle = new a2.Zlib(t4);
        var s3 = this;
        this._hadError = false, this._handle.onerror = function(e6, t5) {
          M2(s3), s3._hadError = true;
          var r3 = new Error(e6);
          r3.errno = t5, r3.code = i2.codes[t5], s3.emit("error", r3);
        };
        var l3 = i2.Z_DEFAULT_COMPRESSION;
        "number" == typeof e5.level && (l3 = e5.level);
        var u3 = i2.Z_DEFAULT_STRATEGY;
        "number" == typeof e5.strategy && (u3 = e5.strategy), this._handle.init(e5.windowBits || i2.Z_DEFAULT_WINDOWBITS, l3, e5.memLevel || i2.Z_DEFAULT_MEMLEVEL, u3, e5.dictionary), this._buffer = r2.allocUnsafe(this._chunkSize), this._offset = 0, this._level = l3, this._strategy = u3, this.once("end", this.close), Object.defineProperty(this, "_closed", { get: function() {
          return !o3._handle;
        }, configurable: true, enumerable: true });
      }
      function M2(e5, i3) {
        i3 && t3.nextTick(i3), e5._handle && (e5._handle.close(), e5._handle = null);
      }
      function T2(e5) {
        e5.emit("close");
      }
      Object.defineProperty(i2, "codes", { enumerable: true, value: Object.freeze(d), writable: false }), i2.Deflate = y2, i2.Inflate = w, i2.Gzip = v2, i2.Gunzip = x2, i2.DeflateRaw = E2, i2.InflateRaw = k2, i2.Unzip = S2, i2.createDeflate = function(e5) {
        return new y2(e5);
      }, i2.createInflate = function(e5) {
        return new w(e5);
      }, i2.createDeflateRaw = function(e5) {
        return new E2(e5);
      }, i2.createInflateRaw = function(e5) {
        return new k2(e5);
      }, i2.createGzip = function(e5) {
        return new v2(e5);
      }, i2.createGunzip = function(e5) {
        return new x2(e5);
      }, i2.createUnzip = function(e5) {
        return new S2(e5);
      }, i2.deflate = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new y2(t4), e5, i3);
      }, i2.deflateSync = function(e5, t4) {
        return b2(new y2(t4), e5);
      }, i2.gzip = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new v2(t4), e5, i3);
      }, i2.gzipSync = function(e5, t4) {
        return b2(new v2(t4), e5);
      }, i2.deflateRaw = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new E2(t4), e5, i3);
      }, i2.deflateRawSync = function(e5, t4) {
        return b2(new E2(t4), e5);
      }, i2.unzip = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new S2(t4), e5, i3);
      }, i2.unzipSync = function(e5, t4) {
        return b2(new S2(t4), e5);
      }, i2.inflate = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new w(t4), e5, i3);
      }, i2.inflateSync = function(e5, t4) {
        return b2(new w(t4), e5);
      }, i2.gunzip = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new x2(t4), e5, i3);
      }, i2.gunzipSync = function(e5, t4) {
        return b2(new x2(t4), e5);
      }, i2.inflateRaw = function(e5, t4, i3) {
        return "function" == typeof t4 && (i3 = t4, t4 = {}), g(new k2(t4), e5, i3);
      }, i2.inflateRawSync = function(e5, t4) {
        return b2(new k2(t4), e5);
      }, o2.inherits(I, n2), I.prototype.params = function(e5, r3, n3) {
        if (e5 < i2.Z_MIN_LEVEL || e5 > i2.Z_MAX_LEVEL) throw new RangeError("Invalid compression level: " + e5);
        if (r3 != i2.Z_FILTERED && r3 != i2.Z_HUFFMAN_ONLY && r3 != i2.Z_RLE && r3 != i2.Z_FIXED && r3 != i2.Z_DEFAULT_STRATEGY) throw new TypeError("Invalid strategy: " + r3);
        if (this._level !== e5 || this._strategy !== r3) {
          var o3 = this;
          this.flush(a2.Z_SYNC_FLUSH, function() {
            s2(o3._handle, "zlib binding closed"), o3._handle.params(e5, r3), o3._hadError || (o3._level = e5, o3._strategy = r3, n3 && n3());
          });
        } else t3.nextTick(n3);
      }, I.prototype.reset = function() {
        return s2(this._handle, "zlib binding closed"), this._handle.reset();
      }, I.prototype._flush = function(e5) {
        this._transform(r2.alloc(0), "", e5);
      }, I.prototype.flush = function(e5, i3) {
        var n3 = this, o3 = this._writableState;
        ("function" == typeof e5 || void 0 === e5 && !i3) && (i3 = e5, e5 = a2.Z_FULL_FLUSH), o3.ended ? i3 && t3.nextTick(i3) : o3.ending ? i3 && this.once("end", i3) : o3.needDrain ? i3 && this.once("drain", function() {
          return n3.flush(e5, i3);
        }) : (this._flushFlag = e5, this.write(r2.alloc(0), "", i3));
      }, I.prototype.close = function(e5) {
        M2(this, e5), t3.nextTick(T2, this);
      }, I.prototype._transform = function(e5, t4, i3) {
        var n3, o3 = this._writableState, s3 = (o3.ending || o3.ended) && (!e5 || o3.length === e5.length);
        return null === e5 || r2.isBuffer(e5) ? this._handle ? (s3 ? n3 = this._finishFlushFlag : (n3 = this._flushFlag, e5.length >= o3.length && (this._flushFlag = this._opts.flush || a2.Z_NO_FLUSH)), void this._processChunk(e5, n3, i3)) : i3(new Error("zlib binding closed")) : i3(new Error("invalid input"));
      }, I.prototype._processChunk = function(e5, t4, i3) {
        var n3 = e5 && e5.length, a3 = this._chunkSize - this._offset, o3 = 0, h3 = this, c3 = "function" == typeof i3;
        if (!c3) {
          var f3, d2 = [], p3 = 0;
          this.on("error", function(e6) {
            f3 = e6;
          }), s2(this._handle, "zlib binding closed");
          do {
            var m2 = this._handle.writeSync(t4, e5, o3, n3, this._buffer, this._offset, a3);
          } while (!this._hadError && b3(m2[0], m2[1]));
          if (this._hadError) throw f3;
          if (p3 >= l2) throw M2(this), new RangeError(u2);
          var _3 = r2.concat(d2, p3);
          return M2(this), _3;
        }
        s2(this._handle, "zlib binding closed");
        var g2 = this._handle.write(t4, e5, o3, n3, this._buffer, this._offset, a3);
        function b3(l3, u3) {
          if (this && (this.buffer = null, this.callback = null), !h3._hadError) {
            var f4 = a3 - u3;
            if (s2(f4 >= 0, "have should not go down"), f4 > 0) {
              var m3 = h3._buffer.slice(h3._offset, h3._offset + f4);
              h3._offset += f4, c3 ? h3.push(m3) : (d2.push(m3), p3 += m3.length);
            }
            if ((0 === u3 || h3._offset >= h3._chunkSize) && (a3 = h3._chunkSize, h3._offset = 0, h3._buffer = r2.allocUnsafe(h3._chunkSize)), 0 === u3) {
              if (o3 += n3 - l3, n3 = l3, !c3) return true;
              var _4 = h3._handle.write(t4, e5, o3, n3, h3._buffer, h3._offset, h3._chunkSize);
              return _4.callback = b3, void (_4.buffer = e5);
            }
            if (!c3) return false;
            i3();
          }
        }
        g2.buffer = e5, g2.callback = b3;
      }, o2.inherits(y2, I), o2.inherits(w, I), o2.inherits(v2, I), o2.inherits(x2, I), o2.inherits(E2, I), o2.inherits(k2, I), o2.inherits(S2, I);
    }).call(this);
  }).call(this, e4("_process"));
}, { "./binding": 30, _process: 63, assert: 23, buffer: 32, stream: 65, util: 84 }], 32: [function(e4, t2, i2) {
  (function(t3) {
    (function() {
      var t4 = e4("base64-js"), r2 = e4("ieee754");
      i2.Buffer = s2, i2.SlowBuffer = g, i2.INSPECT_MAX_BYTES = 50;
      var n2 = 2147483647;
      function a2() {
        try {
          var e5 = new Uint8Array(1);
          return e5.__proto__ = { __proto__: Uint8Array.prototype, foo: function() {
            return 42;
          } }, 42 === e5.foo();
        } catch (e6) {
          return false;
        }
      }
      function o2(e5) {
        if (e5 > n2) throw new RangeError('The value "' + e5 + '" is invalid for option "size"');
        var t5 = new Uint8Array(e5);
        return t5.__proto__ = s2.prototype, t5;
      }
      function s2(e5, t5, i3) {
        if ("number" == typeof e5) {
          if ("string" == typeof t5) throw new TypeError('The "string" argument must be of type string. Received type number');
          return c2(e5);
        }
        return l2(e5, t5, i3);
      }
      function l2(e5, t5, i3) {
        if ("string" == typeof e5) return f2(e5, t5);
        if (ArrayBuffer.isView(e5)) return d(e5);
        if (null == e5) throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e5);
        if (Y2(e5, ArrayBuffer) || e5 && Y2(e5.buffer, ArrayBuffer)) return p2(e5, t5, i3);
        if ("number" == typeof e5) throw new TypeError('The "value" argument must not be of type number. Received type number');
        var r3 = e5.valueOf && e5.valueOf();
        if (null != r3 && r3 !== e5) return s2.from(r3, t5, i3);
        var n3 = m(e5);
        if (n3) return n3;
        if ("undefined" != typeof Symbol && null != Symbol.toPrimitive && "function" == typeof e5[Symbol.toPrimitive]) return s2.from(e5[Symbol.toPrimitive]("string"), t5, i3);
        throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e5);
      }
      function u2(e5) {
        if ("number" != typeof e5) throw new TypeError('"size" argument must be of type number');
        if (e5 < 0) throw new RangeError('The value "' + e5 + '" is invalid for option "size"');
      }
      function h2(e5, t5, i3) {
        return u2(e5), e5 <= 0 ? o2(e5) : void 0 !== t5 ? "string" == typeof i3 ? o2(e5).fill(t5, i3) : o2(e5).fill(t5) : o2(e5);
      }
      function c2(e5) {
        return u2(e5), o2(e5 < 0 ? 0 : 0 | _2(e5));
      }
      function f2(e5, t5) {
        if ("string" == typeof t5 && "" !== t5 || (t5 = "utf8"), !s2.isEncoding(t5)) throw new TypeError("Unknown encoding: " + t5);
        var i3 = 0 | b2(e5, t5), r3 = o2(i3), n3 = r3.write(e5, t5);
        return n3 !== i3 && (r3 = r3.slice(0, n3)), r3;
      }
      function d(e5) {
        for (var t5 = e5.length < 0 ? 0 : 0 | _2(e5.length), i3 = o2(t5), r3 = 0; r3 < t5; r3 += 1) i3[r3] = 255 & e5[r3];
        return i3;
      }
      function p2(e5, t5, i3) {
        if (t5 < 0 || e5.byteLength < t5) throw new RangeError('"offset" is outside of buffer bounds');
        if (e5.byteLength < t5 + (i3 || 0)) throw new RangeError('"length" is outside of buffer bounds');
        var r3;
        return (r3 = void 0 === t5 && void 0 === i3 ? new Uint8Array(e5) : void 0 === i3 ? new Uint8Array(e5, t5) : new Uint8Array(e5, t5, i3)).__proto__ = s2.prototype, r3;
      }
      function m(e5) {
        if (s2.isBuffer(e5)) {
          var t5 = 0 | _2(e5.length), i3 = o2(t5);
          return 0 === i3.length || e5.copy(i3, 0, 0, t5), i3;
        }
        return void 0 !== e5.length ? "number" != typeof e5.length || K(e5.length) ? o2(0) : d(e5) : "Buffer" === e5.type && Array.isArray(e5.data) ? d(e5.data) : void 0;
      }
      function _2(e5) {
        if (e5 >= n2) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + n2.toString(16) + " bytes");
        return 0 | e5;
      }
      function g(e5) {
        return +e5 != e5 && (e5 = 0), s2.alloc(+e5);
      }
      function b2(e5, t5) {
        if (s2.isBuffer(e5)) return e5.length;
        if (ArrayBuffer.isView(e5) || Y2(e5, ArrayBuffer)) return e5.byteLength;
        if ("string" != typeof e5) throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e5);
        var i3 = e5.length, r3 = arguments.length > 2 && true === arguments[2];
        if (!r3 && 0 === i3) return 0;
        for (var n3 = false; ; ) switch (t5) {
          case "ascii":
          case "latin1":
          case "binary":
            return i3;
          case "utf8":
          case "utf-8":
            return H(e5).length;
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return 2 * i3;
          case "hex":
            return i3 >>> 1;
          case "base64":
            return q(e5).length;
          default:
            if (n3) return r3 ? -1 : H(e5).length;
            t5 = ("" + t5).toLowerCase(), n3 = true;
        }
      }
      function y2(e5, t5, i3) {
        var r3 = false;
        if ((void 0 === t5 || t5 < 0) && (t5 = 0), t5 > this.length) return "";
        if ((void 0 === i3 || i3 > this.length) && (i3 = this.length), i3 <= 0) return "";
        if ((i3 >>>= 0) <= (t5 >>>= 0)) return "";
        for (e5 || (e5 = "utf8"); ; ) switch (e5) {
          case "hex":
            return F(this, t5, i3);
          case "utf8":
          case "utf-8":
            return P(this, t5, i3);
          case "ascii":
            return R2(this, t5, i3);
          case "latin1":
          case "binary":
            return z2(this, t5, i3);
          case "base64":
            return T2(this, t5, i3);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return N2(this, t5, i3);
          default:
            if (r3) throw new TypeError("Unknown encoding: " + e5);
            e5 = (e5 + "").toLowerCase(), r3 = true;
        }
      }
      function w(e5, t5, i3) {
        var r3 = e5[t5];
        e5[t5] = e5[i3], e5[i3] = r3;
      }
      function v2(e5, t5, i3, r3, n3) {
        if (0 === e5.length) return -1;
        if ("string" == typeof i3 ? (r3 = i3, i3 = 0) : i3 > 2147483647 ? i3 = 2147483647 : i3 < -2147483648 && (i3 = -2147483648), K(i3 = +i3) && (i3 = n3 ? 0 : e5.length - 1), i3 < 0 && (i3 = e5.length + i3), i3 >= e5.length) {
          if (n3) return -1;
          i3 = e5.length - 1;
        } else if (i3 < 0) {
          if (!n3) return -1;
          i3 = 0;
        }
        if ("string" == typeof t5 && (t5 = s2.from(t5, r3)), s2.isBuffer(t5)) return 0 === t5.length ? -1 : x2(e5, t5, i3, r3, n3);
        if ("number" == typeof t5) return t5 &= 255, "function" == typeof Uint8Array.prototype.indexOf ? n3 ? Uint8Array.prototype.indexOf.call(e5, t5, i3) : Uint8Array.prototype.lastIndexOf.call(e5, t5, i3) : x2(e5, [t5], i3, r3, n3);
        throw new TypeError("val must be string, number or Buffer");
      }
      function x2(e5, t5, i3, r3, n3) {
        var a3, o3 = 1, s3 = e5.length, l3 = t5.length;
        if (void 0 !== r3 && ("ucs2" === (r3 = String(r3).toLowerCase()) || "ucs-2" === r3 || "utf16le" === r3 || "utf-16le" === r3)) {
          if (e5.length < 2 || t5.length < 2) return -1;
          o3 = 2, s3 /= 2, l3 /= 2, i3 /= 2;
        }
        function u3(e6, t6) {
          return 1 === o3 ? e6[t6] : e6.readUInt16BE(t6 * o3);
        }
        if (n3) {
          var h3 = -1;
          for (a3 = i3; a3 < s3; a3++) if (u3(e5, a3) === u3(t5, -1 === h3 ? 0 : a3 - h3)) {
            if (-1 === h3 && (h3 = a3), a3 - h3 + 1 === l3) return h3 * o3;
          } else -1 !== h3 && (a3 -= a3 - h3), h3 = -1;
        } else for (i3 + l3 > s3 && (i3 = s3 - l3), a3 = i3; a3 >= 0; a3--) {
          for (var c3 = true, f3 = 0; f3 < l3; f3++) if (u3(e5, a3 + f3) !== u3(t5, f3)) {
            c3 = false;
            break;
          }
          if (c3) return a3;
        }
        return -1;
      }
      function E2(e5, t5, i3, r3) {
        i3 = Number(i3) || 0;
        var n3 = e5.length - i3;
        r3 ? (r3 = Number(r3)) > n3 && (r3 = n3) : r3 = n3;
        var a3 = t5.length;
        r3 > a3 / 2 && (r3 = a3 / 2);
        for (var o3 = 0; o3 < r3; ++o3) {
          var s3 = parseInt(t5.substr(2 * o3, 2), 16);
          if (K(s3)) return o3;
          e5[i3 + o3] = s3;
        }
        return o3;
      }
      function k2(e5, t5, i3, r3) {
        return V(H(t5, e5.length - i3), e5, i3, r3);
      }
      function S2(e5, t5, i3, r3) {
        return V(Q(t5), e5, i3, r3);
      }
      function A2(e5, t5, i3, r3) {
        return S2(e5, t5, i3, r3);
      }
      function I(e5, t5, i3, r3) {
        return V(q(t5), e5, i3, r3);
      }
      function M2(e5, t5, i3, r3) {
        return V(W(t5, e5.length - i3), e5, i3, r3);
      }
      function T2(e5, i3, r3) {
        return 0 === i3 && r3 === e5.length ? t4.fromByteArray(e5) : t4.fromByteArray(e5.slice(i3, r3));
      }
      function P(e5, t5, i3) {
        i3 = Math.min(e5.length, i3);
        for (var r3 = [], n3 = t5; n3 < i3; ) {
          var a3, o3, s3, l3, u3 = e5[n3], h3 = null, c3 = u3 > 239 ? 4 : u3 > 223 ? 3 : u3 > 191 ? 2 : 1;
          if (n3 + c3 <= i3) switch (c3) {
            case 1:
              u3 < 128 && (h3 = u3);
              break;
            case 2:
              128 == (192 & (a3 = e5[n3 + 1])) && (l3 = (31 & u3) << 6 | 63 & a3) > 127 && (h3 = l3);
              break;
            case 3:
              a3 = e5[n3 + 1], o3 = e5[n3 + 2], 128 == (192 & a3) && 128 == (192 & o3) && (l3 = (15 & u3) << 12 | (63 & a3) << 6 | 63 & o3) > 2047 && (l3 < 55296 || l3 > 57343) && (h3 = l3);
              break;
            case 4:
              a3 = e5[n3 + 1], o3 = e5[n3 + 2], s3 = e5[n3 + 3], 128 == (192 & a3) && 128 == (192 & o3) && 128 == (192 & s3) && (l3 = (15 & u3) << 18 | (63 & a3) << 12 | (63 & o3) << 6 | 63 & s3) > 65535 && l3 < 1114112 && (h3 = l3);
          }
          null === h3 ? (h3 = 65533, c3 = 1) : h3 > 65535 && (h3 -= 65536, r3.push(h3 >>> 10 & 1023 | 55296), h3 = 56320 | 1023 & h3), r3.push(h3), n3 += c3;
        }
        return C2(r3);
      }
      i2.kMaxLength = n2, s2.TYPED_ARRAY_SUPPORT = a2(), s2.TYPED_ARRAY_SUPPORT || "undefined" == typeof console || "function" != typeof console.error || console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."), Object.defineProperty(s2.prototype, "parent", { enumerable: true, get: function() {
        if (s2.isBuffer(this)) return this.buffer;
      } }), Object.defineProperty(s2.prototype, "offset", { enumerable: true, get: function() {
        if (s2.isBuffer(this)) return this.byteOffset;
      } }), "undefined" != typeof Symbol && null != Symbol.species && s2[Symbol.species] === s2 && Object.defineProperty(s2, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }), s2.poolSize = 8192, s2.from = function(e5, t5, i3) {
        return l2(e5, t5, i3);
      }, s2.prototype.__proto__ = Uint8Array.prototype, s2.__proto__ = Uint8Array, s2.alloc = function(e5, t5, i3) {
        return h2(e5, t5, i3);
      }, s2.allocUnsafe = function(e5) {
        return c2(e5);
      }, s2.allocUnsafeSlow = function(e5) {
        return c2(e5);
      }, s2.isBuffer = function(e5) {
        return null != e5 && true === e5._isBuffer && e5 !== s2.prototype;
      }, s2.compare = function(e5, t5) {
        if (Y2(e5, Uint8Array) && (e5 = s2.from(e5, e5.offset, e5.byteLength)), Y2(t5, Uint8Array) && (t5 = s2.from(t5, t5.offset, t5.byteLength)), !s2.isBuffer(e5) || !s2.isBuffer(t5)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
        if (e5 === t5) return 0;
        for (var i3 = e5.length, r3 = t5.length, n3 = 0, a3 = Math.min(i3, r3); n3 < a3; ++n3) if (e5[n3] !== t5[n3]) {
          i3 = e5[n3], r3 = t5[n3];
          break;
        }
        return i3 < r3 ? -1 : r3 < i3 ? 1 : 0;
      }, s2.isEncoding = function(e5) {
        switch (String(e5).toLowerCase()) {
          case "hex":
          case "utf8":
          case "utf-8":
          case "ascii":
          case "latin1":
          case "binary":
          case "base64":
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return true;
          default:
            return false;
        }
      }, s2.concat = function(e5, t5) {
        if (!Array.isArray(e5)) throw new TypeError('"list" argument must be an Array of Buffers');
        if (0 === e5.length) return s2.alloc(0);
        var i3;
        if (void 0 === t5) for (t5 = 0, i3 = 0; i3 < e5.length; ++i3) t5 += e5[i3].length;
        var r3 = s2.allocUnsafe(t5), n3 = 0;
        for (i3 = 0; i3 < e5.length; ++i3) {
          var a3 = e5[i3];
          if (Y2(a3, Uint8Array) && (a3 = s2.from(a3)), !s2.isBuffer(a3)) throw new TypeError('"list" argument must be an Array of Buffers');
          a3.copy(r3, n3), n3 += a3.length;
        }
        return r3;
      }, s2.byteLength = b2, s2.prototype._isBuffer = true, s2.prototype.swap16 = function() {
        var e5 = this.length;
        if (e5 % 2 != 0) throw new RangeError("Buffer size must be a multiple of 16-bits");
        for (var t5 = 0; t5 < e5; t5 += 2) w(this, t5, t5 + 1);
        return this;
      }, s2.prototype.swap32 = function() {
        var e5 = this.length;
        if (e5 % 4 != 0) throw new RangeError("Buffer size must be a multiple of 32-bits");
        for (var t5 = 0; t5 < e5; t5 += 4) w(this, t5, t5 + 3), w(this, t5 + 1, t5 + 2);
        return this;
      }, s2.prototype.swap64 = function() {
        var e5 = this.length;
        if (e5 % 8 != 0) throw new RangeError("Buffer size must be a multiple of 64-bits");
        for (var t5 = 0; t5 < e5; t5 += 8) w(this, t5, t5 + 7), w(this, t5 + 1, t5 + 6), w(this, t5 + 2, t5 + 5), w(this, t5 + 3, t5 + 4);
        return this;
      }, s2.prototype.toString = function() {
        var e5 = this.length;
        return 0 === e5 ? "" : 0 === arguments.length ? P(this, 0, e5) : y2.apply(this, arguments);
      }, s2.prototype.toLocaleString = s2.prototype.toString, s2.prototype.equals = function(e5) {
        if (!s2.isBuffer(e5)) throw new TypeError("Argument must be a Buffer");
        return this === e5 || 0 === s2.compare(this, e5);
      }, s2.prototype.inspect = function() {
        var e5 = "", t5 = i2.INSPECT_MAX_BYTES;
        return e5 = this.toString("hex", 0, t5).replace(/(.{2})/g, "$1 ").trim(), this.length > t5 && (e5 += " ... "), "<Buffer " + e5 + ">";
      }, s2.prototype.compare = function(e5, t5, i3, r3, n3) {
        if (Y2(e5, Uint8Array) && (e5 = s2.from(e5, e5.offset, e5.byteLength)), !s2.isBuffer(e5)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof e5);
        if (void 0 === t5 && (t5 = 0), void 0 === i3 && (i3 = e5 ? e5.length : 0), void 0 === r3 && (r3 = 0), void 0 === n3 && (n3 = this.length), t5 < 0 || i3 > e5.length || r3 < 0 || n3 > this.length) throw new RangeError("out of range index");
        if (r3 >= n3 && t5 >= i3) return 0;
        if (r3 >= n3) return -1;
        if (t5 >= i3) return 1;
        if (this === e5) return 0;
        for (var a3 = (n3 >>>= 0) - (r3 >>>= 0), o3 = (i3 >>>= 0) - (t5 >>>= 0), l3 = Math.min(a3, o3), u3 = this.slice(r3, n3), h3 = e5.slice(t5, i3), c3 = 0; c3 < l3; ++c3) if (u3[c3] !== h3[c3]) {
          a3 = u3[c3], o3 = h3[c3];
          break;
        }
        return a3 < o3 ? -1 : o3 < a3 ? 1 : 0;
      }, s2.prototype.includes = function(e5, t5, i3) {
        return -1 !== this.indexOf(e5, t5, i3);
      }, s2.prototype.indexOf = function(e5, t5, i3) {
        return v2(this, e5, t5, i3, true);
      }, s2.prototype.lastIndexOf = function(e5, t5, i3) {
        return v2(this, e5, t5, i3, false);
      }, s2.prototype.write = function(e5, t5, i3, r3) {
        if (void 0 === t5) r3 = "utf8", i3 = this.length, t5 = 0;
        else if (void 0 === i3 && "string" == typeof t5) r3 = t5, i3 = this.length, t5 = 0;
        else {
          if (!isFinite(t5)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
          t5 >>>= 0, isFinite(i3) ? (i3 >>>= 0, void 0 === r3 && (r3 = "utf8")) : (r3 = i3, i3 = void 0);
        }
        var n3 = this.length - t5;
        if ((void 0 === i3 || i3 > n3) && (i3 = n3), e5.length > 0 && (i3 < 0 || t5 < 0) || t5 > this.length) throw new RangeError("Attempt to write outside buffer bounds");
        r3 || (r3 = "utf8");
        for (var a3 = false; ; ) switch (r3) {
          case "hex":
            return E2(this, e5, t5, i3);
          case "utf8":
          case "utf-8":
            return k2(this, e5, t5, i3);
          case "ascii":
            return S2(this, e5, t5, i3);
          case "latin1":
          case "binary":
            return A2(this, e5, t5, i3);
          case "base64":
            return I(this, e5, t5, i3);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return M2(this, e5, t5, i3);
          default:
            if (a3) throw new TypeError("Unknown encoding: " + r3);
            r3 = ("" + r3).toLowerCase(), a3 = true;
        }
      }, s2.prototype.toJSON = function() {
        return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
      };
      var B2 = 4096;
      function C2(e5) {
        var t5 = e5.length;
        if (t5 <= B2) return String.fromCharCode.apply(String, e5);
        for (var i3 = "", r3 = 0; r3 < t5; ) i3 += String.fromCharCode.apply(String, e5.slice(r3, r3 += B2));
        return i3;
      }
      function R2(e5, t5, i3) {
        var r3 = "";
        i3 = Math.min(e5.length, i3);
        for (var n3 = t5; n3 < i3; ++n3) r3 += String.fromCharCode(127 & e5[n3]);
        return r3;
      }
      function z2(e5, t5, i3) {
        var r3 = "";
        i3 = Math.min(e5.length, i3);
        for (var n3 = t5; n3 < i3; ++n3) r3 += String.fromCharCode(e5[n3]);
        return r3;
      }
      function F(e5, t5, i3) {
        var r3 = e5.length;
        (!t5 || t5 < 0) && (t5 = 0), (!i3 || i3 < 0 || i3 > r3) && (i3 = r3);
        for (var n3 = "", a3 = t5; a3 < i3; ++a3) n3 += G2(e5[a3]);
        return n3;
      }
      function N2(e5, t5, i3) {
        for (var r3 = e5.slice(t5, i3), n3 = "", a3 = 0; a3 < r3.length; a3 += 2) n3 += String.fromCharCode(r3[a3] + 256 * r3[a3 + 1]);
        return n3;
      }
      function O2(e5, t5, i3) {
        if (e5 % 1 != 0 || e5 < 0) throw new RangeError("offset is not uint");
        if (e5 + t5 > i3) throw new RangeError("Trying to access beyond buffer length");
      }
      function D(e5, t5, i3, r3, n3, a3) {
        if (!s2.isBuffer(e5)) throw new TypeError('"buffer" argument must be a Buffer instance');
        if (t5 > n3 || t5 < a3) throw new RangeError('"value" argument is out of bounds');
        if (i3 + r3 > e5.length) throw new RangeError("Index out of range");
      }
      function $(e5, t5, i3, r3, n3, a3) {
        if (i3 + r3 > e5.length) throw new RangeError("Index out of range");
        if (i3 < 0) throw new RangeError("Index out of range");
      }
      function L2(e5, t5, i3, n3, a3) {
        return t5 = +t5, i3 >>>= 0, a3 || $(e5, t5, i3, 4), r2.write(e5, t5, i3, n3, 23, 4), i3 + 4;
      }
      function U(e5, t5, i3, n3, a3) {
        return t5 = +t5, i3 >>>= 0, a3 || $(e5, t5, i3, 8), r2.write(e5, t5, i3, n3, 52, 8), i3 + 8;
      }
      s2.prototype.slice = function(e5, t5) {
        var i3 = this.length;
        (e5 = ~~e5) < 0 ? (e5 += i3) < 0 && (e5 = 0) : e5 > i3 && (e5 = i3), (t5 = void 0 === t5 ? i3 : ~~t5) < 0 ? (t5 += i3) < 0 && (t5 = 0) : t5 > i3 && (t5 = i3), t5 < e5 && (t5 = e5);
        var r3 = this.subarray(e5, t5);
        return r3.__proto__ = s2.prototype, r3;
      }, s2.prototype.readUIntLE = function(e5, t5, i3) {
        e5 >>>= 0, t5 >>>= 0, i3 || O2(e5, t5, this.length);
        for (var r3 = this[e5], n3 = 1, a3 = 0; ++a3 < t5 && (n3 *= 256); ) r3 += this[e5 + a3] * n3;
        return r3;
      }, s2.prototype.readUIntBE = function(e5, t5, i3) {
        e5 >>>= 0, t5 >>>= 0, i3 || O2(e5, t5, this.length);
        for (var r3 = this[e5 + --t5], n3 = 1; t5 > 0 && (n3 *= 256); ) r3 += this[e5 + --t5] * n3;
        return r3;
      }, s2.prototype.readUInt8 = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 1, this.length), this[e5];
      }, s2.prototype.readUInt16LE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 2, this.length), this[e5] | this[e5 + 1] << 8;
      }, s2.prototype.readUInt16BE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 2, this.length), this[e5] << 8 | this[e5 + 1];
      }, s2.prototype.readUInt32LE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), (this[e5] | this[e5 + 1] << 8 | this[e5 + 2] << 16) + 16777216 * this[e5 + 3];
      }, s2.prototype.readUInt32BE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), 16777216 * this[e5] + (this[e5 + 1] << 16 | this[e5 + 2] << 8 | this[e5 + 3]);
      }, s2.prototype.readIntLE = function(e5, t5, i3) {
        e5 >>>= 0, t5 >>>= 0, i3 || O2(e5, t5, this.length);
        for (var r3 = this[e5], n3 = 1, a3 = 0; ++a3 < t5 && (n3 *= 256); ) r3 += this[e5 + a3] * n3;
        return r3 >= (n3 *= 128) && (r3 -= Math.pow(2, 8 * t5)), r3;
      }, s2.prototype.readIntBE = function(e5, t5, i3) {
        e5 >>>= 0, t5 >>>= 0, i3 || O2(e5, t5, this.length);
        for (var r3 = t5, n3 = 1, a3 = this[e5 + --r3]; r3 > 0 && (n3 *= 256); ) a3 += this[e5 + --r3] * n3;
        return a3 >= (n3 *= 128) && (a3 -= Math.pow(2, 8 * t5)), a3;
      }, s2.prototype.readInt8 = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 1, this.length), 128 & this[e5] ? -1 * (255 - this[e5] + 1) : this[e5];
      }, s2.prototype.readInt16LE = function(e5, t5) {
        e5 >>>= 0, t5 || O2(e5, 2, this.length);
        var i3 = this[e5] | this[e5 + 1] << 8;
        return 32768 & i3 ? 4294901760 | i3 : i3;
      }, s2.prototype.readInt16BE = function(e5, t5) {
        e5 >>>= 0, t5 || O2(e5, 2, this.length);
        var i3 = this[e5 + 1] | this[e5] << 8;
        return 32768 & i3 ? 4294901760 | i3 : i3;
      }, s2.prototype.readInt32LE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), this[e5] | this[e5 + 1] << 8 | this[e5 + 2] << 16 | this[e5 + 3] << 24;
      }, s2.prototype.readInt32BE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), this[e5] << 24 | this[e5 + 1] << 16 | this[e5 + 2] << 8 | this[e5 + 3];
      }, s2.prototype.readFloatLE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), r2.read(this, e5, true, 23, 4);
      }, s2.prototype.readFloatBE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 4, this.length), r2.read(this, e5, false, 23, 4);
      }, s2.prototype.readDoubleLE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 8, this.length), r2.read(this, e5, true, 52, 8);
      }, s2.prototype.readDoubleBE = function(e5, t5) {
        return e5 >>>= 0, t5 || O2(e5, 8, this.length), r2.read(this, e5, false, 52, 8);
      }, s2.prototype.writeUIntLE = function(e5, t5, i3, r3) {
        e5 = +e5, t5 >>>= 0, i3 >>>= 0, r3 || D(this, e5, t5, i3, Math.pow(2, 8 * i3) - 1, 0);
        var n3 = 1, a3 = 0;
        for (this[t5] = 255 & e5; ++a3 < i3 && (n3 *= 256); ) this[t5 + a3] = e5 / n3 & 255;
        return t5 + i3;
      }, s2.prototype.writeUIntBE = function(e5, t5, i3, r3) {
        e5 = +e5, t5 >>>= 0, i3 >>>= 0, r3 || D(this, e5, t5, i3, Math.pow(2, 8 * i3) - 1, 0);
        var n3 = i3 - 1, a3 = 1;
        for (this[t5 + n3] = 255 & e5; --n3 >= 0 && (a3 *= 256); ) this[t5 + n3] = e5 / a3 & 255;
        return t5 + i3;
      }, s2.prototype.writeUInt8 = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 1, 255, 0), this[t5] = 255 & e5, t5 + 1;
      }, s2.prototype.writeUInt16LE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 2, 65535, 0), this[t5] = 255 & e5, this[t5 + 1] = e5 >>> 8, t5 + 2;
      }, s2.prototype.writeUInt16BE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 2, 65535, 0), this[t5] = e5 >>> 8, this[t5 + 1] = 255 & e5, t5 + 2;
      }, s2.prototype.writeUInt32LE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 4, 4294967295, 0), this[t5 + 3] = e5 >>> 24, this[t5 + 2] = e5 >>> 16, this[t5 + 1] = e5 >>> 8, this[t5] = 255 & e5, t5 + 4;
      }, s2.prototype.writeUInt32BE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 4, 4294967295, 0), this[t5] = e5 >>> 24, this[t5 + 1] = e5 >>> 16, this[t5 + 2] = e5 >>> 8, this[t5 + 3] = 255 & e5, t5 + 4;
      }, s2.prototype.writeIntLE = function(e5, t5, i3, r3) {
        if (e5 = +e5, t5 >>>= 0, !r3) {
          var n3 = Math.pow(2, 8 * i3 - 1);
          D(this, e5, t5, i3, n3 - 1, -n3);
        }
        var a3 = 0, o3 = 1, s3 = 0;
        for (this[t5] = 255 & e5; ++a3 < i3 && (o3 *= 256); ) e5 < 0 && 0 === s3 && 0 !== this[t5 + a3 - 1] && (s3 = 1), this[t5 + a3] = (e5 / o3 | 0) - s3 & 255;
        return t5 + i3;
      }, s2.prototype.writeIntBE = function(e5, t5, i3, r3) {
        if (e5 = +e5, t5 >>>= 0, !r3) {
          var n3 = Math.pow(2, 8 * i3 - 1);
          D(this, e5, t5, i3, n3 - 1, -n3);
        }
        var a3 = i3 - 1, o3 = 1, s3 = 0;
        for (this[t5 + a3] = 255 & e5; --a3 >= 0 && (o3 *= 256); ) e5 < 0 && 0 === s3 && 0 !== this[t5 + a3 + 1] && (s3 = 1), this[t5 + a3] = (e5 / o3 | 0) - s3 & 255;
        return t5 + i3;
      }, s2.prototype.writeInt8 = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 1, 127, -128), e5 < 0 && (e5 = 255 + e5 + 1), this[t5] = 255 & e5, t5 + 1;
      }, s2.prototype.writeInt16LE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 2, 32767, -32768), this[t5] = 255 & e5, this[t5 + 1] = e5 >>> 8, t5 + 2;
      }, s2.prototype.writeInt16BE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 2, 32767, -32768), this[t5] = e5 >>> 8, this[t5 + 1] = 255 & e5, t5 + 2;
      }, s2.prototype.writeInt32LE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 4, 2147483647, -2147483648), this[t5] = 255 & e5, this[t5 + 1] = e5 >>> 8, this[t5 + 2] = e5 >>> 16, this[t5 + 3] = e5 >>> 24, t5 + 4;
      }, s2.prototype.writeInt32BE = function(e5, t5, i3) {
        return e5 = +e5, t5 >>>= 0, i3 || D(this, e5, t5, 4, 2147483647, -2147483648), e5 < 0 && (e5 = 4294967295 + e5 + 1), this[t5] = e5 >>> 24, this[t5 + 1] = e5 >>> 16, this[t5 + 2] = e5 >>> 8, this[t5 + 3] = 255 & e5, t5 + 4;
      }, s2.prototype.writeFloatLE = function(e5, t5, i3) {
        return L2(this, e5, t5, true, i3);
      }, s2.prototype.writeFloatBE = function(e5, t5, i3) {
        return L2(this, e5, t5, false, i3);
      }, s2.prototype.writeDoubleLE = function(e5, t5, i3) {
        return U(this, e5, t5, true, i3);
      }, s2.prototype.writeDoubleBE = function(e5, t5, i3) {
        return U(this, e5, t5, false, i3);
      }, s2.prototype.copy = function(e5, t5, i3, r3) {
        if (!s2.isBuffer(e5)) throw new TypeError("argument should be a Buffer");
        if (i3 || (i3 = 0), r3 || 0 === r3 || (r3 = this.length), t5 >= e5.length && (t5 = e5.length), t5 || (t5 = 0), r3 > 0 && r3 < i3 && (r3 = i3), r3 === i3) return 0;
        if (0 === e5.length || 0 === this.length) return 0;
        if (t5 < 0) throw new RangeError("targetStart out of bounds");
        if (i3 < 0 || i3 >= this.length) throw new RangeError("Index out of range");
        if (r3 < 0) throw new RangeError("sourceEnd out of bounds");
        r3 > this.length && (r3 = this.length), e5.length - t5 < r3 - i3 && (r3 = e5.length - t5 + i3);
        var n3 = r3 - i3;
        if (this === e5 && "function" == typeof Uint8Array.prototype.copyWithin) this.copyWithin(t5, i3, r3);
        else if (this === e5 && i3 < t5 && t5 < r3) for (var a3 = n3 - 1; a3 >= 0; --a3) e5[a3 + t5] = this[a3 + i3];
        else Uint8Array.prototype.set.call(e5, this.subarray(i3, r3), t5);
        return n3;
      }, s2.prototype.fill = function(e5, t5, i3, r3) {
        if ("string" == typeof e5) {
          if ("string" == typeof t5 ? (r3 = t5, t5 = 0, i3 = this.length) : "string" == typeof i3 && (r3 = i3, i3 = this.length), void 0 !== r3 && "string" != typeof r3) throw new TypeError("encoding must be a string");
          if ("string" == typeof r3 && !s2.isEncoding(r3)) throw new TypeError("Unknown encoding: " + r3);
          if (1 === e5.length) {
            var n3 = e5.charCodeAt(0);
            ("utf8" === r3 && n3 < 128 || "latin1" === r3) && (e5 = n3);
          }
        } else "number" == typeof e5 && (e5 &= 255);
        if (t5 < 0 || this.length < t5 || this.length < i3) throw new RangeError("Out of range index");
        if (i3 <= t5) return this;
        var a3;
        if (t5 >>>= 0, i3 = void 0 === i3 ? this.length : i3 >>> 0, e5 || (e5 = 0), "number" == typeof e5) for (a3 = t5; a3 < i3; ++a3) this[a3] = e5;
        else {
          var o3 = s2.isBuffer(e5) ? e5 : s2.from(e5, r3), l3 = o3.length;
          if (0 === l3) throw new TypeError('The value "' + e5 + '" is invalid for argument "value"');
          for (a3 = 0; a3 < i3 - t5; ++a3) this[a3 + t5] = o3[a3 % l3];
        }
        return this;
      };
      var Z = /[^+/0-9A-Za-z-_]/g;
      function j(e5) {
        if ((e5 = (e5 = e5.split("=")[0]).trim().replace(Z, "")).length < 2) return "";
        for (; e5.length % 4 != 0; ) e5 += "=";
        return e5;
      }
      function G2(e5) {
        return e5 < 16 ? "0" + e5.toString(16) : e5.toString(16);
      }
      function H(e5, t5) {
        var i3;
        t5 = t5 || 1 / 0;
        for (var r3 = e5.length, n3 = null, a3 = [], o3 = 0; o3 < r3; ++o3) {
          if ((i3 = e5.charCodeAt(o3)) > 55295 && i3 < 57344) {
            if (!n3) {
              if (i3 > 56319) {
                (t5 -= 3) > -1 && a3.push(239, 191, 189);
                continue;
              }
              if (o3 + 1 === r3) {
                (t5 -= 3) > -1 && a3.push(239, 191, 189);
                continue;
              }
              n3 = i3;
              continue;
            }
            if (i3 < 56320) {
              (t5 -= 3) > -1 && a3.push(239, 191, 189), n3 = i3;
              continue;
            }
            i3 = 65536 + (n3 - 55296 << 10 | i3 - 56320);
          } else n3 && (t5 -= 3) > -1 && a3.push(239, 191, 189);
          if (n3 = null, i3 < 128) {
            if ((t5 -= 1) < 0) break;
            a3.push(i3);
          } else if (i3 < 2048) {
            if ((t5 -= 2) < 0) break;
            a3.push(i3 >> 6 | 192, 63 & i3 | 128);
          } else if (i3 < 65536) {
            if ((t5 -= 3) < 0) break;
            a3.push(i3 >> 12 | 224, i3 >> 6 & 63 | 128, 63 & i3 | 128);
          } else {
            if (!(i3 < 1114112)) throw new Error("Invalid code point");
            if ((t5 -= 4) < 0) break;
            a3.push(i3 >> 18 | 240, i3 >> 12 & 63 | 128, i3 >> 6 & 63 | 128, 63 & i3 | 128);
          }
        }
        return a3;
      }
      function Q(e5) {
        for (var t5 = [], i3 = 0; i3 < e5.length; ++i3) t5.push(255 & e5.charCodeAt(i3));
        return t5;
      }
      function W(e5, t5) {
        for (var i3, r3, n3, a3 = [], o3 = 0; o3 < e5.length && !((t5 -= 2) < 0); ++o3) r3 = (i3 = e5.charCodeAt(o3)) >> 8, n3 = i3 % 256, a3.push(n3), a3.push(r3);
        return a3;
      }
      function q(e5) {
        return t4.toByteArray(j(e5));
      }
      function V(e5, t5, i3, r3) {
        for (var n3 = 0; n3 < r3 && !(n3 + i3 >= t5.length || n3 >= e5.length); ++n3) t5[n3 + i3] = e5[n3];
        return n3;
      }
      function Y2(e5, t5) {
        return e5 instanceof t5 || null != e5 && null != e5.constructor && null != e5.constructor.name && e5.constructor.name === t5.name;
      }
      function K(e5) {
        return e5 != e5;
      }
    }).call(this);
  }).call(this, e4("buffer").Buffer);
}, { "base64-js": 28, buffer: 32, ieee754: 45 }], 33: [function(e4, t2, i2) {
  var r2 = e4("get-intrinsic"), n2 = e4("./"), a2 = n2(r2("String.prototype.indexOf"));
  t2.exports = function(e5, t3) {
    var i3 = r2(e5, !!t3);
    return "function" == typeof i3 && a2(e5, ".prototype.") > -1 ? n2(i3) : i3;
  };
}, { "./": 34, "get-intrinsic": 39 }], 34: [function(e4, t2, i2) {
  var r2 = e4("function-bind"), n2 = e4("get-intrinsic"), a2 = n2("%Function.prototype.apply%"), o2 = n2("%Function.prototype.call%"), s2 = n2("%Reflect.apply%", true) || r2.call(o2, a2), l2 = n2("%Object.getOwnPropertyDescriptor%", true), u2 = n2("%Object.defineProperty%", true), h2 = n2("%Math.max%");
  if (u2) try {
    u2({}, "a", { value: 1 });
  } catch (e5) {
    u2 = null;
  }
  t2.exports = function(e5) {
    var t3 = s2(r2, o2, arguments);
    return l2 && u2 && l2(t3, "length").configurable && u2(t3, "length", { value: 1 + h2(0, e5.length - (arguments.length - 1)) }), t3;
  };
  var c2 = function() {
    return s2(r2, a2, arguments);
  };
  u2 ? u2(t2.exports, "apply", { value: c2 }) : t2.exports.apply = c2;
}, { "function-bind": 38, "get-intrinsic": 39 }], 35: [function(e4, t2, i2) {
  var r2, n2 = "object" == typeof Reflect ? Reflect : null, a2 = n2 && "function" == typeof n2.apply ? n2.apply : function(e5, t3, i3) {
    return Function.prototype.apply.call(e5, t3, i3);
  };
  function o2(e5) {
    console && console.warn && console.warn(e5);
  }
  r2 = n2 && "function" == typeof n2.ownKeys ? n2.ownKeys : Object.getOwnPropertySymbols ? function(e5) {
    return Object.getOwnPropertyNames(e5).concat(Object.getOwnPropertySymbols(e5));
  } : function(e5) {
    return Object.getOwnPropertyNames(e5);
  };
  var s2 = Number.isNaN || function(e5) {
    return e5 != e5;
  };
  function l2() {
    l2.init.call(this);
  }
  t2.exports = l2, t2.exports.once = w, l2.EventEmitter = l2, l2.prototype._events = void 0, l2.prototype._eventsCount = 0, l2.prototype._maxListeners = void 0;
  var u2 = 10;
  function h2(e5) {
    if ("function" != typeof e5) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e5);
  }
  function c2(e5) {
    return void 0 === e5._maxListeners ? l2.defaultMaxListeners : e5._maxListeners;
  }
  function f2(e5, t3, i3, r3) {
    var n3, a3, s3;
    if (h2(i3), void 0 === (a3 = e5._events) ? (a3 = e5._events = /* @__PURE__ */ Object.create(null), e5._eventsCount = 0) : (void 0 !== a3.newListener && (e5.emit("newListener", t3, i3.listener ? i3.listener : i3), a3 = e5._events), s3 = a3[t3]), void 0 === s3) s3 = a3[t3] = i3, ++e5._eventsCount;
    else if ("function" == typeof s3 ? s3 = a3[t3] = r3 ? [i3, s3] : [s3, i3] : r3 ? s3.unshift(i3) : s3.push(i3), (n3 = c2(e5)) > 0 && s3.length > n3 && !s3.warned) {
      s3.warned = true;
      var l3 = new Error("Possible EventEmitter memory leak detected. " + s3.length + " " + String(t3) + " listeners added. Use emitter.setMaxListeners() to increase limit");
      l3.name = "MaxListenersExceededWarning", l3.emitter = e5, l3.type = t3, l3.count = s3.length, o2(l3);
    }
    return e5;
  }
  function d() {
    if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), this.fired = true, 0 === arguments.length ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
  }
  function p2(e5, t3, i3) {
    var r3 = { fired: false, wrapFn: void 0, target: e5, type: t3, listener: i3 }, n3 = d.bind(r3);
    return n3.listener = i3, r3.wrapFn = n3, n3;
  }
  function m(e5, t3, i3) {
    var r3 = e5._events;
    if (void 0 === r3) return [];
    var n3 = r3[t3];
    return void 0 === n3 ? [] : "function" == typeof n3 ? i3 ? [n3.listener || n3] : [n3] : i3 ? y2(n3) : g(n3, n3.length);
  }
  function _2(e5) {
    var t3 = this._events;
    if (void 0 !== t3) {
      var i3 = t3[e5];
      if ("function" == typeof i3) return 1;
      if (void 0 !== i3) return i3.length;
    }
    return 0;
  }
  function g(e5, t3) {
    for (var i3 = new Array(t3), r3 = 0; r3 < t3; ++r3) i3[r3] = e5[r3];
    return i3;
  }
  function b2(e5, t3) {
    for (; t3 + 1 < e5.length; t3++) e5[t3] = e5[t3 + 1];
    e5.pop();
  }
  function y2(e5) {
    for (var t3 = new Array(e5.length), i3 = 0; i3 < t3.length; ++i3) t3[i3] = e5[i3].listener || e5[i3];
    return t3;
  }
  function w(e5, t3) {
    return new Promise(function(i3, r3) {
      function n3(i4) {
        e5.removeListener(t3, a3), r3(i4);
      }
      function a3() {
        "function" == typeof e5.removeListener && e5.removeListener("error", n3), i3([].slice.call(arguments));
      }
      x2(e5, t3, a3, { once: true }), "error" !== t3 && v2(e5, n3, { once: true });
    });
  }
  function v2(e5, t3, i3) {
    "function" == typeof e5.on && x2(e5, "error", t3, i3);
  }
  function x2(e5, t3, i3, r3) {
    if ("function" == typeof e5.on) r3.once ? e5.once(t3, i3) : e5.on(t3, i3);
    else {
      if ("function" != typeof e5.addEventListener) throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e5);
      e5.addEventListener(t3, function n3(a3) {
        r3.once && e5.removeEventListener(t3, n3), i3(a3);
      });
    }
  }
  Object.defineProperty(l2, "defaultMaxListeners", { enumerable: true, get: function() {
    return u2;
  }, set: function(e5) {
    if ("number" != typeof e5 || e5 < 0 || s2(e5)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e5 + ".");
    u2 = e5;
  } }), l2.init = function() {
    void 0 !== this._events && this._events !== Object.getPrototypeOf(this)._events || (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
  }, l2.prototype.setMaxListeners = function(e5) {
    if ("number" != typeof e5 || e5 < 0 || s2(e5)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e5 + ".");
    return this._maxListeners = e5, this;
  }, l2.prototype.getMaxListeners = function() {
    return c2(this);
  }, l2.prototype.emit = function(e5) {
    for (var t3 = [], i3 = 1; i3 < arguments.length; i3++) t3.push(arguments[i3]);
    var r3 = "error" === e5, n3 = this._events;
    if (void 0 !== n3) r3 = r3 && void 0 === n3.error;
    else if (!r3) return false;
    if (r3) {
      var o3;
      if (t3.length > 0 && (o3 = t3[0]), o3 instanceof Error) throw o3;
      var s3 = new Error("Unhandled error." + (o3 ? " (" + o3.message + ")" : ""));
      throw s3.context = o3, s3;
    }
    var l3 = n3[e5];
    if (void 0 === l3) return false;
    if ("function" == typeof l3) a2(l3, this, t3);
    else {
      var u3 = l3.length, h3 = g(l3, u3);
      for (i3 = 0; i3 < u3; ++i3) a2(h3[i3], this, t3);
    }
    return true;
  }, l2.prototype.addListener = function(e5, t3) {
    return f2(this, e5, t3, false);
  }, l2.prototype.on = l2.prototype.addListener, l2.prototype.prependListener = function(e5, t3) {
    return f2(this, e5, t3, true);
  }, l2.prototype.once = function(e5, t3) {
    return h2(t3), this.on(e5, p2(this, e5, t3)), this;
  }, l2.prototype.prependOnceListener = function(e5, t3) {
    return h2(t3), this.prependListener(e5, p2(this, e5, t3)), this;
  }, l2.prototype.removeListener = function(e5, t3) {
    var i3, r3, n3, a3, o3;
    if (h2(t3), void 0 === (r3 = this._events)) return this;
    if (void 0 === (i3 = r3[e5])) return this;
    if (i3 === t3 || i3.listener === t3) 0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : (delete r3[e5], r3.removeListener && this.emit("removeListener", e5, i3.listener || t3));
    else if ("function" != typeof i3) {
      for (n3 = -1, a3 = i3.length - 1; a3 >= 0; a3--) if (i3[a3] === t3 || i3[a3].listener === t3) {
        o3 = i3[a3].listener, n3 = a3;
        break;
      }
      if (n3 < 0) return this;
      0 === n3 ? i3.shift() : b2(i3, n3), 1 === i3.length && (r3[e5] = i3[0]), void 0 !== r3.removeListener && this.emit("removeListener", e5, o3 || t3);
    }
    return this;
  }, l2.prototype.off = l2.prototype.removeListener, l2.prototype.removeAllListeners = function(e5) {
    var t3, i3, r3;
    if (void 0 === (i3 = this._events)) return this;
    if (void 0 === i3.removeListener) return 0 === arguments.length ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : void 0 !== i3[e5] && (0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : delete i3[e5]), this;
    if (0 === arguments.length) {
      var n3, a3 = Object.keys(i3);
      for (r3 = 0; r3 < a3.length; ++r3) "removeListener" !== (n3 = a3[r3]) && this.removeAllListeners(n3);
      return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
    }
    if ("function" == typeof (t3 = i3[e5])) this.removeListener(e5, t3);
    else if (void 0 !== t3) for (r3 = t3.length - 1; r3 >= 0; r3--) this.removeListener(e5, t3[r3]);
    return this;
  }, l2.prototype.listeners = function(e5) {
    return m(this, e5, true);
  }, l2.prototype.rawListeners = function(e5) {
    return m(this, e5, false);
  }, l2.listenerCount = function(e5, t3) {
    return "function" == typeof e5.listenerCount ? e5.listenerCount(t3) : _2.call(e5, t3);
  }, l2.prototype.listenerCount = _2, l2.prototype.eventNames = function() {
    return this._eventsCount > 0 ? r2(this._events) : [];
  };
}, {}], 36: [function(e4, t2, i2) {
  var r2 = e4("is-callable"), n2 = Object.prototype.toString, a2 = Object.prototype.hasOwnProperty, o2 = function(e5, t3, i3) {
    for (var r3 = 0, n3 = e5.length; r3 < n3; r3++) a2.call(e5, r3) && (null == i3 ? t3(e5[r3], r3, e5) : t3.call(i3, e5[r3], r3, e5));
  }, s2 = function(e5, t3, i3) {
    for (var r3 = 0, n3 = e5.length; r3 < n3; r3++) null == i3 ? t3(e5.charAt(r3), r3, e5) : t3.call(i3, e5.charAt(r3), r3, e5);
  }, l2 = function(e5, t3, i3) {
    for (var r3 in e5) a2.call(e5, r3) && (null == i3 ? t3(e5[r3], r3, e5) : t3.call(i3, e5[r3], r3, e5));
  }, u2 = function(e5, t3, i3) {
    if (!r2(t3)) throw new TypeError("iterator must be a function");
    var a3;
    arguments.length >= 3 && (a3 = i3), "[object Array]" === n2.call(e5) ? o2(e5, t3, a3) : "string" == typeof e5 ? s2(e5, t3, a3) : l2(e5, t3, a3);
  };
  t2.exports = u2;
}, { "is-callable": 48 }], 37: [function(e4, t2, i2) {
  var r2 = "Function.prototype.bind called on incompatible ", n2 = Array.prototype.slice, a2 = Object.prototype.toString, o2 = "[object Function]";
  t2.exports = function(e5) {
    var t3 = this;
    if ("function" != typeof t3 || a2.call(t3) !== o2) throw new TypeError(r2 + t3);
    for (var i3, s2 = n2.call(arguments, 1), l2 = function() {
      if (this instanceof i3) {
        var r3 = t3.apply(this, s2.concat(n2.call(arguments)));
        return Object(r3) === r3 ? r3 : this;
      }
      return t3.apply(e5, s2.concat(n2.call(arguments)));
    }, u2 = Math.max(0, t3.length - s2.length), h2 = [], c2 = 0; c2 < u2; c2++) h2.push("$" + c2);
    if (i3 = Function("binder", "return function (" + h2.join(",") + "){ return binder.apply(this,arguments); }")(l2), t3.prototype) {
      var f2 = function() {
      };
      f2.prototype = t3.prototype, i3.prototype = new f2(), f2.prototype = null;
    }
    return i3;
  };
}, {}], 38: [function(e4, t2, i2) {
  var r2 = e4("./implementation");
  t2.exports = Function.prototype.bind || r2;
}, { "./implementation": 37 }], 39: [function(e4, t2, i2) {
  var r2, n2 = SyntaxError, a2 = Function, o2 = TypeError, s2 = function(e5) {
    try {
      return a2('"use strict"; return (' + e5 + ").constructor;")();
    } catch (e6) {
    }
  }, l2 = Object.getOwnPropertyDescriptor;
  if (l2) try {
    l2({}, "");
  } catch (e5) {
    l2 = null;
  }
  var u2 = function() {
    throw new o2();
  }, h2 = l2 ? function() {
    try {
      return u2;
    } catch (e5) {
      try {
        return l2(arguments, "callee").get;
      } catch (e6) {
        return u2;
      }
    }
  }() : u2, c2 = e4("has-symbols")(), f2 = Object.getPrototypeOf || function(e5) {
    return e5.__proto__;
  }, d = {}, p2 = "undefined" == typeof Uint8Array ? r2 : f2(Uint8Array), m = { "%AggregateError%": "undefined" == typeof AggregateError ? r2 : AggregateError, "%Array%": Array, "%ArrayBuffer%": "undefined" == typeof ArrayBuffer ? r2 : ArrayBuffer, "%ArrayIteratorPrototype%": c2 ? f2([][Symbol.iterator]()) : r2, "%AsyncFromSyncIteratorPrototype%": r2, "%AsyncFunction%": d, "%AsyncGenerator%": d, "%AsyncGeneratorFunction%": d, "%AsyncIteratorPrototype%": d, "%Atomics%": "undefined" == typeof Atomics ? r2 : Atomics, "%BigInt%": "undefined" == typeof BigInt ? r2 : BigInt, "%BigInt64Array%": "undefined" == typeof BigInt64Array ? r2 : BigInt64Array, "%BigUint64Array%": "undefined" == typeof BigUint64Array ? r2 : BigUint64Array, "%Boolean%": Boolean, "%DataView%": "undefined" == typeof DataView ? r2 : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": Error, "%eval%": eval, "%EvalError%": EvalError, "%Float32Array%": "undefined" == typeof Float32Array ? r2 : Float32Array, "%Float64Array%": "undefined" == typeof Float64Array ? r2 : Float64Array, "%FinalizationRegistry%": "undefined" == typeof FinalizationRegistry ? r2 : FinalizationRegistry, "%Function%": a2, "%GeneratorFunction%": d, "%Int8Array%": "undefined" == typeof Int8Array ? r2 : Int8Array, "%Int16Array%": "undefined" == typeof Int16Array ? r2 : Int16Array, "%Int32Array%": "undefined" == typeof Int32Array ? r2 : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": c2 ? f2(f2([][Symbol.iterator]())) : r2, "%JSON%": "object" == typeof JSON ? JSON : r2, "%Map%": "undefined" == typeof Map ? r2 : Map, "%MapIteratorPrototype%": "undefined" != typeof Map && c2 ? f2((/* @__PURE__ */ new Map())[Symbol.iterator]()) : r2, "%Math%": Math, "%Number%": Number, "%Object%": Object, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": "undefined" == typeof Promise ? r2 : Promise, "%Proxy%": "undefined" == typeof Proxy ? r2 : Proxy, "%RangeError%": RangeError, "%ReferenceError%": ReferenceError, "%Reflect%": "undefined" == typeof Reflect ? r2 : Reflect, "%RegExp%": RegExp, "%Set%": "undefined" == typeof Set ? r2 : Set, "%SetIteratorPrototype%": "undefined" != typeof Set && c2 ? f2((/* @__PURE__ */ new Set())[Symbol.iterator]()) : r2, "%SharedArrayBuffer%": "undefined" == typeof SharedArrayBuffer ? r2 : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": c2 ? f2(""[Symbol.iterator]()) : r2, "%Symbol%": c2 ? Symbol : r2, "%SyntaxError%": n2, "%ThrowTypeError%": h2, "%TypedArray%": p2, "%TypeError%": o2, "%Uint8Array%": "undefined" == typeof Uint8Array ? r2 : Uint8Array, "%Uint8ClampedArray%": "undefined" == typeof Uint8ClampedArray ? r2 : Uint8ClampedArray, "%Uint16Array%": "undefined" == typeof Uint16Array ? r2 : Uint16Array, "%Uint32Array%": "undefined" == typeof Uint32Array ? r2 : Uint32Array, "%URIError%": URIError, "%WeakMap%": "undefined" == typeof WeakMap ? r2 : WeakMap, "%WeakRef%": "undefined" == typeof WeakRef ? r2 : WeakRef, "%WeakSet%": "undefined" == typeof WeakSet ? r2 : WeakSet };
  try {
    null.error;
  } catch (e5) {
    var _2 = f2(f2(e5));
    m["%Error.prototype%"] = _2;
  }
  var g = function e5(t3) {
    var i3;
    if ("%AsyncFunction%" === t3) i3 = s2("async function () {}");
    else if ("%GeneratorFunction%" === t3) i3 = s2("function* () {}");
    else if ("%AsyncGeneratorFunction%" === t3) i3 = s2("async function* () {}");
    else if ("%AsyncGenerator%" === t3) {
      var r3 = e5("%AsyncGeneratorFunction%");
      r3 && (i3 = r3.prototype);
    } else if ("%AsyncIteratorPrototype%" === t3) {
      var n3 = e5("%AsyncGenerator%");
      n3 && (i3 = f2(n3.prototype));
    }
    return m[t3] = i3, i3;
  }, b2 = { "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": ["Array", "prototype", "entries"], "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], "%ArrayProto_keys%": ["Array", "prototype", "keys"], "%ArrayProto_values%": ["Array", "prototype", "values"], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": ["Object", "prototype", "toString"], "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": ["Promise", "prototype", "then"], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }, y2 = e4("function-bind"), w = e4("has"), v2 = y2.call(Function.call, Array.prototype.concat), x2 = y2.call(Function.apply, Array.prototype.splice), E2 = y2.call(Function.call, String.prototype.replace), k2 = y2.call(Function.call, String.prototype.slice), S2 = y2.call(Function.call, RegExp.prototype.exec), A2 = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g, I = /\\(\\)?/g, M2 = function(e5) {
    var t3 = k2(e5, 0, 1), i3 = k2(e5, -1);
    if ("%" === t3 && "%" !== i3) throw new n2("invalid intrinsic syntax, expected closing `%`");
    if ("%" === i3 && "%" !== t3) throw new n2("invalid intrinsic syntax, expected opening `%`");
    var r3 = [];
    return E2(e5, A2, function(e6, t4, i4, n3) {
      r3[r3.length] = i4 ? E2(n3, I, "$1") : t4 || e6;
    }), r3;
  }, T2 = function(e5, t3) {
    var i3, r3 = e5;
    if (w(b2, r3) && (r3 = "%" + (i3 = b2[r3])[0] + "%"), w(m, r3)) {
      var a3 = m[r3];
      if (a3 === d && (a3 = g(r3)), void 0 === a3 && !t3) throw new o2("intrinsic " + e5 + " exists, but is not available. Please file an issue!");
      return { alias: i3, name: r3, value: a3 };
    }
    throw new n2("intrinsic " + e5 + " does not exist!");
  };
  t2.exports = function(e5, t3) {
    if ("string" != typeof e5 || 0 === e5.length) throw new o2("intrinsic name must be a non-empty string");
    if (arguments.length > 1 && "boolean" != typeof t3) throw new o2('"allowMissing" argument must be a boolean');
    if (null === S2(/^%?[^%]*%?$/, e5)) throw new n2("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
    var i3 = M2(e5), r3 = i3.length > 0 ? i3[0] : "", a3 = T2("%" + r3 + "%", t3), s3 = a3.name, u3 = a3.value, h3 = false, c3 = a3.alias;
    c3 && (r3 = c3[0], x2(i3, v2([0, 1], c3)));
    for (var f3 = 1, d2 = true; f3 < i3.length; f3 += 1) {
      var p3 = i3[f3], _3 = k2(p3, 0, 1), g2 = k2(p3, -1);
      if (('"' === _3 || "'" === _3 || "`" === _3 || '"' === g2 || "'" === g2 || "`" === g2) && _3 !== g2) throw new n2("property names with quotes must have matching quotes");
      if ("constructor" !== p3 && d2 || (h3 = true), w(m, s3 = "%" + (r3 += "." + p3) + "%")) u3 = m[s3];
      else if (null != u3) {
        if (!(p3 in u3)) {
          if (!t3) throw new o2("base intrinsic for " + e5 + " exists, but the property is not available.");
          return;
        }
        if (l2 && f3 + 1 >= i3.length) {
          var b3 = l2(u3, p3);
          u3 = (d2 = !!b3) && "get" in b3 && !("originalValue" in b3.get) ? b3.get : u3[p3];
        } else d2 = w(u3, p3), u3 = u3[p3];
        d2 && !h3 && (m[s3] = u3);
      }
    }
    return u3;
  };
}, { "function-bind": 38, has: 44, "has-symbols": 41 }], 40: [function(e4, t2, i2) {
  var r2 = e4("get-intrinsic")("%Object.getOwnPropertyDescriptor%", true);
  if (r2) try {
    r2([], "length");
  } catch (e5) {
    r2 = null;
  }
  t2.exports = r2;
}, { "get-intrinsic": 39 }], 41: [function(e4, t2, i2) {
  var r2 = "undefined" != typeof Symbol && Symbol, n2 = e4("./shams");
  t2.exports = function() {
    return "function" == typeof r2 && "function" == typeof Symbol && "symbol" == typeof r2("foo") && "symbol" == typeof Symbol("bar") && n2();
  };
}, { "./shams": 42 }], 42: [function(e4, t2, i2) {
  t2.exports = function() {
    if ("function" != typeof Symbol || "function" != typeof Object.getOwnPropertySymbols) return false;
    if ("symbol" == typeof Symbol.iterator) return true;
    var e5 = {}, t3 = Symbol("test"), i3 = Object(t3);
    if ("string" == typeof t3) return false;
    if ("[object Symbol]" !== Object.prototype.toString.call(t3)) return false;
    if ("[object Symbol]" !== Object.prototype.toString.call(i3)) return false;
    var r2 = 42;
    for (t3 in e5[t3] = r2, e5) return false;
    if ("function" == typeof Object.keys && 0 !== Object.keys(e5).length) return false;
    if ("function" == typeof Object.getOwnPropertyNames && 0 !== Object.getOwnPropertyNames(e5).length) return false;
    var n2 = Object.getOwnPropertySymbols(e5);
    if (1 !== n2.length || n2[0] !== t3) return false;
    if (!Object.prototype.propertyIsEnumerable.call(e5, t3)) return false;
    if ("function" == typeof Object.getOwnPropertyDescriptor) {
      var a2 = Object.getOwnPropertyDescriptor(e5, t3);
      if (a2.value !== r2 || true !== a2.enumerable) return false;
    }
    return true;
  };
}, {}], 43: [function(e4, t2, i2) {
  var r2 = e4("has-symbols/shams");
  t2.exports = function() {
    return r2() && !!Symbol.toStringTag;
  };
}, { "has-symbols/shams": 42 }], 44: [function(e4, t2, i2) {
  var r2 = e4("function-bind");
  t2.exports = r2.call(Function.call, Object.prototype.hasOwnProperty);
}, { "function-bind": 38 }], 45: [function(e4, t2, i2) {
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  i2.read = function(e5, t3, i3, r2, n2) {
    var a2, o2, s2 = 8 * n2 - r2 - 1, l2 = (1 << s2) - 1, u2 = l2 >> 1, h2 = -7, c2 = i3 ? n2 - 1 : 0, f2 = i3 ? -1 : 1, d = e5[t3 + c2];
    for (c2 += f2, a2 = d & (1 << -h2) - 1, d >>= -h2, h2 += s2; h2 > 0; a2 = 256 * a2 + e5[t3 + c2], c2 += f2, h2 -= 8) ;
    for (o2 = a2 & (1 << -h2) - 1, a2 >>= -h2, h2 += r2; h2 > 0; o2 = 256 * o2 + e5[t3 + c2], c2 += f2, h2 -= 8) ;
    if (0 === a2) a2 = 1 - u2;
    else {
      if (a2 === l2) return o2 ? NaN : 1 / 0 * (d ? -1 : 1);
      o2 += Math.pow(2, r2), a2 -= u2;
    }
    return (d ? -1 : 1) * o2 * Math.pow(2, a2 - r2);
  }, i2.write = function(e5, t3, i3, r2, n2, a2) {
    var o2, s2, l2, u2 = 8 * a2 - n2 - 1, h2 = (1 << u2) - 1, c2 = h2 >> 1, f2 = 23 === n2 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = r2 ? 0 : a2 - 1, p2 = r2 ? 1 : -1, m = t3 < 0 || 0 === t3 && 1 / t3 < 0 ? 1 : 0;
    for (t3 = Math.abs(t3), isNaN(t3) || t3 === 1 / 0 ? (s2 = isNaN(t3) ? 1 : 0, o2 = h2) : (o2 = Math.floor(Math.log(t3) / Math.LN2), t3 * (l2 = Math.pow(2, -o2)) < 1 && (o2--, l2 *= 2), (t3 += o2 + c2 >= 1 ? f2 / l2 : f2 * Math.pow(2, 1 - c2)) * l2 >= 2 && (o2++, l2 /= 2), o2 + c2 >= h2 ? (s2 = 0, o2 = h2) : o2 + c2 >= 1 ? (s2 = (t3 * l2 - 1) * Math.pow(2, n2), o2 += c2) : (s2 = t3 * Math.pow(2, c2 - 1) * Math.pow(2, n2), o2 = 0)); n2 >= 8; e5[i3 + d] = 255 & s2, d += p2, s2 /= 256, n2 -= 8) ;
    for (o2 = o2 << n2 | s2, u2 += n2; u2 > 0; e5[i3 + d] = 255 & o2, d += p2, o2 /= 256, u2 -= 8) ;
    e5[i3 + d - p2] |= 128 * m;
  };
}, {}], 46: [function(e4, t2, i2) {
  "function" == typeof Object.create ? t2.exports = function(e5, t3) {
    t3 && (e5.super_ = t3, e5.prototype = Object.create(t3.prototype, { constructor: { value: e5, enumerable: false, writable: true, configurable: true } }));
  } : t2.exports = function(e5, t3) {
    if (t3) {
      e5.super_ = t3;
      var i3 = function() {
      };
      i3.prototype = t3.prototype, e5.prototype = new i3(), e5.prototype.constructor = e5;
    }
  };
}, {}], 47: [function(e4, t2, i2) {
  var r2 = e4("has-tostringtag/shams")(), n2 = e4("call-bind/callBound")("Object.prototype.toString"), a2 = function(e5) {
    return !(r2 && e5 && "object" == typeof e5 && Symbol.toStringTag in e5) && "[object Arguments]" === n2(e5);
  }, o2 = function(e5) {
    return !!a2(e5) || null !== e5 && "object" == typeof e5 && "number" == typeof e5.length && e5.length >= 0 && "[object Array]" !== n2(e5) && "[object Function]" === n2(e5.callee);
  }, s2 = function() {
    return a2(arguments);
  }();
  a2.isLegacyArguments = o2, t2.exports = s2 ? a2 : o2;
}, { "call-bind/callBound": 33, "has-tostringtag/shams": 43 }], 48: [function(e4, t2, i2) {
  var r2, n2, a2 = Function.prototype.toString, o2 = "object" == typeof Reflect && null !== Reflect && Reflect.apply;
  if ("function" == typeof o2 && "function" == typeof Object.defineProperty) try {
    r2 = Object.defineProperty({}, "length", { get: function() {
      throw n2;
    } }), n2 = {}, o2(function() {
      throw 42;
    }, null, r2);
  } catch (e5) {
    e5 !== n2 && (o2 = null);
  }
  else o2 = null;
  var s2 = /^\s*class\b/, l2 = function(e5) {
    try {
      var t3 = a2.call(e5);
      return s2.test(t3);
    } catch (e6) {
      return false;
    }
  }, u2 = function(e5) {
    try {
      return !l2(e5) && (a2.call(e5), true);
    } catch (e6) {
      return false;
    }
  }, h2 = Object.prototype.toString, c2 = "[object Object]", f2 = "[object Function]", d = "[object GeneratorFunction]", p2 = "[object HTMLAllCollection]", m = "[object HTML document.all class]", _2 = "[object HTMLCollection]", g = "function" == typeof Symbol && !!Symbol.toStringTag, b2 = !(0 in [,]), y2 = function() {
    return false;
  };
  if ("object" == typeof document) {
    var w = document.all;
    h2.call(w) === h2.call(document.all) && (y2 = function(e5) {
      if ((b2 || !e5) && (void 0 === e5 || "object" == typeof e5)) try {
        var t3 = h2.call(e5);
        return (t3 === p2 || t3 === m || t3 === _2 || t3 === c2) && null == e5("");
      } catch (e6) {
      }
      return false;
    });
  }
  t2.exports = o2 ? function(e5) {
    if (y2(e5)) return true;
    if (!e5) return false;
    if ("function" != typeof e5 && "object" != typeof e5) return false;
    try {
      o2(e5, null, r2);
    } catch (e6) {
      if (e6 !== n2) return false;
    }
    return !l2(e5) && u2(e5);
  } : function(e5) {
    if (y2(e5)) return true;
    if (!e5) return false;
    if ("function" != typeof e5 && "object" != typeof e5) return false;
    if (g) return u2(e5);
    if (l2(e5)) return false;
    var t3 = h2.call(e5);
    return !(t3 !== f2 && t3 !== d && !/^\[object HTML/.test(t3)) && u2(e5);
  };
}, {}], 49: [function(e4, t2, i2) {
  var r2, n2 = Object.prototype.toString, a2 = Function.prototype.toString, o2 = /^\s*(?:function)?\*/, s2 = e4("has-tostringtag/shams")(), l2 = Object.getPrototypeOf, u2 = function() {
    if (!s2) return false;
    try {
      return Function("return function*() {}")();
    } catch (e5) {
    }
  };
  t2.exports = function(e5) {
    if ("function" != typeof e5) return false;
    if (o2.test(a2.call(e5))) return true;
    if (!s2) return "[object GeneratorFunction]" === n2.call(e5);
    if (!l2) return false;
    if (void 0 === r2) {
      var t3 = u2();
      r2 = !!t3 && l2(t3);
    }
    return l2(e5) === r2;
  };
}, { "has-tostringtag/shams": 43 }], 50: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      var r2 = e4("for-each"), n2 = e4("available-typed-arrays"), a2 = e4("call-bind/callBound"), o2 = a2("Object.prototype.toString"), s2 = e4("has-tostringtag/shams")(), l2 = e4("gopd"), u2 = "undefined" == typeof globalThis ? i3 : globalThis, h2 = n2(), c2 = a2("Array.prototype.indexOf", true) || function(e5, t3) {
        for (var i4 = 0; i4 < e5.length; i4 += 1) if (e5[i4] === t3) return i4;
        return -1;
      }, f2 = a2("String.prototype.slice"), d = {}, p2 = Object.getPrototypeOf;
      s2 && l2 && p2 && r2(h2, function(e5) {
        var t3 = new u2[e5]();
        if (Symbol.toStringTag in t3) {
          var i4 = p2(t3), r3 = l2(i4, Symbol.toStringTag);
          if (!r3) {
            var n3 = p2(i4);
            r3 = l2(n3, Symbol.toStringTag);
          }
          d[e5] = r3.get;
        }
      });
      var m = function(e5) {
        var t3 = false;
        return r2(d, function(i4, r3) {
          if (!t3) try {
            t3 = i4.call(e5) === r3;
          } catch (e6) {
          }
        }), t3;
      };
      t2.exports = function(e5) {
        if (!e5 || "object" != typeof e5) return false;
        if (!s2 || !(Symbol.toStringTag in e5)) {
          var t3 = f2(o2(e5), 8, -1);
          return c2(h2, t3) > -1;
        }
        return !!l2 && m(e5);
      };
    }).call(this);
  }).call(this, void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "available-typed-arrays": 27, "call-bind/callBound": 33, "for-each": 36, gopd: 40, "has-tostringtag/shams": 43 }], 51: [function(e4, t2, i2) {
  var r2 = Object.getOwnPropertySymbols, n2 = Object.prototype.hasOwnProperty, a2 = Object.prototype.propertyIsEnumerable;
  function o2(e5) {
    if (null == e5) throw new TypeError("Object.assign cannot be called with null or undefined");
    return Object(e5);
  }
  function s2() {
    try {
      if (!Object.assign) return false;
      var e5 = new String("abc");
      if (e5[5] = "de", "5" === Object.getOwnPropertyNames(e5)[0]) return false;
      for (var t3 = {}, i3 = 0; i3 < 10; i3++) t3["_" + String.fromCharCode(i3)] = i3;
      var r3 = Object.getOwnPropertyNames(t3).map(function(e6) {
        return t3[e6];
      });
      if ("0123456789" !== r3.join("")) return false;
      var n3 = {};
      return "abcdefghijklmnopqrst".split("").forEach(function(e6) {
        n3[e6] = e6;
      }), "abcdefghijklmnopqrst" === Object.keys(Object.assign({}, n3)).join("");
    } catch (e6) {
      return false;
    }
  }
  t2.exports = s2() ? Object.assign : function(e5, t3) {
    for (var i3, s3, l2 = o2(e5), u2 = 1; u2 < arguments.length; u2++) {
      for (var h2 in i3 = Object(arguments[u2])) n2.call(i3, h2) && (l2[h2] = i3[h2]);
      if (r2) {
        s3 = r2(i3);
        for (var c2 = 0; c2 < s3.length; c2++) a2.call(i3, s3[c2]) && (l2[s3[c2]] = i3[s3[c2]]);
      }
    }
    return l2;
  };
}, {}], 52: [function(e4, t2, i2) {
  var r2 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
  function n2(e5, t3) {
    return Object.prototype.hasOwnProperty.call(e5, t3);
  }
  i2.assign = function(e5) {
    for (var t3 = Array.prototype.slice.call(arguments, 1); t3.length; ) {
      var i3 = t3.shift();
      if (i3) {
        if ("object" != typeof i3) throw new TypeError(i3 + "must be non-object");
        for (var r3 in i3) n2(i3, r3) && (e5[r3] = i3[r3]);
      }
    }
    return e5;
  }, i2.shrinkBuf = function(e5, t3) {
    return e5.length === t3 ? e5 : e5.subarray ? e5.subarray(0, t3) : (e5.length = t3, e5);
  };
  var a2 = { arraySet: function(e5, t3, i3, r3, n3) {
    if (t3.subarray && e5.subarray) e5.set(t3.subarray(i3, i3 + r3), n3);
    else for (var a3 = 0; a3 < r3; a3++) e5[n3 + a3] = t3[i3 + a3];
  }, flattenChunks: function(e5) {
    var t3, i3, r3, n3, a3, o3;
    for (r3 = 0, t3 = 0, i3 = e5.length; t3 < i3; t3++) r3 += e5[t3].length;
    for (o3 = new Uint8Array(r3), n3 = 0, t3 = 0, i3 = e5.length; t3 < i3; t3++) a3 = e5[t3], o3.set(a3, n3), n3 += a3.length;
    return o3;
  } }, o2 = { arraySet: function(e5, t3, i3, r3, n3) {
    for (var a3 = 0; a3 < r3; a3++) e5[n3 + a3] = t3[i3 + a3];
  }, flattenChunks: function(e5) {
    return [].concat.apply([], e5);
  } };
  i2.setTyped = function(e5) {
    e5 ? (i2.Buf8 = Uint8Array, i2.Buf16 = Uint16Array, i2.Buf32 = Int32Array, i2.assign(i2, a2)) : (i2.Buf8 = Array, i2.Buf16 = Array, i2.Buf32 = Array, i2.assign(i2, o2));
  }, i2.setTyped(r2);
}, {}], 53: [function(e4, t2, i2) {
  function r2(e5, t3, i3, r3) {
    for (var n2 = 65535 & e5, a2 = e5 >>> 16 & 65535, o2 = 0; 0 !== i3; ) {
      i3 -= o2 = i3 > 2e3 ? 2e3 : i3;
      do {
        a2 = a2 + (n2 = n2 + t3[r3++] | 0) | 0;
      } while (--o2);
      n2 %= 65521, a2 %= 65521;
    }
    return n2 | a2 << 16;
  }
  t2.exports = r2;
}, {}], 54: [function(e4, t2, i2) {
  t2.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 };
}, {}], 55: [function(e4, t2, i2) {
  function r2() {
    for (var e5, t3 = [], i3 = 0; i3 < 256; i3++) {
      e5 = i3;
      for (var r3 = 0; r3 < 8; r3++) e5 = 1 & e5 ? 3988292384 ^ e5 >>> 1 : e5 >>> 1;
      t3[i3] = e5;
    }
    return t3;
  }
  var n2 = r2();
  function a2(e5, t3, i3, r3) {
    var a3 = n2, o2 = r3 + i3;
    e5 ^= -1;
    for (var s2 = r3; s2 < o2; s2++) e5 = e5 >>> 8 ^ a3[255 & (e5 ^ t3[s2])];
    return ~e5;
  }
  t2.exports = a2;
}, {}], 56: [function(e4, t2, i2) {
  var r2, n2 = e4("../utils/common"), a2 = e4("./trees"), o2 = e4("./adler32"), s2 = e4("./crc32"), l2 = e4("./messages"), u2 = 0, h2 = 1, c2 = 3, f2 = 4, d = 5, p2 = 0, m = 1, _2 = -2, g = -3, b2 = -5, y2 = -1, w = 1, v2 = 2, x2 = 3, E2 = 4, k2 = 0, S2 = 2, A2 = 8, I = 9, M2 = 15, T2 = 8, P = 286, B2 = 30, C2 = 19, R2 = 2 * P + 1, z2 = 15, F = 3, N2 = 258, O2 = N2 + F + 1, D = 32, $ = 42, L2 = 69, U = 73, Z = 91, j = 103, G2 = 113, H = 666, Q = 1, W = 2, q = 3, V = 4, Y2 = 3;
  function K(e5, t3) {
    return e5.msg = l2[t3], t3;
  }
  function J(e5) {
    return (e5 << 1) - (e5 > 4 ? 9 : 0);
  }
  function X(e5) {
    for (var t3 = e5.length; --t3 >= 0; ) e5[t3] = 0;
  }
  function ee(e5) {
    var t3 = e5.state, i3 = t3.pending;
    i3 > e5.avail_out && (i3 = e5.avail_out), 0 !== i3 && (n2.arraySet(e5.output, t3.pending_buf, t3.pending_out, i3, e5.next_out), e5.next_out += i3, t3.pending_out += i3, e5.total_out += i3, e5.avail_out -= i3, t3.pending -= i3, 0 === t3.pending && (t3.pending_out = 0));
  }
  function te(e5, t3) {
    a2._tr_flush_block(e5, e5.block_start >= 0 ? e5.block_start : -1, e5.strstart - e5.block_start, t3), e5.block_start = e5.strstart, ee(e5.strm);
  }
  function ie(e5, t3) {
    e5.pending_buf[e5.pending++] = t3;
  }
  function re(e5, t3) {
    e5.pending_buf[e5.pending++] = t3 >>> 8 & 255, e5.pending_buf[e5.pending++] = 255 & t3;
  }
  function ne(e5, t3, i3, r3) {
    var a3 = e5.avail_in;
    return a3 > r3 && (a3 = r3), 0 === a3 ? 0 : (e5.avail_in -= a3, n2.arraySet(t3, e5.input, e5.next_in, a3, i3), 1 === e5.state.wrap ? e5.adler = o2(e5.adler, t3, a3, i3) : 2 === e5.state.wrap && (e5.adler = s2(e5.adler, t3, a3, i3)), e5.next_in += a3, e5.total_in += a3, a3);
  }
  function ae(e5, t3) {
    var i3, r3, n3 = e5.max_chain_length, a3 = e5.strstart, o3 = e5.prev_length, s3 = e5.nice_match, l3 = e5.strstart > e5.w_size - O2 ? e5.strstart - (e5.w_size - O2) : 0, u3 = e5.window, h3 = e5.w_mask, c3 = e5.prev, f3 = e5.strstart + N2, d2 = u3[a3 + o3 - 1], p3 = u3[a3 + o3];
    e5.prev_length >= e5.good_match && (n3 >>= 2), s3 > e5.lookahead && (s3 = e5.lookahead);
    do {
      if (u3[(i3 = t3) + o3] === p3 && u3[i3 + o3 - 1] === d2 && u3[i3] === u3[a3] && u3[++i3] === u3[a3 + 1]) {
        a3 += 2, i3++;
        do {
        } while (u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && a3 < f3);
        if (r3 = N2 - (f3 - a3), a3 = f3 - N2, r3 > o3) {
          if (e5.match_start = t3, o3 = r3, r3 >= s3) break;
          d2 = u3[a3 + o3 - 1], p3 = u3[a3 + o3];
        }
      }
    } while ((t3 = c3[t3 & h3]) > l3 && 0 != --n3);
    return o3 <= e5.lookahead ? o3 : e5.lookahead;
  }
  function oe(e5) {
    var t3, i3, r3, a3, o3, s3 = e5.w_size;
    do {
      if (a3 = e5.window_size - e5.lookahead - e5.strstart, e5.strstart >= s3 + (s3 - O2)) {
        n2.arraySet(e5.window, e5.window, s3, s3, 0), e5.match_start -= s3, e5.strstart -= s3, e5.block_start -= s3, t3 = i3 = e5.hash_size;
        do {
          r3 = e5.head[--t3], e5.head[t3] = r3 >= s3 ? r3 - s3 : 0;
        } while (--i3);
        t3 = i3 = s3;
        do {
          r3 = e5.prev[--t3], e5.prev[t3] = r3 >= s3 ? r3 - s3 : 0;
        } while (--i3);
        a3 += s3;
      }
      if (0 === e5.strm.avail_in) break;
      if (i3 = ne(e5.strm, e5.window, e5.strstart + e5.lookahead, a3), e5.lookahead += i3, e5.lookahead + e5.insert >= F) for (o3 = e5.strstart - e5.insert, e5.ins_h = e5.window[o3], e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[o3 + 1]) & e5.hash_mask; e5.insert && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[o3 + F - 1]) & e5.hash_mask, e5.prev[o3 & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = o3, o3++, e5.insert--, !(e5.lookahead + e5.insert < F)); ) ;
    } while (e5.lookahead < O2 && 0 !== e5.strm.avail_in);
  }
  function se(e5, t3) {
    var i3 = 65535;
    for (i3 > e5.pending_buf_size - 5 && (i3 = e5.pending_buf_size - 5); ; ) {
      if (e5.lookahead <= 1) {
        if (oe(e5), 0 === e5.lookahead && t3 === u2) return Q;
        if (0 === e5.lookahead) break;
      }
      e5.strstart += e5.lookahead, e5.lookahead = 0;
      var r3 = e5.block_start + i3;
      if ((0 === e5.strstart || e5.strstart >= r3) && (e5.lookahead = e5.strstart - r3, e5.strstart = r3, te(e5, false), 0 === e5.strm.avail_out)) return Q;
      if (e5.strstart - e5.block_start >= e5.w_size - O2 && (te(e5, false), 0 === e5.strm.avail_out)) return Q;
    }
    return e5.insert = 0, t3 === f2 ? (te(e5, true), 0 === e5.strm.avail_out ? q : V) : (e5.strstart > e5.block_start && (te(e5, false), e5.strm.avail_out), Q);
  }
  function le(e5, t3) {
    for (var i3, r3; ; ) {
      if (e5.lookahead < O2) {
        if (oe(e5), e5.lookahead < O2 && t3 === u2) return Q;
        if (0 === e5.lookahead) break;
      }
      if (i3 = 0, e5.lookahead >= F && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + F - 1]) & e5.hash_mask, i3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart), 0 !== i3 && e5.strstart - i3 <= e5.w_size - O2 && (e5.match_length = ae(e5, i3)), e5.match_length >= F) if (r3 = a2._tr_tally(e5, e5.strstart - e5.match_start, e5.match_length - F), e5.lookahead -= e5.match_length, e5.match_length <= e5.max_lazy_match && e5.lookahead >= F) {
        e5.match_length--;
        do {
          e5.strstart++, e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + F - 1]) & e5.hash_mask, i3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart;
        } while (0 != --e5.match_length);
        e5.strstart++;
      } else e5.strstart += e5.match_length, e5.match_length = 0, e5.ins_h = e5.window[e5.strstart], e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + 1]) & e5.hash_mask;
      else r3 = a2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++;
      if (r3 && (te(e5, false), 0 === e5.strm.avail_out)) return Q;
    }
    return e5.insert = e5.strstart < F - 1 ? e5.strstart : F - 1, t3 === f2 ? (te(e5, true), 0 === e5.strm.avail_out ? q : V) : e5.last_lit && (te(e5, false), 0 === e5.strm.avail_out) ? Q : W;
  }
  function ue(e5, t3) {
    for (var i3, r3, n3; ; ) {
      if (e5.lookahead < O2) {
        if (oe(e5), e5.lookahead < O2 && t3 === u2) return Q;
        if (0 === e5.lookahead) break;
      }
      if (i3 = 0, e5.lookahead >= F && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + F - 1]) & e5.hash_mask, i3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart), e5.prev_length = e5.match_length, e5.prev_match = e5.match_start, e5.match_length = F - 1, 0 !== i3 && e5.prev_length < e5.max_lazy_match && e5.strstart - i3 <= e5.w_size - O2 && (e5.match_length = ae(e5, i3), e5.match_length <= 5 && (e5.strategy === w || e5.match_length === F && e5.strstart - e5.match_start > 4096) && (e5.match_length = F - 1)), e5.prev_length >= F && e5.match_length <= e5.prev_length) {
        n3 = e5.strstart + e5.lookahead - F, r3 = a2._tr_tally(e5, e5.strstart - 1 - e5.prev_match, e5.prev_length - F), e5.lookahead -= e5.prev_length - 1, e5.prev_length -= 2;
        do {
          ++e5.strstart <= n3 && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + F - 1]) & e5.hash_mask, i3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart);
        } while (0 != --e5.prev_length);
        if (e5.match_available = 0, e5.match_length = F - 1, e5.strstart++, r3 && (te(e5, false), 0 === e5.strm.avail_out)) return Q;
      } else if (e5.match_available) {
        if ((r3 = a2._tr_tally(e5, 0, e5.window[e5.strstart - 1])) && te(e5, false), e5.strstart++, e5.lookahead--, 0 === e5.strm.avail_out) return Q;
      } else e5.match_available = 1, e5.strstart++, e5.lookahead--;
    }
    return e5.match_available && (r3 = a2._tr_tally(e5, 0, e5.window[e5.strstart - 1]), e5.match_available = 0), e5.insert = e5.strstart < F - 1 ? e5.strstart : F - 1, t3 === f2 ? (te(e5, true), 0 === e5.strm.avail_out ? q : V) : e5.last_lit && (te(e5, false), 0 === e5.strm.avail_out) ? Q : W;
  }
  function he(e5, t3) {
    for (var i3, r3, n3, o3, s3 = e5.window; ; ) {
      if (e5.lookahead <= N2) {
        if (oe(e5), e5.lookahead <= N2 && t3 === u2) return Q;
        if (0 === e5.lookahead) break;
      }
      if (e5.match_length = 0, e5.lookahead >= F && e5.strstart > 0 && (r3 = s3[n3 = e5.strstart - 1]) === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3]) {
        o3 = e5.strstart + N2;
        do {
        } while (r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && r3 === s3[++n3] && n3 < o3);
        e5.match_length = N2 - (o3 - n3), e5.match_length > e5.lookahead && (e5.match_length = e5.lookahead);
      }
      if (e5.match_length >= F ? (i3 = a2._tr_tally(e5, 1, e5.match_length - F), e5.lookahead -= e5.match_length, e5.strstart += e5.match_length, e5.match_length = 0) : (i3 = a2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++), i3 && (te(e5, false), 0 === e5.strm.avail_out)) return Q;
    }
    return e5.insert = 0, t3 === f2 ? (te(e5, true), 0 === e5.strm.avail_out ? q : V) : e5.last_lit && (te(e5, false), 0 === e5.strm.avail_out) ? Q : W;
  }
  function ce(e5, t3) {
    for (var i3; ; ) {
      if (0 === e5.lookahead && (oe(e5), 0 === e5.lookahead)) {
        if (t3 === u2) return Q;
        break;
      }
      if (e5.match_length = 0, i3 = a2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++, i3 && (te(e5, false), 0 === e5.strm.avail_out)) return Q;
    }
    return e5.insert = 0, t3 === f2 ? (te(e5, true), 0 === e5.strm.avail_out ? q : V) : e5.last_lit && (te(e5, false), 0 === e5.strm.avail_out) ? Q : W;
  }
  function fe(e5, t3, i3, r3, n3) {
    this.good_length = e5, this.max_lazy = t3, this.nice_length = i3, this.max_chain = r3, this.func = n3;
  }
  function de(e5) {
    e5.window_size = 2 * e5.w_size, X(e5.head), e5.max_lazy_match = r2[e5.level].max_lazy, e5.good_match = r2[e5.level].good_length, e5.nice_match = r2[e5.level].nice_length, e5.max_chain_length = r2[e5.level].max_chain, e5.strstart = 0, e5.block_start = 0, e5.lookahead = 0, e5.insert = 0, e5.match_length = e5.prev_length = F - 1, e5.match_available = 0, e5.ins_h = 0;
  }
  function pe() {
    this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = A2, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new n2.Buf16(2 * R2), this.dyn_dtree = new n2.Buf16(2 * (2 * B2 + 1)), this.bl_tree = new n2.Buf16(2 * (2 * C2 + 1)), X(this.dyn_ltree), X(this.dyn_dtree), X(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new n2.Buf16(z2 + 1), this.heap = new n2.Buf16(2 * P + 1), X(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new n2.Buf16(2 * P + 1), X(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
  }
  function me(e5) {
    var t3;
    return e5 && e5.state ? (e5.total_in = e5.total_out = 0, e5.data_type = S2, (t3 = e5.state).pending = 0, t3.pending_out = 0, t3.wrap < 0 && (t3.wrap = -t3.wrap), t3.status = t3.wrap ? $ : G2, e5.adler = 2 === t3.wrap ? 0 : 1, t3.last_flush = u2, a2._tr_init(t3), p2) : K(e5, _2);
  }
  function _e2(e5) {
    var t3 = me(e5);
    return t3 === p2 && de(e5.state), t3;
  }
  function ge(e5, t3) {
    return e5 && e5.state ? 2 !== e5.state.wrap ? _2 : (e5.state.gzhead = t3, p2) : _2;
  }
  function be(e5, t3, i3, r3, a3, o3) {
    if (!e5) return _2;
    var s3 = 1;
    if (t3 === y2 && (t3 = 6), r3 < 0 ? (s3 = 0, r3 = -r3) : r3 > 15 && (s3 = 2, r3 -= 16), a3 < 1 || a3 > I || i3 !== A2 || r3 < 8 || r3 > 15 || t3 < 0 || t3 > 9 || o3 < 0 || o3 > E2) return K(e5, _2);
    8 === r3 && (r3 = 9);
    var l3 = new pe();
    return e5.state = l3, l3.strm = e5, l3.wrap = s3, l3.gzhead = null, l3.w_bits = r3, l3.w_size = 1 << l3.w_bits, l3.w_mask = l3.w_size - 1, l3.hash_bits = a3 + 7, l3.hash_size = 1 << l3.hash_bits, l3.hash_mask = l3.hash_size - 1, l3.hash_shift = ~~((l3.hash_bits + F - 1) / F), l3.window = new n2.Buf8(2 * l3.w_size), l3.head = new n2.Buf16(l3.hash_size), l3.prev = new n2.Buf16(l3.w_size), l3.lit_bufsize = 1 << a3 + 6, l3.pending_buf_size = 4 * l3.lit_bufsize, l3.pending_buf = new n2.Buf8(l3.pending_buf_size), l3.d_buf = 1 * l3.lit_bufsize, l3.l_buf = 3 * l3.lit_bufsize, l3.level = t3, l3.strategy = o3, l3.method = i3, _e2(e5);
  }
  function ye(e5, t3) {
    return be(e5, t3, A2, M2, T2, k2);
  }
  function we(e5, t3) {
    var i3, n3, o3, l3;
    if (!e5 || !e5.state || t3 > d || t3 < 0) return e5 ? K(e5, _2) : _2;
    if (n3 = e5.state, !e5.output || !e5.input && 0 !== e5.avail_in || n3.status === H && t3 !== f2) return K(e5, 0 === e5.avail_out ? b2 : _2);
    if (n3.strm = e5, i3 = n3.last_flush, n3.last_flush = t3, n3.status === $) if (2 === n3.wrap) e5.adler = 0, ie(n3, 31), ie(n3, 139), ie(n3, 8), n3.gzhead ? (ie(n3, (n3.gzhead.text ? 1 : 0) + (n3.gzhead.hcrc ? 2 : 0) + (n3.gzhead.extra ? 4 : 0) + (n3.gzhead.name ? 8 : 0) + (n3.gzhead.comment ? 16 : 0)), ie(n3, 255 & n3.gzhead.time), ie(n3, n3.gzhead.time >> 8 & 255), ie(n3, n3.gzhead.time >> 16 & 255), ie(n3, n3.gzhead.time >> 24 & 255), ie(n3, 9 === n3.level ? 2 : n3.strategy >= v2 || n3.level < 2 ? 4 : 0), ie(n3, 255 & n3.gzhead.os), n3.gzhead.extra && n3.gzhead.extra.length && (ie(n3, 255 & n3.gzhead.extra.length), ie(n3, n3.gzhead.extra.length >> 8 & 255)), n3.gzhead.hcrc && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending, 0)), n3.gzindex = 0, n3.status = L2) : (ie(n3, 0), ie(n3, 0), ie(n3, 0), ie(n3, 0), ie(n3, 0), ie(n3, 9 === n3.level ? 2 : n3.strategy >= v2 || n3.level < 2 ? 4 : 0), ie(n3, Y2), n3.status = G2);
    else {
      var g2 = A2 + (n3.w_bits - 8 << 4) << 8;
      g2 |= (n3.strategy >= v2 || n3.level < 2 ? 0 : n3.level < 6 ? 1 : 6 === n3.level ? 2 : 3) << 6, 0 !== n3.strstart && (g2 |= D), g2 += 31 - g2 % 31, n3.status = G2, re(n3, g2), 0 !== n3.strstart && (re(n3, e5.adler >>> 16), re(n3, 65535 & e5.adler)), e5.adler = 1;
    }
    if (n3.status === L2) if (n3.gzhead.extra) {
      for (o3 = n3.pending; n3.gzindex < (65535 & n3.gzhead.extra.length) && (n3.pending !== n3.pending_buf_size || (n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), ee(e5), o3 = n3.pending, n3.pending !== n3.pending_buf_size)); ) ie(n3, 255 & n3.gzhead.extra[n3.gzindex]), n3.gzindex++;
      n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), n3.gzindex === n3.gzhead.extra.length && (n3.gzindex = 0, n3.status = U);
    } else n3.status = U;
    if (n3.status === U) if (n3.gzhead.name) {
      o3 = n3.pending;
      do {
        if (n3.pending === n3.pending_buf_size && (n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), ee(e5), o3 = n3.pending, n3.pending === n3.pending_buf_size)) {
          l3 = 1;
          break;
        }
        l3 = n3.gzindex < n3.gzhead.name.length ? 255 & n3.gzhead.name.charCodeAt(n3.gzindex++) : 0, ie(n3, l3);
      } while (0 !== l3);
      n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), 0 === l3 && (n3.gzindex = 0, n3.status = Z);
    } else n3.status = Z;
    if (n3.status === Z) if (n3.gzhead.comment) {
      o3 = n3.pending;
      do {
        if (n3.pending === n3.pending_buf_size && (n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), ee(e5), o3 = n3.pending, n3.pending === n3.pending_buf_size)) {
          l3 = 1;
          break;
        }
        l3 = n3.gzindex < n3.gzhead.comment.length ? 255 & n3.gzhead.comment.charCodeAt(n3.gzindex++) : 0, ie(n3, l3);
      } while (0 !== l3);
      n3.gzhead.hcrc && n3.pending > o3 && (e5.adler = s2(e5.adler, n3.pending_buf, n3.pending - o3, o3)), 0 === l3 && (n3.status = j);
    } else n3.status = j;
    if (n3.status === j && (n3.gzhead.hcrc ? (n3.pending + 2 > n3.pending_buf_size && ee(e5), n3.pending + 2 <= n3.pending_buf_size && (ie(n3, 255 & e5.adler), ie(n3, e5.adler >> 8 & 255), e5.adler = 0, n3.status = G2)) : n3.status = G2), 0 !== n3.pending) {
      if (ee(e5), 0 === e5.avail_out) return n3.last_flush = -1, p2;
    } else if (0 === e5.avail_in && J(t3) <= J(i3) && t3 !== f2) return K(e5, b2);
    if (n3.status === H && 0 !== e5.avail_in) return K(e5, b2);
    if (0 !== e5.avail_in || 0 !== n3.lookahead || t3 !== u2 && n3.status !== H) {
      var y3 = n3.strategy === v2 ? ce(n3, t3) : n3.strategy === x2 ? he(n3, t3) : r2[n3.level].func(n3, t3);
      if (y3 !== q && y3 !== V || (n3.status = H), y3 === Q || y3 === q) return 0 === e5.avail_out && (n3.last_flush = -1), p2;
      if (y3 === W && (t3 === h2 ? a2._tr_align(n3) : t3 !== d && (a2._tr_stored_block(n3, 0, 0, false), t3 === c2 && (X(n3.head), 0 === n3.lookahead && (n3.strstart = 0, n3.block_start = 0, n3.insert = 0))), ee(e5), 0 === e5.avail_out)) return n3.last_flush = -1, p2;
    }
    return t3 !== f2 ? p2 : n3.wrap <= 0 ? m : (2 === n3.wrap ? (ie(n3, 255 & e5.adler), ie(n3, e5.adler >> 8 & 255), ie(n3, e5.adler >> 16 & 255), ie(n3, e5.adler >> 24 & 255), ie(n3, 255 & e5.total_in), ie(n3, e5.total_in >> 8 & 255), ie(n3, e5.total_in >> 16 & 255), ie(n3, e5.total_in >> 24 & 255)) : (re(n3, e5.adler >>> 16), re(n3, 65535 & e5.adler)), ee(e5), n3.wrap > 0 && (n3.wrap = -n3.wrap), 0 !== n3.pending ? p2 : m);
  }
  function ve(e5) {
    var t3;
    return e5 && e5.state ? (t3 = e5.state.status) !== $ && t3 !== L2 && t3 !== U && t3 !== Z && t3 !== j && t3 !== G2 && t3 !== H ? K(e5, _2) : (e5.state = null, t3 === G2 ? K(e5, g) : p2) : _2;
  }
  function xe(e5, t3) {
    var i3, r3, a3, s3, l3, u3, h3, c3, f3 = t3.length;
    if (!e5 || !e5.state) return _2;
    if (2 === (s3 = (i3 = e5.state).wrap) || 1 === s3 && i3.status !== $ || i3.lookahead) return _2;
    for (1 === s3 && (e5.adler = o2(e5.adler, t3, f3, 0)), i3.wrap = 0, f3 >= i3.w_size && (0 === s3 && (X(i3.head), i3.strstart = 0, i3.block_start = 0, i3.insert = 0), c3 = new n2.Buf8(i3.w_size), n2.arraySet(c3, t3, f3 - i3.w_size, i3.w_size, 0), t3 = c3, f3 = i3.w_size), l3 = e5.avail_in, u3 = e5.next_in, h3 = e5.input, e5.avail_in = f3, e5.next_in = 0, e5.input = t3, oe(i3); i3.lookahead >= F; ) {
      r3 = i3.strstart, a3 = i3.lookahead - (F - 1);
      do {
        i3.ins_h = (i3.ins_h << i3.hash_shift ^ i3.window[r3 + F - 1]) & i3.hash_mask, i3.prev[r3 & i3.w_mask] = i3.head[i3.ins_h], i3.head[i3.ins_h] = r3, r3++;
      } while (--a3);
      i3.strstart = r3, i3.lookahead = F - 1, oe(i3);
    }
    return i3.strstart += i3.lookahead, i3.block_start = i3.strstart, i3.insert = i3.lookahead, i3.lookahead = 0, i3.match_length = i3.prev_length = F - 1, i3.match_available = 0, e5.next_in = u3, e5.input = h3, e5.avail_in = l3, i3.wrap = s3, p2;
  }
  r2 = [new fe(0, 0, 0, 0, se), new fe(4, 4, 8, 4, le), new fe(4, 5, 16, 8, le), new fe(4, 6, 32, 32, le), new fe(4, 4, 16, 16, ue), new fe(8, 16, 32, 32, ue), new fe(8, 16, 128, 128, ue), new fe(8, 32, 128, 256, ue), new fe(32, 128, 258, 1024, ue), new fe(32, 258, 258, 4096, ue)], i2.deflateInit = ye, i2.deflateInit2 = be, i2.deflateReset = _e2, i2.deflateResetKeep = me, i2.deflateSetHeader = ge, i2.deflate = we, i2.deflateEnd = ve, i2.deflateSetDictionary = xe, i2.deflateInfo = "pako deflate (from Nodeca project)";
}, { "../utils/common": 52, "./adler32": 53, "./crc32": 55, "./messages": 60, "./trees": 61 }], 57: [function(e4, t2, i2) {
  var r2 = 30, n2 = 12;
  t2.exports = function(e5, t3) {
    var i3, a2, o2, s2, l2, u2, h2, c2, f2, d, p2, m, _2, g, b2, y2, w, v2, x2, E2, k2, S2, A2, I, M2;
    i3 = e5.state, a2 = e5.next_in, I = e5.input, o2 = a2 + (e5.avail_in - 5), s2 = e5.next_out, M2 = e5.output, l2 = s2 - (t3 - e5.avail_out), u2 = s2 + (e5.avail_out - 257), h2 = i3.dmax, c2 = i3.wsize, f2 = i3.whave, d = i3.wnext, p2 = i3.window, m = i3.hold, _2 = i3.bits, g = i3.lencode, b2 = i3.distcode, y2 = (1 << i3.lenbits) - 1, w = (1 << i3.distbits) - 1;
    e: do {
      _2 < 15 && (m += I[a2++] << _2, _2 += 8, m += I[a2++] << _2, _2 += 8), v2 = g[m & y2];
      t: for (; ; ) {
        if (m >>>= x2 = v2 >>> 24, _2 -= x2, 0 == (x2 = v2 >>> 16 & 255)) M2[s2++] = 65535 & v2;
        else {
          if (!(16 & x2)) {
            if (64 & x2) {
              if (32 & x2) {
                i3.mode = n2;
                break e;
              }
              e5.msg = "invalid literal/length code", i3.mode = r2;
              break e;
            }
            v2 = g[(65535 & v2) + (m & (1 << x2) - 1)];
            continue t;
          }
          for (E2 = 65535 & v2, (x2 &= 15) && (_2 < x2 && (m += I[a2++] << _2, _2 += 8), E2 += m & (1 << x2) - 1, m >>>= x2, _2 -= x2), _2 < 15 && (m += I[a2++] << _2, _2 += 8, m += I[a2++] << _2, _2 += 8), v2 = b2[m & w]; ; ) {
            if (m >>>= x2 = v2 >>> 24, _2 -= x2, 16 & (x2 = v2 >>> 16 & 255)) {
              if (k2 = 65535 & v2, _2 < (x2 &= 15) && (m += I[a2++] << _2, (_2 += 8) < x2 && (m += I[a2++] << _2, _2 += 8)), (k2 += m & (1 << x2) - 1) > h2) {
                e5.msg = "invalid distance too far back", i3.mode = r2;
                break e;
              }
              if (m >>>= x2, _2 -= x2, k2 > (x2 = s2 - l2)) {
                if ((x2 = k2 - x2) > f2 && i3.sane) {
                  e5.msg = "invalid distance too far back", i3.mode = r2;
                  break e;
                }
                if (S2 = 0, A2 = p2, 0 === d) {
                  if (S2 += c2 - x2, x2 < E2) {
                    E2 -= x2;
                    do {
                      M2[s2++] = p2[S2++];
                    } while (--x2);
                    S2 = s2 - k2, A2 = M2;
                  }
                } else if (d < x2) {
                  if (S2 += c2 + d - x2, (x2 -= d) < E2) {
                    E2 -= x2;
                    do {
                      M2[s2++] = p2[S2++];
                    } while (--x2);
                    if (S2 = 0, d < E2) {
                      E2 -= x2 = d;
                      do {
                        M2[s2++] = p2[S2++];
                      } while (--x2);
                      S2 = s2 - k2, A2 = M2;
                    }
                  }
                } else if (S2 += d - x2, x2 < E2) {
                  E2 -= x2;
                  do {
                    M2[s2++] = p2[S2++];
                  } while (--x2);
                  S2 = s2 - k2, A2 = M2;
                }
                for (; E2 > 2; ) M2[s2++] = A2[S2++], M2[s2++] = A2[S2++], M2[s2++] = A2[S2++], E2 -= 3;
                E2 && (M2[s2++] = A2[S2++], E2 > 1 && (M2[s2++] = A2[S2++]));
              } else {
                S2 = s2 - k2;
                do {
                  M2[s2++] = M2[S2++], M2[s2++] = M2[S2++], M2[s2++] = M2[S2++], E2 -= 3;
                } while (E2 > 2);
                E2 && (M2[s2++] = M2[S2++], E2 > 1 && (M2[s2++] = M2[S2++]));
              }
              break;
            }
            if (64 & x2) {
              e5.msg = "invalid distance code", i3.mode = r2;
              break e;
            }
            v2 = b2[(65535 & v2) + (m & (1 << x2) - 1)];
          }
        }
        break;
      }
    } while (a2 < o2 && s2 < u2);
    a2 -= E2 = _2 >> 3, m &= (1 << (_2 -= E2 << 3)) - 1, e5.next_in = a2, e5.next_out = s2, e5.avail_in = a2 < o2 ? o2 - a2 + 5 : 5 - (a2 - o2), e5.avail_out = s2 < u2 ? u2 - s2 + 257 : 257 - (s2 - u2), i3.hold = m, i3.bits = _2;
  };
}, {}], 58: [function(e4, t2, i2) {
  var r2 = e4("../utils/common"), n2 = e4("./adler32"), a2 = e4("./crc32"), o2 = e4("./inffast"), s2 = e4("./inftrees"), l2 = 0, u2 = 1, h2 = 2, c2 = 4, f2 = 5, d = 6, p2 = 0, m = 1, _2 = 2, g = -2, b2 = -3, y2 = -4, w = -5, v2 = 8, x2 = 1, E2 = 2, k2 = 3, S2 = 4, A2 = 5, I = 6, M2 = 7, T2 = 8, P = 9, B2 = 10, C2 = 11, R2 = 12, z2 = 13, F = 14, N2 = 15, O2 = 16, D = 17, $ = 18, L2 = 19, U = 20, Z = 21, j = 22, G2 = 23, H = 24, Q = 25, W = 26, q = 27, V = 28, Y2 = 29, K = 30, J = 31, X = 852, ee = 592, te = 15;
  function ie(e5) {
    return (e5 >>> 24 & 255) + (e5 >>> 8 & 65280) + ((65280 & e5) << 8) + ((255 & e5) << 24);
  }
  function re() {
    this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new r2.Buf16(320), this.work = new r2.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
  }
  function ne(e5) {
    var t3;
    return e5 && e5.state ? (t3 = e5.state, e5.total_in = e5.total_out = t3.total = 0, e5.msg = "", t3.wrap && (e5.adler = 1 & t3.wrap), t3.mode = x2, t3.last = 0, t3.havedict = 0, t3.dmax = 32768, t3.head = null, t3.hold = 0, t3.bits = 0, t3.lencode = t3.lendyn = new r2.Buf32(X), t3.distcode = t3.distdyn = new r2.Buf32(ee), t3.sane = 1, t3.back = -1, p2) : g;
  }
  function ae(e5) {
    var t3;
    return e5 && e5.state ? ((t3 = e5.state).wsize = 0, t3.whave = 0, t3.wnext = 0, ne(e5)) : g;
  }
  function oe(e5, t3) {
    var i3, r3;
    return e5 && e5.state ? (r3 = e5.state, t3 < 0 ? (i3 = 0, t3 = -t3) : (i3 = 1 + (t3 >> 4), t3 < 48 && (t3 &= 15)), t3 && (t3 < 8 || t3 > 15) ? g : (null !== r3.window && r3.wbits !== t3 && (r3.window = null), r3.wrap = i3, r3.wbits = t3, ae(e5))) : g;
  }
  function se(e5, t3) {
    var i3, r3;
    return e5 ? (r3 = new re(), e5.state = r3, r3.window = null, (i3 = oe(e5, t3)) !== p2 && (e5.state = null), i3) : g;
  }
  function le(e5) {
    return se(e5, te);
  }
  var ue, he, ce = true;
  function fe(e5) {
    if (ce) {
      var t3;
      for (ue = new r2.Buf32(512), he = new r2.Buf32(32), t3 = 0; t3 < 144; ) e5.lens[t3++] = 8;
      for (; t3 < 256; ) e5.lens[t3++] = 9;
      for (; t3 < 280; ) e5.lens[t3++] = 7;
      for (; t3 < 288; ) e5.lens[t3++] = 8;
      for (s2(u2, e5.lens, 0, 288, ue, 0, e5.work, { bits: 9 }), t3 = 0; t3 < 32; ) e5.lens[t3++] = 5;
      s2(h2, e5.lens, 0, 32, he, 0, e5.work, { bits: 5 }), ce = false;
    }
    e5.lencode = ue, e5.lenbits = 9, e5.distcode = he, e5.distbits = 5;
  }
  function de(e5, t3, i3, n3) {
    var a3, o3 = e5.state;
    return null === o3.window && (o3.wsize = 1 << o3.wbits, o3.wnext = 0, o3.whave = 0, o3.window = new r2.Buf8(o3.wsize)), n3 >= o3.wsize ? (r2.arraySet(o3.window, t3, i3 - o3.wsize, o3.wsize, 0), o3.wnext = 0, o3.whave = o3.wsize) : ((a3 = o3.wsize - o3.wnext) > n3 && (a3 = n3), r2.arraySet(o3.window, t3, i3 - n3, a3, o3.wnext), (n3 -= a3) ? (r2.arraySet(o3.window, t3, i3 - n3, n3, 0), o3.wnext = n3, o3.whave = o3.wsize) : (o3.wnext += a3, o3.wnext === o3.wsize && (o3.wnext = 0), o3.whave < o3.wsize && (o3.whave += a3))), 0;
  }
  function pe(e5, t3) {
    var i3, X2, ee2, te2, re2, ne2, ae2, oe2, se2, le2, ue2, he2, ce2, pe2, me2, _e22, ge2, be, ye, we, ve, xe, Ee, ke, Se = 0, Ae = new r2.Buf8(4), Ie = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
    if (!e5 || !e5.state || !e5.output || !e5.input && 0 !== e5.avail_in) return g;
    (i3 = e5.state).mode === R2 && (i3.mode = z2), re2 = e5.next_out, ee2 = e5.output, ae2 = e5.avail_out, te2 = e5.next_in, X2 = e5.input, ne2 = e5.avail_in, oe2 = i3.hold, se2 = i3.bits, le2 = ne2, ue2 = ae2, xe = p2;
    e: for (; ; ) switch (i3.mode) {
      case x2:
        if (0 === i3.wrap) {
          i3.mode = z2;
          break;
        }
        for (; se2 < 16; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if (2 & i3.wrap && 35615 === oe2) {
          i3.check = 0, Ae[0] = 255 & oe2, Ae[1] = oe2 >>> 8 & 255, i3.check = a2(i3.check, Ae, 2, 0), oe2 = 0, se2 = 0, i3.mode = E2;
          break;
        }
        if (i3.flags = 0, i3.head && (i3.head.done = false), !(1 & i3.wrap) || (((255 & oe2) << 8) + (oe2 >> 8)) % 31) {
          e5.msg = "incorrect header check", i3.mode = K;
          break;
        }
        if ((15 & oe2) !== v2) {
          e5.msg = "unknown compression method", i3.mode = K;
          break;
        }
        if (se2 -= 4, ve = 8 + (15 & (oe2 >>>= 4)), 0 === i3.wbits) i3.wbits = ve;
        else if (ve > i3.wbits) {
          e5.msg = "invalid window size", i3.mode = K;
          break;
        }
        i3.dmax = 1 << ve, e5.adler = i3.check = 1, i3.mode = 512 & oe2 ? B2 : R2, oe2 = 0, se2 = 0;
        break;
      case E2:
        for (; se2 < 16; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if (i3.flags = oe2, (255 & i3.flags) !== v2) {
          e5.msg = "unknown compression method", i3.mode = K;
          break;
        }
        if (57344 & i3.flags) {
          e5.msg = "unknown header flags set", i3.mode = K;
          break;
        }
        i3.head && (i3.head.text = oe2 >> 8 & 1), 512 & i3.flags && (Ae[0] = 255 & oe2, Ae[1] = oe2 >>> 8 & 255, i3.check = a2(i3.check, Ae, 2, 0)), oe2 = 0, se2 = 0, i3.mode = k2;
      case k2:
        for (; se2 < 32; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        i3.head && (i3.head.time = oe2), 512 & i3.flags && (Ae[0] = 255 & oe2, Ae[1] = oe2 >>> 8 & 255, Ae[2] = oe2 >>> 16 & 255, Ae[3] = oe2 >>> 24 & 255, i3.check = a2(i3.check, Ae, 4, 0)), oe2 = 0, se2 = 0, i3.mode = S2;
      case S2:
        for (; se2 < 16; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        i3.head && (i3.head.xflags = 255 & oe2, i3.head.os = oe2 >> 8), 512 & i3.flags && (Ae[0] = 255 & oe2, Ae[1] = oe2 >>> 8 & 255, i3.check = a2(i3.check, Ae, 2, 0)), oe2 = 0, se2 = 0, i3.mode = A2;
      case A2:
        if (1024 & i3.flags) {
          for (; se2 < 16; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          i3.length = oe2, i3.head && (i3.head.extra_len = oe2), 512 & i3.flags && (Ae[0] = 255 & oe2, Ae[1] = oe2 >>> 8 & 255, i3.check = a2(i3.check, Ae, 2, 0)), oe2 = 0, se2 = 0;
        } else i3.head && (i3.head.extra = null);
        i3.mode = I;
      case I:
        if (1024 & i3.flags && ((he2 = i3.length) > ne2 && (he2 = ne2), he2 && (i3.head && (ve = i3.head.extra_len - i3.length, i3.head.extra || (i3.head.extra = new Array(i3.head.extra_len)), r2.arraySet(i3.head.extra, X2, te2, he2, ve)), 512 & i3.flags && (i3.check = a2(i3.check, X2, he2, te2)), ne2 -= he2, te2 += he2, i3.length -= he2), i3.length)) break e;
        i3.length = 0, i3.mode = M2;
      case M2:
        if (2048 & i3.flags) {
          if (0 === ne2) break e;
          he2 = 0;
          do {
            ve = X2[te2 + he2++], i3.head && ve && i3.length < 65536 && (i3.head.name += String.fromCharCode(ve));
          } while (ve && he2 < ne2);
          if (512 & i3.flags && (i3.check = a2(i3.check, X2, he2, te2)), ne2 -= he2, te2 += he2, ve) break e;
        } else i3.head && (i3.head.name = null);
        i3.length = 0, i3.mode = T2;
      case T2:
        if (4096 & i3.flags) {
          if (0 === ne2) break e;
          he2 = 0;
          do {
            ve = X2[te2 + he2++], i3.head && ve && i3.length < 65536 && (i3.head.comment += String.fromCharCode(ve));
          } while (ve && he2 < ne2);
          if (512 & i3.flags && (i3.check = a2(i3.check, X2, he2, te2)), ne2 -= he2, te2 += he2, ve) break e;
        } else i3.head && (i3.head.comment = null);
        i3.mode = P;
      case P:
        if (512 & i3.flags) {
          for (; se2 < 16; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          if (oe2 !== (65535 & i3.check)) {
            e5.msg = "header crc mismatch", i3.mode = K;
            break;
          }
          oe2 = 0, se2 = 0;
        }
        i3.head && (i3.head.hcrc = i3.flags >> 9 & 1, i3.head.done = true), e5.adler = i3.check = 0, i3.mode = R2;
        break;
      case B2:
        for (; se2 < 32; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        e5.adler = i3.check = ie(oe2), oe2 = 0, se2 = 0, i3.mode = C2;
      case C2:
        if (0 === i3.havedict) return e5.next_out = re2, e5.avail_out = ae2, e5.next_in = te2, e5.avail_in = ne2, i3.hold = oe2, i3.bits = se2, _2;
        e5.adler = i3.check = 1, i3.mode = R2;
      case R2:
        if (t3 === f2 || t3 === d) break e;
      case z2:
        if (i3.last) {
          oe2 >>>= 7 & se2, se2 -= 7 & se2, i3.mode = q;
          break;
        }
        for (; se2 < 3; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        switch (i3.last = 1 & oe2, se2 -= 1, 3 & (oe2 >>>= 1)) {
          case 0:
            i3.mode = F;
            break;
          case 1:
            if (fe(i3), i3.mode = U, t3 === d) {
              oe2 >>>= 2, se2 -= 2;
              break e;
            }
            break;
          case 2:
            i3.mode = D;
            break;
          case 3:
            e5.msg = "invalid block type", i3.mode = K;
        }
        oe2 >>>= 2, se2 -= 2;
        break;
      case F:
        for (oe2 >>>= 7 & se2, se2 -= 7 & se2; se2 < 32; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if ((65535 & oe2) != (oe2 >>> 16 ^ 65535)) {
          e5.msg = "invalid stored block lengths", i3.mode = K;
          break;
        }
        if (i3.length = 65535 & oe2, oe2 = 0, se2 = 0, i3.mode = N2, t3 === d) break e;
      case N2:
        i3.mode = O2;
      case O2:
        if (he2 = i3.length) {
          if (he2 > ne2 && (he2 = ne2), he2 > ae2 && (he2 = ae2), 0 === he2) break e;
          r2.arraySet(ee2, X2, te2, he2, re2), ne2 -= he2, te2 += he2, ae2 -= he2, re2 += he2, i3.length -= he2;
          break;
        }
        i3.mode = R2;
        break;
      case D:
        for (; se2 < 14; ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if (i3.nlen = 257 + (31 & oe2), oe2 >>>= 5, se2 -= 5, i3.ndist = 1 + (31 & oe2), oe2 >>>= 5, se2 -= 5, i3.ncode = 4 + (15 & oe2), oe2 >>>= 4, se2 -= 4, i3.nlen > 286 || i3.ndist > 30) {
          e5.msg = "too many length or distance symbols", i3.mode = K;
          break;
        }
        i3.have = 0, i3.mode = $;
      case $:
        for (; i3.have < i3.ncode; ) {
          for (; se2 < 3; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          i3.lens[Ie[i3.have++]] = 7 & oe2, oe2 >>>= 3, se2 -= 3;
        }
        for (; i3.have < 19; ) i3.lens[Ie[i3.have++]] = 0;
        if (i3.lencode = i3.lendyn, i3.lenbits = 7, Ee = { bits: i3.lenbits }, xe = s2(l2, i3.lens, 0, 19, i3.lencode, 0, i3.work, Ee), i3.lenbits = Ee.bits, xe) {
          e5.msg = "invalid code lengths set", i3.mode = K;
          break;
        }
        i3.have = 0, i3.mode = L2;
      case L2:
        for (; i3.have < i3.nlen + i3.ndist; ) {
          for (; _e22 = (Se = i3.lencode[oe2 & (1 << i3.lenbits) - 1]) >>> 16 & 255, ge2 = 65535 & Se, !((me2 = Se >>> 24) <= se2); ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          if (ge2 < 16) oe2 >>>= me2, se2 -= me2, i3.lens[i3.have++] = ge2;
          else {
            if (16 === ge2) {
              for (ke = me2 + 2; se2 < ke; ) {
                if (0 === ne2) break e;
                ne2--, oe2 += X2[te2++] << se2, se2 += 8;
              }
              if (oe2 >>>= me2, se2 -= me2, 0 === i3.have) {
                e5.msg = "invalid bit length repeat", i3.mode = K;
                break;
              }
              ve = i3.lens[i3.have - 1], he2 = 3 + (3 & oe2), oe2 >>>= 2, se2 -= 2;
            } else if (17 === ge2) {
              for (ke = me2 + 3; se2 < ke; ) {
                if (0 === ne2) break e;
                ne2--, oe2 += X2[te2++] << se2, se2 += 8;
              }
              se2 -= me2, ve = 0, he2 = 3 + (7 & (oe2 >>>= me2)), oe2 >>>= 3, se2 -= 3;
            } else {
              for (ke = me2 + 7; se2 < ke; ) {
                if (0 === ne2) break e;
                ne2--, oe2 += X2[te2++] << se2, se2 += 8;
              }
              se2 -= me2, ve = 0, he2 = 11 + (127 & (oe2 >>>= me2)), oe2 >>>= 7, se2 -= 7;
            }
            if (i3.have + he2 > i3.nlen + i3.ndist) {
              e5.msg = "invalid bit length repeat", i3.mode = K;
              break;
            }
            for (; he2--; ) i3.lens[i3.have++] = ve;
          }
        }
        if (i3.mode === K) break;
        if (0 === i3.lens[256]) {
          e5.msg = "invalid code -- missing end-of-block", i3.mode = K;
          break;
        }
        if (i3.lenbits = 9, Ee = { bits: i3.lenbits }, xe = s2(u2, i3.lens, 0, i3.nlen, i3.lencode, 0, i3.work, Ee), i3.lenbits = Ee.bits, xe) {
          e5.msg = "invalid literal/lengths set", i3.mode = K;
          break;
        }
        if (i3.distbits = 6, i3.distcode = i3.distdyn, Ee = { bits: i3.distbits }, xe = s2(h2, i3.lens, i3.nlen, i3.ndist, i3.distcode, 0, i3.work, Ee), i3.distbits = Ee.bits, xe) {
          e5.msg = "invalid distances set", i3.mode = K;
          break;
        }
        if (i3.mode = U, t3 === d) break e;
      case U:
        i3.mode = Z;
      case Z:
        if (ne2 >= 6 && ae2 >= 258) {
          e5.next_out = re2, e5.avail_out = ae2, e5.next_in = te2, e5.avail_in = ne2, i3.hold = oe2, i3.bits = se2, o2(e5, ue2), re2 = e5.next_out, ee2 = e5.output, ae2 = e5.avail_out, te2 = e5.next_in, X2 = e5.input, ne2 = e5.avail_in, oe2 = i3.hold, se2 = i3.bits, i3.mode === R2 && (i3.back = -1);
          break;
        }
        for (i3.back = 0; _e22 = (Se = i3.lencode[oe2 & (1 << i3.lenbits) - 1]) >>> 16 & 255, ge2 = 65535 & Se, !((me2 = Se >>> 24) <= se2); ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if (_e22 && !(240 & _e22)) {
          for (be = me2, ye = _e22, we = ge2; _e22 = (Se = i3.lencode[we + ((oe2 & (1 << be + ye) - 1) >> be)]) >>> 16 & 255, ge2 = 65535 & Se, !(be + (me2 = Se >>> 24) <= se2); ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          oe2 >>>= be, se2 -= be, i3.back += be;
        }
        if (oe2 >>>= me2, se2 -= me2, i3.back += me2, i3.length = ge2, 0 === _e22) {
          i3.mode = W;
          break;
        }
        if (32 & _e22) {
          i3.back = -1, i3.mode = R2;
          break;
        }
        if (64 & _e22) {
          e5.msg = "invalid literal/length code", i3.mode = K;
          break;
        }
        i3.extra = 15 & _e22, i3.mode = j;
      case j:
        if (i3.extra) {
          for (ke = i3.extra; se2 < ke; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          i3.length += oe2 & (1 << i3.extra) - 1, oe2 >>>= i3.extra, se2 -= i3.extra, i3.back += i3.extra;
        }
        i3.was = i3.length, i3.mode = G2;
      case G2:
        for (; _e22 = (Se = i3.distcode[oe2 & (1 << i3.distbits) - 1]) >>> 16 & 255, ge2 = 65535 & Se, !((me2 = Se >>> 24) <= se2); ) {
          if (0 === ne2) break e;
          ne2--, oe2 += X2[te2++] << se2, se2 += 8;
        }
        if (!(240 & _e22)) {
          for (be = me2, ye = _e22, we = ge2; _e22 = (Se = i3.distcode[we + ((oe2 & (1 << be + ye) - 1) >> be)]) >>> 16 & 255, ge2 = 65535 & Se, !(be + (me2 = Se >>> 24) <= se2); ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          oe2 >>>= be, se2 -= be, i3.back += be;
        }
        if (oe2 >>>= me2, se2 -= me2, i3.back += me2, 64 & _e22) {
          e5.msg = "invalid distance code", i3.mode = K;
          break;
        }
        i3.offset = ge2, i3.extra = 15 & _e22, i3.mode = H;
      case H:
        if (i3.extra) {
          for (ke = i3.extra; se2 < ke; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          i3.offset += oe2 & (1 << i3.extra) - 1, oe2 >>>= i3.extra, se2 -= i3.extra, i3.back += i3.extra;
        }
        if (i3.offset > i3.dmax) {
          e5.msg = "invalid distance too far back", i3.mode = K;
          break;
        }
        i3.mode = Q;
      case Q:
        if (0 === ae2) break e;
        if (he2 = ue2 - ae2, i3.offset > he2) {
          if ((he2 = i3.offset - he2) > i3.whave && i3.sane) {
            e5.msg = "invalid distance too far back", i3.mode = K;
            break;
          }
          he2 > i3.wnext ? (he2 -= i3.wnext, ce2 = i3.wsize - he2) : ce2 = i3.wnext - he2, he2 > i3.length && (he2 = i3.length), pe2 = i3.window;
        } else pe2 = ee2, ce2 = re2 - i3.offset, he2 = i3.length;
        he2 > ae2 && (he2 = ae2), ae2 -= he2, i3.length -= he2;
        do {
          ee2[re2++] = pe2[ce2++];
        } while (--he2);
        0 === i3.length && (i3.mode = Z);
        break;
      case W:
        if (0 === ae2) break e;
        ee2[re2++] = i3.length, ae2--, i3.mode = Z;
        break;
      case q:
        if (i3.wrap) {
          for (; se2 < 32; ) {
            if (0 === ne2) break e;
            ne2--, oe2 |= X2[te2++] << se2, se2 += 8;
          }
          if (ue2 -= ae2, e5.total_out += ue2, i3.total += ue2, ue2 && (e5.adler = i3.check = i3.flags ? a2(i3.check, ee2, ue2, re2 - ue2) : n2(i3.check, ee2, ue2, re2 - ue2)), ue2 = ae2, (i3.flags ? oe2 : ie(oe2)) !== i3.check) {
            e5.msg = "incorrect data check", i3.mode = K;
            break;
          }
          oe2 = 0, se2 = 0;
        }
        i3.mode = V;
      case V:
        if (i3.wrap && i3.flags) {
          for (; se2 < 32; ) {
            if (0 === ne2) break e;
            ne2--, oe2 += X2[te2++] << se2, se2 += 8;
          }
          if (oe2 !== (4294967295 & i3.total)) {
            e5.msg = "incorrect length check", i3.mode = K;
            break;
          }
          oe2 = 0, se2 = 0;
        }
        i3.mode = Y2;
      case Y2:
        xe = m;
        break e;
      case K:
        xe = b2;
        break e;
      case J:
        return y2;
      default:
        return g;
    }
    return e5.next_out = re2, e5.avail_out = ae2, e5.next_in = te2, e5.avail_in = ne2, i3.hold = oe2, i3.bits = se2, (i3.wsize || ue2 !== e5.avail_out && i3.mode < K && (i3.mode < q || t3 !== c2)) && de(e5, e5.output, e5.next_out, ue2 - e5.avail_out), le2 -= e5.avail_in, ue2 -= e5.avail_out, e5.total_in += le2, e5.total_out += ue2, i3.total += ue2, i3.wrap && ue2 && (e5.adler = i3.check = i3.flags ? a2(i3.check, ee2, ue2, e5.next_out - ue2) : n2(i3.check, ee2, ue2, e5.next_out - ue2)), e5.data_type = i3.bits + (i3.last ? 64 : 0) + (i3.mode === R2 ? 128 : 0) + (i3.mode === U || i3.mode === N2 ? 256 : 0), (0 === le2 && 0 === ue2 || t3 === c2) && xe === p2 && (xe = w), xe;
  }
  function me(e5) {
    if (!e5 || !e5.state) return g;
    var t3 = e5.state;
    return t3.window && (t3.window = null), e5.state = null, p2;
  }
  function _e2(e5, t3) {
    var i3;
    return e5 && e5.state && 2 & (i3 = e5.state).wrap ? (i3.head = t3, t3.done = false, p2) : g;
  }
  function ge(e5, t3) {
    var i3, r3 = t3.length;
    return e5 && e5.state ? 0 !== (i3 = e5.state).wrap && i3.mode !== C2 ? g : i3.mode === C2 && n2(1, t3, r3, 0) !== i3.check ? b2 : de(e5, t3, r3, r3) ? (i3.mode = J, y2) : (i3.havedict = 1, p2) : g;
  }
  i2.inflateReset = ae, i2.inflateReset2 = oe, i2.inflateResetKeep = ne, i2.inflateInit = le, i2.inflateInit2 = se, i2.inflate = pe, i2.inflateEnd = me, i2.inflateGetHeader = _e2, i2.inflateSetDictionary = ge, i2.inflateInfo = "pako inflate (from Nodeca project)";
}, { "../utils/common": 52, "./adler32": 53, "./crc32": 55, "./inffast": 57, "./inftrees": 59 }], 59: [function(e4, t2, i2) {
  var r2 = e4("../utils/common"), n2 = 15, a2 = 852, o2 = 592, s2 = 0, l2 = 1, u2 = 2, h2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], c2 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], f2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], d = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
  t2.exports = function(e5, t3, i3, p2, m, _2, g, b2) {
    var y2, w, v2, x2, E2, k2, S2, A2, I, M2 = b2.bits, T2 = 0, P = 0, B2 = 0, C2 = 0, R2 = 0, z2 = 0, F = 0, N2 = 0, O2 = 0, D = 0, $ = null, L2 = 0, U = new r2.Buf16(n2 + 1), Z = new r2.Buf16(n2 + 1), j = null, G2 = 0;
    for (T2 = 0; T2 <= n2; T2++) U[T2] = 0;
    for (P = 0; P < p2; P++) U[t3[i3 + P]]++;
    for (R2 = M2, C2 = n2; C2 >= 1 && 0 === U[C2]; C2--) ;
    if (R2 > C2 && (R2 = C2), 0 === C2) return m[_2++] = 20971520, m[_2++] = 20971520, b2.bits = 1, 0;
    for (B2 = 1; B2 < C2 && 0 === U[B2]; B2++) ;
    for (R2 < B2 && (R2 = B2), N2 = 1, T2 = 1; T2 <= n2; T2++) if (N2 <<= 1, (N2 -= U[T2]) < 0) return -1;
    if (N2 > 0 && (e5 === s2 || 1 !== C2)) return -1;
    for (Z[1] = 0, T2 = 1; T2 < n2; T2++) Z[T2 + 1] = Z[T2] + U[T2];
    for (P = 0; P < p2; P++) 0 !== t3[i3 + P] && (g[Z[t3[i3 + P]]++] = P);
    if (e5 === s2 ? ($ = j = g, k2 = 19) : e5 === l2 ? ($ = h2, L2 -= 257, j = c2, G2 -= 257, k2 = 256) : ($ = f2, j = d, k2 = -1), D = 0, P = 0, T2 = B2, E2 = _2, z2 = R2, F = 0, v2 = -1, x2 = (O2 = 1 << R2) - 1, e5 === l2 && O2 > a2 || e5 === u2 && O2 > o2) return 1;
    for (; ; ) {
      S2 = T2 - F, g[P] < k2 ? (A2 = 0, I = g[P]) : g[P] > k2 ? (A2 = j[G2 + g[P]], I = $[L2 + g[P]]) : (A2 = 96, I = 0), y2 = 1 << T2 - F, B2 = w = 1 << z2;
      do {
        m[E2 + (D >> F) + (w -= y2)] = S2 << 24 | A2 << 16 | I;
      } while (0 !== w);
      for (y2 = 1 << T2 - 1; D & y2; ) y2 >>= 1;
      if (0 !== y2 ? (D &= y2 - 1, D += y2) : D = 0, P++, 0 == --U[T2]) {
        if (T2 === C2) break;
        T2 = t3[i3 + g[P]];
      }
      if (T2 > R2 && (D & x2) !== v2) {
        for (0 === F && (F = R2), E2 += B2, N2 = 1 << (z2 = T2 - F); z2 + F < C2 && !((N2 -= U[z2 + F]) <= 0); ) z2++, N2 <<= 1;
        if (O2 += 1 << z2, e5 === l2 && O2 > a2 || e5 === u2 && O2 > o2) return 1;
        m[v2 = D & x2] = R2 << 24 | z2 << 16 | E2 - _2;
      }
    }
    return 0 !== D && (m[E2 + D] = T2 - F << 24 | 64 << 16), b2.bits = R2, 0;
  };
}, { "../utils/common": 52 }], 60: [function(e4, t2, i2) {
  t2.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" };
}, {}], 61: [function(e4, t2, i2) {
  var r2 = e4("../utils/common"), n2 = 4, a2 = 0, o2 = 1, s2 = 2;
  function l2(e5) {
    for (var t3 = e5.length; --t3 >= 0; ) e5[t3] = 0;
  }
  var u2 = 0, h2 = 1, c2 = 2, f2 = 3, d = 258, p2 = 29, m = 256, _2 = m + 1 + p2, g = 30, b2 = 19, y2 = 2 * _2 + 1, w = 15, v2 = 16, x2 = 7, E2 = 256, k2 = 16, S2 = 17, A2 = 18, I = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], M2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], T2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], P = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], B2 = 512, C2 = new Array(2 * (_2 + 2));
  l2(C2);
  var R2 = new Array(2 * g);
  l2(R2);
  var z2 = new Array(B2);
  l2(z2);
  var F = new Array(d - f2 + 1);
  l2(F);
  var N2 = new Array(p2);
  l2(N2);
  var O2, D, $, L2 = new Array(g);
  function U(e5, t3, i3, r3, n3) {
    this.static_tree = e5, this.extra_bits = t3, this.extra_base = i3, this.elems = r3, this.max_length = n3, this.has_stree = e5 && e5.length;
  }
  function Z(e5, t3) {
    this.dyn_tree = e5, this.max_code = 0, this.stat_desc = t3;
  }
  function j(e5) {
    return e5 < 256 ? z2[e5] : z2[256 + (e5 >>> 7)];
  }
  function G2(e5, t3) {
    e5.pending_buf[e5.pending++] = 255 & t3, e5.pending_buf[e5.pending++] = t3 >>> 8 & 255;
  }
  function H(e5, t3, i3) {
    e5.bi_valid > v2 - i3 ? (e5.bi_buf |= t3 << e5.bi_valid & 65535, G2(e5, e5.bi_buf), e5.bi_buf = t3 >> v2 - e5.bi_valid, e5.bi_valid += i3 - v2) : (e5.bi_buf |= t3 << e5.bi_valid & 65535, e5.bi_valid += i3);
  }
  function Q(e5, t3, i3) {
    H(e5, i3[2 * t3], i3[2 * t3 + 1]);
  }
  function W(e5, t3) {
    var i3 = 0;
    do {
      i3 |= 1 & e5, e5 >>>= 1, i3 <<= 1;
    } while (--t3 > 0);
    return i3 >>> 1;
  }
  function q(e5) {
    16 === e5.bi_valid ? (G2(e5, e5.bi_buf), e5.bi_buf = 0, e5.bi_valid = 0) : e5.bi_valid >= 8 && (e5.pending_buf[e5.pending++] = 255 & e5.bi_buf, e5.bi_buf >>= 8, e5.bi_valid -= 8);
  }
  function V(e5, t3) {
    var i3, r3, n3, a3, o3, s3, l3 = t3.dyn_tree, u3 = t3.max_code, h3 = t3.stat_desc.static_tree, c3 = t3.stat_desc.has_stree, f3 = t3.stat_desc.extra_bits, d2 = t3.stat_desc.extra_base, p3 = t3.stat_desc.max_length, m2 = 0;
    for (a3 = 0; a3 <= w; a3++) e5.bl_count[a3] = 0;
    for (l3[2 * e5.heap[e5.heap_max] + 1] = 0, i3 = e5.heap_max + 1; i3 < y2; i3++) (a3 = l3[2 * l3[2 * (r3 = e5.heap[i3]) + 1] + 1] + 1) > p3 && (a3 = p3, m2++), l3[2 * r3 + 1] = a3, r3 > u3 || (e5.bl_count[a3]++, o3 = 0, r3 >= d2 && (o3 = f3[r3 - d2]), s3 = l3[2 * r3], e5.opt_len += s3 * (a3 + o3), c3 && (e5.static_len += s3 * (h3[2 * r3 + 1] + o3)));
    if (0 !== m2) {
      do {
        for (a3 = p3 - 1; 0 === e5.bl_count[a3]; ) a3--;
        e5.bl_count[a3]--, e5.bl_count[a3 + 1] += 2, e5.bl_count[p3]--, m2 -= 2;
      } while (m2 > 0);
      for (a3 = p3; 0 !== a3; a3--) for (r3 = e5.bl_count[a3]; 0 !== r3; ) (n3 = e5.heap[--i3]) > u3 || (l3[2 * n3 + 1] !== a3 && (e5.opt_len += (a3 - l3[2 * n3 + 1]) * l3[2 * n3], l3[2 * n3 + 1] = a3), r3--);
    }
  }
  function Y2(e5, t3, i3) {
    var r3, n3, a3 = new Array(w + 1), o3 = 0;
    for (r3 = 1; r3 <= w; r3++) a3[r3] = o3 = o3 + i3[r3 - 1] << 1;
    for (n3 = 0; n3 <= t3; n3++) {
      var s3 = e5[2 * n3 + 1];
      0 !== s3 && (e5[2 * n3] = W(a3[s3]++, s3));
    }
  }
  function K() {
    var e5, t3, i3, r3, n3, a3 = new Array(w + 1);
    for (i3 = 0, r3 = 0; r3 < p2 - 1; r3++) for (N2[r3] = i3, e5 = 0; e5 < 1 << I[r3]; e5++) F[i3++] = r3;
    for (F[i3 - 1] = r3, n3 = 0, r3 = 0; r3 < 16; r3++) for (L2[r3] = n3, e5 = 0; e5 < 1 << M2[r3]; e5++) z2[n3++] = r3;
    for (n3 >>= 7; r3 < g; r3++) for (L2[r3] = n3 << 7, e5 = 0; e5 < 1 << M2[r3] - 7; e5++) z2[256 + n3++] = r3;
    for (t3 = 0; t3 <= w; t3++) a3[t3] = 0;
    for (e5 = 0; e5 <= 143; ) C2[2 * e5 + 1] = 8, e5++, a3[8]++;
    for (; e5 <= 255; ) C2[2 * e5 + 1] = 9, e5++, a3[9]++;
    for (; e5 <= 279; ) C2[2 * e5 + 1] = 7, e5++, a3[7]++;
    for (; e5 <= 287; ) C2[2 * e5 + 1] = 8, e5++, a3[8]++;
    for (Y2(C2, _2 + 1, a3), e5 = 0; e5 < g; e5++) R2[2 * e5 + 1] = 5, R2[2 * e5] = W(e5, 5);
    O2 = new U(C2, I, m + 1, _2, w), D = new U(R2, M2, 0, g, w), $ = new U(new Array(0), T2, 0, b2, x2);
  }
  function J(e5) {
    var t3;
    for (t3 = 0; t3 < _2; t3++) e5.dyn_ltree[2 * t3] = 0;
    for (t3 = 0; t3 < g; t3++) e5.dyn_dtree[2 * t3] = 0;
    for (t3 = 0; t3 < b2; t3++) e5.bl_tree[2 * t3] = 0;
    e5.dyn_ltree[2 * E2] = 1, e5.opt_len = e5.static_len = 0, e5.last_lit = e5.matches = 0;
  }
  function X(e5) {
    e5.bi_valid > 8 ? G2(e5, e5.bi_buf) : e5.bi_valid > 0 && (e5.pending_buf[e5.pending++] = e5.bi_buf), e5.bi_buf = 0, e5.bi_valid = 0;
  }
  function ee(e5, t3, i3, n3) {
    X(e5), G2(e5, i3), G2(e5, ~i3), r2.arraySet(e5.pending_buf, e5.window, t3, i3, e5.pending), e5.pending += i3;
  }
  function te(e5, t3, i3, r3) {
    var n3 = 2 * t3, a3 = 2 * i3;
    return e5[n3] < e5[a3] || e5[n3] === e5[a3] && r3[t3] <= r3[i3];
  }
  function ie(e5, t3, i3) {
    for (var r3 = e5.heap[i3], n3 = i3 << 1; n3 <= e5.heap_len && (n3 < e5.heap_len && te(t3, e5.heap[n3 + 1], e5.heap[n3], e5.depth) && n3++, !te(t3, r3, e5.heap[n3], e5.depth)); ) e5.heap[i3] = e5.heap[n3], i3 = n3, n3 <<= 1;
    e5.heap[i3] = r3;
  }
  function re(e5, t3, i3) {
    var r3, n3, a3, o3, s3 = 0;
    if (0 !== e5.last_lit) do {
      r3 = e5.pending_buf[e5.d_buf + 2 * s3] << 8 | e5.pending_buf[e5.d_buf + 2 * s3 + 1], n3 = e5.pending_buf[e5.l_buf + s3], s3++, 0 === r3 ? Q(e5, n3, t3) : (Q(e5, (a3 = F[n3]) + m + 1, t3), 0 !== (o3 = I[a3]) && H(e5, n3 -= N2[a3], o3), Q(e5, a3 = j(--r3), i3), 0 !== (o3 = M2[a3]) && H(e5, r3 -= L2[a3], o3));
    } while (s3 < e5.last_lit);
    Q(e5, E2, t3);
  }
  function ne(e5, t3) {
    var i3, r3, n3, a3 = t3.dyn_tree, o3 = t3.stat_desc.static_tree, s3 = t3.stat_desc.has_stree, l3 = t3.stat_desc.elems, u3 = -1;
    for (e5.heap_len = 0, e5.heap_max = y2, i3 = 0; i3 < l3; i3++) 0 !== a3[2 * i3] ? (e5.heap[++e5.heap_len] = u3 = i3, e5.depth[i3] = 0) : a3[2 * i3 + 1] = 0;
    for (; e5.heap_len < 2; ) a3[2 * (n3 = e5.heap[++e5.heap_len] = u3 < 2 ? ++u3 : 0)] = 1, e5.depth[n3] = 0, e5.opt_len--, s3 && (e5.static_len -= o3[2 * n3 + 1]);
    for (t3.max_code = u3, i3 = e5.heap_len >> 1; i3 >= 1; i3--) ie(e5, a3, i3);
    n3 = l3;
    do {
      i3 = e5.heap[1], e5.heap[1] = e5.heap[e5.heap_len--], ie(e5, a3, 1), r3 = e5.heap[1], e5.heap[--e5.heap_max] = i3, e5.heap[--e5.heap_max] = r3, a3[2 * n3] = a3[2 * i3] + a3[2 * r3], e5.depth[n3] = (e5.depth[i3] >= e5.depth[r3] ? e5.depth[i3] : e5.depth[r3]) + 1, a3[2 * i3 + 1] = a3[2 * r3 + 1] = n3, e5.heap[1] = n3++, ie(e5, a3, 1);
    } while (e5.heap_len >= 2);
    e5.heap[--e5.heap_max] = e5.heap[1], V(e5, t3), Y2(a3, u3, e5.bl_count);
  }
  function ae(e5, t3, i3) {
    var r3, n3, a3 = -1, o3 = t3[1], s3 = 0, l3 = 7, u3 = 4;
    for (0 === o3 && (l3 = 138, u3 = 3), t3[2 * (i3 + 1) + 1] = 65535, r3 = 0; r3 <= i3; r3++) n3 = o3, o3 = t3[2 * (r3 + 1) + 1], ++s3 < l3 && n3 === o3 || (s3 < u3 ? e5.bl_tree[2 * n3] += s3 : 0 !== n3 ? (n3 !== a3 && e5.bl_tree[2 * n3]++, e5.bl_tree[2 * k2]++) : s3 <= 10 ? e5.bl_tree[2 * S2]++ : e5.bl_tree[2 * A2]++, s3 = 0, a3 = n3, 0 === o3 ? (l3 = 138, u3 = 3) : n3 === o3 ? (l3 = 6, u3 = 3) : (l3 = 7, u3 = 4));
  }
  function oe(e5, t3, i3) {
    var r3, n3, a3 = -1, o3 = t3[1], s3 = 0, l3 = 7, u3 = 4;
    for (0 === o3 && (l3 = 138, u3 = 3), r3 = 0; r3 <= i3; r3++) if (n3 = o3, o3 = t3[2 * (r3 + 1) + 1], !(++s3 < l3 && n3 === o3)) {
      if (s3 < u3) do {
        Q(e5, n3, e5.bl_tree);
      } while (0 != --s3);
      else 0 !== n3 ? (n3 !== a3 && (Q(e5, n3, e5.bl_tree), s3--), Q(e5, k2, e5.bl_tree), H(e5, s3 - 3, 2)) : s3 <= 10 ? (Q(e5, S2, e5.bl_tree), H(e5, s3 - 3, 3)) : (Q(e5, A2, e5.bl_tree), H(e5, s3 - 11, 7));
      s3 = 0, a3 = n3, 0 === o3 ? (l3 = 138, u3 = 3) : n3 === o3 ? (l3 = 6, u3 = 3) : (l3 = 7, u3 = 4);
    }
  }
  function se(e5) {
    var t3;
    for (ae(e5, e5.dyn_ltree, e5.l_desc.max_code), ae(e5, e5.dyn_dtree, e5.d_desc.max_code), ne(e5, e5.bl_desc), t3 = b2 - 1; t3 >= 3 && 0 === e5.bl_tree[2 * P[t3] + 1]; t3--) ;
    return e5.opt_len += 3 * (t3 + 1) + 5 + 5 + 4, t3;
  }
  function le(e5, t3, i3, r3) {
    var n3;
    for (H(e5, t3 - 257, 5), H(e5, i3 - 1, 5), H(e5, r3 - 4, 4), n3 = 0; n3 < r3; n3++) H(e5, e5.bl_tree[2 * P[n3] + 1], 3);
    oe(e5, e5.dyn_ltree, t3 - 1), oe(e5, e5.dyn_dtree, i3 - 1);
  }
  function ue(e5) {
    var t3, i3 = 4093624447;
    for (t3 = 0; t3 <= 31; t3++, i3 >>>= 1) if (1 & i3 && 0 !== e5.dyn_ltree[2 * t3]) return a2;
    if (0 !== e5.dyn_ltree[18] || 0 !== e5.dyn_ltree[20] || 0 !== e5.dyn_ltree[26]) return o2;
    for (t3 = 32; t3 < m; t3++) if (0 !== e5.dyn_ltree[2 * t3]) return o2;
    return a2;
  }
  l2(L2);
  var he = false;
  function ce(e5) {
    he || (K(), he = true), e5.l_desc = new Z(e5.dyn_ltree, O2), e5.d_desc = new Z(e5.dyn_dtree, D), e5.bl_desc = new Z(e5.bl_tree, $), e5.bi_buf = 0, e5.bi_valid = 0, J(e5);
  }
  function fe(e5, t3, i3, r3) {
    H(e5, (u2 << 1) + (r3 ? 1 : 0), 3), ee(e5, t3, i3);
  }
  function de(e5) {
    H(e5, h2 << 1, 3), Q(e5, E2, C2), q(e5);
  }
  function pe(e5, t3, i3, r3) {
    var a3, o3, l3 = 0;
    e5.level > 0 ? (e5.strm.data_type === s2 && (e5.strm.data_type = ue(e5)), ne(e5, e5.l_desc), ne(e5, e5.d_desc), l3 = se(e5), a3 = e5.opt_len + 3 + 7 >>> 3, (o3 = e5.static_len + 3 + 7 >>> 3) <= a3 && (a3 = o3)) : a3 = o3 = i3 + 5, i3 + 4 <= a3 && -1 !== t3 ? fe(e5, t3, i3, r3) : e5.strategy === n2 || o3 === a3 ? (H(e5, (h2 << 1) + (r3 ? 1 : 0), 3), re(e5, C2, R2)) : (H(e5, (c2 << 1) + (r3 ? 1 : 0), 3), le(e5, e5.l_desc.max_code + 1, e5.d_desc.max_code + 1, l3 + 1), re(e5, e5.dyn_ltree, e5.dyn_dtree)), J(e5), r3 && X(e5);
  }
  function me(e5, t3, i3) {
    return e5.pending_buf[e5.d_buf + 2 * e5.last_lit] = t3 >>> 8 & 255, e5.pending_buf[e5.d_buf + 2 * e5.last_lit + 1] = 255 & t3, e5.pending_buf[e5.l_buf + e5.last_lit] = 255 & i3, e5.last_lit++, 0 === t3 ? e5.dyn_ltree[2 * i3]++ : (e5.matches++, t3--, e5.dyn_ltree[2 * (F[i3] + m + 1)]++, e5.dyn_dtree[2 * j(t3)]++), e5.last_lit === e5.lit_bufsize - 1;
  }
  i2._tr_init = ce, i2._tr_stored_block = fe, i2._tr_flush_block = pe, i2._tr_tally = me, i2._tr_align = de;
}, { "../utils/common": 52 }], 62: [function(e4, t2, i2) {
  function r2() {
    this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
  }
  t2.exports = r2;
}, {}], 63: [function(e4, t2, i2) {
  var r2, n2, a2 = t2.exports = {};
  function o2() {
    throw new Error("setTimeout has not been defined");
  }
  function s2() {
    throw new Error("clearTimeout has not been defined");
  }
  function l2(e5) {
    if (r2 === setTimeout) return setTimeout(e5, 0);
    if ((r2 === o2 || !r2) && setTimeout) return r2 = setTimeout, setTimeout(e5, 0);
    try {
      return r2(e5, 0);
    } catch (t3) {
      try {
        return r2.call(null, e5, 0);
      } catch (t4) {
        return r2.call(this, e5, 0);
      }
    }
  }
  function u2(e5) {
    if (n2 === clearTimeout) return clearTimeout(e5);
    if ((n2 === s2 || !n2) && clearTimeout) return n2 = clearTimeout, clearTimeout(e5);
    try {
      return n2(e5);
    } catch (t3) {
      try {
        return n2.call(null, e5);
      } catch (t4) {
        return n2.call(this, e5);
      }
    }
  }
  !function() {
    try {
      r2 = "function" == typeof setTimeout ? setTimeout : o2;
    } catch (e5) {
      r2 = o2;
    }
    try {
      n2 = "function" == typeof clearTimeout ? clearTimeout : s2;
    } catch (e5) {
      n2 = s2;
    }
  }();
  var h2, c2 = [], f2 = false, d = -1;
  function p2() {
    f2 && h2 && (f2 = false, h2.length ? c2 = h2.concat(c2) : d = -1, c2.length && m());
  }
  function m() {
    if (!f2) {
      var e5 = l2(p2);
      f2 = true;
      for (var t3 = c2.length; t3; ) {
        for (h2 = c2, c2 = []; ++d < t3; ) h2 && h2[d].run();
        d = -1, t3 = c2.length;
      }
      h2 = null, f2 = false, u2(e5);
    }
  }
  function _2(e5, t3) {
    this.fun = e5, this.array = t3;
  }
  function g() {
  }
  a2.nextTick = function(e5) {
    var t3 = new Array(arguments.length - 1);
    if (arguments.length > 1) for (var i3 = 1; i3 < arguments.length; i3++) t3[i3 - 1] = arguments[i3];
    c2.push(new _2(e5, t3)), 1 !== c2.length || f2 || l2(m);
  }, _2.prototype.run = function() {
    this.fun.apply(null, this.array);
  }, a2.title = "browser", a2.browser = true, a2.env = {}, a2.argv = [], a2.version = "", a2.versions = {}, a2.on = g, a2.addListener = g, a2.once = g, a2.off = g, a2.removeListener = g, a2.removeAllListeners = g, a2.emit = g, a2.prependListener = g, a2.prependOnceListener = g, a2.listeners = function(e5) {
    return [];
  }, a2.binding = function(e5) {
    throw new Error("process.binding is not supported");
  }, a2.cwd = function() {
    return "/";
  }, a2.chdir = function(e5) {
    throw new Error("process.chdir is not supported");
  }, a2.umask = function() {
    return 0;
  };
}, {}], 64: [function(e4, t2, i2) {
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  var r2 = e4("buffer"), n2 = r2.Buffer;
  function a2(e5, t3) {
    for (var i3 in e5) t3[i3] = e5[i3];
  }
  function o2(e5, t3, i3) {
    return n2(e5, t3, i3);
  }
  n2.from && n2.alloc && n2.allocUnsafe && n2.allocUnsafeSlow ? t2.exports = r2 : (a2(r2, i2), i2.Buffer = o2), o2.prototype = Object.create(n2.prototype), a2(n2, o2), o2.from = function(e5, t3, i3) {
    if ("number" == typeof e5) throw new TypeError("Argument must not be a number");
    return n2(e5, t3, i3);
  }, o2.alloc = function(e5, t3, i3) {
    if ("number" != typeof e5) throw new TypeError("Argument must be a number");
    var r3 = n2(e5);
    return void 0 !== t3 ? "string" == typeof i3 ? r3.fill(t3, i3) : r3.fill(t3) : r3.fill(0), r3;
  }, o2.allocUnsafe = function(e5) {
    if ("number" != typeof e5) throw new TypeError("Argument must be a number");
    return n2(e5);
  }, o2.allocUnsafeSlow = function(e5) {
    if ("number" != typeof e5) throw new TypeError("Argument must be a number");
    return r2.SlowBuffer(e5);
  };
}, { buffer: 32 }], 65: [function(e4, t2, i2) {
  t2.exports = n2;
  var r2 = e4("events").EventEmitter;
  function n2() {
    r2.call(this);
  }
  e4("inherits")(n2, r2), n2.Readable = e4("readable-stream/lib/_stream_readable.js"), n2.Writable = e4("readable-stream/lib/_stream_writable.js"), n2.Duplex = e4("readable-stream/lib/_stream_duplex.js"), n2.Transform = e4("readable-stream/lib/_stream_transform.js"), n2.PassThrough = e4("readable-stream/lib/_stream_passthrough.js"), n2.finished = e4("readable-stream/lib/internal/streams/end-of-stream.js"), n2.pipeline = e4("readable-stream/lib/internal/streams/pipeline.js"), n2.Stream = n2, n2.prototype.pipe = function(e5, t3) {
    var i3 = this;
    function n3(t4) {
      e5.writable && false === e5.write(t4) && i3.pause && i3.pause();
    }
    function a2() {
      i3.readable && i3.resume && i3.resume();
    }
    i3.on("data", n3), e5.on("drain", a2), e5._isStdio || t3 && false === t3.end || (i3.on("end", s2), i3.on("close", l2));
    var o2 = false;
    function s2() {
      o2 || (o2 = true, e5.end());
    }
    function l2() {
      o2 || (o2 = true, "function" == typeof e5.destroy && e5.destroy());
    }
    function u2(e6) {
      if (h2(), 0 === r2.listenerCount(this, "error")) throw e6;
    }
    function h2() {
      i3.removeListener("data", n3), e5.removeListener("drain", a2), i3.removeListener("end", s2), i3.removeListener("close", l2), i3.removeListener("error", u2), e5.removeListener("error", u2), i3.removeListener("end", h2), i3.removeListener("close", h2), e5.removeListener("close", h2);
    }
    return i3.on("error", u2), e5.on("error", u2), i3.on("end", h2), i3.on("close", h2), e5.on("close", h2), e5.emit("pipe", i3), e5;
  };
}, { events: 35, inherits: 46, "readable-stream/lib/_stream_duplex.js": 67, "readable-stream/lib/_stream_passthrough.js": 68, "readable-stream/lib/_stream_readable.js": 69, "readable-stream/lib/_stream_transform.js": 70, "readable-stream/lib/_stream_writable.js": 71, "readable-stream/lib/internal/streams/end-of-stream.js": 75, "readable-stream/lib/internal/streams/pipeline.js": 77 }], 66: [function(e4, t2, i2) {
  function r2(e5, t3) {
    e5.prototype = Object.create(t3.prototype), e5.prototype.constructor = e5, e5.__proto__ = t3;
  }
  var n2 = {};
  function a2(e5, t3, i3) {
    function a3(e6, i4, r3) {
      return "string" == typeof t3 ? t3 : t3(e6, i4, r3);
    }
    i3 || (i3 = Error);
    var o3 = function(e6) {
      function t4(t5, i4, r3) {
        return e6.call(this, a3(t5, i4, r3)) || this;
      }
      return r2(t4, e6), t4;
    }(i3);
    o3.prototype.name = i3.name, o3.prototype.code = e5, n2[e5] = o3;
  }
  function o2(e5, t3) {
    if (Array.isArray(e5)) {
      var i3 = e5.length;
      return e5 = e5.map(function(e6) {
        return String(e6);
      }), i3 > 2 ? "one of ".concat(t3, " ").concat(e5.slice(0, i3 - 1).join(", "), ", or ") + e5[i3 - 1] : 2 === i3 ? "one of ".concat(t3, " ").concat(e5[0], " or ").concat(e5[1]) : "of ".concat(t3, " ").concat(e5[0]);
    }
    return "of ".concat(t3, " ").concat(String(e5));
  }
  function s2(e5, t3, i3) {
    return e5.substr(0, t3.length) === t3;
  }
  function l2(e5, t3, i3) {
    return (void 0 === i3 || i3 > e5.length) && (i3 = e5.length), e5.substring(i3 - t3.length, i3) === t3;
  }
  function u2(e5, t3, i3) {
    return "number" != typeof i3 && (i3 = 0), !(i3 + t3.length > e5.length) && -1 !== e5.indexOf(t3, i3);
  }
  a2("ERR_INVALID_OPT_VALUE", function(e5, t3) {
    return 'The value "' + t3 + '" is invalid for option "' + e5 + '"';
  }, TypeError), a2("ERR_INVALID_ARG_TYPE", function(e5, t3, i3) {
    var r3, n3;
    if ("string" == typeof t3 && s2(t3, "not ") ? (r3 = "must not be", t3 = t3.replace(/^not /, "")) : r3 = "must be", l2(e5, " argument")) n3 = "The ".concat(e5, " ").concat(r3, " ").concat(o2(t3, "type"));
    else {
      var a3 = u2(e5, ".") ? "property" : "argument";
      n3 = 'The "'.concat(e5, '" ').concat(a3, " ").concat(r3, " ").concat(o2(t3, "type"));
    }
    return n3 += ". Received type ".concat(typeof i3);
  }, TypeError), a2("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"), a2("ERR_METHOD_NOT_IMPLEMENTED", function(e5) {
    return "The " + e5 + " method is not implemented";
  }), a2("ERR_STREAM_PREMATURE_CLOSE", "Premature close"), a2("ERR_STREAM_DESTROYED", function(e5) {
    return "Cannot call " + e5 + " after a stream was destroyed";
  }), a2("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"), a2("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"), a2("ERR_STREAM_WRITE_AFTER_END", "write after end"), a2("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError), a2("ERR_UNKNOWN_ENCODING", function(e5) {
    return "Unknown encoding: " + e5;
  }, TypeError), a2("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"), t2.exports.codes = n2;
}, {}], 67: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      var r2 = Object.keys || function(e5) {
        var t3 = [];
        for (var i4 in e5) t3.push(i4);
        return t3;
      };
      t2.exports = u2;
      var n2 = e4("./_stream_readable"), a2 = e4("./_stream_writable");
      e4("inherits")(u2, n2);
      for (var o2 = r2(a2.prototype), s2 = 0; s2 < o2.length; s2++) {
        var l2 = o2[s2];
        u2.prototype[l2] || (u2.prototype[l2] = a2.prototype[l2]);
      }
      function u2(e5) {
        if (!(this instanceof u2)) return new u2(e5);
        n2.call(this, e5), a2.call(this, e5), this.allowHalfOpen = true, e5 && (false === e5.readable && (this.readable = false), false === e5.writable && (this.writable = false), false === e5.allowHalfOpen && (this.allowHalfOpen = false, this.once("end", h2)));
      }
      function h2() {
        this._writableState.ended || i3.nextTick(c2, this);
      }
      function c2(e5) {
        e5.end();
      }
      Object.defineProperty(u2.prototype, "writableHighWaterMark", { enumerable: false, get: function() {
        return this._writableState.highWaterMark;
      } }), Object.defineProperty(u2.prototype, "writableBuffer", { enumerable: false, get: function() {
        return this._writableState && this._writableState.getBuffer();
      } }), Object.defineProperty(u2.prototype, "writableLength", { enumerable: false, get: function() {
        return this._writableState.length;
      } }), Object.defineProperty(u2.prototype, "destroyed", { enumerable: false, get: function() {
        return void 0 !== this._readableState && void 0 !== this._writableState && this._readableState.destroyed && this._writableState.destroyed;
      }, set: function(e5) {
        void 0 !== this._readableState && void 0 !== this._writableState && (this._readableState.destroyed = e5, this._writableState.destroyed = e5);
      } });
    }).call(this);
  }).call(this, e4("_process"));
}, { "./_stream_readable": 69, "./_stream_writable": 71, _process: 63, inherits: 46 }], 68: [function(e4, t2, i2) {
  t2.exports = n2;
  var r2 = e4("./_stream_transform");
  function n2(e5) {
    if (!(this instanceof n2)) return new n2(e5);
    r2.call(this, e5);
  }
  e4("inherits")(n2, r2), n2.prototype._transform = function(e5, t3, i3) {
    i3(null, e5);
  };
}, { "./_stream_transform": 70, inherits: 46 }], 69: [function(e4, t2, i2) {
  (function(i3, r2) {
    (function() {
      var n2;
      t2.exports = M2, M2.ReadableState = I, e4("events").EventEmitter;
      var a2 = function(e5, t3) {
        return e5.listeners(t3).length;
      }, o2 = e4("./internal/streams/stream"), s2 = e4("buffer").Buffer, l2 = r2.Uint8Array || function() {
      };
      function u2(e5) {
        return s2.from(e5);
      }
      function h2(e5) {
        return s2.isBuffer(e5) || e5 instanceof l2;
      }
      var c2, f2 = e4("util");
      c2 = f2 && f2.debuglog ? f2.debuglog("stream") : function() {
      };
      var d, p2, m, _2 = e4("./internal/streams/buffer_list"), g = e4("./internal/streams/destroy"), b2 = e4("./internal/streams/state").getHighWaterMark, y2 = e4("../errors").codes, w = y2.ERR_INVALID_ARG_TYPE, v2 = y2.ERR_STREAM_PUSH_AFTER_EOF, x2 = y2.ERR_METHOD_NOT_IMPLEMENTED, E2 = y2.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
      e4("inherits")(M2, o2);
      var k2 = g.errorOrDestroy, S2 = ["error", "close", "destroy", "pause", "resume"];
      function A2(e5, t3, i4) {
        if ("function" == typeof e5.prependListener) return e5.prependListener(t3, i4);
        e5._events && e5._events[t3] ? Array.isArray(e5._events[t3]) ? e5._events[t3].unshift(i4) : e5._events[t3] = [i4, e5._events[t3]] : e5.on(t3, i4);
      }
      function I(t3, i4, r3) {
        n2 = n2 || e4("./_stream_duplex"), t3 = t3 || {}, "boolean" != typeof r3 && (r3 = i4 instanceof n2), this.objectMode = !!t3.objectMode, r3 && (this.objectMode = this.objectMode || !!t3.readableObjectMode), this.highWaterMark = b2(this, t3, "readableHighWaterMark", r3), this.buffer = new _2(), 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 = false !== t3.emitClose, this.autoDestroy = !!t3.autoDestroy, this.destroyed = false, this.defaultEncoding = t3.defaultEncoding || "utf8", this.awaitDrain = 0, this.readingMore = false, this.decoder = null, this.encoding = null, t3.encoding && (d || (d = e4("string_decoder/").StringDecoder), this.decoder = new d(t3.encoding), this.encoding = t3.encoding);
      }
      function M2(t3) {
        if (n2 = n2 || e4("./_stream_duplex"), !(this instanceof M2)) return new M2(t3);
        var i4 = this instanceof n2;
        this._readableState = new I(t3, this, i4), this.readable = true, t3 && ("function" == typeof t3.read && (this._read = t3.read), "function" == typeof t3.destroy && (this._destroy = t3.destroy)), o2.call(this);
      }
      function T2(e5, t3, i4, r3, n3) {
        c2("readableAddChunk", t3);
        var a3, o3 = e5._readableState;
        if (null === t3) o3.reading = false, F(e5, o3);
        else if (n3 || (a3 = B2(o3, t3)), a3) k2(e5, a3);
        else if (o3.objectMode || t3 && t3.length > 0) if ("string" == typeof t3 || o3.objectMode || Object.getPrototypeOf(t3) === s2.prototype || (t3 = u2(t3)), r3) o3.endEmitted ? k2(e5, new E2()) : P(e5, o3, t3, true);
        else if (o3.ended) k2(e5, new v2());
        else {
          if (o3.destroyed) return false;
          o3.reading = false, o3.decoder && !i4 ? (t3 = o3.decoder.write(t3), o3.objectMode || 0 !== t3.length ? P(e5, o3, t3, false) : D(e5, o3)) : P(e5, o3, t3, false);
        }
        else r3 || (o3.reading = false, D(e5, o3));
        return !o3.ended && (o3.length < o3.highWaterMark || 0 === o3.length);
      }
      function P(e5, t3, i4, r3) {
        t3.flowing && 0 === t3.length && !t3.sync ? (t3.awaitDrain = 0, e5.emit("data", i4)) : (t3.length += t3.objectMode ? 1 : i4.length, r3 ? t3.buffer.unshift(i4) : t3.buffer.push(i4), t3.needReadable && N2(e5)), D(e5, t3);
      }
      function B2(e5, t3) {
        var i4;
        return h2(t3) || "string" == typeof t3 || void 0 === t3 || e5.objectMode || (i4 = new w("chunk", ["string", "Buffer", "Uint8Array"], t3)), i4;
      }
      Object.defineProperty(M2.prototype, "destroyed", { enumerable: false, get: function() {
        return void 0 !== this._readableState && this._readableState.destroyed;
      }, set: function(e5) {
        this._readableState && (this._readableState.destroyed = e5);
      } }), M2.prototype.destroy = g.destroy, M2.prototype._undestroy = g.undestroy, M2.prototype._destroy = function(e5, t3) {
        t3(e5);
      }, M2.prototype.push = function(e5, t3) {
        var i4, r3 = this._readableState;
        return r3.objectMode ? i4 = true : "string" == typeof e5 && ((t3 = t3 || r3.defaultEncoding) !== r3.encoding && (e5 = s2.from(e5, t3), t3 = ""), i4 = true), T2(this, e5, t3, false, i4);
      }, M2.prototype.unshift = function(e5) {
        return T2(this, e5, null, true, false);
      }, M2.prototype.isPaused = function() {
        return false === this._readableState.flowing;
      }, M2.prototype.setEncoding = function(t3) {
        d || (d = e4("string_decoder/").StringDecoder);
        var i4 = new d(t3);
        this._readableState.decoder = i4, this._readableState.encoding = this._readableState.decoder.encoding;
        for (var r3 = this._readableState.buffer.head, n3 = ""; null !== r3; ) n3 += i4.write(r3.data), r3 = r3.next;
        return this._readableState.buffer.clear(), "" !== n3 && this._readableState.buffer.push(n3), this._readableState.length = n3.length, this;
      };
      var C2 = 1073741824;
      function R2(e5) {
        return e5 >= C2 ? e5 = C2 : (e5--, e5 |= e5 >>> 1, e5 |= e5 >>> 2, e5 |= e5 >>> 4, e5 |= e5 >>> 8, e5 |= e5 >>> 16, e5++), e5;
      }
      function z2(e5, t3) {
        return e5 <= 0 || 0 === t3.length && t3.ended ? 0 : t3.objectMode ? 1 : e5 != e5 ? t3.flowing && t3.length ? t3.buffer.head.data.length : t3.length : (e5 > t3.highWaterMark && (t3.highWaterMark = R2(e5)), e5 <= t3.length ? e5 : t3.ended ? t3.length : (t3.needReadable = true, 0));
      }
      function F(e5, t3) {
        if (c2("onEofChunk"), !t3.ended) {
          if (t3.decoder) {
            var i4 = t3.decoder.end();
            i4 && i4.length && (t3.buffer.push(i4), t3.length += t3.objectMode ? 1 : i4.length);
          }
          t3.ended = true, t3.sync ? N2(e5) : (t3.needReadable = false, t3.emittedReadable || (t3.emittedReadable = true, O2(e5)));
        }
      }
      function N2(e5) {
        var t3 = e5._readableState;
        c2("emitReadable", t3.needReadable, t3.emittedReadable), t3.needReadable = false, t3.emittedReadable || (c2("emitReadable", t3.flowing), t3.emittedReadable = true, i3.nextTick(O2, e5));
      }
      function O2(e5) {
        var t3 = e5._readableState;
        c2("emitReadable_", t3.destroyed, t3.length, t3.ended), t3.destroyed || !t3.length && !t3.ended || (e5.emit("readable"), t3.emittedReadable = false), t3.needReadable = !t3.flowing && !t3.ended && t3.length <= t3.highWaterMark, H(e5);
      }
      function D(e5, t3) {
        t3.readingMore || (t3.readingMore = true, i3.nextTick($, e5, t3));
      }
      function $(e5, t3) {
        for (; !t3.reading && !t3.ended && (t3.length < t3.highWaterMark || t3.flowing && 0 === t3.length); ) {
          var i4 = t3.length;
          if (c2("maybeReadMore read 0"), e5.read(0), i4 === t3.length) break;
        }
        t3.readingMore = false;
      }
      function L2(e5) {
        return function() {
          var t3 = e5._readableState;
          c2("pipeOnDrain", t3.awaitDrain), t3.awaitDrain && t3.awaitDrain--, 0 === t3.awaitDrain && a2(e5, "data") && (t3.flowing = true, H(e5));
        };
      }
      function U(e5) {
        var t3 = e5._readableState;
        t3.readableListening = e5.listenerCount("readable") > 0, t3.resumeScheduled && !t3.paused ? t3.flowing = true : e5.listenerCount("data") > 0 && e5.resume();
      }
      function Z(e5) {
        c2("readable nexttick read 0"), e5.read(0);
      }
      function j(e5, t3) {
        t3.resumeScheduled || (t3.resumeScheduled = true, i3.nextTick(G2, e5, t3));
      }
      function G2(e5, t3) {
        c2("resume", t3.reading), t3.reading || e5.read(0), t3.resumeScheduled = false, e5.emit("resume"), H(e5), t3.flowing && !t3.reading && e5.read(0);
      }
      function H(e5) {
        var t3 = e5._readableState;
        for (c2("flow", t3.flowing); t3.flowing && null !== e5.read(); ) ;
      }
      function Q(e5, t3) {
        return 0 === t3.length ? null : (t3.objectMode ? i4 = t3.buffer.shift() : !e5 || e5 >= t3.length ? (i4 = t3.decoder ? t3.buffer.join("") : 1 === t3.buffer.length ? t3.buffer.first() : t3.buffer.concat(t3.length), t3.buffer.clear()) : i4 = t3.buffer.consume(e5, t3.decoder), i4);
        var i4;
      }
      function W(e5) {
        var t3 = e5._readableState;
        c2("endReadable", t3.endEmitted), t3.endEmitted || (t3.ended = true, i3.nextTick(q, t3, e5));
      }
      function q(e5, t3) {
        if (c2("endReadableNT", e5.endEmitted, e5.length), !e5.endEmitted && 0 === e5.length && (e5.endEmitted = true, t3.readable = false, t3.emit("end"), e5.autoDestroy)) {
          var i4 = t3._writableState;
          (!i4 || i4.autoDestroy && i4.finished) && t3.destroy();
        }
      }
      function V(e5, t3) {
        for (var i4 = 0, r3 = e5.length; i4 < r3; i4++) if (e5[i4] === t3) return i4;
        return -1;
      }
      M2.prototype.read = function(e5) {
        c2("read", e5), e5 = parseInt(e5, 10);
        var t3 = this._readableState, i4 = e5;
        if (0 !== e5 && (t3.emittedReadable = false), 0 === e5 && t3.needReadable && ((0 !== t3.highWaterMark ? t3.length >= t3.highWaterMark : t3.length > 0) || t3.ended)) return c2("read: emitReadable", t3.length, t3.ended), 0 === t3.length && t3.ended ? W(this) : N2(this), null;
        if (0 === (e5 = z2(e5, t3)) && t3.ended) return 0 === t3.length && W(this), null;
        var r3, n3 = t3.needReadable;
        return c2("need readable", n3), (0 === t3.length || t3.length - e5 < t3.highWaterMark) && c2("length less than watermark", n3 = true), t3.ended || t3.reading ? c2("reading or ended", n3 = false) : n3 && (c2("do read"), t3.reading = true, t3.sync = true, 0 === t3.length && (t3.needReadable = true), this._read(t3.highWaterMark), t3.sync = false, t3.reading || (e5 = z2(i4, t3))), null === (r3 = e5 > 0 ? Q(e5, t3) : null) ? (t3.needReadable = t3.length <= t3.highWaterMark, e5 = 0) : (t3.length -= e5, t3.awaitDrain = 0), 0 === t3.length && (t3.ended || (t3.needReadable = true), i4 !== e5 && t3.ended && W(this)), null !== r3 && this.emit("data", r3), r3;
      }, M2.prototype._read = function(e5) {
        k2(this, new x2("_read()"));
      }, M2.prototype.pipe = function(e5, t3) {
        var r3 = this, n3 = this._readableState;
        switch (n3.pipesCount) {
          case 0:
            n3.pipes = e5;
            break;
          case 1:
            n3.pipes = [n3.pipes, e5];
            break;
          default:
            n3.pipes.push(e5);
        }
        n3.pipesCount += 1, c2("pipe count=%d opts=%j", n3.pipesCount, t3);
        var o3 = t3 && false === t3.end || e5 === i3.stdout || e5 === i3.stderr ? g2 : l3;
        function s3(e6, t4) {
          c2("onunpipe"), e6 === r3 && t4 && false === t4.hasUnpiped && (t4.hasUnpiped = true, f3());
        }
        function l3() {
          c2("onend"), e5.end();
        }
        n3.endEmitted ? i3.nextTick(o3) : r3.once("end", o3), e5.on("unpipe", s3);
        var u3 = L2(r3);
        e5.on("drain", u3);
        var h3 = false;
        function f3() {
          c2("cleanup"), e5.removeListener("close", m2), e5.removeListener("finish", _3), e5.removeListener("drain", u3), e5.removeListener("error", p3), e5.removeListener("unpipe", s3), r3.removeListener("end", l3), r3.removeListener("end", g2), r3.removeListener("data", d2), h3 = true, !n3.awaitDrain || e5._writableState && !e5._writableState.needDrain || u3();
        }
        function d2(t4) {
          c2("ondata");
          var i4 = e5.write(t4);
          c2("dest.write", i4), false === i4 && ((1 === n3.pipesCount && n3.pipes === e5 || n3.pipesCount > 1 && -1 !== V(n3.pipes, e5)) && !h3 && (c2("false write response, pause", n3.awaitDrain), n3.awaitDrain++), r3.pause());
        }
        function p3(t4) {
          c2("onerror", t4), g2(), e5.removeListener("error", p3), 0 === a2(e5, "error") && k2(e5, t4);
        }
        function m2() {
          e5.removeListener("finish", _3), g2();
        }
        function _3() {
          c2("onfinish"), e5.removeListener("close", m2), g2();
        }
        function g2() {
          c2("unpipe"), r3.unpipe(e5);
        }
        return r3.on("data", d2), A2(e5, "error", p3), e5.once("close", m2), e5.once("finish", _3), e5.emit("pipe", r3), n3.flowing || (c2("pipe resume"), r3.resume()), e5;
      }, M2.prototype.unpipe = function(e5) {
        var t3 = this._readableState, i4 = { hasUnpiped: false };
        if (0 === t3.pipesCount) return this;
        if (1 === t3.pipesCount) return e5 && e5 !== t3.pipes || (e5 || (e5 = t3.pipes), t3.pipes = null, t3.pipesCount = 0, t3.flowing = false, e5 && e5.emit("unpipe", this, i4)), this;
        if (!e5) {
          var r3 = t3.pipes, n3 = t3.pipesCount;
          t3.pipes = null, t3.pipesCount = 0, t3.flowing = false;
          for (var a3 = 0; a3 < n3; a3++) r3[a3].emit("unpipe", this, { hasUnpiped: false });
          return this;
        }
        var o3 = V(t3.pipes, e5);
        return -1 === o3 || (t3.pipes.splice(o3, 1), t3.pipesCount -= 1, 1 === t3.pipesCount && (t3.pipes = t3.pipes[0]), e5.emit("unpipe", this, i4)), this;
      }, M2.prototype.on = function(e5, t3) {
        var r3 = o2.prototype.on.call(this, e5, t3), n3 = this._readableState;
        return "data" === e5 ? (n3.readableListening = this.listenerCount("readable") > 0, false !== n3.flowing && this.resume()) : "readable" === e5 && (n3.endEmitted || n3.readableListening || (n3.readableListening = n3.needReadable = true, n3.flowing = false, n3.emittedReadable = false, c2("on readable", n3.length, n3.reading), n3.length ? N2(this) : n3.reading || i3.nextTick(Z, this))), r3;
      }, M2.prototype.addListener = M2.prototype.on, M2.prototype.removeListener = function(e5, t3) {
        var r3 = o2.prototype.removeListener.call(this, e5, t3);
        return "readable" === e5 && i3.nextTick(U, this), r3;
      }, M2.prototype.removeAllListeners = function(e5) {
        var t3 = o2.prototype.removeAllListeners.apply(this, arguments);
        return "readable" !== e5 && void 0 !== e5 || i3.nextTick(U, this), t3;
      }, M2.prototype.resume = function() {
        var e5 = this._readableState;
        return e5.flowing || (c2("resume"), e5.flowing = !e5.readableListening, j(this, e5)), e5.paused = false, this;
      }, M2.prototype.pause = function() {
        return c2("call pause flowing=%j", this._readableState.flowing), false !== this._readableState.flowing && (c2("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState.paused = true, this;
      }, M2.prototype.wrap = function(e5) {
        var t3 = this, i4 = this._readableState, r3 = false;
        for (var n3 in e5.on("end", function() {
          if (c2("wrapped end"), i4.decoder && !i4.ended) {
            var e6 = i4.decoder.end();
            e6 && e6.length && t3.push(e6);
          }
          t3.push(null);
        }), e5.on("data", function(n4) {
          c2("wrapped data"), i4.decoder && (n4 = i4.decoder.write(n4)), i4.objectMode && null == n4 || (i4.objectMode || n4 && n4.length) && (t3.push(n4) || (r3 = true, e5.pause()));
        }), e5) void 0 === this[n3] && "function" == typeof e5[n3] && (this[n3] = /* @__PURE__ */ function(t4) {
          return function() {
            return e5[t4].apply(e5, arguments);
          };
        }(n3));
        for (var a3 = 0; a3 < S2.length; a3++) e5.on(S2[a3], this.emit.bind(this, S2[a3]));
        return this._read = function(t4) {
          c2("wrapped _read", t4), r3 && (r3 = false, e5.resume());
        }, this;
      }, "function" == typeof Symbol && (M2.prototype[Symbol.asyncIterator] = function() {
        return void 0 === p2 && (p2 = e4("./internal/streams/async_iterator")), p2(this);
      }), Object.defineProperty(M2.prototype, "readableHighWaterMark", { enumerable: false, get: function() {
        return this._readableState.highWaterMark;
      } }), Object.defineProperty(M2.prototype, "readableBuffer", { enumerable: false, get: function() {
        return this._readableState && this._readableState.buffer;
      } }), Object.defineProperty(M2.prototype, "readableFlowing", { enumerable: false, get: function() {
        return this._readableState.flowing;
      }, set: function(e5) {
        this._readableState && (this._readableState.flowing = e5);
      } }), M2._fromList = Q, Object.defineProperty(M2.prototype, "readableLength", { enumerable: false, get: function() {
        return this._readableState.length;
      } }), "function" == typeof Symbol && (M2.from = function(t3, i4) {
        return void 0 === m && (m = e4("./internal/streams/from")), m(M2, t3, i4);
      });
    }).call(this);
  }).call(this, e4("_process"), void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "../errors": 66, "./_stream_duplex": 67, "./internal/streams/async_iterator": 72, "./internal/streams/buffer_list": 73, "./internal/streams/destroy": 74, "./internal/streams/from": 76, "./internal/streams/state": 78, "./internal/streams/stream": 79, _process: 63, buffer: 32, events: 35, inherits: 46, "string_decoder/": 80, util: 29 }], 70: [function(e4, t2, i2) {
  t2.exports = h2;
  var r2 = e4("../errors").codes, n2 = r2.ERR_METHOD_NOT_IMPLEMENTED, a2 = r2.ERR_MULTIPLE_CALLBACK, o2 = r2.ERR_TRANSFORM_ALREADY_TRANSFORMING, s2 = r2.ERR_TRANSFORM_WITH_LENGTH_0, l2 = e4("./_stream_duplex");
  function u2(e5, t3) {
    var i3 = this._transformState;
    i3.transforming = false;
    var r3 = i3.writecb;
    if (null === r3) return this.emit("error", new a2());
    i3.writechunk = null, i3.writecb = null, null != t3 && this.push(t3), r3(e5);
    var n3 = this._readableState;
    n3.reading = false, (n3.needReadable || n3.length < n3.highWaterMark) && this._read(n3.highWaterMark);
  }
  function h2(e5) {
    if (!(this instanceof h2)) return new h2(e5);
    l2.call(this, e5), this._transformState = { afterTransform: u2.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }, this._readableState.needReadable = true, this._readableState.sync = false, e5 && ("function" == typeof e5.transform && (this._transform = e5.transform), "function" == typeof e5.flush && (this._flush = e5.flush)), this.on("prefinish", c2);
  }
  function c2() {
    var e5 = this;
    "function" != typeof this._flush || this._readableState.destroyed ? f2(this, null, null) : this._flush(function(t3, i3) {
      f2(e5, t3, i3);
    });
  }
  function f2(e5, t3, i3) {
    if (t3) return e5.emit("error", t3);
    if (null != i3 && e5.push(i3), e5._writableState.length) throw new s2();
    if (e5._transformState.transforming) throw new o2();
    return e5.push(null);
  }
  e4("inherits")(h2, l2), h2.prototype.push = function(e5, t3) {
    return this._transformState.needTransform = false, l2.prototype.push.call(this, e5, t3);
  }, h2.prototype._transform = function(e5, t3, i3) {
    i3(new n2("_transform()"));
  }, h2.prototype._write = function(e5, t3, i3) {
    var r3 = this._transformState;
    if (r3.writecb = i3, r3.writechunk = e5, r3.writeencoding = t3, !r3.transforming) {
      var n3 = this._readableState;
      (r3.needTransform || n3.needReadable || n3.length < n3.highWaterMark) && this._read(n3.highWaterMark);
    }
  }, h2.prototype._read = function(e5) {
    var t3 = this._transformState;
    null === t3.writechunk || t3.transforming ? t3.needTransform = true : (t3.transforming = true, this._transform(t3.writechunk, t3.writeencoding, t3.afterTransform));
  }, h2.prototype._destroy = function(e5, t3) {
    l2.prototype._destroy.call(this, e5, function(e6) {
      t3(e6);
    });
  };
}, { "../errors": 66, "./_stream_duplex": 67, inherits: 46 }], 71: [function(e4, t2, i2) {
  (function(i3, r2) {
    (function() {
      function n2(e5) {
        var t3 = this;
        this.next = null, this.entry = null, this.finish = function() {
          G2(t3, e5);
        };
      }
      var a2;
      t2.exports = I, I.WritableState = A2;
      var o2 = { deprecate: e4("util-deprecate") }, s2 = e4("./internal/streams/stream"), l2 = e4("buffer").Buffer, u2 = r2.Uint8Array || function() {
      };
      function h2(e5) {
        return l2.from(e5);
      }
      function c2(e5) {
        return l2.isBuffer(e5) || e5 instanceof u2;
      }
      var f2, d = e4("./internal/streams/destroy"), p2 = e4("./internal/streams/state").getHighWaterMark, m = e4("../errors").codes, _2 = m.ERR_INVALID_ARG_TYPE, g = m.ERR_METHOD_NOT_IMPLEMENTED, b2 = m.ERR_MULTIPLE_CALLBACK, y2 = m.ERR_STREAM_CANNOT_PIPE, w = m.ERR_STREAM_DESTROYED, v2 = m.ERR_STREAM_NULL_VALUES, x2 = m.ERR_STREAM_WRITE_AFTER_END, E2 = m.ERR_UNKNOWN_ENCODING, k2 = d.errorOrDestroy;
      function S2() {
      }
      function A2(t3, i4, r3) {
        a2 = a2 || e4("./_stream_duplex"), t3 = t3 || {}, "boolean" != typeof r3 && (r3 = i4 instanceof a2), this.objectMode = !!t3.objectMode, r3 && (this.objectMode = this.objectMode || !!t3.writableObjectMode), this.highWaterMark = p2(this, t3, "writableHighWaterMark", r3), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false;
        var o3 = false === t3.decodeStrings;
        this.decodeStrings = !o3, this.defaultEncoding = t3.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = function(e5) {
          F(i4, e5);
        }, this.writecb = null, this.writelen = 0, this.bufferedRequest = null, this.lastBufferedRequest = null, this.pendingcb = 0, this.prefinished = false, this.errorEmitted = false, this.emitClose = false !== t3.emitClose, this.autoDestroy = !!t3.autoDestroy, this.bufferedRequestCount = 0, this.corkedRequestsFree = new n2(this);
      }
      function I(t3) {
        var i4 = this instanceof (a2 = a2 || e4("./_stream_duplex"));
        if (!i4 && !f2.call(I, this)) return new I(t3);
        this._writableState = new A2(t3, this, i4), this.writable = true, t3 && ("function" == typeof t3.write && (this._write = t3.write), "function" == typeof t3.writev && (this._writev = t3.writev), "function" == typeof t3.destroy && (this._destroy = t3.destroy), "function" == typeof t3.final && (this._final = t3.final)), s2.call(this);
      }
      function M2(e5, t3) {
        var r3 = new x2();
        k2(e5, r3), i3.nextTick(t3, r3);
      }
      function T2(e5, t3, r3, n3) {
        var a3;
        return null === r3 ? a3 = new v2() : "string" == typeof r3 || t3.objectMode || (a3 = new _2("chunk", ["string", "Buffer"], r3)), !a3 || (k2(e5, a3), i3.nextTick(n3, a3), false);
      }
      function P(e5, t3, i4) {
        return e5.objectMode || false === e5.decodeStrings || "string" != typeof t3 || (t3 = l2.from(t3, i4)), t3;
      }
      function B2(e5, t3, i4, r3, n3, a3) {
        if (!i4) {
          var o3 = P(t3, r3, n3);
          r3 !== o3 && (i4 = true, n3 = "buffer", r3 = o3);
        }
        var s3 = t3.objectMode ? 1 : r3.length;
        t3.length += s3;
        var l3 = t3.length < t3.highWaterMark;
        if (l3 || (t3.needDrain = true), t3.writing || t3.corked) {
          var u3 = t3.lastBufferedRequest;
          t3.lastBufferedRequest = { chunk: r3, encoding: n3, isBuf: i4, callback: a3, next: null }, u3 ? u3.next = t3.lastBufferedRequest : t3.bufferedRequest = t3.lastBufferedRequest, t3.bufferedRequestCount += 1;
        } else C2(e5, t3, false, s3, r3, n3, a3);
        return l3;
      }
      function C2(e5, t3, i4, r3, n3, a3, o3) {
        t3.writelen = r3, t3.writecb = o3, t3.writing = true, t3.sync = true, t3.destroyed ? t3.onwrite(new w("write")) : i4 ? e5._writev(n3, t3.onwrite) : e5._write(n3, a3, t3.onwrite), t3.sync = false;
      }
      function R2(e5, t3, r3, n3, a3) {
        --t3.pendingcb, r3 ? (i3.nextTick(a3, n3), i3.nextTick(Z, e5, t3), e5._writableState.errorEmitted = true, k2(e5, n3)) : (a3(n3), e5._writableState.errorEmitted = true, k2(e5, n3), Z(e5, t3));
      }
      function z2(e5) {
        e5.writing = false, e5.writecb = null, e5.length -= e5.writelen, e5.writelen = 0;
      }
      function F(e5, t3) {
        var r3 = e5._writableState, n3 = r3.sync, a3 = r3.writecb;
        if ("function" != typeof a3) throw new b2();
        if (z2(r3), t3) R2(e5, r3, n3, t3, a3);
        else {
          var o3 = $(r3) || e5.destroyed;
          o3 || r3.corked || r3.bufferProcessing || !r3.bufferedRequest || D(e5, r3), n3 ? i3.nextTick(N2, e5, r3, o3, a3) : N2(e5, r3, o3, a3);
        }
      }
      function N2(e5, t3, i4, r3) {
        i4 || O2(e5, t3), t3.pendingcb--, r3(), Z(e5, t3);
      }
      function O2(e5, t3) {
        0 === t3.length && t3.needDrain && (t3.needDrain = false, e5.emit("drain"));
      }
      function D(e5, t3) {
        t3.bufferProcessing = true;
        var i4 = t3.bufferedRequest;
        if (e5._writev && i4 && i4.next) {
          var r3 = t3.bufferedRequestCount, a3 = new Array(r3), o3 = t3.corkedRequestsFree;
          o3.entry = i4;
          for (var s3 = 0, l3 = true; i4; ) a3[s3] = i4, i4.isBuf || (l3 = false), i4 = i4.next, s3 += 1;
          a3.allBuffers = l3, C2(e5, t3, true, t3.length, a3, "", o3.finish), t3.pendingcb++, t3.lastBufferedRequest = null, o3.next ? (t3.corkedRequestsFree = o3.next, o3.next = null) : t3.corkedRequestsFree = new n2(t3), t3.bufferedRequestCount = 0;
        } else {
          for (; i4; ) {
            var u3 = i4.chunk, h3 = i4.encoding, c3 = i4.callback;
            if (C2(e5, t3, false, t3.objectMode ? 1 : u3.length, u3, h3, c3), i4 = i4.next, t3.bufferedRequestCount--, t3.writing) break;
          }
          null === i4 && (t3.lastBufferedRequest = null);
        }
        t3.bufferedRequest = i4, t3.bufferProcessing = false;
      }
      function $(e5) {
        return e5.ending && 0 === e5.length && null === e5.bufferedRequest && !e5.finished && !e5.writing;
      }
      function L2(e5, t3) {
        e5._final(function(i4) {
          t3.pendingcb--, i4 && k2(e5, i4), t3.prefinished = true, e5.emit("prefinish"), Z(e5, t3);
        });
      }
      function U(e5, t3) {
        t3.prefinished || t3.finalCalled || ("function" != typeof e5._final || t3.destroyed ? (t3.prefinished = true, e5.emit("prefinish")) : (t3.pendingcb++, t3.finalCalled = true, i3.nextTick(L2, e5, t3)));
      }
      function Z(e5, t3) {
        var i4 = $(t3);
        if (i4 && (U(e5, t3), 0 === t3.pendingcb && (t3.finished = true, e5.emit("finish"), t3.autoDestroy))) {
          var r3 = e5._readableState;
          (!r3 || r3.autoDestroy && r3.endEmitted) && e5.destroy();
        }
        return i4;
      }
      function j(e5, t3, r3) {
        t3.ending = true, Z(e5, t3), r3 && (t3.finished ? i3.nextTick(r3) : e5.once("finish", r3)), t3.ended = true, e5.writable = false;
      }
      function G2(e5, t3, i4) {
        var r3 = e5.entry;
        for (e5.entry = null; r3; ) {
          var n3 = r3.callback;
          t3.pendingcb--, n3(i4), r3 = r3.next;
        }
        t3.corkedRequestsFree.next = e5;
      }
      e4("inherits")(I, s2), A2.prototype.getBuffer = function() {
        for (var e5 = this.bufferedRequest, t3 = []; e5; ) t3.push(e5), e5 = e5.next;
        return t3;
      }, function() {
        try {
          Object.defineProperty(A2.prototype, "buffer", { get: o2.deprecate(function() {
            return this.getBuffer();
          }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") });
        } catch (e5) {
        }
      }(), "function" == typeof Symbol && Symbol.hasInstance && "function" == typeof Function.prototype[Symbol.hasInstance] ? (f2 = Function.prototype[Symbol.hasInstance], Object.defineProperty(I, Symbol.hasInstance, { value: function(e5) {
        return !!f2.call(this, e5) || this === I && e5 && e5._writableState instanceof A2;
      } })) : f2 = function(e5) {
        return e5 instanceof this;
      }, I.prototype.pipe = function() {
        k2(this, new y2());
      }, I.prototype.write = function(e5, t3, i4) {
        var r3 = this._writableState, n3 = false, a3 = !r3.objectMode && c2(e5);
        return a3 && !l2.isBuffer(e5) && (e5 = h2(e5)), "function" == typeof t3 && (i4 = t3, t3 = null), a3 ? t3 = "buffer" : t3 || (t3 = r3.defaultEncoding), "function" != typeof i4 && (i4 = S2), r3.ending ? M2(this, i4) : (a3 || T2(this, r3, e5, i4)) && (r3.pendingcb++, n3 = B2(this, r3, a3, e5, t3, i4)), n3;
      }, I.prototype.cork = function() {
        this._writableState.corked++;
      }, I.prototype.uncork = function() {
        var e5 = this._writableState;
        e5.corked && (e5.corked--, e5.writing || e5.corked || e5.bufferProcessing || !e5.bufferedRequest || D(this, e5));
      }, I.prototype.setDefaultEncoding = function(e5) {
        if ("string" == typeof e5 && (e5 = e5.toLowerCase()), !(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((e5 + "").toLowerCase()) > -1)) throw new E2(e5);
        return this._writableState.defaultEncoding = e5, this;
      }, Object.defineProperty(I.prototype, "writableBuffer", { enumerable: false, get: function() {
        return this._writableState && this._writableState.getBuffer();
      } }), Object.defineProperty(I.prototype, "writableHighWaterMark", { enumerable: false, get: function() {
        return this._writableState.highWaterMark;
      } }), I.prototype._write = function(e5, t3, i4) {
        i4(new g("_write()"));
      }, I.prototype._writev = null, I.prototype.end = function(e5, t3, i4) {
        var r3 = this._writableState;
        return "function" == typeof e5 ? (i4 = e5, e5 = null, t3 = null) : "function" == typeof t3 && (i4 = t3, t3 = null), null != e5 && this.write(e5, t3), r3.corked && (r3.corked = 1, this.uncork()), r3.ending || j(this, r3, i4), this;
      }, Object.defineProperty(I.prototype, "writableLength", { enumerable: false, get: function() {
        return this._writableState.length;
      } }), Object.defineProperty(I.prototype, "destroyed", { enumerable: false, get: function() {
        return void 0 !== this._writableState && this._writableState.destroyed;
      }, set: function(e5) {
        this._writableState && (this._writableState.destroyed = e5);
      } }), I.prototype.destroy = d.destroy, I.prototype._undestroy = d.undestroy, I.prototype._destroy = function(e5, t3) {
        t3(e5);
      };
    }).call(this);
  }).call(this, e4("_process"), void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "../errors": 66, "./_stream_duplex": 67, "./internal/streams/destroy": 74, "./internal/streams/state": 78, "./internal/streams/stream": 79, _process: 63, buffer: 32, inherits: 46, "util-deprecate": 81 }], 72: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      var r2;
      function n2(e5, t3, i4) {
        return t3 in e5 ? Object.defineProperty(e5, t3, { value: i4, enumerable: true, configurable: true, writable: true }) : e5[t3] = i4, e5;
      }
      var a2 = e4("./end-of-stream"), o2 = Symbol("lastResolve"), s2 = Symbol("lastReject"), l2 = Symbol("error"), u2 = Symbol("ended"), h2 = Symbol("lastPromise"), c2 = Symbol("handlePromise"), f2 = Symbol("stream");
      function d(e5, t3) {
        return { value: e5, done: t3 };
      }
      function p2(e5) {
        var t3 = e5[o2];
        if (null !== t3) {
          var i4 = e5[f2].read();
          null !== i4 && (e5[h2] = null, e5[o2] = null, e5[s2] = null, t3(d(i4, false)));
        }
      }
      function m(e5) {
        i3.nextTick(p2, e5);
      }
      function _2(e5, t3) {
        return function(i4, r3) {
          e5.then(function() {
            t3[u2] ? i4(d(void 0, true)) : t3[c2](i4, r3);
          }, r3);
        };
      }
      var g = Object.getPrototypeOf(function() {
      }), b2 = Object.setPrototypeOf((r2 = { get stream() {
        return this[f2];
      }, next: function() {
        var e5 = this, t3 = this[l2];
        if (null !== t3) return Promise.reject(t3);
        if (this[u2]) return Promise.resolve(d(void 0, true));
        if (this[f2].destroyed) return new Promise(function(t4, r4) {
          i3.nextTick(function() {
            e5[l2] ? r4(e5[l2]) : t4(d(void 0, true));
          });
        });
        var r3, n3 = this[h2];
        if (n3) r3 = new Promise(_2(n3, this));
        else {
          var a3 = this[f2].read();
          if (null !== a3) return Promise.resolve(d(a3, false));
          r3 = new Promise(this[c2]);
        }
        return this[h2] = r3, r3;
      } }, n2(r2, Symbol.asyncIterator, function() {
        return this;
      }), n2(r2, "return", function() {
        var e5 = this;
        return new Promise(function(t3, i4) {
          e5[f2].destroy(null, function(e6) {
            e6 ? i4(e6) : t3(d(void 0, true));
          });
        });
      }), r2), g), y2 = function(e5) {
        var t3, i4 = Object.create(b2, (n2(t3 = {}, f2, { value: e5, writable: true }), n2(t3, o2, { value: null, writable: true }), n2(t3, s2, { value: null, writable: true }), n2(t3, l2, { value: null, writable: true }), n2(t3, u2, { value: e5._readableState.endEmitted, writable: true }), n2(t3, c2, { value: function(e6, t4) {
          var r3 = i4[f2].read();
          r3 ? (i4[h2] = null, i4[o2] = null, i4[s2] = null, e6(d(r3, false))) : (i4[o2] = e6, i4[s2] = t4);
        }, writable: true }), t3));
        return i4[h2] = null, a2(e5, function(e6) {
          if (e6 && "ERR_STREAM_PREMATURE_CLOSE" !== e6.code) {
            var t4 = i4[s2];
            return null !== t4 && (i4[h2] = null, i4[o2] = null, i4[s2] = null, t4(e6)), void (i4[l2] = e6);
          }
          var r3 = i4[o2];
          null !== r3 && (i4[h2] = null, i4[o2] = null, i4[s2] = null, r3(d(void 0, true))), i4[u2] = true;
        }), e5.on("readable", m.bind(null, i4)), i4;
      };
      t2.exports = y2;
    }).call(this);
  }).call(this, e4("_process"));
}, { "./end-of-stream": 75, _process: 63 }], 73: [function(e4, t2, i2) {
  function r2(e5, t3) {
    var i3 = Object.keys(e5);
    if (Object.getOwnPropertySymbols) {
      var r3 = Object.getOwnPropertySymbols(e5);
      t3 && (r3 = r3.filter(function(t4) {
        return Object.getOwnPropertyDescriptor(e5, t4).enumerable;
      })), i3.push.apply(i3, r3);
    }
    return i3;
  }
  function n2(e5) {
    for (var t3 = 1; t3 < arguments.length; t3++) {
      var i3 = null != arguments[t3] ? arguments[t3] : {};
      t3 % 2 ? r2(Object(i3), true).forEach(function(t4) {
        a2(e5, t4, i3[t4]);
      }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e5, Object.getOwnPropertyDescriptors(i3)) : r2(Object(i3)).forEach(function(t4) {
        Object.defineProperty(e5, t4, Object.getOwnPropertyDescriptor(i3, t4));
      });
    }
    return e5;
  }
  function a2(e5, t3, i3) {
    return t3 in e5 ? Object.defineProperty(e5, t3, { value: i3, enumerable: true, configurable: true, writable: true }) : e5[t3] = i3, e5;
  }
  function o2(e5, t3) {
    if (!(e5 instanceof t3)) throw new TypeError("Cannot call a class as a function");
  }
  function s2(e5, t3) {
    for (var i3 = 0; i3 < t3.length; i3++) {
      var r3 = t3[i3];
      r3.enumerable = r3.enumerable || false, r3.configurable = true, "value" in r3 && (r3.writable = true), Object.defineProperty(e5, r3.key, r3);
    }
  }
  function l2(e5, t3, i3) {
    return t3 && s2(e5.prototype, t3), e5;
  }
  var u2 = e4("buffer").Buffer, h2 = e4("util").inspect, c2 = h2 && h2.custom || "inspect";
  function f2(e5, t3, i3) {
    u2.prototype.copy.call(e5, t3, i3);
  }
  t2.exports = function() {
    function e5() {
      o2(this, e5), this.head = null, this.tail = null, this.length = 0;
    }
    return l2(e5, [{ key: "push", value: function(e6) {
      var t3 = { data: e6, next: null };
      this.length > 0 ? this.tail.next = t3 : this.head = t3, this.tail = t3, ++this.length;
    } }, { key: "unshift", value: function(e6) {
      var t3 = { data: e6, next: this.head };
      0 === this.length && (this.tail = t3), this.head = t3, ++this.length;
    } }, { key: "shift", value: function() {
      if (0 !== this.length) {
        var e6 = this.head.data;
        return 1 === this.length ? this.head = this.tail = null : this.head = this.head.next, --this.length, e6;
      }
    } }, { key: "clear", value: function() {
      this.head = this.tail = null, this.length = 0;
    } }, { key: "join", value: function(e6) {
      if (0 === this.length) return "";
      for (var t3 = this.head, i3 = "" + t3.data; t3 = t3.next; ) i3 += e6 + t3.data;
      return i3;
    } }, { key: "concat", value: function(e6) {
      if (0 === this.length) return u2.alloc(0);
      for (var t3 = u2.allocUnsafe(e6 >>> 0), i3 = this.head, r3 = 0; i3; ) f2(i3.data, t3, r3), r3 += i3.data.length, i3 = i3.next;
      return t3;
    } }, { key: "consume", value: function(e6, t3) {
      var i3;
      return e6 < this.head.data.length ? (i3 = this.head.data.slice(0, e6), this.head.data = this.head.data.slice(e6)) : i3 = e6 === this.head.data.length ? this.shift() : t3 ? this._getString(e6) : this._getBuffer(e6), i3;
    } }, { key: "first", value: function() {
      return this.head.data;
    } }, { key: "_getString", value: function(e6) {
      var t3 = this.head, i3 = 1, r3 = t3.data;
      for (e6 -= r3.length; t3 = t3.next; ) {
        var n3 = t3.data, a3 = e6 > n3.length ? n3.length : e6;
        if (a3 === n3.length ? r3 += n3 : r3 += n3.slice(0, e6), 0 == (e6 -= a3)) {
          a3 === n3.length ? (++i3, t3.next ? this.head = t3.next : this.head = this.tail = null) : (this.head = t3, t3.data = n3.slice(a3));
          break;
        }
        ++i3;
      }
      return this.length -= i3, r3;
    } }, { key: "_getBuffer", value: function(e6) {
      var t3 = u2.allocUnsafe(e6), i3 = this.head, r3 = 1;
      for (i3.data.copy(t3), e6 -= i3.data.length; i3 = i3.next; ) {
        var n3 = i3.data, a3 = e6 > n3.length ? n3.length : e6;
        if (n3.copy(t3, t3.length - e6, 0, a3), 0 == (e6 -= a3)) {
          a3 === n3.length ? (++r3, i3.next ? this.head = i3.next : this.head = this.tail = null) : (this.head = i3, i3.data = n3.slice(a3));
          break;
        }
        ++r3;
      }
      return this.length -= r3, t3;
    } }, { key: c2, value: function(e6, t3) {
      return h2(this, n2({}, t3, { depth: 0, customInspect: false }));
    } }]), e5;
  }();
}, { buffer: 32, util: 29 }], 74: [function(e4, t2, i2) {
  (function(e5) {
    (function() {
      function i3(t3, i4) {
        var a3 = this, s3 = this._readableState && this._readableState.destroyed, l2 = this._writableState && this._writableState.destroyed;
        return s3 || l2 ? (i4 ? i4(t3) : t3 && (this._writableState ? this._writableState.errorEmitted || (this._writableState.errorEmitted = true, e5.nextTick(o2, this, t3)) : e5.nextTick(o2, this, t3)), this) : (this._readableState && (this._readableState.destroyed = true), this._writableState && (this._writableState.destroyed = true), this._destroy(t3 || null, function(t4) {
          !i4 && t4 ? a3._writableState ? a3._writableState.errorEmitted ? e5.nextTick(n2, a3) : (a3._writableState.errorEmitted = true, e5.nextTick(r2, a3, t4)) : e5.nextTick(r2, a3, t4) : i4 ? (e5.nextTick(n2, a3), i4(t4)) : e5.nextTick(n2, a3);
        }), this);
      }
      function r2(e6, t3) {
        o2(e6, t3), n2(e6);
      }
      function n2(e6) {
        e6._writableState && !e6._writableState.emitClose || e6._readableState && !e6._readableState.emitClose || e6.emit("close");
      }
      function a2() {
        this._readableState && (this._readableState.destroyed = false, this._readableState.reading = false, this._readableState.ended = false, this._readableState.endEmitted = false), 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 o2(e6, t3) {
        e6.emit("error", t3);
      }
      function s2(e6, t3) {
        var i4 = e6._readableState, r3 = e6._writableState;
        i4 && i4.autoDestroy || r3 && r3.autoDestroy ? e6.destroy(t3) : e6.emit("error", t3);
      }
      t2.exports = { destroy: i3, undestroy: a2, errorOrDestroy: s2 };
    }).call(this);
  }).call(this, e4("_process"));
}, { _process: 63 }], 75: [function(e4, t2, i2) {
  var r2 = e4("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;
  function n2(e5) {
    var t3 = false;
    return function() {
      if (!t3) {
        t3 = true;
        for (var i3 = arguments.length, r3 = new Array(i3), n3 = 0; n3 < i3; n3++) r3[n3] = arguments[n3];
        e5.apply(this, r3);
      }
    };
  }
  function a2() {
  }
  function o2(e5) {
    return e5.setHeader && "function" == typeof e5.abort;
  }
  function s2(e5, t3, i3) {
    if ("function" == typeof t3) return s2(e5, null, t3);
    t3 || (t3 = {}), i3 = n2(i3 || a2);
    var l2 = t3.readable || false !== t3.readable && e5.readable, u2 = t3.writable || false !== t3.writable && e5.writable, h2 = function() {
      e5.writable || f2();
    }, c2 = e5._writableState && e5._writableState.finished, f2 = function() {
      u2 = false, c2 = true, l2 || i3.call(e5);
    }, d = e5._readableState && e5._readableState.endEmitted, p2 = function() {
      l2 = false, d = true, u2 || i3.call(e5);
    }, m = function(t4) {
      i3.call(e5, t4);
    }, _2 = function() {
      var t4;
      return l2 && !d ? (e5._readableState && e5._readableState.ended || (t4 = new r2()), i3.call(e5, t4)) : u2 && !c2 ? (e5._writableState && e5._writableState.ended || (t4 = new r2()), i3.call(e5, t4)) : void 0;
    }, g = function() {
      e5.req.on("finish", f2);
    };
    return o2(e5) ? (e5.on("complete", f2), e5.on("abort", _2), e5.req ? g() : e5.on("request", g)) : u2 && !e5._writableState && (e5.on("end", h2), e5.on("close", h2)), e5.on("end", p2), e5.on("finish", f2), false !== t3.error && e5.on("error", m), e5.on("close", _2), function() {
      e5.removeListener("complete", f2), e5.removeListener("abort", _2), e5.removeListener("request", g), e5.req && e5.req.removeListener("finish", f2), e5.removeListener("end", h2), e5.removeListener("close", h2), e5.removeListener("finish", f2), e5.removeListener("end", p2), e5.removeListener("error", m), e5.removeListener("close", _2);
    };
  }
  t2.exports = s2;
}, { "../../../errors": 66 }], 76: [function(e4, t2, i2) {
  t2.exports = function() {
    throw new Error("Readable.from is not available in the browser");
  };
}, {}], 77: [function(e4, t2, i2) {
  var r2;
  function n2(e5) {
    var t3 = false;
    return function() {
      t3 || (t3 = true, e5.apply(void 0, arguments));
    };
  }
  var a2 = e4("../../../errors").codes, o2 = a2.ERR_MISSING_ARGS, s2 = a2.ERR_STREAM_DESTROYED;
  function l2(e5) {
    if (e5) throw e5;
  }
  function u2(e5) {
    return e5.setHeader && "function" == typeof e5.abort;
  }
  function h2(t3, i3, a3, o3) {
    o3 = n2(o3);
    var l3 = false;
    t3.on("close", function() {
      l3 = true;
    }), void 0 === r2 && (r2 = e4("./end-of-stream")), r2(t3, { readable: i3, writable: a3 }, function(e5) {
      if (e5) return o3(e5);
      l3 = true, o3();
    });
    var h3 = false;
    return function(e5) {
      if (!l3 && !h3) return h3 = true, u2(t3) ? t3.abort() : "function" == typeof t3.destroy ? t3.destroy() : void o3(e5 || new s2("pipe"));
    };
  }
  function c2(e5) {
    e5();
  }
  function f2(e5, t3) {
    return e5.pipe(t3);
  }
  function d(e5) {
    return e5.length ? "function" != typeof e5[e5.length - 1] ? l2 : e5.pop() : l2;
  }
  function p2() {
    for (var e5 = arguments.length, t3 = new Array(e5), i3 = 0; i3 < e5; i3++) t3[i3] = arguments[i3];
    var r3, n3 = d(t3);
    if (Array.isArray(t3[0]) && (t3 = t3[0]), t3.length < 2) throw new o2("streams");
    var a3 = t3.map(function(e6, i4) {
      var o3 = i4 < t3.length - 1;
      return h2(e6, o3, i4 > 0, function(e7) {
        r3 || (r3 = e7), e7 && a3.forEach(c2), o3 || (a3.forEach(c2), n3(r3));
      });
    });
    return t3.reduce(f2);
  }
  t2.exports = p2;
}, { "../../../errors": 66, "./end-of-stream": 75 }], 78: [function(e4, t2, i2) {
  var r2 = e4("../../../errors").codes.ERR_INVALID_OPT_VALUE;
  function n2(e5, t3, i3) {
    return null != e5.highWaterMark ? e5.highWaterMark : t3 ? e5[i3] : null;
  }
  function a2(e5, t3, i3, a3) {
    var o2 = n2(t3, a3, i3);
    if (null != o2) {
      if (!isFinite(o2) || Math.floor(o2) !== o2 || o2 < 0) throw new r2(a3 ? i3 : "highWaterMark", o2);
      return Math.floor(o2);
    }
    return e5.objectMode ? 16 : 16384;
  }
  t2.exports = { getHighWaterMark: a2 };
}, { "../../../errors": 66 }], 79: [function(e4, t2, i2) {
  t2.exports = e4("events").EventEmitter;
}, { events: 35 }], 80: [function(e4, t2, i2) {
  var r2 = e4("safe-buffer").Buffer, n2 = r2.isEncoding || function(e5) {
    switch ((e5 = "" + e5) && e5.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 a2(e5) {
    if (!e5) return "utf8";
    for (var t3; ; ) switch (e5) {
      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 e5;
      default:
        if (t3) return;
        e5 = ("" + e5).toLowerCase(), t3 = true;
    }
  }
  function o2(e5) {
    var t3 = a2(e5);
    if ("string" != typeof t3 && (r2.isEncoding === n2 || !n2(e5))) throw new Error("Unknown encoding: " + e5);
    return t3 || e5;
  }
  function s2(e5) {
    var t3;
    switch (this.encoding = o2(e5), this.encoding) {
      case "utf16le":
        this.text = p2, this.end = m, t3 = 4;
        break;
      case "utf8":
        this.fillLast = c2, t3 = 4;
        break;
      case "base64":
        this.text = _2, this.end = g, t3 = 3;
        break;
      default:
        return this.write = b2, void (this.end = y2);
    }
    this.lastNeed = 0, this.lastTotal = 0, this.lastChar = r2.allocUnsafe(t3);
  }
  function l2(e5) {
    return e5 <= 127 ? 0 : e5 >> 5 == 6 ? 2 : e5 >> 4 == 14 ? 3 : e5 >> 3 == 30 ? 4 : e5 >> 6 == 2 ? -1 : -2;
  }
  function u2(e5, t3, i3) {
    var r3 = t3.length - 1;
    if (r3 < i3) return 0;
    var n3 = l2(t3[r3]);
    return n3 >= 0 ? (n3 > 0 && (e5.lastNeed = n3 - 1), n3) : --r3 < i3 || -2 === n3 ? 0 : (n3 = l2(t3[r3])) >= 0 ? (n3 > 0 && (e5.lastNeed = n3 - 2), n3) : --r3 < i3 || -2 === n3 ? 0 : (n3 = l2(t3[r3])) >= 0 ? (n3 > 0 && (2 === n3 ? n3 = 0 : e5.lastNeed = n3 - 3), n3) : 0;
  }
  function h2(e5, t3, i3) {
    if (128 != (192 & t3[0])) return e5.lastNeed = 0, "�";
    if (e5.lastNeed > 1 && t3.length > 1) {
      if (128 != (192 & t3[1])) return e5.lastNeed = 1, "�";
      if (e5.lastNeed > 2 && t3.length > 2 && 128 != (192 & t3[2])) return e5.lastNeed = 2, "�";
    }
  }
  function c2(e5) {
    var t3 = this.lastTotal - this.lastNeed, i3 = h2(this, e5);
    return void 0 !== i3 ? i3 : this.lastNeed <= e5.length ? (e5.copy(this.lastChar, t3, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal)) : (e5.copy(this.lastChar, t3, 0, e5.length), void (this.lastNeed -= e5.length));
  }
  function f2(e5, t3) {
    var i3 = u2(this, e5, t3);
    if (!this.lastNeed) return e5.toString("utf8", t3);
    this.lastTotal = i3;
    var r3 = e5.length - (i3 - this.lastNeed);
    return e5.copy(this.lastChar, 0, r3), e5.toString("utf8", t3, r3);
  }
  function d(e5) {
    var t3 = e5 && e5.length ? this.write(e5) : "";
    return this.lastNeed ? t3 + "�" : t3;
  }
  function p2(e5, t3) {
    if ((e5.length - t3) % 2 == 0) {
      var i3 = e5.toString("utf16le", t3);
      if (i3) {
        var r3 = i3.charCodeAt(i3.length - 1);
        if (r3 >= 55296 && r3 <= 56319) return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e5[e5.length - 2], this.lastChar[1] = e5[e5.length - 1], i3.slice(0, -1);
      }
      return i3;
    }
    return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e5[e5.length - 1], e5.toString("utf16le", t3, e5.length - 1);
  }
  function m(e5) {
    var t3 = e5 && e5.length ? this.write(e5) : "";
    if (this.lastNeed) {
      var i3 = this.lastTotal - this.lastNeed;
      return t3 + this.lastChar.toString("utf16le", 0, i3);
    }
    return t3;
  }
  function _2(e5, t3) {
    var i3 = (e5.length - t3) % 3;
    return 0 === i3 ? e5.toString("base64", t3) : (this.lastNeed = 3 - i3, this.lastTotal = 3, 1 === i3 ? this.lastChar[0] = e5[e5.length - 1] : (this.lastChar[0] = e5[e5.length - 2], this.lastChar[1] = e5[e5.length - 1]), e5.toString("base64", t3, e5.length - i3));
  }
  function g(e5) {
    var t3 = e5 && e5.length ? this.write(e5) : "";
    return this.lastNeed ? t3 + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t3;
  }
  function b2(e5) {
    return e5.toString(this.encoding);
  }
  function y2(e5) {
    return e5 && e5.length ? this.write(e5) : "";
  }
  i2.StringDecoder = s2, s2.prototype.write = function(e5) {
    if (0 === e5.length) return "";
    var t3, i3;
    if (this.lastNeed) {
      if (void 0 === (t3 = this.fillLast(e5))) return "";
      i3 = this.lastNeed, this.lastNeed = 0;
    } else i3 = 0;
    return i3 < e5.length ? t3 ? t3 + this.text(e5, i3) : this.text(e5, i3) : t3 || "";
  }, s2.prototype.end = d, s2.prototype.text = f2, s2.prototype.fillLast = function(e5) {
    if (this.lastNeed <= e5.length) return e5.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal);
    e5.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e5.length), this.lastNeed -= e5.length;
  };
}, { "safe-buffer": 64 }], 81: [function(e4, t2, i2) {
  (function(e5) {
    (function() {
      function i3(e6, t3) {
        if (r2("noDeprecation")) return e6;
        var i4 = false;
        function n2() {
          if (!i4) {
            if (r2("throwDeprecation")) throw new Error(t3);
            r2("traceDeprecation") ? console.trace(t3) : console.warn(t3), i4 = true;
          }
          return e6.apply(this, arguments);
        }
        return n2;
      }
      function r2(t3) {
        try {
          if (!e5.localStorage) return false;
        } catch (e6) {
          return false;
        }
        var i4 = e5.localStorage[t3];
        return null != i4 && "true" === String(i4).toLowerCase();
      }
      t2.exports = i3;
    }).call(this);
  }).call(this, void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, {}], 82: [function(e4, t2, i2) {
  arguments[4][25][0].apply(i2, arguments);
}, { dup: 25 }], 83: [function(e4, t2, i2) {
  var r2 = e4("is-arguments"), n2 = e4("is-generator-function"), a2 = e4("which-typed-array"), o2 = e4("is-typed-array");
  function s2(e5) {
    return e5.call.bind(e5);
  }
  var l2 = "undefined" != typeof BigInt, u2 = "undefined" != typeof Symbol, h2 = s2(Object.prototype.toString), c2 = s2(Number.prototype.valueOf), f2 = s2(String.prototype.valueOf), d = s2(Boolean.prototype.valueOf);
  if (l2) var p2 = s2(BigInt.prototype.valueOf);
  if (u2) var m = s2(Symbol.prototype.valueOf);
  function _2(e5, t3) {
    if ("object" != typeof e5) return false;
    try {
      return t3(e5), true;
    } catch (e6) {
      return false;
    }
  }
  function g(e5) {
    return "undefined" != typeof Promise && e5 instanceof Promise || null !== e5 && "object" == typeof e5 && "function" == typeof e5.then && "function" == typeof e5.catch;
  }
  function b2(e5) {
    return "undefined" != typeof ArrayBuffer && ArrayBuffer.isView ? ArrayBuffer.isView(e5) : o2(e5) || U(e5);
  }
  function y2(e5) {
    return "Uint8Array" === a2(e5);
  }
  function w(e5) {
    return "Uint8ClampedArray" === a2(e5);
  }
  function v2(e5) {
    return "Uint16Array" === a2(e5);
  }
  function x2(e5) {
    return "Uint32Array" === a2(e5);
  }
  function E2(e5) {
    return "Int8Array" === a2(e5);
  }
  function k2(e5) {
    return "Int16Array" === a2(e5);
  }
  function S2(e5) {
    return "Int32Array" === a2(e5);
  }
  function A2(e5) {
    return "Float32Array" === a2(e5);
  }
  function I(e5) {
    return "Float64Array" === a2(e5);
  }
  function M2(e5) {
    return "BigInt64Array" === a2(e5);
  }
  function T2(e5) {
    return "BigUint64Array" === a2(e5);
  }
  function P(e5) {
    return "[object Map]" === h2(e5);
  }
  function B2(e5) {
    return "undefined" != typeof Map && (P.working ? P(e5) : e5 instanceof Map);
  }
  function C2(e5) {
    return "[object Set]" === h2(e5);
  }
  function R2(e5) {
    return "undefined" != typeof Set && (C2.working ? C2(e5) : e5 instanceof Set);
  }
  function z2(e5) {
    return "[object WeakMap]" === h2(e5);
  }
  function F(e5) {
    return "undefined" != typeof WeakMap && (z2.working ? z2(e5) : e5 instanceof WeakMap);
  }
  function N2(e5) {
    return "[object WeakSet]" === h2(e5);
  }
  function O2(e5) {
    return N2(e5);
  }
  function D(e5) {
    return "[object ArrayBuffer]" === h2(e5);
  }
  function $(e5) {
    return "undefined" != typeof ArrayBuffer && (D.working ? D(e5) : e5 instanceof ArrayBuffer);
  }
  function L2(e5) {
    return "[object DataView]" === h2(e5);
  }
  function U(e5) {
    return "undefined" != typeof DataView && (L2.working ? L2(e5) : e5 instanceof DataView);
  }
  i2.isArgumentsObject = r2, i2.isGeneratorFunction = n2, i2.isTypedArray = o2, i2.isPromise = g, i2.isArrayBufferView = b2, i2.isUint8Array = y2, i2.isUint8ClampedArray = w, i2.isUint16Array = v2, i2.isUint32Array = x2, i2.isInt8Array = E2, i2.isInt16Array = k2, i2.isInt32Array = S2, i2.isFloat32Array = A2, i2.isFloat64Array = I, i2.isBigInt64Array = M2, i2.isBigUint64Array = T2, P.working = "undefined" != typeof Map && P(/* @__PURE__ */ new Map()), i2.isMap = B2, C2.working = "undefined" != typeof Set && C2(/* @__PURE__ */ new Set()), i2.isSet = R2, z2.working = "undefined" != typeof WeakMap && z2(/* @__PURE__ */ new WeakMap()), i2.isWeakMap = F, N2.working = "undefined" != typeof WeakSet && N2(/* @__PURE__ */ new WeakSet()), i2.isWeakSet = O2, D.working = "undefined" != typeof ArrayBuffer && D(new ArrayBuffer()), i2.isArrayBuffer = $, L2.working = "undefined" != typeof ArrayBuffer && "undefined" != typeof DataView && L2(new DataView(new ArrayBuffer(1), 0, 1)), i2.isDataView = U;
  var Z = "undefined" != typeof SharedArrayBuffer ? SharedArrayBuffer : void 0;
  function j(e5) {
    return "[object SharedArrayBuffer]" === h2(e5);
  }
  function G2(e5) {
    return void 0 !== Z && (void 0 === j.working && (j.working = j(new Z())), j.working ? j(e5) : e5 instanceof Z);
  }
  function H(e5) {
    return "[object AsyncFunction]" === h2(e5);
  }
  function Q(e5) {
    return "[object Map Iterator]" === h2(e5);
  }
  function W(e5) {
    return "[object Set Iterator]" === h2(e5);
  }
  function q(e5) {
    return "[object Generator]" === h2(e5);
  }
  function V(e5) {
    return "[object WebAssembly.Module]" === h2(e5);
  }
  function Y2(e5) {
    return _2(e5, c2);
  }
  function K(e5) {
    return _2(e5, f2);
  }
  function J(e5) {
    return _2(e5, d);
  }
  function X(e5) {
    return l2 && _2(e5, p2);
  }
  function ee(e5) {
    return u2 && _2(e5, m);
  }
  function te(e5) {
    return Y2(e5) || K(e5) || J(e5) || X(e5) || ee(e5);
  }
  function ie(e5) {
    return "undefined" != typeof Uint8Array && ($(e5) || G2(e5));
  }
  i2.isSharedArrayBuffer = G2, i2.isAsyncFunction = H, i2.isMapIterator = Q, i2.isSetIterator = W, i2.isGeneratorObject = q, i2.isWebAssemblyCompiledModule = V, i2.isNumberObject = Y2, i2.isStringObject = K, i2.isBooleanObject = J, i2.isBigIntObject = X, i2.isSymbolObject = ee, i2.isBoxedPrimitive = te, i2.isAnyArrayBuffer = ie, ["isProxy", "isExternal", "isModuleNamespaceObject"].forEach(function(e5) {
    Object.defineProperty(i2, e5, { enumerable: false, value: function() {
      throw new Error(e5 + " is not supported in userland");
    } });
  });
}, { "is-arguments": 47, "is-generator-function": 49, "is-typed-array": 50, "which-typed-array": 85 }], 84: [function(e4, t2, i2) {
  (function(t3) {
    (function() {
      var r2 = Object.getOwnPropertyDescriptors || function(e5) {
        for (var t4 = Object.keys(e5), i3 = {}, r3 = 0; r3 < t4.length; r3++) i3[t4[r3]] = Object.getOwnPropertyDescriptor(e5, t4[r3]);
        return i3;
      }, n2 = /%[sdj%]/g;
      i2.format = function(e5) {
        if (!E2(e5)) {
          for (var t4 = [], i3 = 0; i3 < arguments.length; i3++) t4.push(l2(arguments[i3]));
          return t4.join(" ");
        }
        i3 = 1;
        for (var r3 = arguments, a3 = r3.length, o3 = String(e5).replace(n2, function(e6) {
          if ("%%" === e6) return "%";
          if (i3 >= a3) return e6;
          switch (e6) {
            case "%s":
              return String(r3[i3++]);
            case "%d":
              return Number(r3[i3++]);
            case "%j":
              try {
                return JSON.stringify(r3[i3++]);
              } catch (e7) {
                return "[Circular]";
              }
            default:
              return e6;
          }
        }), s3 = r3[i3]; i3 < a3; s3 = r3[++i3]) w(s3) || !I(s3) ? o3 += " " + s3 : o3 += " " + l2(s3);
        return o3;
      }, i2.deprecate = function(e5, r3) {
        if (void 0 !== t3 && true === t3.noDeprecation) return e5;
        if (void 0 === t3) return function() {
          return i2.deprecate(e5, r3).apply(this, arguments);
        };
        var n3 = false;
        function a3() {
          if (!n3) {
            if (t3.throwDeprecation) throw new Error(r3);
            t3.traceDeprecation ? console.trace(r3) : console.error(r3), n3 = true;
          }
          return e5.apply(this, arguments);
        }
        return a3;
      };
      var a2 = {}, o2 = /^$/;
      if (t3.env.NODE_DEBUG) {
        var s2 = t3.env.NODE_DEBUG;
        s2 = s2.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase(), o2 = new RegExp("^" + s2 + "$", "i");
      }
      function l2(e5, t4) {
        var r3 = { seen: [], stylize: h2 };
        return arguments.length >= 3 && (r3.depth = arguments[2]), arguments.length >= 4 && (r3.colors = arguments[3]), y2(t4) ? r3.showHidden = t4 : t4 && i2._extend(r3, t4), S2(r3.showHidden) && (r3.showHidden = false), S2(r3.depth) && (r3.depth = 2), S2(r3.colors) && (r3.colors = false), S2(r3.customInspect) && (r3.customInspect = true), r3.colors && (r3.stylize = u2), f2(r3, e5, r3.depth);
      }
      function u2(e5, t4) {
        var i3 = l2.styles[t4];
        return i3 ? "\x1B[" + l2.colors[i3][0] + "m" + e5 + "\x1B[" + l2.colors[i3][1] + "m" : e5;
      }
      function h2(e5, t4) {
        return e5;
      }
      function c2(e5) {
        var t4 = {};
        return e5.forEach(function(e6, i3) {
          t4[e6] = true;
        }), t4;
      }
      function f2(e5, t4, r3) {
        if (e5.customInspect && t4 && P(t4.inspect) && t4.inspect !== i2.inspect && (!t4.constructor || t4.constructor.prototype !== t4)) {
          var n3 = t4.inspect(r3, e5);
          return E2(n3) || (n3 = f2(e5, n3, r3)), n3;
        }
        var a3 = d(e5, t4);
        if (a3) return a3;
        var o3 = Object.keys(t4), s3 = c2(o3);
        if (e5.showHidden && (o3 = Object.getOwnPropertyNames(t4)), T2(t4) && (o3.indexOf("message") >= 0 || o3.indexOf("description") >= 0)) return p2(t4);
        if (0 === o3.length) {
          if (P(t4)) {
            var l3 = t4.name ? ": " + t4.name : "";
            return e5.stylize("[Function" + l3 + "]", "special");
          }
          if (A2(t4)) return e5.stylize(RegExp.prototype.toString.call(t4), "regexp");
          if (M2(t4)) return e5.stylize(Date.prototype.toString.call(t4), "date");
          if (T2(t4)) return p2(t4);
        }
        var u3, h3 = "", y3 = false, w2 = ["{", "}"];
        return b2(t4) && (y3 = true, w2 = ["[", "]"]), P(t4) && (h3 = " [Function" + (t4.name ? ": " + t4.name : "") + "]"), A2(t4) && (h3 = " " + RegExp.prototype.toString.call(t4)), M2(t4) && (h3 = " " + Date.prototype.toUTCString.call(t4)), T2(t4) && (h3 = " " + p2(t4)), 0 !== o3.length || y3 && 0 != t4.length ? r3 < 0 ? A2(t4) ? e5.stylize(RegExp.prototype.toString.call(t4), "regexp") : e5.stylize("[Object]", "special") : (e5.seen.push(t4), u3 = y3 ? m(e5, t4, r3, s3, o3) : o3.map(function(i3) {
          return _2(e5, t4, r3, s3, i3, y3);
        }), e5.seen.pop(), g(u3, h3, w2)) : w2[0] + h3 + w2[1];
      }
      function d(e5, t4) {
        if (S2(t4)) return e5.stylize("undefined", "undefined");
        if (E2(t4)) {
          var i3 = "'" + JSON.stringify(t4).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
          return e5.stylize(i3, "string");
        }
        return x2(t4) ? e5.stylize("" + t4, "number") : y2(t4) ? e5.stylize("" + t4, "boolean") : w(t4) ? e5.stylize("null", "null") : void 0;
      }
      function p2(e5) {
        return "[" + Error.prototype.toString.call(e5) + "]";
      }
      function m(e5, t4, i3, r3, n3) {
        for (var a3 = [], o3 = 0, s3 = t4.length; o3 < s3; ++o3) N2(t4, String(o3)) ? a3.push(_2(e5, t4, i3, r3, String(o3), true)) : a3.push("");
        return n3.forEach(function(n4) {
          n4.match(/^\d+$/) || a3.push(_2(e5, t4, i3, r3, n4, true));
        }), a3;
      }
      function _2(e5, t4, i3, r3, n3, a3) {
        var o3, s3, l3;
        if ((l3 = Object.getOwnPropertyDescriptor(t4, n3) || { value: t4[n3] }).get ? s3 = l3.set ? e5.stylize("[Getter/Setter]", "special") : e5.stylize("[Getter]", "special") : l3.set && (s3 = e5.stylize("[Setter]", "special")), N2(r3, n3) || (o3 = "[" + n3 + "]"), s3 || (e5.seen.indexOf(l3.value) < 0 ? (s3 = w(i3) ? f2(e5, l3.value, null) : f2(e5, l3.value, i3 - 1)).indexOf("\n") > -1 && (s3 = a3 ? s3.split("\n").map(function(e6) {
          return "  " + e6;
        }).join("\n").slice(2) : "\n" + s3.split("\n").map(function(e6) {
          return "   " + e6;
        }).join("\n")) : s3 = e5.stylize("[Circular]", "special")), S2(o3)) {
          if (a3 && n3.match(/^\d+$/)) return s3;
          (o3 = JSON.stringify("" + n3)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/) ? (o3 = o3.slice(1, -1), o3 = e5.stylize(o3, "name")) : (o3 = o3.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), o3 = e5.stylize(o3, "string"));
        }
        return o3 + ": " + s3;
      }
      function g(e5, t4, i3) {
        return e5.reduce(function(e6, t5) {
          return t5.indexOf("\n"), e6 + t5.replace(/\u001b\[\d\d?m/g, "").length + 1;
        }, 0) > 60 ? i3[0] + ("" === t4 ? "" : t4 + "\n ") + " " + e5.join(",\n  ") + " " + i3[1] : i3[0] + t4 + " " + e5.join(", ") + " " + i3[1];
      }
      function b2(e5) {
        return Array.isArray(e5);
      }
      function y2(e5) {
        return "boolean" == typeof e5;
      }
      function w(e5) {
        return null === e5;
      }
      function v2(e5) {
        return null == e5;
      }
      function x2(e5) {
        return "number" == typeof e5;
      }
      function E2(e5) {
        return "string" == typeof e5;
      }
      function k2(e5) {
        return "symbol" == typeof e5;
      }
      function S2(e5) {
        return void 0 === e5;
      }
      function A2(e5) {
        return I(e5) && "[object RegExp]" === C2(e5);
      }
      function I(e5) {
        return "object" == typeof e5 && null !== e5;
      }
      function M2(e5) {
        return I(e5) && "[object Date]" === C2(e5);
      }
      function T2(e5) {
        return I(e5) && ("[object Error]" === C2(e5) || e5 instanceof Error);
      }
      function P(e5) {
        return "function" == typeof e5;
      }
      function B2(e5) {
        return null === e5 || "boolean" == typeof e5 || "number" == typeof e5 || "string" == typeof e5 || "symbol" == typeof e5 || void 0 === e5;
      }
      function C2(e5) {
        return Object.prototype.toString.call(e5);
      }
      function R2(e5) {
        return e5 < 10 ? "0" + e5.toString(10) : e5.toString(10);
      }
      i2.debuglog = function(e5) {
        if (e5 = e5.toUpperCase(), !a2[e5]) if (o2.test(e5)) {
          var r3 = t3.pid;
          a2[e5] = function() {
            var t4 = i2.format.apply(i2, arguments);
            console.error("%s %d: %s", e5, r3, t4);
          };
        } else a2[e5] = function() {
        };
        return a2[e5];
      }, i2.inspect = l2, l2.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, l2.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, i2.types = e4("./support/types"), i2.isArray = b2, i2.isBoolean = y2, i2.isNull = w, i2.isNullOrUndefined = v2, i2.isNumber = x2, i2.isString = E2, i2.isSymbol = k2, i2.isUndefined = S2, i2.isRegExp = A2, i2.types.isRegExp = A2, i2.isObject = I, i2.isDate = M2, i2.types.isDate = M2, i2.isError = T2, i2.types.isNativeError = T2, i2.isFunction = P, i2.isPrimitive = B2, i2.isBuffer = e4("./support/isBuffer");
      var z2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
      function F() {
        var e5 = /* @__PURE__ */ new Date(), t4 = [R2(e5.getHours()), R2(e5.getMinutes()), R2(e5.getSeconds())].join(":");
        return [e5.getDate(), z2[e5.getMonth()], t4].join(" ");
      }
      function N2(e5, t4) {
        return Object.prototype.hasOwnProperty.call(e5, t4);
      }
      i2.log = function() {
        console.log("%s - %s", F(), i2.format.apply(i2, arguments));
      }, i2.inherits = e4("inherits"), i2._extend = function(e5, t4) {
        if (!t4 || !I(t4)) return e5;
        for (var i3 = Object.keys(t4), r3 = i3.length; r3--; ) e5[i3[r3]] = t4[i3[r3]];
        return e5;
      };
      var O2 = "undefined" != typeof Symbol ? Symbol("util.promisify.custom") : void 0;
      function D(e5, t4) {
        if (!e5) {
          var i3 = new Error("Promise was rejected with a falsy value");
          i3.reason = e5, e5 = i3;
        }
        return t4(e5);
      }
      function $(e5) {
        if ("function" != typeof e5) throw new TypeError('The "original" argument must be of type Function');
        function i3() {
          for (var i4 = [], r3 = 0; r3 < arguments.length; r3++) i4.push(arguments[r3]);
          var n3 = i4.pop();
          if ("function" != typeof n3) throw new TypeError("The last argument must be of type Function");
          var a3 = this, o3 = function() {
            return n3.apply(a3, arguments);
          };
          e5.apply(this, i4).then(function(e6) {
            t3.nextTick(o3.bind(null, null, e6));
          }, function(e6) {
            t3.nextTick(D.bind(null, e6, o3));
          });
        }
        return Object.setPrototypeOf(i3, Object.getPrototypeOf(e5)), Object.defineProperties(i3, r2(e5)), i3;
      }
      i2.promisify = function(e5) {
        if ("function" != typeof e5) throw new TypeError('The "original" argument must be of type Function');
        if (O2 && e5[O2]) {
          var t4;
          if ("function" != typeof (t4 = e5[O2])) throw new TypeError('The "util.promisify.custom" argument must be of type Function');
          return Object.defineProperty(t4, O2, { value: t4, enumerable: false, writable: false, configurable: true }), t4;
        }
        function t4() {
          for (var t5, i3, r3 = new Promise(function(e6, r4) {
            t5 = e6, i3 = r4;
          }), n3 = [], a3 = 0; a3 < arguments.length; a3++) n3.push(arguments[a3]);
          n3.push(function(e6, r4) {
            e6 ? i3(e6) : t5(r4);
          });
          try {
            e5.apply(this, n3);
          } catch (e6) {
            i3(e6);
          }
          return r3;
        }
        return Object.setPrototypeOf(t4, Object.getPrototypeOf(e5)), O2 && Object.defineProperty(t4, O2, { value: t4, enumerable: false, writable: false, configurable: true }), Object.defineProperties(t4, r2(e5));
      }, i2.promisify.custom = O2, i2.callbackify = $;
    }).call(this);
  }).call(this, e4("_process"));
}, { "./support/isBuffer": 82, "./support/types": 83, _process: 63, inherits: 46 }], 85: [function(e4, t2, i2) {
  (function(i3) {
    (function() {
      var r2 = e4("for-each"), n2 = e4("available-typed-arrays"), a2 = e4("call-bind/callBound"), o2 = e4("gopd"), s2 = a2("Object.prototype.toString"), l2 = e4("has-tostringtag/shams")(), u2 = "undefined" == typeof globalThis ? i3 : globalThis, h2 = n2(), c2 = a2("String.prototype.slice"), f2 = {}, d = Object.getPrototypeOf;
      l2 && o2 && d && r2(h2, function(e5) {
        if ("function" == typeof u2[e5]) {
          var t3 = new u2[e5]();
          if (Symbol.toStringTag in t3) {
            var i4 = d(t3), r3 = o2(i4, Symbol.toStringTag);
            if (!r3) {
              var n3 = d(i4);
              r3 = o2(n3, Symbol.toStringTag);
            }
            f2[e5] = r3.get;
          }
        }
      });
      var p2 = function(e5) {
        var t3 = false;
        return r2(f2, function(i4, r3) {
          if (!t3) try {
            var n3 = i4.call(e5);
            n3 === r3 && (t3 = n3);
          } catch (e6) {
          }
        }), t3;
      }, m = e4("is-typed-array");
      t2.exports = function(e5) {
        return !!m(e5) && (l2 && Symbol.toStringTag in e5 ? p2(e5) : c2(s2(e5), 8, -1));
      };
    }).call(this);
  }).call(this, void 0 !== commonjsGlobal ? commonjsGlobal : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {});
}, { "available-typed-arrays": 27, "call-bind/callBound": 33, "for-each": 36, gopd: 40, "has-tostringtag/shams": 43, "is-typed-array": 50 }] }, {}, [20])(20);
var browserExports = browser$1.exports, PNGFilterType, PNGFilterType2, PNGColorType, PNGColorType2;
function png() {
  return { mime: "image/png", hasAlpha: true, encode: (e4, { deflateLevel: t2 = 9, deflateStrategy: i2 = 3, filterType: r2 = PNGFilterType.AUTO, colorType: n2, inputHasAlpha: a2 = true, ...o2 } = {}) => {
    const s2 = new browserExports.PNG({ width: e4.width, height: e4.height });
    return s2.data = e4.data, browserExports.PNG.sync.write(s2, { ...o2, deflateLevel: t2, deflateStrategy: i2, filterType: r2, colorType: void 0 !== n2 ? n2 : a2 ? PNGColorType.COLOR_ALPHA : PNGColorType.COLOR, inputHasAlpha: a2 });
  }, decode: (e4, t2) => {
    const i2 = browserExports.PNG.sync.read(e4, t2);
    return { data: i2.data, width: i2.width, height: i2.height };
  } };
}
PNGFilterType2 = PNGFilterType || (PNGFilterType = {}), PNGFilterType2[PNGFilterType2.AUTO = -1] = "AUTO", PNGFilterType2[PNGFilterType2.NONE = 0] = "NONE", PNGFilterType2[PNGFilterType2.SUB = 1] = "SUB", PNGFilterType2[PNGFilterType2.UP = 2] = "UP", PNGFilterType2[PNGFilterType2.AVERAGE = 3] = "AVERAGE", PNGFilterType2[PNGFilterType2.PATH = 4] = "PATH", PNGColorType2 = PNGColorType || (PNGColorType = {}), PNGColorType2[PNGColorType2.GRAYSCALE = 0] = "GRAYSCALE", PNGColorType2[PNGColorType2.COLOR = 2] = "COLOR", PNGColorType2[PNGColorType2.GRAYSCALE_ALPHA = 4] = "GRAYSCALE_ALPHA", PNGColorType2[PNGColorType2.COLOR_ALPHA = 6] = "COLOR_ALPHA";
var UTIF = { exports: {} }, common = {}, hasRequiredCommon;
function requireCommon() {
  return hasRequiredCommon || (hasRequiredCommon = 1, function(e4) {
    var t2 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array;
    function i2(e5, t3) {
      return Object.prototype.hasOwnProperty.call(e5, t3);
    }
    e4.assign = function(e5) {
      for (var t3 = Array.prototype.slice.call(arguments, 1); t3.length; ) {
        var r3 = t3.shift();
        if (r3) {
          if ("object" != typeof r3) throw new TypeError(r3 + "must be non-object");
          for (var n3 in r3) i2(r3, n3) && (e5[n3] = r3[n3]);
        }
      }
      return e5;
    }, e4.shrinkBuf = function(e5, t3) {
      return e5.length === t3 ? e5 : e5.subarray ? e5.subarray(0, t3) : (e5.length = t3, e5);
    };
    var r2 = { arraySet: function(e5, t3, i3, r3, n3) {
      if (t3.subarray && e5.subarray) e5.set(t3.subarray(i3, i3 + r3), n3);
      else for (var a2 = 0; a2 < r3; a2++) e5[n3 + a2] = t3[i3 + a2];
    }, flattenChunks: function(e5) {
      var t3, i3, r3, n3, a2, o2;
      for (r3 = 0, t3 = 0, i3 = e5.length; t3 < i3; t3++) r3 += e5[t3].length;
      for (o2 = new Uint8Array(r3), n3 = 0, t3 = 0, i3 = e5.length; t3 < i3; t3++) a2 = e5[t3], o2.set(a2, n3), n3 += a2.length;
      return o2;
    } }, n2 = { arraySet: function(e5, t3, i3, r3, n3) {
      for (var a2 = 0; a2 < r3; a2++) e5[n3 + a2] = t3[i3 + a2];
    }, flattenChunks: function(e5) {
      return [].concat.apply([], e5);
    } };
    e4.setTyped = function(t3) {
      t3 ? (e4.Buf8 = Uint8Array, e4.Buf16 = Uint16Array, e4.Buf32 = Int32Array, e4.assign(e4, r2)) : (e4.Buf8 = Array, e4.Buf16 = Array, e4.Buf32 = Array, e4.assign(e4, n2));
    }, e4.setTyped(t2);
  }(common)), common;
}
var deflate$1 = {}, deflate = {}, trees = {}, hasRequiredTrees, adler32_1, hasRequiredAdler32, crc32_1, hasRequiredCrc32, messages, hasRequiredMessages, hasRequiredDeflate$1;
function requireTrees() {
  if (hasRequiredTrees) return trees;
  hasRequiredTrees = 1;
  var e4 = requireCommon(), t2 = 0, i2 = 1;
  function r2(e5) {
    for (var t3 = e5.length; --t3 >= 0; ) e5[t3] = 0;
  }
  var n2 = 0, a2 = 29, o2 = 256, s2 = o2 + 1 + a2, l2 = 30, u2 = 19, h2 = 2 * s2 + 1, c2 = 15, f2 = 16, d = 7, p2 = 256, m = 16, _2 = 17, g = 18, b2 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], y2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], w = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], v2 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], x2 = new Array(2 * (s2 + 2));
  r2(x2);
  var E2 = new Array(2 * l2);
  r2(E2);
  var k2 = new Array(512);
  r2(k2);
  var S2 = new Array(256);
  r2(S2);
  var A2 = new Array(a2);
  r2(A2);
  var I, M2, T2, P = new Array(l2);
  function B2(e5, t3, i3, r3, n3) {
    this.static_tree = e5, this.extra_bits = t3, this.extra_base = i3, this.elems = r3, this.max_length = n3, this.has_stree = e5 && e5.length;
  }
  function C2(e5, t3) {
    this.dyn_tree = e5, this.max_code = 0, this.stat_desc = t3;
  }
  function R2(e5) {
    return e5 < 256 ? k2[e5] : k2[256 + (e5 >>> 7)];
  }
  function z2(e5, t3) {
    e5.pending_buf[e5.pending++] = 255 & t3, e5.pending_buf[e5.pending++] = t3 >>> 8 & 255;
  }
  function F(e5, t3, i3) {
    e5.bi_valid > f2 - i3 ? (e5.bi_buf |= t3 << e5.bi_valid & 65535, z2(e5, e5.bi_buf), e5.bi_buf = t3 >> f2 - e5.bi_valid, e5.bi_valid += i3 - f2) : (e5.bi_buf |= t3 << e5.bi_valid & 65535, e5.bi_valid += i3);
  }
  function N2(e5, t3, i3) {
    F(e5, i3[2 * t3], i3[2 * t3 + 1]);
  }
  function O2(e5, t3) {
    var i3 = 0;
    do {
      i3 |= 1 & e5, e5 >>>= 1, i3 <<= 1;
    } while (--t3 > 0);
    return i3 >>> 1;
  }
  function D(e5, t3, i3) {
    var r3, n3, a3 = new Array(c2 + 1), o3 = 0;
    for (r3 = 1; r3 <= c2; r3++) a3[r3] = o3 = o3 + i3[r3 - 1] << 1;
    for (n3 = 0; n3 <= t3; n3++) {
      var s3 = e5[2 * n3 + 1];
      0 !== s3 && (e5[2 * n3] = O2(a3[s3]++, s3));
    }
  }
  function $(e5) {
    var t3;
    for (t3 = 0; t3 < s2; t3++) e5.dyn_ltree[2 * t3] = 0;
    for (t3 = 0; t3 < l2; t3++) e5.dyn_dtree[2 * t3] = 0;
    for (t3 = 0; t3 < u2; t3++) e5.bl_tree[2 * t3] = 0;
    e5.dyn_ltree[2 * p2] = 1, e5.opt_len = e5.static_len = 0, e5.last_lit = e5.matches = 0;
  }
  function L2(e5) {
    e5.bi_valid > 8 ? z2(e5, e5.bi_buf) : e5.bi_valid > 0 && (e5.pending_buf[e5.pending++] = e5.bi_buf), e5.bi_buf = 0, e5.bi_valid = 0;
  }
  function U(e5, t3, i3, r3) {
    var n3 = 2 * t3, a3 = 2 * i3;
    return e5[n3] < e5[a3] || e5[n3] === e5[a3] && r3[t3] <= r3[i3];
  }
  function Z(e5, t3, i3) {
    for (var r3 = e5.heap[i3], n3 = i3 << 1; n3 <= e5.heap_len && (n3 < e5.heap_len && U(t3, e5.heap[n3 + 1], e5.heap[n3], e5.depth) && n3++, !U(t3, r3, e5.heap[n3], e5.depth)); ) e5.heap[i3] = e5.heap[n3], i3 = n3, n3 <<= 1;
    e5.heap[i3] = r3;
  }
  function j(e5, t3, i3) {
    var r3, n3, a3, s3, l3 = 0;
    if (0 !== e5.last_lit) do {
      r3 = e5.pending_buf[e5.d_buf + 2 * l3] << 8 | e5.pending_buf[e5.d_buf + 2 * l3 + 1], n3 = e5.pending_buf[e5.l_buf + l3], l3++, 0 === r3 ? N2(e5, n3, t3) : (N2(e5, (a3 = S2[n3]) + o2 + 1, t3), 0 !== (s3 = b2[a3]) && F(e5, n3 -= A2[a3], s3), N2(e5, a3 = R2(--r3), i3), 0 !== (s3 = y2[a3]) && F(e5, r3 -= P[a3], s3));
    } while (l3 < e5.last_lit);
    N2(e5, p2, t3);
  }
  function G2(e5, t3) {
    var i3, r3, n3, a3 = t3.dyn_tree, o3 = t3.stat_desc.static_tree, s3 = t3.stat_desc.has_stree, l3 = t3.stat_desc.elems, u3 = -1;
    for (e5.heap_len = 0, e5.heap_max = h2, i3 = 0; i3 < l3; i3++) 0 !== a3[2 * i3] ? (e5.heap[++e5.heap_len] = u3 = i3, e5.depth[i3] = 0) : a3[2 * i3 + 1] = 0;
    for (; e5.heap_len < 2; ) a3[2 * (n3 = e5.heap[++e5.heap_len] = u3 < 2 ? ++u3 : 0)] = 1, e5.depth[n3] = 0, e5.opt_len--, s3 && (e5.static_len -= o3[2 * n3 + 1]);
    for (t3.max_code = u3, i3 = e5.heap_len >> 1; i3 >= 1; i3--) Z(e5, a3, i3);
    n3 = l3;
    do {
      i3 = e5.heap[1], e5.heap[1] = e5.heap[e5.heap_len--], Z(e5, a3, 1), r3 = e5.heap[1], e5.heap[--e5.heap_max] = i3, e5.heap[--e5.heap_max] = r3, a3[2 * n3] = a3[2 * i3] + a3[2 * r3], e5.depth[n3] = (e5.depth[i3] >= e5.depth[r3] ? e5.depth[i3] : e5.depth[r3]) + 1, a3[2 * i3 + 1] = a3[2 * r3 + 1] = n3, e5.heap[1] = n3++, Z(e5, a3, 1);
    } while (e5.heap_len >= 2);
    e5.heap[--e5.heap_max] = e5.heap[1], function(e6, t4) {
      var i4, r4, n4, a4, o4, s4, l4 = t4.dyn_tree, u4 = t4.max_code, f3 = t4.stat_desc.static_tree, d2 = t4.stat_desc.has_stree, p3 = t4.stat_desc.extra_bits, m2 = t4.stat_desc.extra_base, _3 = t4.stat_desc.max_length, g2 = 0;
      for (a4 = 0; a4 <= c2; a4++) e6.bl_count[a4] = 0;
      for (l4[2 * e6.heap[e6.heap_max] + 1] = 0, i4 = e6.heap_max + 1; i4 < h2; i4++) (a4 = l4[2 * l4[2 * (r4 = e6.heap[i4]) + 1] + 1] + 1) > _3 && (a4 = _3, g2++), l4[2 * r4 + 1] = a4, r4 > u4 || (e6.bl_count[a4]++, o4 = 0, r4 >= m2 && (o4 = p3[r4 - m2]), s4 = l4[2 * r4], e6.opt_len += s4 * (a4 + o4), d2 && (e6.static_len += s4 * (f3[2 * r4 + 1] + o4)));
      if (0 !== g2) {
        do {
          for (a4 = _3 - 1; 0 === e6.bl_count[a4]; ) a4--;
          e6.bl_count[a4]--, e6.bl_count[a4 + 1] += 2, e6.bl_count[_3]--, g2 -= 2;
        } while (g2 > 0);
        for (a4 = _3; 0 !== a4; a4--) for (r4 = e6.bl_count[a4]; 0 !== r4; ) (n4 = e6.heap[--i4]) > u4 || (l4[2 * n4 + 1] !== a4 && (e6.opt_len += (a4 - l4[2 * n4 + 1]) * l4[2 * n4], l4[2 * n4 + 1] = a4), r4--);
      }
    }(e5, t3), D(a3, u3, e5.bl_count);
  }
  function H(e5, t3, i3) {
    var r3, n3, a3 = -1, o3 = t3[1], s3 = 0, l3 = 7, u3 = 4;
    for (0 === o3 && (l3 = 138, u3 = 3), t3[2 * (i3 + 1) + 1] = 65535, r3 = 0; r3 <= i3; r3++) n3 = o3, o3 = t3[2 * (r3 + 1) + 1], ++s3 < l3 && n3 === o3 || (s3 < u3 ? e5.bl_tree[2 * n3] += s3 : 0 !== n3 ? (n3 !== a3 && e5.bl_tree[2 * n3]++, e5.bl_tree[2 * m]++) : s3 <= 10 ? e5.bl_tree[2 * _2]++ : e5.bl_tree[2 * g]++, s3 = 0, a3 = n3, 0 === o3 ? (l3 = 138, u3 = 3) : n3 === o3 ? (l3 = 6, u3 = 3) : (l3 = 7, u3 = 4));
  }
  function Q(e5, t3, i3) {
    var r3, n3, a3 = -1, o3 = t3[1], s3 = 0, l3 = 7, u3 = 4;
    for (0 === o3 && (l3 = 138, u3 = 3), r3 = 0; r3 <= i3; r3++) if (n3 = o3, o3 = t3[2 * (r3 + 1) + 1], !(++s3 < l3 && n3 === o3)) {
      if (s3 < u3) do {
        N2(e5, n3, e5.bl_tree);
      } while (0 != --s3);
      else 0 !== n3 ? (n3 !== a3 && (N2(e5, n3, e5.bl_tree), s3--), N2(e5, m, e5.bl_tree), F(e5, s3 - 3, 2)) : s3 <= 10 ? (N2(e5, _2, e5.bl_tree), F(e5, s3 - 3, 3)) : (N2(e5, g, e5.bl_tree), F(e5, s3 - 11, 7));
      s3 = 0, a3 = n3, 0 === o3 ? (l3 = 138, u3 = 3) : n3 === o3 ? (l3 = 6, u3 = 3) : (l3 = 7, u3 = 4);
    }
  }
  r2(P);
  var W = false;
  function q(t3, i3, r3, a3) {
    F(t3, (n2 << 1) + (a3 ? 1 : 0), 3), function(t4, i4, r4, n3) {
      L2(t4), z2(t4, r4), z2(t4, ~r4), e4.arraySet(t4.pending_buf, t4.window, i4, r4, t4.pending), t4.pending += r4;
    }(t3, i3, r3);
  }
  return trees._tr_init = function(e5) {
    W || (!function() {
      var e6, t3, i3, r3, n3, h3 = new Array(c2 + 1);
      for (i3 = 0, r3 = 0; r3 < a2 - 1; r3++) for (A2[r3] = i3, e6 = 0; e6 < 1 << b2[r3]; e6++) S2[i3++] = r3;
      for (S2[i3 - 1] = r3, n3 = 0, r3 = 0; r3 < 16; r3++) for (P[r3] = n3, e6 = 0; e6 < 1 << y2[r3]; e6++) k2[n3++] = r3;
      for (n3 >>= 7; r3 < l2; r3++) for (P[r3] = n3 << 7, e6 = 0; e6 < 1 << y2[r3] - 7; e6++) k2[256 + n3++] = r3;
      for (t3 = 0; t3 <= c2; t3++) h3[t3] = 0;
      for (e6 = 0; e6 <= 143; ) x2[2 * e6 + 1] = 8, e6++, h3[8]++;
      for (; e6 <= 255; ) x2[2 * e6 + 1] = 9, e6++, h3[9]++;
      for (; e6 <= 279; ) x2[2 * e6 + 1] = 7, e6++, h3[7]++;
      for (; e6 <= 287; ) x2[2 * e6 + 1] = 8, e6++, h3[8]++;
      for (D(x2, s2 + 1, h3), e6 = 0; e6 < l2; e6++) E2[2 * e6 + 1] = 5, E2[2 * e6] = O2(e6, 5);
      I = new B2(x2, b2, o2 + 1, s2, c2), M2 = new B2(E2, y2, 0, l2, c2), T2 = new B2(new Array(0), w, 0, u2, d);
    }(), W = true), e5.l_desc = new C2(e5.dyn_ltree, I), e5.d_desc = new C2(e5.dyn_dtree, M2), e5.bl_desc = new C2(e5.bl_tree, T2), e5.bi_buf = 0, e5.bi_valid = 0, $(e5);
  }, trees._tr_stored_block = q, trees._tr_flush_block = function(e5, r3, n3, a3) {
    var s3, l3, h3 = 0;
    e5.level > 0 ? (2 === e5.strm.data_type && (e5.strm.data_type = function(e6) {
      var r4, n4 = 4093624447;
      for (r4 = 0; r4 <= 31; r4++, n4 >>>= 1) if (1 & n4 && 0 !== e6.dyn_ltree[2 * r4]) return t2;
      if (0 !== e6.dyn_ltree[18] || 0 !== e6.dyn_ltree[20] || 0 !== e6.dyn_ltree[26]) return i2;
      for (r4 = 32; r4 < o2; r4++) if (0 !== e6.dyn_ltree[2 * r4]) return i2;
      return t2;
    }(e5)), G2(e5, e5.l_desc), G2(e5, e5.d_desc), h3 = function(e6) {
      var t3;
      for (H(e6, e6.dyn_ltree, e6.l_desc.max_code), H(e6, e6.dyn_dtree, e6.d_desc.max_code), G2(e6, e6.bl_desc), t3 = u2 - 1; t3 >= 3 && 0 === e6.bl_tree[2 * v2[t3] + 1]; t3--) ;
      return e6.opt_len += 3 * (t3 + 1) + 5 + 5 + 4, t3;
    }(e5), s3 = e5.opt_len + 3 + 7 >>> 3, (l3 = e5.static_len + 3 + 7 >>> 3) <= s3 && (s3 = l3)) : s3 = l3 = n3 + 5, n3 + 4 <= s3 && -1 !== r3 ? q(e5, r3, n3, a3) : 4 === e5.strategy || l3 === s3 ? (F(e5, 2 + (a3 ? 1 : 0), 3), j(e5, x2, E2)) : (F(e5, 4 + (a3 ? 1 : 0), 3), function(e6, t3, i3, r4) {
      var n4;
      for (F(e6, t3 - 257, 5), F(e6, i3 - 1, 5), F(e6, r4 - 4, 4), n4 = 0; n4 < r4; n4++) F(e6, e6.bl_tree[2 * v2[n4] + 1], 3);
      Q(e6, e6.dyn_ltree, t3 - 1), Q(e6, e6.dyn_dtree, i3 - 1);
    }(e5, e5.l_desc.max_code + 1, e5.d_desc.max_code + 1, h3 + 1), j(e5, e5.dyn_ltree, e5.dyn_dtree)), $(e5), a3 && L2(e5);
  }, trees._tr_tally = function(e5, t3, i3) {
    return e5.pending_buf[e5.d_buf + 2 * e5.last_lit] = t3 >>> 8 & 255, e5.pending_buf[e5.d_buf + 2 * e5.last_lit + 1] = 255 & t3, e5.pending_buf[e5.l_buf + e5.last_lit] = 255 & i3, e5.last_lit++, 0 === t3 ? e5.dyn_ltree[2 * i3]++ : (e5.matches++, t3--, e5.dyn_ltree[2 * (S2[i3] + o2 + 1)]++, e5.dyn_dtree[2 * R2(t3)]++), e5.last_lit === e5.lit_bufsize - 1;
  }, trees._tr_align = function(e5) {
    F(e5, 2, 3), N2(e5, p2, x2), function(e6) {
      16 === e6.bi_valid ? (z2(e6, e6.bi_buf), e6.bi_buf = 0, e6.bi_valid = 0) : e6.bi_valid >= 8 && (e6.pending_buf[e6.pending++] = 255 & e6.bi_buf, e6.bi_buf >>= 8, e6.bi_valid -= 8);
    }(e5);
  }, trees;
}
function requireAdler32() {
  if (hasRequiredAdler32) return adler32_1;
  return hasRequiredAdler32 = 1, adler32_1 = function(e4, t2, i2, r2) {
    for (var n2 = 65535 & e4, a2 = e4 >>> 16 & 65535, o2 = 0; 0 !== i2; ) {
      i2 -= o2 = i2 > 2e3 ? 2e3 : i2;
      do {
        a2 = a2 + (n2 = n2 + t2[r2++] | 0) | 0;
      } while (--o2);
      n2 %= 65521, a2 %= 65521;
    }
    return n2 | a2 << 16;
  }, adler32_1;
}
function requireCrc32() {
  if (hasRequiredCrc32) return crc32_1;
  hasRequiredCrc32 = 1;
  var e4 = function() {
    for (var e5, t2 = [], i2 = 0; i2 < 256; i2++) {
      e5 = i2;
      for (var r2 = 0; r2 < 8; r2++) e5 = 1 & e5 ? 3988292384 ^ e5 >>> 1 : e5 >>> 1;
      t2[i2] = e5;
    }
    return t2;
  }();
  return crc32_1 = function(t2, i2, r2, n2) {
    var a2 = e4, o2 = n2 + r2;
    t2 ^= -1;
    for (var s2 = n2; s2 < o2; s2++) t2 = t2 >>> 8 ^ a2[255 & (t2 ^ i2[s2])];
    return ~t2;
  }, crc32_1;
}
function requireMessages() {
  return hasRequiredMessages ? messages : (hasRequiredMessages = 1, messages = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" });
}
function requireDeflate$1() {
  if (hasRequiredDeflate$1) return deflate;
  hasRequiredDeflate$1 = 1;
  var e4, t2 = requireCommon(), i2 = requireTrees(), r2 = requireAdler32(), n2 = requireCrc32(), a2 = requireMessages(), o2 = 0, s2 = 4, l2 = 0, u2 = -2, h2 = -1, c2 = 4, f2 = 2, d = 8, p2 = 9, m = 286, _2 = 30, g = 19, b2 = 2 * m + 1, y2 = 15, w = 3, v2 = 258, x2 = v2 + w + 1, E2 = 42, k2 = 103, S2 = 113, A2 = 666, I = 1, M2 = 2, T2 = 3, P = 4;
  function B2(e5, t3) {
    return e5.msg = a2[t3], t3;
  }
  function C2(e5) {
    return (e5 << 1) - (e5 > 4 ? 9 : 0);
  }
  function R2(e5) {
    for (var t3 = e5.length; --t3 >= 0; ) e5[t3] = 0;
  }
  function z2(e5) {
    var i3 = e5.state, r3 = i3.pending;
    r3 > e5.avail_out && (r3 = e5.avail_out), 0 !== r3 && (t2.arraySet(e5.output, i3.pending_buf, i3.pending_out, r3, e5.next_out), e5.next_out += r3, i3.pending_out += r3, e5.total_out += r3, e5.avail_out -= r3, i3.pending -= r3, 0 === i3.pending && (i3.pending_out = 0));
  }
  function F(e5, t3) {
    i2._tr_flush_block(e5, e5.block_start >= 0 ? e5.block_start : -1, e5.strstart - e5.block_start, t3), e5.block_start = e5.strstart, z2(e5.strm);
  }
  function N2(e5, t3) {
    e5.pending_buf[e5.pending++] = t3;
  }
  function O2(e5, t3) {
    e5.pending_buf[e5.pending++] = t3 >>> 8 & 255, e5.pending_buf[e5.pending++] = 255 & t3;
  }
  function D(e5, t3) {
    var i3, r3, n3 = e5.max_chain_length, a3 = e5.strstart, o3 = e5.prev_length, s3 = e5.nice_match, l3 = e5.strstart > e5.w_size - x2 ? e5.strstart - (e5.w_size - x2) : 0, u3 = e5.window, h3 = e5.w_mask, c3 = e5.prev, f3 = e5.strstart + v2, d2 = u3[a3 + o3 - 1], p3 = u3[a3 + o3];
    e5.prev_length >= e5.good_match && (n3 >>= 2), s3 > e5.lookahead && (s3 = e5.lookahead);
    do {
      if (u3[(i3 = t3) + o3] === p3 && u3[i3 + o3 - 1] === d2 && u3[i3] === u3[a3] && u3[++i3] === u3[a3 + 1]) {
        a3 += 2, i3++;
        do {
        } while (u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && u3[++a3] === u3[++i3] && a3 < f3);
        if (r3 = v2 - (f3 - a3), a3 = f3 - v2, r3 > o3) {
          if (e5.match_start = t3, o3 = r3, r3 >= s3) break;
          d2 = u3[a3 + o3 - 1], p3 = u3[a3 + o3];
        }
      }
    } while ((t3 = c3[t3 & h3]) > l3 && 0 != --n3);
    return o3 <= e5.lookahead ? o3 : e5.lookahead;
  }
  function $(e5) {
    var i3, a3, o3, s3, l3, u3, h3, c3, f3, d2, p3 = e5.w_size;
    do {
      if (s3 = e5.window_size - e5.lookahead - e5.strstart, e5.strstart >= p3 + (p3 - x2)) {
        t2.arraySet(e5.window, e5.window, p3, p3, 0), e5.match_start -= p3, e5.strstart -= p3, e5.block_start -= p3, i3 = a3 = e5.hash_size;
        do {
          o3 = e5.head[--i3], e5.head[i3] = o3 >= p3 ? o3 - p3 : 0;
        } while (--a3);
        i3 = a3 = p3;
        do {
          o3 = e5.prev[--i3], e5.prev[i3] = o3 >= p3 ? o3 - p3 : 0;
        } while (--a3);
        s3 += p3;
      }
      if (0 === e5.strm.avail_in) break;
      if (u3 = e5.strm, h3 = e5.window, c3 = e5.strstart + e5.lookahead, f3 = s3, d2 = void 0, (d2 = u3.avail_in) > f3 && (d2 = f3), a3 = 0 === d2 ? 0 : (u3.avail_in -= d2, t2.arraySet(h3, u3.input, u3.next_in, d2, c3), 1 === u3.state.wrap ? u3.adler = r2(u3.adler, h3, d2, c3) : 2 === u3.state.wrap && (u3.adler = n2(u3.adler, h3, d2, c3)), u3.next_in += d2, u3.total_in += d2, d2), e5.lookahead += a3, e5.lookahead + e5.insert >= w) for (l3 = e5.strstart - e5.insert, e5.ins_h = e5.window[l3], e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[l3 + 1]) & e5.hash_mask; e5.insert && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[l3 + w - 1]) & e5.hash_mask, e5.prev[l3 & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = l3, l3++, e5.insert--, !(e5.lookahead + e5.insert < w)); ) ;
    } while (e5.lookahead < x2 && 0 !== e5.strm.avail_in);
  }
  function L2(e5, t3) {
    for (var r3, n3; ; ) {
      if (e5.lookahead < x2) {
        if ($(e5), e5.lookahead < x2 && t3 === o2) return I;
        if (0 === e5.lookahead) break;
      }
      if (r3 = 0, e5.lookahead >= w && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + w - 1]) & e5.hash_mask, r3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart), 0 !== r3 && e5.strstart - r3 <= e5.w_size - x2 && (e5.match_length = D(e5, r3)), e5.match_length >= w) if (n3 = i2._tr_tally(e5, e5.strstart - e5.match_start, e5.match_length - w), e5.lookahead -= e5.match_length, e5.match_length <= e5.max_lazy_match && e5.lookahead >= w) {
        e5.match_length--;
        do {
          e5.strstart++, e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + w - 1]) & e5.hash_mask, r3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart;
        } while (0 != --e5.match_length);
        e5.strstart++;
      } else e5.strstart += e5.match_length, e5.match_length = 0, e5.ins_h = e5.window[e5.strstart], e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + 1]) & e5.hash_mask;
      else n3 = i2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++;
      if (n3 && (F(e5, false), 0 === e5.strm.avail_out)) return I;
    }
    return e5.insert = e5.strstart < w - 1 ? e5.strstart : w - 1, t3 === s2 ? (F(e5, true), 0 === e5.strm.avail_out ? T2 : P) : e5.last_lit && (F(e5, false), 0 === e5.strm.avail_out) ? I : M2;
  }
  function U(e5, t3) {
    for (var r3, n3, a3; ; ) {
      if (e5.lookahead < x2) {
        if ($(e5), e5.lookahead < x2 && t3 === o2) return I;
        if (0 === e5.lookahead) break;
      }
      if (r3 = 0, e5.lookahead >= w && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + w - 1]) & e5.hash_mask, r3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart), e5.prev_length = e5.match_length, e5.prev_match = e5.match_start, e5.match_length = w - 1, 0 !== r3 && e5.prev_length < e5.max_lazy_match && e5.strstart - r3 <= e5.w_size - x2 && (e5.match_length = D(e5, r3), e5.match_length <= 5 && (1 === e5.strategy || e5.match_length === w && e5.strstart - e5.match_start > 4096) && (e5.match_length = w - 1)), e5.prev_length >= w && e5.match_length <= e5.prev_length) {
        a3 = e5.strstart + e5.lookahead - w, n3 = i2._tr_tally(e5, e5.strstart - 1 - e5.prev_match, e5.prev_length - w), e5.lookahead -= e5.prev_length - 1, e5.prev_length -= 2;
        do {
          ++e5.strstart <= a3 && (e5.ins_h = (e5.ins_h << e5.hash_shift ^ e5.window[e5.strstart + w - 1]) & e5.hash_mask, r3 = e5.prev[e5.strstart & e5.w_mask] = e5.head[e5.ins_h], e5.head[e5.ins_h] = e5.strstart);
        } while (0 != --e5.prev_length);
        if (e5.match_available = 0, e5.match_length = w - 1, e5.strstart++, n3 && (F(e5, false), 0 === e5.strm.avail_out)) return I;
      } else if (e5.match_available) {
        if ((n3 = i2._tr_tally(e5, 0, e5.window[e5.strstart - 1])) && F(e5, false), e5.strstart++, e5.lookahead--, 0 === e5.strm.avail_out) return I;
      } else e5.match_available = 1, e5.strstart++, e5.lookahead--;
    }
    return e5.match_available && (n3 = i2._tr_tally(e5, 0, e5.window[e5.strstart - 1]), e5.match_available = 0), e5.insert = e5.strstart < w - 1 ? e5.strstart : w - 1, t3 === s2 ? (F(e5, true), 0 === e5.strm.avail_out ? T2 : P) : e5.last_lit && (F(e5, false), 0 === e5.strm.avail_out) ? I : M2;
  }
  function Z(e5, t3, i3, r3, n3) {
    this.good_length = e5, this.max_lazy = t3, this.nice_length = i3, this.max_chain = r3, this.func = n3;
  }
  function j() {
    this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = d, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new t2.Buf16(2 * b2), this.dyn_dtree = new t2.Buf16(2 * (2 * _2 + 1)), this.bl_tree = new t2.Buf16(2 * (2 * g + 1)), R2(this.dyn_ltree), R2(this.dyn_dtree), R2(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new t2.Buf16(y2 + 1), this.heap = new t2.Buf16(2 * m + 1), R2(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new t2.Buf16(2 * m + 1), R2(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0;
  }
  function G2(e5) {
    var t3;
    return e5 && e5.state ? (e5.total_in = e5.total_out = 0, e5.data_type = f2, (t3 = e5.state).pending = 0, t3.pending_out = 0, t3.wrap < 0 && (t3.wrap = -t3.wrap), t3.status = t3.wrap ? E2 : S2, e5.adler = 2 === t3.wrap ? 0 : 1, t3.last_flush = o2, i2._tr_init(t3), l2) : B2(e5, u2);
  }
  function H(t3) {
    var i3 = G2(t3);
    return i3 === l2 && function(t4) {
      t4.window_size = 2 * t4.w_size, R2(t4.head), t4.max_lazy_match = e4[t4.level].max_lazy, t4.good_match = e4[t4.level].good_length, t4.nice_match = e4[t4.level].nice_length, t4.max_chain_length = e4[t4.level].max_chain, t4.strstart = 0, t4.block_start = 0, t4.lookahead = 0, t4.insert = 0, t4.match_length = t4.prev_length = w - 1, t4.match_available = 0, t4.ins_h = 0;
    }(t3.state), i3;
  }
  function Q(e5, i3, r3, n3, a3, o3) {
    if (!e5) return u2;
    var s3 = 1;
    if (i3 === h2 && (i3 = 6), n3 < 0 ? (s3 = 0, n3 = -n3) : n3 > 15 && (s3 = 2, n3 -= 16), a3 < 1 || a3 > p2 || r3 !== d || n3 < 8 || n3 > 15 || i3 < 0 || i3 > 9 || o3 < 0 || o3 > c2) return B2(e5, u2);
    8 === n3 && (n3 = 9);
    var l3 = new j();
    return e5.state = l3, l3.strm = e5, l3.wrap = s3, l3.gzhead = null, l3.w_bits = n3, l3.w_size = 1 << l3.w_bits, l3.w_mask = l3.w_size - 1, l3.hash_bits = a3 + 7, l3.hash_size = 1 << l3.hash_bits, l3.hash_mask = l3.hash_size - 1, l3.hash_shift = ~~((l3.hash_bits + w - 1) / w), l3.window = new t2.Buf8(2 * l3.w_size), l3.head = new t2.Buf16(l3.hash_size), l3.prev = new t2.Buf16(l3.w_size), l3.lit_bufsize = 1 << a3 + 6, l3.pending_buf_size = 4 * l3.lit_bufsize, l3.pending_buf = new t2.Buf8(l3.pending_buf_size), l3.d_buf = 1 * l3.lit_bufsize, l3.l_buf = 3 * l3.lit_bufsize, l3.level = i3, l3.strategy = o3, l3.method = r3, H(e5);
  }
  return e4 = [new Z(0, 0, 0, 0, function(e5, t3) {
    var i3 = 65535;
    for (i3 > e5.pending_buf_size - 5 && (i3 = e5.pending_buf_size - 5); ; ) {
      if (e5.lookahead <= 1) {
        if ($(e5), 0 === e5.lookahead && t3 === o2) return I;
        if (0 === e5.lookahead) break;
      }
      e5.strstart += e5.lookahead, e5.lookahead = 0;
      var r3 = e5.block_start + i3;
      if ((0 === e5.strstart || e5.strstart >= r3) && (e5.lookahead = e5.strstart - r3, e5.strstart = r3, F(e5, false), 0 === e5.strm.avail_out)) return I;
      if (e5.strstart - e5.block_start >= e5.w_size - x2 && (F(e5, false), 0 === e5.strm.avail_out)) return I;
    }
    return e5.insert = 0, t3 === s2 ? (F(e5, true), 0 === e5.strm.avail_out ? T2 : P) : (e5.strstart > e5.block_start && (F(e5, false), e5.strm.avail_out), I);
  }), new Z(4, 4, 8, 4, L2), new Z(4, 5, 16, 8, L2), new Z(4, 6, 32, 32, L2), new Z(4, 4, 16, 16, U), new Z(8, 16, 32, 32, U), new Z(8, 16, 128, 128, U), new Z(8, 32, 128, 256, U), new Z(32, 128, 258, 1024, U), new Z(32, 258, 258, 4096, U)], deflate.deflateInit = function(e5, t3) {
    return Q(e5, t3, d, 15, 8, 0);
  }, deflate.deflateInit2 = Q, deflate.deflateReset = H, deflate.deflateResetKeep = G2, deflate.deflateSetHeader = function(e5, t3) {
    return e5 && e5.state ? 2 !== e5.state.wrap ? u2 : (e5.state.gzhead = t3, l2) : u2;
  }, deflate.deflate = function(t3, r3) {
    var a3, h3, c3, f3;
    if (!t3 || !t3.state || r3 > 5 || r3 < 0) return t3 ? B2(t3, u2) : u2;
    if (h3 = t3.state, !t3.output || !t3.input && 0 !== t3.avail_in || h3.status === A2 && r3 !== s2) return B2(t3, 0 === t3.avail_out ? -5 : u2);
    if (h3.strm = t3, a3 = h3.last_flush, h3.last_flush = r3, h3.status === E2) if (2 === h3.wrap) t3.adler = 0, N2(h3, 31), N2(h3, 139), N2(h3, 8), h3.gzhead ? (N2(h3, (h3.gzhead.text ? 1 : 0) + (h3.gzhead.hcrc ? 2 : 0) + (h3.gzhead.extra ? 4 : 0) + (h3.gzhead.name ? 8 : 0) + (h3.gzhead.comment ? 16 : 0)), N2(h3, 255 & h3.gzhead.time), N2(h3, h3.gzhead.time >> 8 & 255), N2(h3, h3.gzhead.time >> 16 & 255), N2(h3, h3.gzhead.time >> 24 & 255), N2(h3, 9 === h3.level ? 2 : h3.strategy >= 2 || h3.level < 2 ? 4 : 0), N2(h3, 255 & h3.gzhead.os), h3.gzhead.extra && h3.gzhead.extra.length && (N2(h3, 255 & h3.gzhead.extra.length), N2(h3, h3.gzhead.extra.length >> 8 & 255)), h3.gzhead.hcrc && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending, 0)), h3.gzindex = 0, h3.status = 69) : (N2(h3, 0), N2(h3, 0), N2(h3, 0), N2(h3, 0), N2(h3, 0), N2(h3, 9 === h3.level ? 2 : h3.strategy >= 2 || h3.level < 2 ? 4 : 0), N2(h3, 3), h3.status = S2);
    else {
      var p3 = d + (h3.w_bits - 8 << 4) << 8;
      p3 |= (h3.strategy >= 2 || h3.level < 2 ? 0 : h3.level < 6 ? 1 : 6 === h3.level ? 2 : 3) << 6, 0 !== h3.strstart && (p3 |= 32), p3 += 31 - p3 % 31, h3.status = S2, O2(h3, p3), 0 !== h3.strstart && (O2(h3, t3.adler >>> 16), O2(h3, 65535 & t3.adler)), t3.adler = 1;
    }
    if (69 === h3.status) if (h3.gzhead.extra) {
      for (c3 = h3.pending; h3.gzindex < (65535 & h3.gzhead.extra.length) && (h3.pending !== h3.pending_buf_size || (h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), z2(t3), c3 = h3.pending, h3.pending !== h3.pending_buf_size)); ) N2(h3, 255 & h3.gzhead.extra[h3.gzindex]), h3.gzindex++;
      h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), h3.gzindex === h3.gzhead.extra.length && (h3.gzindex = 0, h3.status = 73);
    } else h3.status = 73;
    if (73 === h3.status) if (h3.gzhead.name) {
      c3 = h3.pending;
      do {
        if (h3.pending === h3.pending_buf_size && (h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), z2(t3), c3 = h3.pending, h3.pending === h3.pending_buf_size)) {
          f3 = 1;
          break;
        }
        f3 = h3.gzindex < h3.gzhead.name.length ? 255 & h3.gzhead.name.charCodeAt(h3.gzindex++) : 0, N2(h3, f3);
      } while (0 !== f3);
      h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), 0 === f3 && (h3.gzindex = 0, h3.status = 91);
    } else h3.status = 91;
    if (91 === h3.status) if (h3.gzhead.comment) {
      c3 = h3.pending;
      do {
        if (h3.pending === h3.pending_buf_size && (h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), z2(t3), c3 = h3.pending, h3.pending === h3.pending_buf_size)) {
          f3 = 1;
          break;
        }
        f3 = h3.gzindex < h3.gzhead.comment.length ? 255 & h3.gzhead.comment.charCodeAt(h3.gzindex++) : 0, N2(h3, f3);
      } while (0 !== f3);
      h3.gzhead.hcrc && h3.pending > c3 && (t3.adler = n2(t3.adler, h3.pending_buf, h3.pending - c3, c3)), 0 === f3 && (h3.status = k2);
    } else h3.status = k2;
    if (h3.status === k2 && (h3.gzhead.hcrc ? (h3.pending + 2 > h3.pending_buf_size && z2(t3), h3.pending + 2 <= h3.pending_buf_size && (N2(h3, 255 & t3.adler), N2(h3, t3.adler >> 8 & 255), t3.adler = 0, h3.status = S2)) : h3.status = S2), 0 !== h3.pending) {
      if (z2(t3), 0 === t3.avail_out) return h3.last_flush = -1, l2;
    } else if (0 === t3.avail_in && C2(r3) <= C2(a3) && r3 !== s2) return B2(t3, -5);
    if (h3.status === A2 && 0 !== t3.avail_in) return B2(t3, -5);
    if (0 !== t3.avail_in || 0 !== h3.lookahead || r3 !== o2 && h3.status !== A2) {
      var m2 = 2 === h3.strategy ? function(e5, t4) {
        for (var r4; ; ) {
          if (0 === e5.lookahead && ($(e5), 0 === e5.lookahead)) {
            if (t4 === o2) return I;
            break;
          }
          if (e5.match_length = 0, r4 = i2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++, r4 && (F(e5, false), 0 === e5.strm.avail_out)) return I;
        }
        return e5.insert = 0, t4 === s2 ? (F(e5, true), 0 === e5.strm.avail_out ? T2 : P) : e5.last_lit && (F(e5, false), 0 === e5.strm.avail_out) ? I : M2;
      }(h3, r3) : 3 === h3.strategy ? function(e5, t4) {
        for (var r4, n3, a4, l3, u3 = e5.window; ; ) {
          if (e5.lookahead <= v2) {
            if ($(e5), e5.lookahead <= v2 && t4 === o2) return I;
            if (0 === e5.lookahead) break;
          }
          if (e5.match_length = 0, e5.lookahead >= w && e5.strstart > 0 && (n3 = u3[a4 = e5.strstart - 1]) === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4]) {
            l3 = e5.strstart + v2;
            do {
            } while (n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && n3 === u3[++a4] && a4 < l3);
            e5.match_length = v2 - (l3 - a4), e5.match_length > e5.lookahead && (e5.match_length = e5.lookahead);
          }
          if (e5.match_length >= w ? (r4 = i2._tr_tally(e5, 1, e5.match_length - w), e5.lookahead -= e5.match_length, e5.strstart += e5.match_length, e5.match_length = 0) : (r4 = i2._tr_tally(e5, 0, e5.window[e5.strstart]), e5.lookahead--, e5.strstart++), r4 && (F(e5, false), 0 === e5.strm.avail_out)) return I;
        }
        return e5.insert = 0, t4 === s2 ? (F(e5, true), 0 === e5.strm.avail_out ? T2 : P) : e5.last_lit && (F(e5, false), 0 === e5.strm.avail_out) ? I : M2;
      }(h3, r3) : e4[h3.level].func(h3, r3);
      if (m2 !== T2 && m2 !== P || (h3.status = A2), m2 === I || m2 === T2) return 0 === t3.avail_out && (h3.last_flush = -1), l2;
      if (m2 === M2 && (1 === r3 ? i2._tr_align(h3) : 5 !== r3 && (i2._tr_stored_block(h3, 0, 0, false), 3 === r3 && (R2(h3.head), 0 === h3.lookahead && (h3.strstart = 0, h3.block_start = 0, h3.insert = 0))), z2(t3), 0 === t3.avail_out)) return h3.last_flush = -1, l2;
    }
    return r3 !== s2 ? l2 : h3.wrap <= 0 ? 1 : (2 === h3.wrap ? (N2(h3, 255 & t3.adler), N2(h3, t3.adler >> 8 & 255), N2(h3, t3.adler >> 16 & 255), N2(h3, t3.adler >> 24 & 255), N2(h3, 255 & t3.total_in), N2(h3, t3.total_in >> 8 & 255), N2(h3, t3.total_in >> 16 & 255), N2(h3, t3.total_in >> 24 & 255)) : (O2(h3, t3.adler >>> 16), O2(h3, 65535 & t3.adler)), z2(t3), h3.wrap > 0 && (h3.wrap = -h3.wrap), 0 !== h3.pending ? l2 : 1);
  }, deflate.deflateEnd = function(e5) {
    var t3;
    return e5 && e5.state ? (t3 = e5.state.status) !== E2 && 69 !== t3 && 73 !== t3 && 91 !== t3 && t3 !== k2 && t3 !== S2 && t3 !== A2 ? B2(e5, u2) : (e5.state = null, t3 === S2 ? B2(e5, -3) : l2) : u2;
  }, deflate.deflateSetDictionary = function(e5, i3) {
    var n3, a3, o3, s3, h3, c3, f3, d2, p3 = i3.length;
    if (!e5 || !e5.state) return u2;
    if (2 === (s3 = (n3 = e5.state).wrap) || 1 === s3 && n3.status !== E2 || n3.lookahead) return u2;
    for (1 === s3 && (e5.adler = r2(e5.adler, i3, p3, 0)), n3.wrap = 0, p3 >= n3.w_size && (0 === s3 && (R2(n3.head), n3.strstart = 0, n3.block_start = 0, n3.insert = 0), d2 = new t2.Buf8(n3.w_size), t2.arraySet(d2, i3, p3 - n3.w_size, n3.w_size, 0), i3 = d2, p3 = n3.w_size), h3 = e5.avail_in, c3 = e5.next_in, f3 = e5.input, e5.avail_in = p3, e5.next_in = 0, e5.input = i3, $(n3); n3.lookahead >= w; ) {
      a3 = n3.strstart, o3 = n3.lookahead - (w - 1);
      do {
        n3.ins_h = (n3.ins_h << n3.hash_shift ^ n3.window[a3 + w - 1]) & n3.hash_mask, n3.prev[a3 & n3.w_mask] = n3.head[n3.ins_h], n3.head[n3.ins_h] = a3, a3++;
      } while (--o3);
      n3.strstart = a3, n3.lookahead = w - 1, $(n3);
    }
    return n3.strstart += n3.lookahead, n3.block_start = n3.strstart, n3.insert = n3.lookahead, n3.lookahead = 0, n3.match_length = n3.prev_length = w - 1, n3.match_available = 0, e5.next_in = c3, e5.input = f3, e5.avail_in = h3, n3.wrap = s3, l2;
  }, deflate.deflateInfo = "pako deflate (from Nodeca project)", deflate;
}
var strings = {}, hasRequiredStrings, zstream, hasRequiredZstream, hasRequiredDeflate;
function requireStrings() {
  if (hasRequiredStrings) return strings;
  hasRequiredStrings = 1;
  var e4 = requireCommon(), t2 = true, i2 = true;
  try {
    String.fromCharCode.apply(null, [0]);
  } catch (e5) {
    t2 = false;
  }
  try {
    String.fromCharCode.apply(null, new Uint8Array(1));
  } catch (e5) {
    i2 = false;
  }
  for (var r2 = new e4.Buf8(256), n2 = 0; n2 < 256; n2++) r2[n2] = n2 >= 252 ? 6 : n2 >= 248 ? 5 : n2 >= 240 ? 4 : n2 >= 224 ? 3 : n2 >= 192 ? 2 : 1;
  function a2(r3, n3) {
    if (n3 < 65534 && (r3.subarray && i2 || !r3.subarray && t2)) return String.fromCharCode.apply(null, e4.shrinkBuf(r3, n3));
    for (var a3 = "", o2 = 0; o2 < n3; o2++) a3 += String.fromCharCode(r3[o2]);
    return a3;
  }
  return r2[254] = r2[254] = 1, strings.string2buf = function(t3) {
    var i3, r3, n3, a3, o2, s2 = t3.length, l2 = 0;
    for (a3 = 0; a3 < s2; a3++) 55296 == (64512 & (r3 = t3.charCodeAt(a3))) && a3 + 1 < s2 && 56320 == (64512 & (n3 = t3.charCodeAt(a3 + 1))) && (r3 = 65536 + (r3 - 55296 << 10) + (n3 - 56320), a3++), l2 += r3 < 128 ? 1 : r3 < 2048 ? 2 : r3 < 65536 ? 3 : 4;
    for (i3 = new e4.Buf8(l2), o2 = 0, a3 = 0; o2 < l2; a3++) 55296 == (64512 & (r3 = t3.charCodeAt(a3))) && a3 + 1 < s2 && 56320 == (64512 & (n3 = t3.charCodeAt(a3 + 1))) && (r3 = 65536 + (r3 - 55296 << 10) + (n3 - 56320), a3++), r3 < 128 ? i3[o2++] = r3 : r3 < 2048 ? (i3[o2++] = 192 | r3 >>> 6, i3[o2++] = 128 | 63 & r3) : r3 < 65536 ? (i3[o2++] = 224 | r3 >>> 12, i3[o2++] = 128 | r3 >>> 6 & 63, i3[o2++] = 128 | 63 & r3) : (i3[o2++] = 240 | r3 >>> 18, i3[o2++] = 128 | r3 >>> 12 & 63, i3[o2++] = 128 | r3 >>> 6 & 63, i3[o2++] = 128 | 63 & r3);
    return i3;
  }, strings.buf2binstring = function(e5) {
    return a2(e5, e5.length);
  }, strings.binstring2buf = function(t3) {
    for (var i3 = new e4.Buf8(t3.length), r3 = 0, n3 = i3.length; r3 < n3; r3++) i3[r3] = t3.charCodeAt(r3);
    return i3;
  }, strings.buf2string = function(e5, t3) {
    var i3, n3, o2, s2, l2 = t3 || e5.length, u2 = new Array(2 * l2);
    for (n3 = 0, i3 = 0; i3 < l2; ) if ((o2 = e5[i3++]) < 128) u2[n3++] = o2;
    else if ((s2 = r2[o2]) > 4) u2[n3++] = 65533, i3 += s2 - 1;
    else {
      for (o2 &= 2 === s2 ? 31 : 3 === s2 ? 15 : 7; s2 > 1 && i3 < l2; ) o2 = o2 << 6 | 63 & e5[i3++], s2--;
      s2 > 1 ? u2[n3++] = 65533 : o2 < 65536 ? u2[n3++] = o2 : (o2 -= 65536, u2[n3++] = 55296 | o2 >> 10 & 1023, u2[n3++] = 56320 | 1023 & o2);
    }
    return a2(u2, n3);
  }, strings.utf8border = function(e5, t3) {
    var i3;
    for ((t3 = t3 || e5.length) > e5.length && (t3 = e5.length), i3 = t3 - 1; i3 >= 0 && 128 == (192 & e5[i3]); ) i3--;
    return i3 < 0 || 0 === i3 ? t3 : i3 + r2[e5[i3]] > t3 ? i3 : t3;
  }, strings;
}
function requireZstream() {
  if (hasRequiredZstream) return zstream;
  return hasRequiredZstream = 1, zstream = function() {
    this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0;
  };
}
function requireDeflate() {
  if (hasRequiredDeflate) return deflate$1;
  hasRequiredDeflate = 1;
  var e4 = requireDeflate$1(), t2 = requireCommon(), i2 = requireStrings(), r2 = requireMessages(), n2 = requireZstream(), a2 = Object.prototype.toString, o2 = 0, s2 = -1, l2 = 0, u2 = 8;
  function h2(c3) {
    if (!(this instanceof h2)) return new h2(c3);
    this.options = t2.assign({ level: s2, method: u2, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: l2, to: "" }, c3 || {});
    var f2 = this.options;
    f2.raw && f2.windowBits > 0 ? f2.windowBits = -f2.windowBits : f2.gzip && f2.windowBits > 0 && f2.windowBits < 16 && (f2.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new n2(), this.strm.avail_out = 0;
    var d = e4.deflateInit2(this.strm, f2.level, f2.method, f2.windowBits, f2.memLevel, f2.strategy);
    if (d !== o2) throw new Error(r2[d]);
    if (f2.header && e4.deflateSetHeader(this.strm, f2.header), f2.dictionary) {
      var p2;
      if (p2 = "string" == typeof f2.dictionary ? i2.string2buf(f2.dictionary) : "[object ArrayBuffer]" === a2.call(f2.dictionary) ? new Uint8Array(f2.dictionary) : f2.dictionary, (d = e4.deflateSetDictionary(this.strm, p2)) !== o2) throw new Error(r2[d]);
      this._dict_set = true;
    }
  }
  function c2(e5, t3) {
    var i3 = new h2(t3);
    if (i3.push(e5, true), i3.err) throw i3.msg || r2[i3.err];
    return i3.result;
  }
  return h2.prototype.push = function(r3, n3) {
    var s3, l3, u3 = this.strm, h3 = this.options.chunkSize;
    if (this.ended) return false;
    l3 = n3 === ~~n3 ? n3 : true === n3 ? 4 : 0, "string" == typeof r3 ? u3.input = i2.string2buf(r3) : "[object ArrayBuffer]" === a2.call(r3) ? u3.input = new Uint8Array(r3) : u3.input = r3, u3.next_in = 0, u3.avail_in = u3.input.length;
    do {
      if (0 === u3.avail_out && (u3.output = new t2.Buf8(h3), u3.next_out = 0, u3.avail_out = h3), 1 !== (s3 = e4.deflate(u3, l3)) && s3 !== o2) return this.onEnd(s3), this.ended = true, false;
      0 !== u3.avail_out && (0 !== u3.avail_in || 4 !== l3 && 2 !== l3) || ("string" === this.options.to ? this.onData(i2.buf2binstring(t2.shrinkBuf(u3.output, u3.next_out))) : this.onData(t2.shrinkBuf(u3.output, u3.next_out)));
    } while ((u3.avail_in > 0 || 0 === u3.avail_out) && 1 !== s3);
    return 4 === l3 ? (s3 = e4.deflateEnd(this.strm), this.onEnd(s3), this.ended = true, s3 === o2) : 2 !== l3 || (this.onEnd(o2), u3.avail_out = 0, true);
  }, h2.prototype.onData = function(e5) {
    this.chunks.push(e5);
  }, h2.prototype.onEnd = function(e5) {
    e5 === o2 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = t2.flattenChunks(this.chunks)), this.chunks = [], this.err = e5, this.msg = this.strm.msg;
  }, deflate$1.Deflate = h2, deflate$1.deflate = c2, deflate$1.deflateRaw = function(e5, t3) {
    return (t3 = t3 || {}).raw = true, c2(e5, t3);
  }, deflate$1.gzip = function(e5, t3) {
    return (t3 = t3 || {}).gzip = true, c2(e5, t3);
  }, deflate$1;
}
var inflate$1 = {}, inflate = {}, inffast, hasRequiredInffast, inftrees, hasRequiredInftrees, hasRequiredInflate$1, constants, hasRequiredConstants, gzheader, hasRequiredGzheader, hasRequiredInflate, pako_1, hasRequiredPako;
function requireInffast() {
  if (hasRequiredInffast) return inffast;
  hasRequiredInffast = 1;
  return inffast = function(e4, t2) {
    var i2, r2, n2, a2, o2, s2, l2, u2, h2, c2, f2, d, p2, m, _2, g, b2, y2, w, v2, x2, E2, k2, S2, A2;
    i2 = e4.state, r2 = e4.next_in, S2 = e4.input, n2 = r2 + (e4.avail_in - 5), a2 = e4.next_out, A2 = e4.output, o2 = a2 - (t2 - e4.avail_out), s2 = a2 + (e4.avail_out - 257), l2 = i2.dmax, u2 = i2.wsize, h2 = i2.whave, c2 = i2.wnext, f2 = i2.window, d = i2.hold, p2 = i2.bits, m = i2.lencode, _2 = i2.distcode, g = (1 << i2.lenbits) - 1, b2 = (1 << i2.distbits) - 1;
    e: do {
      p2 < 15 && (d += S2[r2++] << p2, p2 += 8, d += S2[r2++] << p2, p2 += 8), y2 = m[d & g];
      t: for (; ; ) {
        if (d >>>= w = y2 >>> 24, p2 -= w, 0 === (w = y2 >>> 16 & 255)) A2[a2++] = 65535 & y2;
        else {
          if (!(16 & w)) {
            if (64 & w) {
              if (32 & w) {
                i2.mode = 12;
                break e;
              }
              e4.msg = "invalid literal/length code", i2.mode = 30;
              break e;
            }
            y2 = m[(65535 & y2) + (d & (1 << w) - 1)];
            continue t;
          }
          for (v2 = 65535 & y2, (w &= 15) && (p2 < w && (d += S2[r2++] << p2, p2 += 8), v2 += d & (1 << w) - 1, d >>>= w, p2 -= w), p2 < 15 && (d += S2[r2++] << p2, p2 += 8, d += S2[r2++] << p2, p2 += 8), y2 = _2[d & b2]; ; ) {
            if (d >>>= w = y2 >>> 24, p2 -= w, 16 & (w = y2 >>> 16 & 255)) {
              if (x2 = 65535 & y2, p2 < (w &= 15) && (d += S2[r2++] << p2, (p2 += 8) < w && (d += S2[r2++] << p2, p2 += 8)), (x2 += d & (1 << w) - 1) > l2) {
                e4.msg = "invalid distance too far back", i2.mode = 30;
                break e;
              }
              if (d >>>= w, p2 -= w, x2 > (w = a2 - o2)) {
                if ((w = x2 - w) > h2 && i2.sane) {
                  e4.msg = "invalid distance too far back", i2.mode = 30;
                  break e;
                }
                if (E2 = 0, k2 = f2, 0 === c2) {
                  if (E2 += u2 - w, w < v2) {
                    v2 -= w;
                    do {
                      A2[a2++] = f2[E2++];
                    } while (--w);
                    E2 = a2 - x2, k2 = A2;
                  }
                } else if (c2 < w) {
                  if (E2 += u2 + c2 - w, (w -= c2) < v2) {
                    v2 -= w;
                    do {
                      A2[a2++] = f2[E2++];
                    } while (--w);
                    if (E2 = 0, c2 < v2) {
                      v2 -= w = c2;
                      do {
                        A2[a2++] = f2[E2++];
                      } while (--w);
                      E2 = a2 - x2, k2 = A2;
                    }
                  }
                } else if (E2 += c2 - w, w < v2) {
                  v2 -= w;
                  do {
                    A2[a2++] = f2[E2++];
                  } while (--w);
                  E2 = a2 - x2, k2 = A2;
                }
                for (; v2 > 2; ) A2[a2++] = k2[E2++], A2[a2++] = k2[E2++], A2[a2++] = k2[E2++], v2 -= 3;
                v2 && (A2[a2++] = k2[E2++], v2 > 1 && (A2[a2++] = k2[E2++]));
              } else {
                E2 = a2 - x2;
                do {
                  A2[a2++] = A2[E2++], A2[a2++] = A2[E2++], A2[a2++] = A2[E2++], v2 -= 3;
                } while (v2 > 2);
                v2 && (A2[a2++] = A2[E2++], v2 > 1 && (A2[a2++] = A2[E2++]));
              }
              break;
            }
            if (64 & w) {
              e4.msg = "invalid distance code", i2.mode = 30;
              break e;
            }
            y2 = _2[(65535 & y2) + (d & (1 << w) - 1)];
          }
        }
        break;
      }
    } while (r2 < n2 && a2 < s2);
    r2 -= v2 = p2 >> 3, d &= (1 << (p2 -= v2 << 3)) - 1, e4.next_in = r2, e4.next_out = a2, e4.avail_in = r2 < n2 ? n2 - r2 + 5 : 5 - (r2 - n2), e4.avail_out = a2 < s2 ? s2 - a2 + 257 : 257 - (a2 - s2), i2.hold = d, i2.bits = p2;
  }, inffast;
}
function requireInftrees() {
  if (hasRequiredInftrees) return inftrees;
  hasRequiredInftrees = 1;
  var e4 = requireCommon(), t2 = 15, i2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], r2 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], n2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], a2 = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64];
  return inftrees = function(o2, s2, l2, u2, h2, c2, f2, d) {
    var p2, m, _2, g, b2, y2, w, v2, x2, E2 = d.bits, k2 = 0, S2 = 0, A2 = 0, I = 0, M2 = 0, T2 = 0, P = 0, B2 = 0, C2 = 0, R2 = 0, z2 = null, F = 0, N2 = new e4.Buf16(16), O2 = new e4.Buf16(16), D = null, $ = 0;
    for (k2 = 0; k2 <= t2; k2++) N2[k2] = 0;
    for (S2 = 0; S2 < u2; S2++) N2[s2[l2 + S2]]++;
    for (M2 = E2, I = t2; I >= 1 && 0 === N2[I]; I--) ;
    if (M2 > I && (M2 = I), 0 === I) return h2[c2++] = 20971520, h2[c2++] = 20971520, d.bits = 1, 0;
    for (A2 = 1; A2 < I && 0 === N2[A2]; A2++) ;
    for (M2 < A2 && (M2 = A2), B2 = 1, k2 = 1; k2 <= t2; k2++) if (B2 <<= 1, (B2 -= N2[k2]) < 0) return -1;
    if (B2 > 0 && (0 === o2 || 1 !== I)) return -1;
    for (O2[1] = 0, k2 = 1; k2 < t2; k2++) O2[k2 + 1] = O2[k2] + N2[k2];
    for (S2 = 0; S2 < u2; S2++) 0 !== s2[l2 + S2] && (f2[O2[s2[l2 + S2]]++] = S2);
    if (0 === o2 ? (z2 = D = f2, y2 = 19) : 1 === o2 ? (z2 = i2, F -= 257, D = r2, $ -= 257, y2 = 256) : (z2 = n2, D = a2, y2 = -1), R2 = 0, S2 = 0, k2 = A2, b2 = c2, T2 = M2, P = 0, _2 = -1, g = (C2 = 1 << M2) - 1, 1 === o2 && C2 > 852 || 2 === o2 && C2 > 592) return 1;
    for (; ; ) {
      w = k2 - P, f2[S2] < y2 ? (v2 = 0, x2 = f2[S2]) : f2[S2] > y2 ? (v2 = D[$ + f2[S2]], x2 = z2[F + f2[S2]]) : (v2 = 96, x2 = 0), p2 = 1 << k2 - P, A2 = m = 1 << T2;
      do {
        h2[b2 + (R2 >> P) + (m -= p2)] = w << 24 | v2 << 16 | x2;
      } while (0 !== m);
      for (p2 = 1 << k2 - 1; R2 & p2; ) p2 >>= 1;
      if (0 !== p2 ? (R2 &= p2 - 1, R2 += p2) : R2 = 0, S2++, 0 == --N2[k2]) {
        if (k2 === I) break;
        k2 = s2[l2 + f2[S2]];
      }
      if (k2 > M2 && (R2 & g) !== _2) {
        for (0 === P && (P = M2), b2 += A2, B2 = 1 << (T2 = k2 - P); T2 + P < I && !((B2 -= N2[T2 + P]) <= 0); ) T2++, B2 <<= 1;
        if (C2 += 1 << T2, 1 === o2 && C2 > 852 || 2 === o2 && C2 > 592) return 1;
        h2[_2 = R2 & g] = M2 << 24 | T2 << 16 | b2 - c2;
      }
    }
    return 0 !== R2 && (h2[b2 + R2] = k2 - P << 24 | 64 << 16), d.bits = M2, 0;
  };
}
function requireInflate$1() {
  if (hasRequiredInflate$1) return inflate;
  hasRequiredInflate$1 = 1;
  var e4 = requireCommon(), t2 = requireAdler32(), i2 = requireCrc32(), r2 = requireInffast(), n2 = requireInftrees(), a2 = 1, o2 = 2, s2 = 0, l2 = -2, u2 = 1, h2 = 12, c2 = 30, f2 = 852, d = 592;
  function p2(e5) {
    return (e5 >>> 24 & 255) + (e5 >>> 8 & 65280) + ((65280 & e5) << 8) + ((255 & e5) << 24);
  }
  function m() {
    this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new e4.Buf16(320), this.work = new e4.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0;
  }
  function _2(t3) {
    var i3;
    return t3 && t3.state ? (i3 = t3.state, t3.total_in = t3.total_out = i3.total = 0, t3.msg = "", i3.wrap && (t3.adler = 1 & i3.wrap), i3.mode = u2, i3.last = 0, i3.havedict = 0, i3.dmax = 32768, i3.head = null, i3.hold = 0, i3.bits = 0, i3.lencode = i3.lendyn = new e4.Buf32(f2), i3.distcode = i3.distdyn = new e4.Buf32(d), i3.sane = 1, i3.back = -1, s2) : l2;
  }
  function g(e5) {
    var t3;
    return e5 && e5.state ? ((t3 = e5.state).wsize = 0, t3.whave = 0, t3.wnext = 0, _2(e5)) : l2;
  }
  function b2(e5, t3) {
    var i3, r3;
    return e5 && e5.state ? (r3 = e5.state, t3 < 0 ? (i3 = 0, t3 = -t3) : (i3 = 1 + (t3 >> 4), t3 < 48 && (t3 &= 15)), t3 && (t3 < 8 || t3 > 15) ? l2 : (null !== r3.window && r3.wbits !== t3 && (r3.window = null), r3.wrap = i3, r3.wbits = t3, g(e5))) : l2;
  }
  function y2(e5, t3) {
    var i3, r3;
    return e5 ? (r3 = new m(), e5.state = r3, r3.window = null, (i3 = b2(e5, t3)) !== s2 && (e5.state = null), i3) : l2;
  }
  var w, v2, x2 = true;
  function E2(t3) {
    if (x2) {
      var i3;
      for (w = new e4.Buf32(512), v2 = new e4.Buf32(32), i3 = 0; i3 < 144; ) t3.lens[i3++] = 8;
      for (; i3 < 256; ) t3.lens[i3++] = 9;
      for (; i3 < 280; ) t3.lens[i3++] = 7;
      for (; i3 < 288; ) t3.lens[i3++] = 8;
      for (n2(a2, t3.lens, 0, 288, w, 0, t3.work, { bits: 9 }), i3 = 0; i3 < 32; ) t3.lens[i3++] = 5;
      n2(o2, t3.lens, 0, 32, v2, 0, t3.work, { bits: 5 }), x2 = false;
    }
    t3.lencode = w, t3.lenbits = 9, t3.distcode = v2, t3.distbits = 5;
  }
  function k2(t3, i3, r3, n3) {
    var a3, o3 = t3.state;
    return null === o3.window && (o3.wsize = 1 << o3.wbits, o3.wnext = 0, o3.whave = 0, o3.window = new e4.Buf8(o3.wsize)), n3 >= o3.wsize ? (e4.arraySet(o3.window, i3, r3 - o3.wsize, o3.wsize, 0), o3.wnext = 0, o3.whave = o3.wsize) : ((a3 = o3.wsize - o3.wnext) > n3 && (a3 = n3), e4.arraySet(o3.window, i3, r3 - n3, a3, o3.wnext), (n3 -= a3) ? (e4.arraySet(o3.window, i3, r3 - n3, n3, 0), o3.wnext = n3, o3.whave = o3.wsize) : (o3.wnext += a3, o3.wnext === o3.wsize && (o3.wnext = 0), o3.whave < o3.wsize && (o3.whave += a3))), 0;
  }
  return inflate.inflateReset = g, inflate.inflateReset2 = b2, inflate.inflateResetKeep = _2, inflate.inflateInit = function(e5) {
    return y2(e5, 15);
  }, inflate.inflateInit2 = y2, inflate.inflate = function(f3, d2) {
    var m2, _3, g2, b3, y3, w2, v3, x3, S2, A2, I, M2, T2, P, B2, C2, R2, z2, F, N2, O2, D, $, L2, U = 0, Z = new e4.Buf8(4), j = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
    if (!f3 || !f3.state || !f3.output || !f3.input && 0 !== f3.avail_in) return l2;
    (m2 = f3.state).mode === h2 && (m2.mode = 13), y3 = f3.next_out, g2 = f3.output, v3 = f3.avail_out, b3 = f3.next_in, _3 = f3.input, w2 = f3.avail_in, x3 = m2.hold, S2 = m2.bits, A2 = w2, I = v3, D = s2;
    e: for (; ; ) switch (m2.mode) {
      case u2:
        if (0 === m2.wrap) {
          m2.mode = 13;
          break;
        }
        for (; S2 < 16; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if (2 & m2.wrap && 35615 === x3) {
          m2.check = 0, Z[0] = 255 & x3, Z[1] = x3 >>> 8 & 255, m2.check = i2(m2.check, Z, 2, 0), x3 = 0, S2 = 0, m2.mode = 2;
          break;
        }
        if (m2.flags = 0, m2.head && (m2.head.done = false), !(1 & m2.wrap) || (((255 & x3) << 8) + (x3 >> 8)) % 31) {
          f3.msg = "incorrect header check", m2.mode = c2;
          break;
        }
        if (8 != (15 & x3)) {
          f3.msg = "unknown compression method", m2.mode = c2;
          break;
        }
        if (S2 -= 4, O2 = 8 + (15 & (x3 >>>= 4)), 0 === m2.wbits) m2.wbits = O2;
        else if (O2 > m2.wbits) {
          f3.msg = "invalid window size", m2.mode = c2;
          break;
        }
        m2.dmax = 1 << O2, f3.adler = m2.check = 1, m2.mode = 512 & x3 ? 10 : h2, x3 = 0, S2 = 0;
        break;
      case 2:
        for (; S2 < 16; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if (m2.flags = x3, 8 != (255 & m2.flags)) {
          f3.msg = "unknown compression method", m2.mode = c2;
          break;
        }
        if (57344 & m2.flags) {
          f3.msg = "unknown header flags set", m2.mode = c2;
          break;
        }
        m2.head && (m2.head.text = x3 >> 8 & 1), 512 & m2.flags && (Z[0] = 255 & x3, Z[1] = x3 >>> 8 & 255, m2.check = i2(m2.check, Z, 2, 0)), x3 = 0, S2 = 0, m2.mode = 3;
      case 3:
        for (; S2 < 32; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        m2.head && (m2.head.time = x3), 512 & m2.flags && (Z[0] = 255 & x3, Z[1] = x3 >>> 8 & 255, Z[2] = x3 >>> 16 & 255, Z[3] = x3 >>> 24 & 255, m2.check = i2(m2.check, Z, 4, 0)), x3 = 0, S2 = 0, m2.mode = 4;
      case 4:
        for (; S2 < 16; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        m2.head && (m2.head.xflags = 255 & x3, m2.head.os = x3 >> 8), 512 & m2.flags && (Z[0] = 255 & x3, Z[1] = x3 >>> 8 & 255, m2.check = i2(m2.check, Z, 2, 0)), x3 = 0, S2 = 0, m2.mode = 5;
      case 5:
        if (1024 & m2.flags) {
          for (; S2 < 16; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          m2.length = x3, m2.head && (m2.head.extra_len = x3), 512 & m2.flags && (Z[0] = 255 & x3, Z[1] = x3 >>> 8 & 255, m2.check = i2(m2.check, Z, 2, 0)), x3 = 0, S2 = 0;
        } else m2.head && (m2.head.extra = null);
        m2.mode = 6;
      case 6:
        if (1024 & m2.flags && ((M2 = m2.length) > w2 && (M2 = w2), M2 && (m2.head && (O2 = m2.head.extra_len - m2.length, m2.head.extra || (m2.head.extra = new Array(m2.head.extra_len)), e4.arraySet(m2.head.extra, _3, b3, M2, O2)), 512 & m2.flags && (m2.check = i2(m2.check, _3, M2, b3)), w2 -= M2, b3 += M2, m2.length -= M2), m2.length)) break e;
        m2.length = 0, m2.mode = 7;
      case 7:
        if (2048 & m2.flags) {
          if (0 === w2) break e;
          M2 = 0;
          do {
            O2 = _3[b3 + M2++], m2.head && O2 && m2.length < 65536 && (m2.head.name += String.fromCharCode(O2));
          } while (O2 && M2 < w2);
          if (512 & m2.flags && (m2.check = i2(m2.check, _3, M2, b3)), w2 -= M2, b3 += M2, O2) break e;
        } else m2.head && (m2.head.name = null);
        m2.length = 0, m2.mode = 8;
      case 8:
        if (4096 & m2.flags) {
          if (0 === w2) break e;
          M2 = 0;
          do {
            O2 = _3[b3 + M2++], m2.head && O2 && m2.length < 65536 && (m2.head.comment += String.fromCharCode(O2));
          } while (O2 && M2 < w2);
          if (512 & m2.flags && (m2.check = i2(m2.check, _3, M2, b3)), w2 -= M2, b3 += M2, O2) break e;
        } else m2.head && (m2.head.comment = null);
        m2.mode = 9;
      case 9:
        if (512 & m2.flags) {
          for (; S2 < 16; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          if (x3 !== (65535 & m2.check)) {
            f3.msg = "header crc mismatch", m2.mode = c2;
            break;
          }
          x3 = 0, S2 = 0;
        }
        m2.head && (m2.head.hcrc = m2.flags >> 9 & 1, m2.head.done = true), f3.adler = m2.check = 0, m2.mode = h2;
        break;
      case 10:
        for (; S2 < 32; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        f3.adler = m2.check = p2(x3), x3 = 0, S2 = 0, m2.mode = 11;
      case 11:
        if (0 === m2.havedict) return f3.next_out = y3, f3.avail_out = v3, f3.next_in = b3, f3.avail_in = w2, m2.hold = x3, m2.bits = S2, 2;
        f3.adler = m2.check = 1, m2.mode = h2;
      case h2:
        if (5 === d2 || 6 === d2) break e;
      case 13:
        if (m2.last) {
          x3 >>>= 7 & S2, S2 -= 7 & S2, m2.mode = 27;
          break;
        }
        for (; S2 < 3; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        switch (m2.last = 1 & x3, S2 -= 1, 3 & (x3 >>>= 1)) {
          case 0:
            m2.mode = 14;
            break;
          case 1:
            if (E2(m2), m2.mode = 20, 6 === d2) {
              x3 >>>= 2, S2 -= 2;
              break e;
            }
            break;
          case 2:
            m2.mode = 17;
            break;
          case 3:
            f3.msg = "invalid block type", m2.mode = c2;
        }
        x3 >>>= 2, S2 -= 2;
        break;
      case 14:
        for (x3 >>>= 7 & S2, S2 -= 7 & S2; S2 < 32; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if ((65535 & x3) != (x3 >>> 16 ^ 65535)) {
          f3.msg = "invalid stored block lengths", m2.mode = c2;
          break;
        }
        if (m2.length = 65535 & x3, x3 = 0, S2 = 0, m2.mode = 15, 6 === d2) break e;
      case 15:
        m2.mode = 16;
      case 16:
        if (M2 = m2.length) {
          if (M2 > w2 && (M2 = w2), M2 > v3 && (M2 = v3), 0 === M2) break e;
          e4.arraySet(g2, _3, b3, M2, y3), w2 -= M2, b3 += M2, v3 -= M2, y3 += M2, m2.length -= M2;
          break;
        }
        m2.mode = h2;
        break;
      case 17:
        for (; S2 < 14; ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if (m2.nlen = 257 + (31 & x3), x3 >>>= 5, S2 -= 5, m2.ndist = 1 + (31 & x3), x3 >>>= 5, S2 -= 5, m2.ncode = 4 + (15 & x3), x3 >>>= 4, S2 -= 4, m2.nlen > 286 || m2.ndist > 30) {
          f3.msg = "too many length or distance symbols", m2.mode = c2;
          break;
        }
        m2.have = 0, m2.mode = 18;
      case 18:
        for (; m2.have < m2.ncode; ) {
          for (; S2 < 3; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          m2.lens[j[m2.have++]] = 7 & x3, x3 >>>= 3, S2 -= 3;
        }
        for (; m2.have < 19; ) m2.lens[j[m2.have++]] = 0;
        if (m2.lencode = m2.lendyn, m2.lenbits = 7, $ = { bits: m2.lenbits }, D = n2(0, m2.lens, 0, 19, m2.lencode, 0, m2.work, $), m2.lenbits = $.bits, D) {
          f3.msg = "invalid code lengths set", m2.mode = c2;
          break;
        }
        m2.have = 0, m2.mode = 19;
      case 19:
        for (; m2.have < m2.nlen + m2.ndist; ) {
          for (; C2 = (U = m2.lencode[x3 & (1 << m2.lenbits) - 1]) >>> 16 & 255, R2 = 65535 & U, !((B2 = U >>> 24) <= S2); ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          if (R2 < 16) x3 >>>= B2, S2 -= B2, m2.lens[m2.have++] = R2;
          else {
            if (16 === R2) {
              for (L2 = B2 + 2; S2 < L2; ) {
                if (0 === w2) break e;
                w2--, x3 += _3[b3++] << S2, S2 += 8;
              }
              if (x3 >>>= B2, S2 -= B2, 0 === m2.have) {
                f3.msg = "invalid bit length repeat", m2.mode = c2;
                break;
              }
              O2 = m2.lens[m2.have - 1], M2 = 3 + (3 & x3), x3 >>>= 2, S2 -= 2;
            } else if (17 === R2) {
              for (L2 = B2 + 3; S2 < L2; ) {
                if (0 === w2) break e;
                w2--, x3 += _3[b3++] << S2, S2 += 8;
              }
              S2 -= B2, O2 = 0, M2 = 3 + (7 & (x3 >>>= B2)), x3 >>>= 3, S2 -= 3;
            } else {
              for (L2 = B2 + 7; S2 < L2; ) {
                if (0 === w2) break e;
                w2--, x3 += _3[b3++] << S2, S2 += 8;
              }
              S2 -= B2, O2 = 0, M2 = 11 + (127 & (x3 >>>= B2)), x3 >>>= 7, S2 -= 7;
            }
            if (m2.have + M2 > m2.nlen + m2.ndist) {
              f3.msg = "invalid bit length repeat", m2.mode = c2;
              break;
            }
            for (; M2--; ) m2.lens[m2.have++] = O2;
          }
        }
        if (m2.mode === c2) break;
        if (0 === m2.lens[256]) {
          f3.msg = "invalid code -- missing end-of-block", m2.mode = c2;
          break;
        }
        if (m2.lenbits = 9, $ = { bits: m2.lenbits }, D = n2(a2, m2.lens, 0, m2.nlen, m2.lencode, 0, m2.work, $), m2.lenbits = $.bits, D) {
          f3.msg = "invalid literal/lengths set", m2.mode = c2;
          break;
        }
        if (m2.distbits = 6, m2.distcode = m2.distdyn, $ = { bits: m2.distbits }, D = n2(o2, m2.lens, m2.nlen, m2.ndist, m2.distcode, 0, m2.work, $), m2.distbits = $.bits, D) {
          f3.msg = "invalid distances set", m2.mode = c2;
          break;
        }
        if (m2.mode = 20, 6 === d2) break e;
      case 20:
        m2.mode = 21;
      case 21:
        if (w2 >= 6 && v3 >= 258) {
          f3.next_out = y3, f3.avail_out = v3, f3.next_in = b3, f3.avail_in = w2, m2.hold = x3, m2.bits = S2, r2(f3, I), y3 = f3.next_out, g2 = f3.output, v3 = f3.avail_out, b3 = f3.next_in, _3 = f3.input, w2 = f3.avail_in, x3 = m2.hold, S2 = m2.bits, m2.mode === h2 && (m2.back = -1);
          break;
        }
        for (m2.back = 0; C2 = (U = m2.lencode[x3 & (1 << m2.lenbits) - 1]) >>> 16 & 255, R2 = 65535 & U, !((B2 = U >>> 24) <= S2); ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if (C2 && !(240 & C2)) {
          for (z2 = B2, F = C2, N2 = R2; C2 = (U = m2.lencode[N2 + ((x3 & (1 << z2 + F) - 1) >> z2)]) >>> 16 & 255, R2 = 65535 & U, !(z2 + (B2 = U >>> 24) <= S2); ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          x3 >>>= z2, S2 -= z2, m2.back += z2;
        }
        if (x3 >>>= B2, S2 -= B2, m2.back += B2, m2.length = R2, 0 === C2) {
          m2.mode = 26;
          break;
        }
        if (32 & C2) {
          m2.back = -1, m2.mode = h2;
          break;
        }
        if (64 & C2) {
          f3.msg = "invalid literal/length code", m2.mode = c2;
          break;
        }
        m2.extra = 15 & C2, m2.mode = 22;
      case 22:
        if (m2.extra) {
          for (L2 = m2.extra; S2 < L2; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          m2.length += x3 & (1 << m2.extra) - 1, x3 >>>= m2.extra, S2 -= m2.extra, m2.back += m2.extra;
        }
        m2.was = m2.length, m2.mode = 23;
      case 23:
        for (; C2 = (U = m2.distcode[x3 & (1 << m2.distbits) - 1]) >>> 16 & 255, R2 = 65535 & U, !((B2 = U >>> 24) <= S2); ) {
          if (0 === w2) break e;
          w2--, x3 += _3[b3++] << S2, S2 += 8;
        }
        if (!(240 & C2)) {
          for (z2 = B2, F = C2, N2 = R2; C2 = (U = m2.distcode[N2 + ((x3 & (1 << z2 + F) - 1) >> z2)]) >>> 16 & 255, R2 = 65535 & U, !(z2 + (B2 = U >>> 24) <= S2); ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          x3 >>>= z2, S2 -= z2, m2.back += z2;
        }
        if (x3 >>>= B2, S2 -= B2, m2.back += B2, 64 & C2) {
          f3.msg = "invalid distance code", m2.mode = c2;
          break;
        }
        m2.offset = R2, m2.extra = 15 & C2, m2.mode = 24;
      case 24:
        if (m2.extra) {
          for (L2 = m2.extra; S2 < L2; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          m2.offset += x3 & (1 << m2.extra) - 1, x3 >>>= m2.extra, S2 -= m2.extra, m2.back += m2.extra;
        }
        if (m2.offset > m2.dmax) {
          f3.msg = "invalid distance too far back", m2.mode = c2;
          break;
        }
        m2.mode = 25;
      case 25:
        if (0 === v3) break e;
        if (M2 = I - v3, m2.offset > M2) {
          if ((M2 = m2.offset - M2) > m2.whave && m2.sane) {
            f3.msg = "invalid distance too far back", m2.mode = c2;
            break;
          }
          M2 > m2.wnext ? (M2 -= m2.wnext, T2 = m2.wsize - M2) : T2 = m2.wnext - M2, M2 > m2.length && (M2 = m2.length), P = m2.window;
        } else P = g2, T2 = y3 - m2.offset, M2 = m2.length;
        M2 > v3 && (M2 = v3), v3 -= M2, m2.length -= M2;
        do {
          g2[y3++] = P[T2++];
        } while (--M2);
        0 === m2.length && (m2.mode = 21);
        break;
      case 26:
        if (0 === v3) break e;
        g2[y3++] = m2.length, v3--, m2.mode = 21;
        break;
      case 27:
        if (m2.wrap) {
          for (; S2 < 32; ) {
            if (0 === w2) break e;
            w2--, x3 |= _3[b3++] << S2, S2 += 8;
          }
          if (I -= v3, f3.total_out += I, m2.total += I, I && (f3.adler = m2.check = m2.flags ? i2(m2.check, g2, I, y3 - I) : t2(m2.check, g2, I, y3 - I)), I = v3, (m2.flags ? x3 : p2(x3)) !== m2.check) {
            f3.msg = "incorrect data check", m2.mode = c2;
            break;
          }
          x3 = 0, S2 = 0;
        }
        m2.mode = 28;
      case 28:
        if (m2.wrap && m2.flags) {
          for (; S2 < 32; ) {
            if (0 === w2) break e;
            w2--, x3 += _3[b3++] << S2, S2 += 8;
          }
          if (x3 !== (4294967295 & m2.total)) {
            f3.msg = "incorrect length check", m2.mode = c2;
            break;
          }
          x3 = 0, S2 = 0;
        }
        m2.mode = 29;
      case 29:
        D = 1;
        break e;
      case c2:
        D = -3;
        break e;
      case 31:
        return -4;
      default:
        return l2;
    }
    return f3.next_out = y3, f3.avail_out = v3, f3.next_in = b3, f3.avail_in = w2, m2.hold = x3, m2.bits = S2, (m2.wsize || I !== f3.avail_out && m2.mode < c2 && (m2.mode < 27 || 4 !== d2)) && k2(f3, f3.output, f3.next_out, I - f3.avail_out), A2 -= f3.avail_in, I -= f3.avail_out, f3.total_in += A2, f3.total_out += I, m2.total += I, m2.wrap && I && (f3.adler = m2.check = m2.flags ? i2(m2.check, g2, I, f3.next_out - I) : t2(m2.check, g2, I, f3.next_out - I)), f3.data_type = m2.bits + (m2.last ? 64 : 0) + (m2.mode === h2 ? 128 : 0) + (20 === m2.mode || 15 === m2.mode ? 256 : 0), (0 === A2 && 0 === I || 4 === d2) && D === s2 && (D = -5), D;
  }, inflate.inflateEnd = function(e5) {
    if (!e5 || !e5.state) return l2;
    var t3 = e5.state;
    return t3.window && (t3.window = null), e5.state = null, s2;
  }, inflate.inflateGetHeader = function(e5, t3) {
    var i3;
    return e5 && e5.state && 2 & (i3 = e5.state).wrap ? (i3.head = t3, t3.done = false, s2) : l2;
  }, inflate.inflateSetDictionary = function(e5, i3) {
    var r3, n3 = i3.length;
    return e5 && e5.state ? 0 !== (r3 = e5.state).wrap && 11 !== r3.mode ? l2 : 11 === r3.mode && t2(1, i3, n3, 0) !== r3.check ? -3 : k2(e5, i3, n3, n3) ? (r3.mode = 31, -4) : (r3.havedict = 1, s2) : l2;
  }, inflate.inflateInfo = "pako inflate (from Nodeca project)", inflate;
}
function requireConstants() {
  return hasRequiredConstants ? constants : (hasRequiredConstants = 1, constants = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 });
}
function requireGzheader() {
  if (hasRequiredGzheader) return gzheader;
  return hasRequiredGzheader = 1, gzheader = function() {
    this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false;
  };
}
function requireInflate() {
  if (hasRequiredInflate) return inflate$1;
  hasRequiredInflate = 1;
  var e4 = requireInflate$1(), t2 = requireCommon(), i2 = requireStrings(), r2 = requireConstants(), n2 = requireMessages(), a2 = requireZstream(), o2 = requireGzheader(), s2 = Object.prototype.toString;
  function l2(u3) {
    if (!(this instanceof l2)) return new l2(u3);
    this.options = t2.assign({ chunkSize: 16384, windowBits: 0, to: "" }, u3 || {});
    var h2 = this.options;
    h2.raw && h2.windowBits >= 0 && h2.windowBits < 16 && (h2.windowBits = -h2.windowBits, 0 === h2.windowBits && (h2.windowBits = -15)), !(h2.windowBits >= 0 && h2.windowBits < 16) || u3 && u3.windowBits || (h2.windowBits += 32), h2.windowBits > 15 && h2.windowBits < 48 && (15 & h2.windowBits || (h2.windowBits |= 15)), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new a2(), this.strm.avail_out = 0;
    var c2 = e4.inflateInit2(this.strm, h2.windowBits);
    if (c2 !== r2.Z_OK) throw new Error(n2[c2]);
    if (this.header = new o2(), e4.inflateGetHeader(this.strm, this.header), h2.dictionary && ("string" == typeof h2.dictionary ? h2.dictionary = i2.string2buf(h2.dictionary) : "[object ArrayBuffer]" === s2.call(h2.dictionary) && (h2.dictionary = new Uint8Array(h2.dictionary)), h2.raw && (c2 = e4.inflateSetDictionary(this.strm, h2.dictionary)) !== r2.Z_OK)) throw new Error(n2[c2]);
  }
  function u2(e5, t3) {
    var i3 = new l2(t3);
    if (i3.push(e5, true), i3.err) throw i3.msg || n2[i3.err];
    return i3.result;
  }
  return l2.prototype.push = function(n3, a3) {
    var o3, l3, u3, h2, c2, f2 = this.strm, d = this.options.chunkSize, p2 = this.options.dictionary, m = false;
    if (this.ended) return false;
    l3 = a3 === ~~a3 ? a3 : true === a3 ? r2.Z_FINISH : r2.Z_NO_FLUSH, "string" == typeof n3 ? f2.input = i2.binstring2buf(n3) : "[object ArrayBuffer]" === s2.call(n3) ? f2.input = new Uint8Array(n3) : f2.input = n3, f2.next_in = 0, f2.avail_in = f2.input.length;
    do {
      if (0 === f2.avail_out && (f2.output = new t2.Buf8(d), f2.next_out = 0, f2.avail_out = d), (o3 = e4.inflate(f2, r2.Z_NO_FLUSH)) === r2.Z_NEED_DICT && p2 && (o3 = e4.inflateSetDictionary(this.strm, p2)), o3 === r2.Z_BUF_ERROR && true === m && (o3 = r2.Z_OK, m = false), o3 !== r2.Z_STREAM_END && o3 !== r2.Z_OK) return this.onEnd(o3), this.ended = true, false;
      f2.next_out && (0 !== f2.avail_out && o3 !== r2.Z_STREAM_END && (0 !== f2.avail_in || l3 !== r2.Z_FINISH && l3 !== r2.Z_SYNC_FLUSH) || ("string" === this.options.to ? (u3 = i2.utf8border(f2.output, f2.next_out), h2 = f2.next_out - u3, c2 = i2.buf2string(f2.output, u3), f2.next_out = h2, f2.avail_out = d - h2, h2 && t2.arraySet(f2.output, f2.output, u3, h2, 0), this.onData(c2)) : this.onData(t2.shrinkBuf(f2.output, f2.next_out)))), 0 === f2.avail_in && 0 === f2.avail_out && (m = true);
    } while ((f2.avail_in > 0 || 0 === f2.avail_out) && o3 !== r2.Z_STREAM_END);
    return o3 === r2.Z_STREAM_END && (l3 = r2.Z_FINISH), l3 === r2.Z_FINISH ? (o3 = e4.inflateEnd(this.strm), this.onEnd(o3), this.ended = true, o3 === r2.Z_OK) : l3 !== r2.Z_SYNC_FLUSH || (this.onEnd(r2.Z_OK), f2.avail_out = 0, true);
  }, l2.prototype.onData = function(e5) {
    this.chunks.push(e5);
  }, l2.prototype.onEnd = function(e5) {
    e5 === r2.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = t2.flattenChunks(this.chunks)), this.chunks = [], this.err = e5, this.msg = this.strm.msg;
  }, inflate$1.Inflate = l2, inflate$1.inflate = u2, inflate$1.inflateRaw = function(e5, t3) {
    return (t3 = t3 || {}).raw = true, u2(e5, t3);
  }, inflate$1.ungzip = u2, inflate$1;
}
function requirePako() {
  if (hasRequiredPako) return pako_1;
  hasRequiredPako = 1;
  var e4 = {};
  return (0, requireCommon().assign)(e4, requireDeflate(), requireInflate(), requireConstants()), pako_1 = e4;
}
!function(e4) {
  !function() {
    var t2 = {};
    function i2() {
      console.log.apply(console, arguments);
    }
    e4.exports = t2, function(e5, t3) {
      !function() {
        var t4 = function() {
          function e6(e7) {
            this.message = "JPEG error: " + e7;
          }
          return e6.prototype = new Error(), e6.prototype.name = "JpegError", e6.constructor = e6, e6;
        }(), i3 = function() {
          var e6 = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), i4 = 4017, n2 = 799, a2 = 3406, o2 = 2276, s2 = 1567, l2 = 3784, u2 = 5793, h2 = 2896;
          function c2(e7) {
            null == e7 && (e7 = {}), null == e7.w && (e7.w = -1), this.V = e7.n, this.N = e7.w;
          }
          function f2(e7, t5) {
            for (var i5, r3, n3, a3 = 0, o3 = [], s3 = 16; s3 > 0 && !e7[s3 - 1]; ) s3--;
            o3.push({ children: [], index: 0 });
            var l3 = o3[0];
            for (i5 = 0; i5 < s3; i5++) {
              for (r3 = 0; r3 < e7[i5]; r3++) {
                for ((l3 = o3.pop()).children[l3.index] = t5[a3]; l3.index > 0; ) l3 = o3.pop();
                for (l3.index++, o3.push(l3); o3.length <= i5; ) o3.push(n3 = { children: [], index: 0 }), l3.children[l3.index] = n3.children, l3 = n3;
                a3++;
              }
              i5 + 1 < s3 && (o3.push(n3 = { children: [], index: 0 }), l3.children[l3.index] = n3.children, l3 = n3);
            }
            return o3[0].children;
          }
          function d(e7, t5, i5) {
            return 64 * ((e7.P + 1) * t5 + i5);
          }
          function p2(i5, n3, a3, o3, s3, l3, u3, h3, c3, f3) {
            null == f3 && (f3 = false);
            var p3, m2, _3, b2, y2, w, v2, x2, E2, k2, S2, A2 = a3.m, I = a3.Z, M2 = n3, T2 = 0, P = 0, B2 = 0, C2 = 0, R2 = 0, z2 = 0;
            function F() {
              if (P > 0) return P--, T2 >> P & 1;
              if (255 === (T2 = i5[n3++])) {
                var e7 = i5[n3++];
                if (e7) {
                  if (220 === e7 && f3) {
                    var o4 = r2(i5, n3 += 2);
                    if (n3 += 2, o4 > 0 && o4 !== a3.s) throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", o4);
                  } else if (217 === e7) {
                    if (f3) {
                      var s4 = 8 * R2;
                      if (s4 > 0 && s4 < a3.s / 10) throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter", s4);
                    }
                    throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data");
                  }
                  throw new t4("unexpected marker");
                }
              }
              return P = 7, T2 >>> 7;
            }
            function N2(e7) {
              for (var i6 = e7; ; ) {
                switch (typeof (i6 = i6[F()])) {
                  case "number":
                    return i6;
                  case "object":
                    continue;
                }
                throw new t4("invalid huffman sequence");
              }
            }
            function O2(e7) {
              for (var t5 = 0; e7 > 0; ) t5 = t5 << 1 | F(), e7--;
              return t5;
            }
            function D(e7) {
              if (1 === e7) return 1 === F() ? 1 : -1;
              var t5 = O2(e7);
              return t5 >= 1 << e7 - 1 ? t5 : t5 + (-1 << e7) + 1;
            }
            function $(e7, t5, i6, r3, n4) {
              var a4 = i6 % A2;
              R2 = (i6 / A2 | 0) * e7.A + r3;
              var o4 = a4 * e7.h + n4;
              t5(e7, d(e7, R2, o4));
            }
            function L2(e7, t5, i6) {
              R2 = i6 / e7.P | 0;
              var r3 = i6 % e7.P;
              t5(e7, d(e7, R2, r3));
            }
            var U = o3.length;
            for (v2 = I ? 0 === l3 ? 0 === h3 ? function(e7, t5) {
              var i6 = N2(e7.J), r3 = 0 === i6 ? 0 : D(i6) << c3;
              e7.D[t5] = e7.Q += r3;
            } : function(e7, t5) {
              e7.D[t5] |= F() << c3;
            } : 0 === h3 ? function(t5, i6) {
              if (B2 > 0) B2--;
              else for (var r3 = l3, n4 = u3; r3 <= n4; ) {
                var a4 = N2(t5.i), o4 = 15 & a4, s4 = a4 >> 4;
                if (0 !== o4) {
                  var h4 = e6[r3 += s4];
                  t5.D[i6 + h4] = D(o4) * (1 << c3), r3++;
                } else {
                  if (s4 < 15) {
                    B2 = O2(s4) + (1 << s4) - 1;
                    break;
                  }
                  r3 += 16;
                }
              }
            } : function(i6, r3) {
              for (var n4, a4, o4 = l3, s4 = u3, h4 = 0; o4 <= s4; ) {
                var f4 = r3 + e6[o4], d2 = i6.D[f4] < 0 ? -1 : 1;
                switch (C2) {
                  case 0:
                    if (h4 = (a4 = N2(i6.i)) >> 4, 0 == (n4 = 15 & a4)) h4 < 15 ? (B2 = O2(h4) + (1 << h4), C2 = 4) : (h4 = 16, C2 = 1);
                    else {
                      if (1 !== n4) throw new t4("invalid ACn encoding");
                      p3 = D(n4), C2 = h4 ? 2 : 3;
                    }
                    continue;
                  case 1:
                  case 2:
                    i6.D[f4] ? i6.D[f4] += d2 * (F() << c3) : 0 == --h4 && (C2 = 2 === C2 ? 3 : 0);
                    break;
                  case 3:
                    i6.D[f4] ? i6.D[f4] += d2 * (F() << c3) : (i6.D[f4] = p3 << c3, C2 = 0);
                    break;
                  case 4:
                    i6.D[f4] && (i6.D[f4] += d2 * (F() << c3));
                }
                o4++;
              }
              4 === C2 && 0 == --B2 && (C2 = 0);
            } : function(t5, i6) {
              var r3 = N2(t5.J), n4 = 0 === r3 ? 0 : D(r3), a4 = 1;
              for (t5.D[i6] = t5.Q += n4; a4 < 64; ) {
                var o4 = N2(t5.i), s4 = 15 & o4, l4 = o4 >> 4;
                if (0 !== s4) {
                  var u4 = e6[a4 += l4];
                  t5.D[i6 + u4] = D(s4), a4++;
                } else {
                  if (l4 < 15) break;
                  a4 += 16;
                }
              }
            }, E2 = 1 === U ? o3[0].P * o3[0].c : A2 * a3.R; z2 <= E2; ) {
              var Z = s3 ? Math.min(E2 - z2, s3) : E2;
              if (Z > 0) {
                for (_3 = 0; _3 < U; _3++) o3[_3].Q = 0;
                if (B2 = 0, 1 === U) for (m2 = o3[0], w = 0; w < Z; w++) L2(m2, v2, z2), z2++;
                else for (w = 0; w < Z; w++) {
                  for (_3 = 0; _3 < U; _3++) for (k2 = (m2 = o3[_3]).h, S2 = m2.A, b2 = 0; b2 < S2; b2++) for (y2 = 0; y2 < k2; y2++) $(m2, v2, z2, b2, y2);
                  z2++;
                }
              }
              if (P = 0, !(x2 = g(i5, n3))) break;
              if (x2.u && (n3 = x2.offset), !(x2.M >= 65488 && x2.M <= 65495)) break;
              n3 += 2;
            }
            return n3 - M2;
          }
          function m(e7, r3, c3) {
            var f3, d2, p3, m2, _3, g2, b2, y2, w, v2, x2, E2, k2, S2, A2, I, M2, T2 = e7.$, P = e7.D;
            if (!T2) throw new t4("missing required Quantization Table.");
            for (var B2 = 0; B2 < 64; B2 += 8) w = P[r3 + B2], v2 = P[r3 + B2 + 1], x2 = P[r3 + B2 + 2], E2 = P[r3 + B2 + 3], k2 = P[r3 + B2 + 4], S2 = P[r3 + B2 + 5], A2 = P[r3 + B2 + 6], I = P[r3 + B2 + 7], w *= T2[B2], v2 | x2 | E2 | k2 | S2 | A2 | I ? (v2 *= T2[B2 + 1], x2 *= T2[B2 + 2], E2 *= T2[B2 + 3], k2 *= T2[B2 + 4], S2 *= T2[B2 + 5], A2 *= T2[B2 + 6], I *= T2[B2 + 7], d2 = (f3 = (f3 = u2 * w + 128 >> 8) + (d2 = u2 * k2 + 128 >> 8) + 1 >> 1) - d2, M2 = (p3 = x2) * l2 + (m2 = A2) * s2 + 128 >> 8, p3 = p3 * s2 - m2 * l2 + 128 >> 8, b2 = (_3 = (_3 = h2 * (v2 - I) + 128 >> 8) + (b2 = S2 << 4) + 1 >> 1) - b2, g2 = (y2 = (y2 = h2 * (v2 + I) + 128 >> 8) + (g2 = E2 << 4) + 1 >> 1) - g2, m2 = (f3 = f3 + (m2 = M2) + 1 >> 1) - m2, p3 = (d2 = d2 + p3 + 1 >> 1) - p3, M2 = _3 * o2 + y2 * a2 + 2048 >> 12, _3 = _3 * a2 - y2 * o2 + 2048 >> 12, y2 = M2, M2 = g2 * n2 + b2 * i4 + 2048 >> 12, g2 = g2 * i4 - b2 * n2 + 2048 >> 12, b2 = M2, c3[B2] = f3 + y2, c3[B2 + 7] = f3 - y2, c3[B2 + 1] = d2 + b2, c3[B2 + 6] = d2 - b2, c3[B2 + 2] = p3 + g2, c3[B2 + 5] = p3 - g2, c3[B2 + 3] = m2 + _3, c3[B2 + 4] = m2 - _3) : (M2 = u2 * w + 512 >> 10, c3[B2] = M2, c3[B2 + 1] = M2, c3[B2 + 2] = M2, c3[B2 + 3] = M2, c3[B2 + 4] = M2, c3[B2 + 5] = M2, c3[B2 + 6] = M2, c3[B2 + 7] = M2);
            for (var C2 = 0; C2 < 8; ++C2) w = c3[C2], (v2 = c3[C2 + 8]) | (x2 = c3[C2 + 16]) | (E2 = c3[C2 + 24]) | (k2 = c3[C2 + 32]) | (S2 = c3[C2 + 40]) | (A2 = c3[C2 + 48]) | (I = c3[C2 + 56]) ? (d2 = (f3 = 4112 + ((f3 = u2 * w + 2048 >> 12) + (d2 = u2 * k2 + 2048 >> 12) + 1 >> 1)) - d2, M2 = (p3 = x2) * l2 + (m2 = A2) * s2 + 2048 >> 12, p3 = p3 * s2 - m2 * l2 + 2048 >> 12, m2 = M2, b2 = (_3 = (_3 = h2 * (v2 - I) + 2048 >> 12) + (b2 = S2) + 1 >> 1) - b2, g2 = (y2 = (y2 = h2 * (v2 + I) + 2048 >> 12) + (g2 = E2) + 1 >> 1) - g2, M2 = _3 * o2 + y2 * a2 + 2048 >> 12, _3 = _3 * a2 - y2 * o2 + 2048 >> 12, y2 = M2, M2 = g2 * n2 + b2 * i4 + 2048 >> 12, g2 = g2 * i4 - b2 * n2 + 2048 >> 12, (w = (f3 = f3 + m2 + 1 >> 1) + y2) < 16 ? w = 0 : w >= 4080 ? w = 255 : w >>= 4, (v2 = (d2 = d2 + p3 + 1 >> 1) + (b2 = M2)) < 16 ? v2 = 0 : v2 >= 4080 ? v2 = 255 : v2 >>= 4, (x2 = (p3 = d2 - p3) + g2) < 16 ? x2 = 0 : x2 >= 4080 ? x2 = 255 : x2 >>= 4, (E2 = (m2 = f3 - m2) + _3) < 16 ? E2 = 0 : E2 >= 4080 ? E2 = 255 : E2 >>= 4, (k2 = m2 - _3) < 16 ? k2 = 0 : k2 >= 4080 ? k2 = 255 : k2 >>= 4, (S2 = p3 - g2) < 16 ? S2 = 0 : S2 >= 4080 ? S2 = 255 : S2 >>= 4, (A2 = d2 - b2) < 16 ? A2 = 0 : A2 >= 4080 ? A2 = 255 : A2 >>= 4, (I = f3 - y2) < 16 ? I = 0 : I >= 4080 ? I = 255 : I >>= 4, P[r3 + C2] = w, P[r3 + C2 + 8] = v2, P[r3 + C2 + 16] = x2, P[r3 + C2 + 24] = E2, P[r3 + C2 + 32] = k2, P[r3 + C2 + 40] = S2, P[r3 + C2 + 48] = A2, P[r3 + C2 + 56] = I) : (M2 = (M2 = u2 * w + 8192 >> 14) < -2040 ? 0 : M2 >= 2024 ? 255 : M2 + 2056 >> 4, P[r3 + C2] = M2, P[r3 + C2 + 8] = M2, P[r3 + C2 + 16] = M2, P[r3 + C2 + 24] = M2, P[r3 + C2 + 32] = M2, P[r3 + C2 + 40] = M2, P[r3 + C2 + 48] = M2, P[r3 + C2 + 56] = M2);
          }
          function _2(e7, t5) {
            for (var i5 = t5.P, r3 = t5.c, n3 = new Int16Array(64), a3 = 0; a3 < r3; a3++) for (var o3 = 0; o3 < i5; o3++) {
              m(t5, d(t5, a3, o3), n3);
            }
            return t5.D;
          }
          function g(e7, t5, i5) {
            null == i5 && (i5 = t5);
            var n3 = e7.length - 1, a3 = i5 < t5 ? i5 : t5;
            if (t5 >= n3) return null;
            var o3 = r2(e7, t5);
            if (o3 >= 65472 && o3 <= 65534) return { u: null, M: o3, offset: t5 };
            for (var s3 = r2(e7, a3); !(s3 >= 65472 && s3 <= 65534); ) {
              if (++a3 >= n3) return null;
              s3 = r2(e7, a3);
            }
            return { u: o3.toString(16), M: s3, offset: a3 };
          }
          return c2.prototype = { parse(i5, n3) {
            null == n3 && (n3 = {});
            var a3, o3, s3 = n3.F, l3 = 0, u3 = null, h3 = null, c3 = 0;
            function d2() {
              var e7 = r2(i5, l3), t5 = (l3 += 2) + e7 - 2, n4 = g(i5, t5, l3);
              n4 && n4.u && (t5 = n4.offset);
              var a4 = i5.subarray(l3, t5);
              return l3 += a4.length, a4;
            }
            function m2(e7) {
              for (var t5 = Math.ceil(e7.o / 8 / e7.X), i6 = Math.ceil(e7.s / 8 / e7.B), r3 = 0; r3 < e7.W.length; r3++) {
                Z = e7.W[r3];
                var n4 = Math.ceil(Math.ceil(e7.o / 8) * Z.h / e7.X), a4 = Math.ceil(Math.ceil(e7.s / 8) * Z.A / e7.B), o4 = t5 * Z.h, s4 = 64 * (i6 * Z.A) * (o4 + 1);
                Z.D = new Int16Array(s4), Z.P = n4, Z.c = a4;
              }
              e7.m = t5, e7.R = i6;
            }
            var b2 = [], y2 = [], w = [], v2 = r2(i5, l3);
            if (l3 += 2, 65496 !== v2) throw new t4("SOI not found");
            v2 = r2(i5, l3), l3 += 2;
            e: for (; 65497 !== v2; ) {
              var x2, E2, k2;
              switch (v2) {
                case 65504:
                case 65505:
                case 65506:
                case 65507:
                case 65508:
                case 65509:
                case 65510:
                case 65511:
                case 65512:
                case 65513:
                case 65514:
                case 65515:
                case 65516:
                case 65517:
                case 65518:
                case 65519:
                case 65534:
                  var S2 = d2();
                  65504 === v2 && 74 === S2[0] && 70 === S2[1] && 73 === S2[2] && 70 === S2[3] && 0 === S2[4] && (u3 = { version: { d: S2[5], T: S2[6] }, K: S2[7], j: S2[8] << 8 | S2[9], H: S2[10] << 8 | S2[11], S: S2[12], I: S2[13], C: S2.subarray(14, 14 + 3 * S2[12] * S2[13]) }), 65518 === v2 && 65 === S2[0] && 100 === S2[1] && 111 === S2[2] && 98 === S2[3] && 101 === S2[4] && (h3 = { version: S2[5] << 8 | S2[6], k: S2[7] << 8 | S2[8], q: S2[9] << 8 | S2[10], a: S2[11] });
                  break;
                case 65499:
                  for (var A2 = r2(i5, l3) + (l3 += 2) - 2; l3 < A2; ) {
                    var I = i5[l3++], M2 = new Uint16Array(64);
                    if (I >> 4) {
                      if (I >> 4 != 1) throw new t4("DQT - invalid table spec");
                      for (E2 = 0; E2 < 64; E2++) M2[e6[E2]] = r2(i5, l3), l3 += 2;
                    } else for (E2 = 0; E2 < 64; E2++) M2[e6[E2]] = i5[l3++];
                    b2[15 & I] = M2;
                  }
                  break;
                case 65472:
                case 65473:
                case 65474:
                  if (a3) throw new t4("Only single frame JPEGs supported");
                  l3 += 2, (a3 = {}).G = 65473 === v2, a3.Z = 65474 === v2, a3.precision = i5[l3++];
                  var T2, P = r2(i5, l3), B2 = 0, C2 = 0;
                  l3 += 2, a3.s = s3 || P, a3.o = r2(i5, l3), l3 += 2, a3.W = [], a3._ = {};
                  var R2 = i5[l3++];
                  for (x2 = 0; x2 < R2; x2++) {
                    T2 = i5[l3];
                    var z2 = i5[l3 + 1] >> 4, F = 15 & i5[l3 + 1];
                    B2 < z2 && (B2 = z2), C2 < F && (C2 = F);
                    var N2 = i5[l3 + 2];
                    k2 = a3.W.push({ h: z2, A: F, L: N2, $: null }), a3._[T2] = k2 - 1, l3 += 3;
                  }
                  a3.X = B2, a3.B = C2, m2(a3);
                  break;
                case 65476:
                  var O2 = r2(i5, l3);
                  for (l3 += 2, x2 = 2; x2 < O2; ) {
                    var D = i5[l3++], $ = new Uint8Array(16), L2 = 0;
                    for (E2 = 0; E2 < 16; E2++, l3++) L2 += $[E2] = i5[l3];
                    var U = new Uint8Array(L2);
                    for (E2 = 0; E2 < L2; E2++, l3++) U[E2] = i5[l3];
                    x2 += 17 + L2, (D >> 4 ? y2 : w)[15 & D] = f2($, U);
                  }
                  break;
                case 65501:
                  o3 = r2(i5, l3 += 2), l3 += 2;
                  break;
                case 65498:
                  var Z, j = 1 == ++c3 && !s3;
                  l3 += 2;
                  var G2 = i5[l3++], H = [];
                  for (x2 = 0; x2 < G2; x2++) {
                    var Q = i5[l3++], W = a3._[Q];
                    (Z = a3.W[W]).index = Q;
                    var q = i5[l3++];
                    Z.J = w[q >> 4], Z.i = y2[15 & q], H.push(Z);
                  }
                  var V = i5[l3++], Y2 = i5[l3++], K = i5[l3++];
                  try {
                    var J = p2(i5, l3, a3, H, o3, V, Y2, K >> 4, 15 & K, j);
                    l3 += J;
                  } catch (e7) {
                    if (e7 instanceof DNLMarkerError) return this.parse(i5, { F: e7.s });
                    if (e7 instanceof EOIMarkerError) break e;
                    throw e7;
                  }
                  break;
                case 65500:
                  l3 += 4;
                  break;
                case 65535:
                  255 !== i5[l3] && l3--;
                  break;
                default:
                  var X = g(i5, l3 - 2, l3 - 3);
                  if (X && X.u) {
                    l3 = X.offset;
                    break;
                  }
                  if (l3 >= i5.length - 1) break e;
                  throw new t4("JpegImage.parse - unknown marker: " + v2.toString(16));
              }
              v2 = r2(i5, l3), l3 += 2;
            }
            for (this.width = a3.o, this.height = a3.s, this.g = u3, this.b = h3, this.W = [], x2 = 0; x2 < a3.W.length; x2++) {
              var ee = b2[(Z = a3.W[x2]).L];
              ee && (Z.$ = ee), this.W.push({ index: Z.index, e: _2(0, Z), l: Z.h / a3.X, t: Z.A / a3.B, P: Z.P, c: Z.c });
            }
            this.p = this.W.length;
          }, Y(e7, t5, i5) {
            null == i5 && (i5 = false);
            var r3, n3, a3, o3, s3, l3, u3, h3, c3, f3, d2, p3, m2 = this.width / e7, _3 = this.height / t5, g2 = 0, b2 = this.W.length, y2 = e7 * t5 * b2, w = new Uint8ClampedArray(y2), v2 = new Uint32Array(e7), x2 = 4294967288;
            for (u3 = 0; u3 < b2; u3++) {
              if (n3 = (r3 = this.W[u3]).l * m2, a3 = r3.t * _3, g2 = u3, d2 = r3.e, o3 = r3.P + 1 << 3, n3 !== p3) {
                for (s3 = 0; s3 < e7; s3++) h3 = 0 | s3 * n3, v2[s3] = (h3 & x2) << 3 | 7 & h3;
                p3 = n3;
              }
              for (l3 = 0; l3 < t5; l3++) for (f3 = o3 * ((h3 = 0 | l3 * a3) & x2) | (7 & h3) << 3, s3 = 0; s3 < e7; s3++) w[g2] = d2[f3 + v2[s3]], g2 += b2;
            }
            var E2 = this.V;
            if (i5 || 4 !== b2 || E2 || (E2 = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255])), E2) for (u3 = 0; u3 < y2; ) for (h3 = 0, c3 = 0; h3 < b2; h3++, u3++, c3 += 2) w[u3] = (w[u3] * E2[c3] >> 8) + E2[c3 + 1];
            return w;
          }, get f() {
            return this.b ? !!this.b.a : 3 === this.p ? 0 !== this.N && (82 !== this.W[0].index || 71 !== this.W[1].index || 66 !== this.W[2].index) : 1 === this.N;
          }, z: function(e7) {
            for (var t5, i5, r3, n3 = 0, a3 = e7.length; n3 < a3; n3 += 3) t5 = e7[n3], i5 = e7[n3 + 1], r3 = e7[n3 + 2], e7[n3] = t5 - 179.456 + 1.402 * r3, e7[n3 + 1] = t5 + 135.459 - 0.344 * i5 - 0.714 * r3, e7[n3 + 2] = t5 - 226.816 + 1.772 * i5;
            return e7;
          }, O: function(e7) {
            for (var t5, i5, r3, n3, a3 = 0, o3 = 0, s3 = e7.length; o3 < s3; o3 += 4) t5 = e7[o3], i5 = e7[o3 + 1], r3 = e7[o3 + 2], n3 = e7[o3 + 3], e7[a3++] = i5 * (-660635669420364e-19 * i5 + 437130475926232e-18 * r3 - 54080610064599e-18 * t5 + 48449797120281e-17 * n3 - 0.154362151871126) - 122.67195406894 + r3 * (-957964378445773e-18 * r3 + 817076911346625e-18 * t5 - 0.00477271405408747 * n3 + 1.53380253221734) + t5 * (961250184130688e-18 * t5 - 0.00266257332283933 * n3 + 0.48357088451265) + n3 * (-336197177618394e-18 * n3 + 0.484791561490776), e7[a3++] = 107.268039397724 + i5 * (219927104525741e-19 * i5 - 640992018297945e-18 * r3 + 659397001245577e-18 * t5 + 426105652938837e-18 * n3 - 0.176491792462875) + r3 * (-778269941513683e-18 * r3 + 0.00130872261408275 * t5 + 770482631801132e-18 * n3 - 0.151051492775562) + t5 * (0.00126935368114843 * t5 - 0.00265090189010898 * n3 + 0.25802910206845) + n3 * (-318913117588328e-18 * n3 - 0.213742400323665), e7[a3++] = i5 * (-570115196973677e-18 * i5 - 263409051004589e-19 * r3 + 0.0020741088115012 * t5 - 0.00288260236853442 * n3 + 0.814272968359295) - 20.810012546947 + r3 * (-153496057440975e-19 * r3 - 132689043961446e-18 * t5 + 560833691242812e-18 * n3 - 0.195152027534049) + t5 * (0.00174418132927582 * t5 - 0.00255243321439347 * n3 + 0.116935020465145) + n3 * (-343531996510555e-18 * n3 + 0.24165260232407);
            return e7.subarray(0, a3);
          }, r: function(e7) {
            for (var t5, i5, r3, n3 = 0, a3 = e7.length; n3 < a3; n3 += 4) t5 = e7[n3], i5 = e7[n3 + 1], r3 = e7[n3 + 2], e7[n3] = 434.456 - t5 - 1.402 * r3, e7[n3 + 1] = 119.541 - t5 + 0.344 * i5 + 0.714 * r3, e7[n3 + 2] = 481.816 - t5 - 1.772 * i5;
            return e7;
          }, U: function(e7) {
            for (var t5, i5, r3, n3, a3 = 0, o3 = 0, s3 = e7.length; o3 < s3; o3 += 4) t5 = e7[o3], i5 = e7[o3 + 1], r3 = e7[o3 + 2], n3 = e7[o3 + 3], e7[a3++] = 255 + t5 * (-6747147073602441e-20 * t5 + 8379262121013727e-19 * i5 + 2894718188643294e-19 * r3 + 0.003264231057537806 * n3 - 1.1185611867203937) + i5 * (26374107616089405e-21 * i5 - 8626949158638572e-20 * r3 - 2748769067499491e-19 * n3 - 0.02155688794978967) + r3 * (-3878099212869363e-20 * r3 - 3267808279485286e-19 * n3 + 0.0686742238595345) - n3 * (3361971776183937e-19 * n3 + 0.7430659151342254), e7[a3++] = 255 + t5 * (13596372813588848e-20 * t5 + 924537132573585e-18 * i5 + 10567359618683593e-20 * r3 + 4791864687436512e-19 * n3 - 0.3109689587515875) + i5 * (-23545346108370344e-20 * i5 + 2702845253534714e-19 * r3 + 0.0020200308977307156 * n3 - 0.7488052167015494) + r3 * (6834815998235662e-20 * r3 + 15168452363460973e-20 * n3 - 0.09751927774728933) - n3 * (3189131175883281e-19 * n3 + 0.7364883807733168), e7[a3++] = 255 + t5 * (13598650411385307e-21 * t5 + 12423956175490851e-20 * i5 + 4751985097583589e-19 * r3 - 36729317476630422e-22 * n3 - 0.05562186980264034) + i5 * (16141380598724676e-20 * i5 + 9692239130725186e-19 * r3 + 7782692450036253e-19 * n3 - 0.44015232367526463) + r3 * (5068882914068769e-22 * r3 + 0.0017778369011375071 * n3 - 0.7591454649749609) - n3 * (3435319965105553e-19 * n3 + 0.7063770186160144);
            return e7.subarray(0, a3);
          }, getData: function(e7) {
            var i5 = e7.width, r3 = e7.height, n3 = e7.forceRGB, a3 = e7.isSourcePDF;
            if (this.p > 4) throw new t4("Unsupported color mode");
            var o3 = this.Y(i5, r3, a3);
            if (1 === this.p && n3) {
              for (var s3 = o3.length, l3 = new Uint8ClampedArray(3 * s3), u3 = 0, h3 = 0; h3 < s3; h3++) {
                var c3 = o3[h3];
                l3[u3++] = c3, l3[u3++] = c3, l3[u3++] = c3;
              }
              return l3;
            }
            if (3 === this.p && this.f) return this.z(o3);
            if (4 === this.p) {
              if (this.f) return n3 ? this.O(o3) : this.r(o3);
              if (n3) return this.U(o3);
            }
            return o3;
          } }, c2;
        }();
        function r2(e6, t5) {
          return e6[t5] << 8 | e6[t5 + 1];
        }
        e5.JpegDecoder = i3;
      }(), e5.encodeImage = function(t4, i3, r2, n2) {
        var a2 = { t256: [i3], t257: [r2], t258: [8, 8, 8, 8], t259: [1], t262: [2], t273: [1e3], t277: [4], t278: [r2], t279: [i3 * r2 * 4], t282: [[72, 1]], t283: [[72, 1]], t284: [1], t286: [[0, 1]], t287: [[0, 1]], t296: [1], t305: ["Photopea (UTIF.js)"], t338: [1] };
        if (n2) for (var o2 in n2) a2[o2] = n2[o2];
        var s2 = new Uint8Array(e5.encode([a2])), l2 = new Uint8Array(t4), u2 = new Uint8Array(1e3 + i3 * r2 * 4);
        for (o2 = 0; o2 < s2.length; o2++) u2[o2] = s2[o2];
        for (o2 = 0; o2 < l2.length; o2++) u2[1e3 + o2] = l2[o2];
        return u2.buffer;
      }, e5.encode = function(t4) {
        var i3 = new Uint8Array(2e4), r2 = 4, n2 = e5._binBE;
        i3[0] = i3[1] = 77, n2.writeUshort(i3, 2, 42);
        var a2 = 8;
        n2.writeUint(i3, r2, a2), r2 += 4;
        for (var o2 = 0; o2 < t4.length; o2++) {
          var s2 = e5._writeIFD(n2, e5._types.basic, i3, a2, t4[o2]);
          a2 = s2[1], o2 < t4.length - 1 && (3 & a2 && (a2 += 4 - (3 & a2)), n2.writeUint(i3, s2[0], a2));
        }
        return i3.slice(0, a2).buffer;
      }, e5.decode = function(t4, r2) {
        null == r2 && (r2 = { parseMN: true, debug: false });
        var n2 = new Uint8Array(t4), a2 = 0, o2 = e5._binBE.readASCII(n2, a2, 2);
        a2 += 2;
        var s2 = "II" == o2 ? e5._binLE : e5._binBE;
        s2.readUshort(n2, a2), a2 += 2;
        var l2 = s2.readUint(n2, a2);
        a2 += 4;
        for (var u2 = []; ; ) {
          var h2 = s2.readUshort(n2, l2), c2 = s2.readUshort(n2, l2 + 4);
          if (0 != h2 && (c2 < 1 || 13 < c2)) {
            i2("error in TIFF");
            break;
          }
          if (e5._readIFD(s2, n2, l2, u2, 0, r2), 0 == (l2 = s2.readUint(n2, l2 + 2 + 12 * h2))) break;
        }
        return u2;
      }, e5.decodeImage = function(t4, r2, n2) {
        if (!r2.data) {
          var a2 = new Uint8Array(t4), o2 = e5._binBE.readASCII(a2, 0, 2);
          if (null != r2.t256) {
            r2.isLE = "II" == o2, r2.width = r2.t256[0], r2.height = r2.t257[0];
            var s2 = r2.t259 ? r2.t259[0] : 1, l2 = r2.t266 ? r2.t266[0] : 1;
            r2.t284 && 2 == r2.t284[0] && i2("PlanarConfiguration 2 should not be used!"), 7 == s2 && r2.t258 && r2.t258.length > 3 && (r2.t258 = r2.t258.slice(0, 3));
            var u2 = r2.t277 ? r2.t277[0] : 1, h2 = (r2.t258 ? r2.t258[0] : 1) * u2;
            1 == s2 && null != r2.t279 && r2.t278 && 32803 == r2.t262[0] && (h2 = Math.round(8 * r2.t279[0] / (r2.width * r2.t278[0]))), r2.t50885 && 4 == r2.t50885[0] && (h2 = 3 * r2.t258[0]);
            var c2 = 8 * Math.ceil(r2.width * h2 / 8), f2 = r2.t273;
            (null == f2 || r2.t322) && (f2 = r2.t324);
            var d = r2.t279;
            1 == s2 && 1 == f2.length && (d = [r2.height * (c2 >>> 3)]), (null == d || r2.t322) && (d = r2.t325);
            var p2 = new Uint8Array(r2.height * (c2 >>> 3)), m = 0;
            if (null != r2.t322) {
              var _2 = r2.t322[0], g = r2.t323[0], b2 = Math.floor((r2.width + _2 - 1) / _2), y2 = Math.floor((r2.height + g - 1) / g), w = new Uint8Array(0 | Math.ceil(_2 * g * h2 / 8));
              console.log("====", b2, y2);
              for (var v2 = 0; v2 < y2; v2++) for (var x2 = 0; x2 < b2; x2++) {
                var E2 = v2 * b2 + x2;
                w.fill(0), e5.decode._decompress(r2, n2, a2, f2[E2], d[E2], s2, w, 0, l2, _2, g), 6 == s2 ? p2 = w : e5._copyTile(w, 0 | Math.ceil(_2 * h2 / 8), g, p2, 0 | Math.ceil(r2.width * h2 / 8), r2.height, 0 | Math.ceil(x2 * _2 * h2 / 8), v2 * g);
              }
              m = 8 * p2.length;
            } else {
              if (null == f2) return;
              var k2 = r2.t278 ? r2.t278[0] : r2.height;
              k2 = Math.min(k2, r2.height);
              for (E2 = 0; E2 < f2.length; E2++) e5.decode._decompress(r2, n2, a2, f2[E2], d[E2], s2, p2, 0 | Math.ceil(m / 8), l2, r2.width, k2), m += c2 * k2;
              m = Math.min(m, 8 * p2.length);
            }
            r2.data = new Uint8Array(p2.buffer, 0, 0 | Math.ceil(m / 8));
          }
        }
      }, e5.decode._decompress = function(r2, n2, a2, o2, s2, l2, u2, h2, c2, f2, d) {
        if (r2.t271 && "Panasonic" == r2.t271[0] && r2.t45 && 6 == r2.t45[0] && (l2 = 34316), 1 == l2) for (var p2 = 0; p2 < s2; p2++) u2[h2 + p2] = a2[o2 + p2];
        else if (2 == l2) e5.decode._decodeG2(a2, o2, s2, u2, h2, f2, c2);
        else if (3 == l2) e5.decode._decodeG3(a2, o2, s2, u2, h2, f2, c2, !!r2.t292 && !(1 & ~r2.t292[0]));
        else if (4 == l2) e5.decode._decodeG4(a2, o2, s2, u2, h2, f2, c2);
        else if (5 == l2) e5.decode._decodeLZW(a2, o2, s2, u2, h2, 8);
        else if (6 == l2) e5.decode._decodeOldJPEG(r2, a2, o2, s2, u2, h2);
        else if (7 == l2 || 34892 == l2) e5.decode._decodeNewJPEG(r2, a2, o2, s2, u2, h2);
        else if (8 == l2 || 32946 == l2) {
          var m = new Uint8Array(a2.buffer, o2 + 2, s2 - 6), _2 = t3.inflateRaw(m);
          h2 + _2.length <= u2.length && u2.set(_2, h2);
        } else 9 == l2 ? e5.decode._decodeVC5(a2, o2, s2, u2, h2, r2.t33422) : 32767 == l2 ? e5.decode._decodeARW(r2, a2, o2, s2, u2, h2) : 32773 == l2 ? e5.decode._decodePackBits(a2, o2, s2, u2, h2) : 32809 == l2 ? e5.decode._decodeThunder(a2, o2, s2, u2, h2) : 34316 == l2 ? e5.decode._decodePanasonic(r2, a2, o2, s2, u2, h2) : 34713 == l2 ? e5.decode._decodeNikon(r2, n2, a2, o2, s2, u2, h2) : 34676 == l2 ? e5.decode._decodeLogLuv32(r2, a2, o2, s2, u2, h2) : i2("Unknown compression", l2);
        var g = r2.t258 ? Math.min(32, r2.t258[0]) : 1, b2 = r2.t277 ? r2.t277[0] : 1, y2 = g * b2 >>> 3, w = Math.ceil(g * b2 * f2 / 8);
        if (16 == g && !r2.isLE && null == r2.t33422) for (var v2 = 0; v2 < d; v2++) for (var x2 = h2 + v2 * w, E2 = 1; E2 < w; E2 += 2) {
          var k2 = u2[x2 + E2];
          u2[x2 + E2] = u2[x2 + E2 - 1], u2[x2 + E2 - 1] = k2;
        }
        if (r2.t317 && 2 == r2.t317[0]) for (v2 = 0; v2 < d; v2++) {
          var S2 = h2 + v2 * w;
          if (16 == g) for (p2 = y2; p2 < w; p2 += 2) {
            var A2 = (u2[S2 + p2 + 1] << 8 | u2[S2 + p2]) + (u2[S2 + p2 - y2 + 1] << 8 | u2[S2 + p2 - y2]);
            u2[S2 + p2] = 255 & A2, u2[S2 + p2 + 1] = A2 >>> 8 & 255;
          }
          else if (3 == b2) for (p2 = 3; p2 < w; p2 += 3) u2[S2 + p2] = u2[S2 + p2] + u2[S2 + p2 - 3] & 255, u2[S2 + p2 + 1] = u2[S2 + p2 + 1] + u2[S2 + p2 - 2] & 255, u2[S2 + p2 + 2] = u2[S2 + p2 + 2] + u2[S2 + p2 - 1] & 255;
          else for (p2 = y2; p2 < w; p2++) u2[S2 + p2] = u2[S2 + p2] + u2[S2 + p2 - y2] & 255;
        }
      }, e5.decode._decodePanasonic = function(e6, t4, i3, r2, n2, a2) {
        var o2, s2, l2, u2, h2, c2, f2, d, p2 = t4.buffer, m = e6.t2[0], _2 = e6.t3[0], g = e6.t10[0], b2 = e6.t45[0], y2 = 0, w = 0, v2 = 0, x2 = 0, E2 = 6 == b2 ? new Uint32Array(18) : new Uint8Array(16), k2 = [0, 0], S2 = [0, 0], A2 = 0, I = new Uint8Array(16384), M2 = new Uint16Array(n2.buffer);
        function T2(e7) {
          if (0 == v2) {
            var t5 = new Uint8Array(p2, i3 + w + 8184, 8200), r3 = new Uint8Array(p2, i3 + w, 8184);
            I.set(t5), I.set(r3, t5.length), w += 16384;
          }
          if (5 != b2) return (I[x2 = (v2 = v2 - e7 & 131071) >> 3 ^ 16368] | I[x2 + 1] << 8) >> (7 & v2) & ~(-1 << e7);
          for (o2 = 0; o2 < 16; o2++) E2[o2] = I[v2++], v2 &= 16383;
        }
        function P(e7) {
          return I[v2 + 15 - e7];
        }
        function B2() {
          k2[0] = 0, k2[1] = 0, S2[0] = 0, S2[1] = 0;
        }
        if (7 == b2) throw b2;
        if (6 == b2) {
          var C2 = 12 == g, R2 = C2 ? function() {
            E2[0] = P(0) << 4 | P(1) >> 4, E2[1] = 4095 & ((15 & P(1)) << 8 | P(2)), E2[2] = P(3) >> 6 & 3, E2[3] = (63 & P(3)) << 2 | P(4) >> 6, E2[4] = (63 & P(4)) << 2 | P(5) >> 6, E2[5] = (63 & P(5)) << 2 | P(6) >> 6, E2[6] = P(6) >> 4 & 3, E2[7] = (15 & P(6)) << 4 | P(7) >> 4, E2[8] = (15 & P(7)) << 4 | P(8) >> 4, E2[9] = (15 & P(8)) << 4 | P(9) >> 4, E2[10] = P(9) >> 2 & 3, E2[11] = (3 & P(9)) << 6 | P(10) >> 2, E2[12] = (3 & P(10)) << 6 | P(11) >> 2, E2[13] = (3 & P(11)) << 6 | P(12) >> 2, E2[14] = 3 & P(12), E2[15] = P(13), E2[16] = P(14), E2[17] = P(15), v2 += 16, x2 = 0;
          } : function() {
            E2[0] = P(0) << 6 | P(1) >> 2, E2[1] = 16383 & ((3 & P(1)) << 12 | P(2) << 4 | P(3) >> 4), E2[2] = P(3) >> 2 & 3, E2[3] = (3 & P(3)) << 8 | P(4), E2[4] = P(5) << 2 | P(6) >> 6, E2[5] = (63 & P(6)) << 4 | P(7) >> 4, E2[6] = P(7) >> 2 & 3, E2[7] = (3 & P(7)) << 8 | P(8), E2[8] = P(9) << 2 & 1020 | P(10) >> 6, E2[9] = 1023 & (P(10) << 4 | P(11) >> 4), E2[10] = P(11) >> 2 & 3, E2[11] = (3 & P(11)) << 8 | P(12), E2[12] = 1023 & (P(13) << 2 & 1020 | P(14) >> 6), E2[13] = 1023 & (P(14) << 4 | P(15) >> 4), v2 += 16, x2 = 0;
          }, z2 = C2 ? 14 : 11, F = C2 ? 128 : 512, N2 = C2 ? 2048 : 8192, O2 = C2 ? 16383 : 65535, D = C2 ? 4095 : 16383, $ = m / z2, L2 = 16 * $, U = C2 ? 18 : 14;
          for (c2 = 0; c2 < _2 - 15; c2 += 16) {
            var Z = Math.min(16, _2 - c2), j = L2 * Z;
            for (I = new Uint8Array(p2, i3 + y2, j), v2 = 0, y2 += j, d = 0, f2 = 0; d < Z; d++, f2 = 0) {
              A2 = (c2 + d) * m;
              for (var G2 = 0; G2 < $; G2++) for (R2(), B2(), l2 = 0, h2 = 0, o2 = 0; o2 < z2; o2++) {
                if (u2 = 1 & o2, o2 % 3 == 2) {
                  var H = x2 < U ? E2[x2++] : 0;
                  3 == H && (H = 4), h2 = F << H, l2 = 1 << H;
                }
                var Q = x2 < U ? E2[x2++] : 0;
                k2[u2] ? (Q *= l2, h2 < N2 && S2[u2] > h2 && (Q += S2[u2] - h2), S2[u2] = Q) : (k2[u2] = Q, Q ? S2[u2] = Q : Q = S2[u2]), M2[A2 + f2++] = Q - 15 <= O2 ? Q - 15 & O2 : Q + 2147483633 >> 31 & D;
              }
            }
          }
        } else if (5 == b2) {
          var W = 12 == g ? 10 : 9;
          for (c2 = 0; c2 < _2; c2++) for (f2 = 0; f2 < m; f2 += W) T2(0), 12 == g ? (M2[A2++] = ((15 & E2[1]) << 8) + E2[0], M2[A2++] = 16 * E2[2] + (E2[1] >> 4), M2[A2++] = ((15 & E2[4]) << 8) + E2[3], M2[A2++] = 16 * E2[5] + (E2[4] >> 4), M2[A2++] = ((15 & E2[7]) << 8) + E2[6], M2[A2++] = 16 * E2[8] + (E2[7] >> 4), M2[A2++] = ((15 & E2[10]) << 8) + E2[9], M2[A2++] = 16 * E2[11] + (E2[10] >> 4), M2[A2++] = ((15 & E2[13]) << 8) + E2[12], M2[A2++] = 16 * E2[14] + (E2[13] >> 4)) : 14 == g && (M2[A2++] = E2[0] + ((63 & E2[1]) << 8), M2[A2++] = (E2[1] >> 6) + 4 * E2[2] + ((15 & E2[3]) << 10), M2[A2++] = (E2[3] >> 4) + 16 * E2[4] + ((3 & E2[5]) << 12), M2[A2++] = ((252 & E2[5]) >> 2) + (E2[6] << 6), M2[A2++] = E2[7] + ((63 & E2[8]) << 8), M2[A2++] = (E2[8] >> 6) + 4 * E2[9] + ((15 & E2[10]) << 10), M2[A2++] = (E2[10] >> 4) + 16 * E2[11] + ((3 & E2[12]) << 12), M2[A2++] = ((252 & E2[12]) >> 2) + (E2[13] << 6), M2[A2++] = E2[14] + ((63 & E2[15]) << 8));
        } else {
          if (4 != b2) throw b2;
          for (c2 = 0; c2 < _2; c2++) for (f2 = 0; f2 < m; f2++) u2 = 1 & (o2 = f2 % 14), 0 == o2 && B2(), o2 % 3 == 2 && (l2 = 4 >> 3 - T2(2)), S2[u2] ? 0 != (s2 = T2(8)) && (k2[u2] -= 128 << l2, (k2[u2] < 0 || 4 == l2) && (k2[u2] &= ~(-1 << l2)), k2[u2] += s2 << l2) : (S2[u2] = T2(8), (S2[u2] || o2 > 11) && (k2[u2] = S2[u2] << 4 | T2(4))), M2[A2++] = k2[1 & f2];
        }
      }, e5.decode._decodeVC5 = /* @__PURE__ */ function() {
        var t4, i3, r2, n2 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], a2 = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1];
        function o2(e6) {
          var t5 = e6[1], i4 = e6[0][t5 >>> 3] >>> 7 - (7 & t5) & 1;
          return e6[1]++, i4;
        }
        function s2(e6, i4) {
          if (null == t4) {
            t4 = {};
            for (var r3 = 0; r3 < n2.length; r3 += 4) t4[n2[r3 + 1]] = n2.slice(r3, r3 + 4);
          }
          for (var a3 = o2(e6), s3 = t4[a3]; null == s3; ) a3 = a3 << 1 | o2(e6), s3 = t4[a3];
          var l3 = s3[3];
          0 != l3 && (l3 = 0 == o2(e6) ? l3 : -l3), i4[0] = s3[2], i4[1] = l3;
        }
        function l2(e6, t5) {
          for (var i4 = 0; i4 < t5; i4++) 1 & ~e6 || e6++, e6 >>>= 1;
          return e6;
        }
        function u2(e6, t5) {
          return e6 >> t5;
        }
        function h2(e6, t5, i4, r3, n3, a3) {
          t5[i4] = u2(u2(11 * e6[n3] - 4 * e6[n3 + a3] + e6[n3 + a3 + a3] + 4, 3) + e6[r3], 1), t5[i4 + a3] = u2(u2(5 * e6[n3] + 4 * e6[n3 + a3] - e6[n3 + a3 + a3] + 4, 3) - e6[r3], 1);
        }
        function c2(e6, t5, i4, r3, n3, a3) {
          var o3 = e6[n3 - a3] - e6[n3 + a3], s3 = e6[n3], l3 = e6[r3];
          t5[i4] = u2(u2(o3 + 4, 3) + s3 + l3, 1), t5[i4 + a3] = u2(u2(4 - o3, 3) + s3 - l3, 1);
        }
        function f2(e6, t5, i4, r3, n3, a3) {
          t5[i4] = u2(u2(5 * e6[n3] + 4 * e6[n3 - a3] - e6[n3 - a3 - a3] + 4, 3) + e6[r3], 1), t5[i4 + a3] = u2(u2(11 * e6[n3] - 4 * e6[n3 - a3] + e6[n3 - a3 - a3] + 4, 3) - e6[r3], 1);
        }
        function d(e6) {
          return e6 = r2[e6 = e6 < 0 ? 0 : e6 > 4095 ? 4095 : e6] >>> 2;
        }
        return function(t5, n3, o3, u3, p2, m) {
          u3 = new Uint16Array(u3.buffer);
          var _2, g, b2, y2, w, v2, x2, E2, k2 = Date.now(), S2 = e5._binBE, A2 = n3 + o3;
          n3 += 4;
          for (var I = 1 == m[0]; n3 < A2; ) {
            var M2 = S2.readShort(t5, n3), T2 = S2.readUshort(t5, n3 + 2);
            if (n3 += 4, 12 == M2) N2 = T2;
            else if (20 == M2) _2 = T2;
            else if (21 == M2) g = T2;
            else if (48 == M2) b2 = T2;
            else if (53 == M2) y2 = T2;
            else if (35 == M2) ;
            else if (62 == M2) w = T2;
            else if (101 == M2) ;
            else if (109 == M2) v2 = T2;
            else if (84 == M2) ;
            else if (106 == M2) ;
            else if (107 == M2) ;
            else if (108 == M2) ;
            else if (102 == M2) ;
            else if (104 == M2) ie = T2;
            else if (105 == M2) ;
            else {
              var P = M2 < 0 ? -M2 : M2, B2 = 65280 & P, C2 = 0;
              if (24576 & P && (8192 & P ? (C2 = 65535 & T2, C2 += (255 & P) << 16) : C2 = 65535 & T2), 24576 & ~P) {
                if (16388 == P) n3 += 4 * C2;
                else if (8192 != B2 && 8448 != B2 && 9216 != B2) throw P.toString(16);
              } else {
                if (null == x2) {
                  x2 = [];
                  for (var R2 = 0; R2 < 4; R2++) x2[R2] = new Int16Array((_2 >>> 1) * (g >>> 1));
                  E2 = new Int16Array((_2 >>> 1) * (g >>> 1)), i3 = new Int16Array(1024);
                  for (R2 = 0; R2 < 1024; R2++) {
                    var z2 = R2 - 512, F = Math.abs(z2), N2 = Math.floor(768 * F * F * F / 16581375) + F;
                    i3[R2] = Math.sign(z2) * N2;
                  }
                  r2 = new Uint16Array(4096);
                  for (R2 = 0; R2 < 4096; R2++) {
                    var O2 = R2, D = 65535 * (Math.pow(113, O2 / 4095) - 1) / 112;
                    r2[R2] = Math.min(D, 65535);
                  }
                }
                var $ = x2[w], L2 = l2(_2, 1 + a2[b2]), U = l2(g, 1 + a2[b2]);
                if (0 == b2) for (var Z = 0; Z < U; Z++) for (var j = 0; j < L2; j++) {
                  var G2 = n3 + 2 * (Z * L2 + j);
                  $[Z * (_2 >>> 1) + j] = t5[G2] << 8 | t5[G2 + 1];
                }
                else {
                  var H = [t5, 8 * n3], Q = [], W = 0, q = L2 * U, V = [0, 0], Y2 = 0;
                  for (T2 = 0; W < q; ) for (s2(H, V), Y2 = V[0], T2 = V[1]; Y2 > 0; ) Q[W++] = T2, Y2--;
                  var K = (b2 - 1) % 3, J = 1 != K ? L2 : 0, X = 0 != K ? U : 0;
                  for (Z = 0; Z < U; Z++) {
                    var ee = (Z + X) * (_2 >>> 1) + J, te = Z * L2;
                    for (j = 0; j < L2; j++) $[ee + j] = i3[Q[te + j] + 512] * y2;
                  }
                  if (2 == K) {
                    var ie = _2 >>> 1, re = 2 * L2, ne = 2 * U;
                    for (Z = 0; Z < U; Z++) for (j = 0; j < re; j++) {
                      R2 = 2 * Z * ie + j;
                      var ae = U * ie + (se = Z * ie + j);
                      0 == Z ? h2($, E2, R2, ae, se, ie) : Z == U - 1 ? f2($, E2, R2, ae, se, ie) : c2($, E2, R2, ae, se, ie);
                    }
                    var oe = $;
                    $ = E2, E2 = oe;
                    for (Z = 0; Z < ne; Z++) for (j = 0; j < L2; j++) {
                      var se;
                      R2 = Z * ie + 2 * j, ae = L2 + (se = Z * ie + j);
                      0 == j ? h2($, E2, R2, ae, se, 1) : j == L2 - 1 ? f2($, E2, R2, ae, se, 1) : c2($, E2, R2, ae, se, 1);
                    }
                    oe = $;
                    $ = E2, E2 = oe;
                    for (var le = [], ue = 2 - ~~((b2 - 1) / 3), he = 0; he < 3; he++) le[he] = v2 >> 14 - 2 * he & 3;
                    var ce = le[ue];
                    if (0 != ce) for (Z = 0; Z < ne; Z++) for (j = 0; j < re; j++) {
                      $[R2 = Z * ie + j] = $[R2] << ce;
                    }
                  }
                }
                if (9 == b2 && 3 == w) {
                  var fe = x2[0], de = x2[1], pe = x2[2], me = x2[3];
                  for (Z = 0; Z < g; Z += 2) for (j = 0; j < _2; j += 2) {
                    var _e2 = Z * _2 + j, ge = fe[G2 = (Z >>> 1) * (_2 >>> 1) + (j >>> 1)], be = de[G2] - 2048, ye = pe[G2] - 2048, we = me[G2] - 2048, ve = (be << 1) + ge, xe = (ye << 1) + ge, Ee = ge + we, ke = ge - we;
                    I ? (u3[_e2] = d(Ee), u3[_e2 + 1] = d(xe), u3[_e2 + _2] = d(ve), u3[_e2 + _2 + 1] = d(ke)) : (u3[_e2] = d(ve), u3[_e2 + 1] = d(Ee), u3[_e2 + _2] = d(ke), u3[_e2 + _2 + 1] = d(xe));
                  }
                }
                n3 += 4 * C2;
              }
            }
          }
          console.log(Date.now() - k2);
        };
      }(), e5.decode._decodeLogLuv32 = function(e6, t4, i3, r2, n2, a2) {
        for (var o2 = e6.width, s2 = 4 * o2, l2 = 0, u2 = new Uint8Array(s2); l2 < r2; ) {
          for (var h2 = 0; h2 < s2; ) {
            var c2 = t4[i3 + l2];
            if (l2++, c2 < 128) {
              for (var f2 = 0; f2 < c2; f2++) u2[h2 + f2] = t4[i3 + l2 + f2];
              h2 += c2, l2 += c2;
            } else {
              c2 -= 126;
              for (f2 = 0; f2 < c2; f2++) u2[h2 + f2] = t4[i3 + l2];
              h2 += c2, l2++;
            }
          }
          for (var d = 0; d < o2; d++) n2[a2 + 0] = u2[d], n2[a2 + 1] = u2[d + o2], n2[a2 + 2] = u2[d + 2 * o2], n2[a2 + 4] = u2[d + 3 * o2], a2 += 6;
        }
      }, e5.decode._ljpeg_diff = function(t4, i3, r2) {
        var n2, a2, o2 = e5.decode._getbithuff;
        return n2 = o2(t4, i3, r2[0], r2), (a2 = o2(t4, i3, n2, 0)) & 1 << n2 - 1 || (a2 -= (1 << n2) - 1), a2;
      }, e5.decode._decodeARW = function(t4, i3, r2, n2, a2, o2) {
        var s2 = t4.t256[0], l2 = t4.t257[0], u2 = t4.t258[0], h2 = t4.isLE ? e5._binLE : e5._binBE;
        if (s2 * l2 == n2 || s2 * l2 * 1.5 == n2) if (s2 * l2 * 1.5 != n2) {
          var c2, f2, d, p2, m, _2, g, b2, y2 = new Uint16Array(16), w = new Uint8Array(s2 + 1);
          for (M2 = 0; M2 < l2; M2++) {
            for (var v2 = 0; v2 < s2; v2++) w[v2] = i3[r2++];
            for (b2 = 0, I = 0; I < s2 - 30; b2 += 16) {
              for (f2 = 2047 & (c2 = h2.readUint(w, b2)), d = 2047 & c2 >>> 11, p2 = 15 & c2 >>> 22, m = 15 & c2 >>> 26, _2 = 0; _2 < 4 && 128 << _2 <= f2 - d; _2++) ;
              for (g = 30, x2 = 0; x2 < 16; x2++) x2 == p2 ? y2[x2] = f2 : x2 == m ? y2[x2] = d : (y2[x2] = ((h2.readUshort(w, b2 + (g >> 3)) >>> (7 & g) & 127) << _2) + d, y2[x2] > 2047 && (y2[x2] = 2047), g += 7);
              for (x2 = 0; x2 < 16; x2++, I += 2) {
                N2 = y2[x2] << 1;
                e5.decode._putsF(a2, (M2 * s2 + I) * u2, N2 << 16 - u2);
              }
              I -= 1 & I ? 1 : 31;
            }
          }
        } else for (var x2 = 0; x2 < n2; x2 += 3) {
          var E2 = i3[r2 + x2 + 0], k2 = i3[r2 + x2 + 1], S2 = i3[r2 + x2 + 2];
          a2[o2 + x2] = k2 << 4 | E2 >>> 4, a2[o2 + x2 + 1] = E2 << 4 | S2 >>> 4, a2[o2 + x2 + 2] = S2 << 4 | k2 >>> 4;
        }
        else {
          l2 += 8;
          var A2, I, M2, T2 = [r2, 0, 0, 0], P = new Uint16Array(32770), B2 = [3857, 3856, 3599, 3342, 3085, 2828, 2571, 2314, 2057, 1800, 1543, 1286, 1029, 772, 771, 768, 514, 513], C2 = 0, R2 = e5.decode._ljpeg_diff;
          for (P[0] = 15, A2 = x2 = 0; x2 < 18; x2++) for (var z2 = 32768 >>> (B2[x2] >>> 8), F = 0; F < z2; F++) P[++A2] = B2[x2];
          for (I = s2; I--; ) for (M2 = 0; M2 < l2 + 1; M2 += 2) if (M2 == l2 && (M2 = 1), C2 += R2(i3, T2, P), M2 < l2) {
            var N2 = 4095 & C2;
            e5.decode._putsF(a2, (M2 * s2 + I) * u2, N2 << 16 - u2);
          }
        }
      }, e5.decode._decodeNikon = function(t4, i3, r2, n2, a2, o2, s2) {
        var l2 = [[0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12], [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 57, 90, 56, 39, 22, 5, 4, 3, 2, 1, 0, 11, 12, 12], [0, 0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12], [0, 0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14], [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 8, 92, 75, 58, 41, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14], [0, 0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14]], u2 = t4.t256[0], h2 = t4.t257[0], c2 = t4.t258[0], f2 = 0, d = 0, p2 = e5.decode._make_decoder, m = e5.decode._getbithuff, _2 = i3[0].exifIFD.makerNote, g = _2.t150 ? _2.t150 : _2.t140, b2 = 0, y2 = g[b2++], w = g[b2++];
        73 != y2 && 88 != w || (b2 += 2110), 70 == y2 && (f2 = 2), 14 == c2 && (f2 += 3);
        for (var v2 = [[0, 0], [0, 0]], x2 = t4.isLE ? e5._binLE : e5._binBE, E2 = 0; E2 < 2; E2++) for (var k2 = 0; k2 < 2; k2++) v2[E2][k2] = x2.readShort(g, b2), b2 += 2;
        var S2, A2, I, M2, T2, P = 1 << c2 & 32767, B2 = 0, C2 = x2.readShort(g, b2);
        b2 += 2, C2 > 1 && (B2 = Math.floor(P / (C2 - 1))), 68 == y2 && 32 == w && B2 > 0 && (d = x2.readShort(g, 562));
        var R2 = [0, 0], z2 = p2(l2[f2]), F = [n2, 0, 0, 0];
        for (S2 = 0; S2 < h2; S2++) for (d && S2 == d && (z2 = p2(l2[f2 + 1])), A2 = 0; A2 < u2; A2++) {
          E2 = m(r2, F, z2[0], z2), (T2 = 1 + (m(r2, F, (I = 15 & E2) - (M2 = E2 >>> 4), 0) << 1) << M2 >>> 1) & 1 << I - 1 || (T2 -= (1 << I) - (0 == M2 ? 1 : 0)), A2 < 2 ? R2[A2] = v2[1 & S2][A2] += T2 : R2[1 & A2] += T2;
          var N2 = Math.min(Math.max(R2[1 & A2], 0), (1 << c2) - 1), O2 = (S2 * u2 + A2) * c2;
          e5.decode._putsF(o2, O2, N2 << 16 - c2);
        }
      }, e5.decode._putsF = function(e6, t4, i3) {
        i3 <<= 8 - (7 & t4);
        var r2 = t4 >>> 3;
        e6[r2] |= i3 >>> 16, e6[r2 + 1] |= i3 >>> 8, e6[r2 + 2] |= i3;
      }, e5.decode._getbithuff = function(t4, i3, r2, n2) {
        var a2;
        e5.decode._get_byte;
        var o2 = i3[0], s2 = i3[1], l2 = i3[2], u2 = i3[3];
        if (0 == r2 || l2 < 0) return 0;
        for (; !u2 && l2 < r2 && -1 != (a2 = t4[o2++]) && !(u2 = 0); ) s2 = (s2 << 8) + a2, l2 += 8;
        if (a2 = s2 << 32 - l2 >>> 32 - r2, n2 ? (l2 -= n2[a2 + 1] >>> 8, a2 = 255 & n2[a2 + 1]) : l2 -= r2, l2 < 0) throw "e";
        return i3[0] = o2, i3[1] = s2, i3[2] = l2, i3[3] = u2, a2;
      }, e5.decode._make_decoder = function(e6) {
        var t4, i3, r2, n2, a2, o2 = [];
        for (t4 = 16; 0 != t4 && !e6[t4]; t4--) ;
        var s2 = 17;
        for (o2[0] = t4, r2 = i3 = 1; i3 <= t4; i3++) for (n2 = 0; n2 < e6[i3]; n2++, ++s2) for (a2 = 0; a2 < 1 << t4 - i3; a2++) r2 <= 1 << t4 && (o2[r2++] = i3 << 8 | e6[s2]);
        return o2;
      }, e5.decode._decodeNewJPEG = function(t4, i3, r2, n2, a2, o2) {
        n2 = Math.min(n2, i3.length - r2);
        var s2 = t4.t347, l2 = s2 ? s2.length : 0, u2 = new Uint8Array(l2 + n2);
        if (s2) {
          for (var h2 = 0, c2 = 0; c2 < l2 - 1 && (255 != s2[c2] || 217 != s2[c2 + 1]); c2++) u2[h2++] = s2[c2];
          var f2 = i3[r2], d = i3[r2 + 1];
          255 == f2 && 216 == d || (u2[h2++] = f2, u2[h2++] = d);
          for (c2 = 2; c2 < n2; c2++) u2[h2++] = i3[r2 + c2];
        } else for (c2 = 0; c2 < n2; c2++) u2[c2] = i3[r2 + c2];
        if (32803 == t4.t262[0] || 7 == t4.t259[0] && 34892 == t4.t262[0]) {
          var p2 = t4.t258[0], m = e5.LosslessJpegDecode(u2), _2 = m.length;
          if (16 == p2) if (t4.isLE) for (c2 = 0; c2 < _2; c2++) a2[o2 + (c2 << 1)] = 255 & m[c2], a2[o2 + (c2 << 1) + 1] = m[c2] >>> 8;
          else for (c2 = 0; c2 < _2; c2++) a2[o2 + (c2 << 1)] = m[c2] >>> 8, a2[o2 + (c2 << 1) + 1] = 255 & m[c2];
          else if (14 == p2 || 12 == p2 || 10 == p2) {
            var g = 16 - p2;
            for (c2 = 0; c2 < _2; c2++) e5.decode._putsF(a2, c2 * p2, m[c2] << g);
          } else {
            if (8 != p2) throw new Error("unsupported bit depth " + p2);
            for (c2 = 0; c2 < _2; c2++) a2[o2 + c2] = m[c2];
          }
        } else {
          var b2 = new e5.JpegDecoder();
          b2.parse(u2);
          var y2 = b2.getData({ width: b2.width, height: b2.height, forceRGB: true, isSourcePDF: false });
          for (c2 = 0; c2 < y2.length; c2++) a2[o2 + c2] = y2[c2];
        }
        6 == t4.t262[0] && (t4.t262[0] = 2);
      }, e5.decode._decodeOldJPEGInit = function(e6, t4, r2, n2) {
        var a2, o2, s2, l2, u2, h2 = 216, c2 = 0, f2 = 0, d = false, p2 = e6.t513, m = p2 ? p2[0] : 0, _2 = e6.t514, g = _2 ? _2[0] : 0, b2 = e6.t324 || e6.t273 || p2, y2 = e6.t530, w = 0, v2 = 0, x2 = e6.t277 ? e6.t277[0] : 1, E2 = e6.t515;
        if (b2 && (f2 = b2[0], d = b2.length > 1), !d) {
          if (255 == t4[r2] && t4[r2 + 1] == h2) return { jpegOffset: r2 };
          if (null != p2 && (255 == t4[r2 + m] && t4[r2 + m + 1] == h2 ? c2 = r2 + m : i2("JPEGInterchangeFormat does not point to SOI"), null == _2 ? i2("JPEGInterchangeFormatLength field is missing") : (m >= f2 || m + g <= f2) && i2("JPEGInterchangeFormatLength field value is invalid"), null != c2)) return { jpegOffset: c2 };
        }
        if (null != y2 && (w = y2[0], v2 = y2[1]), null != p2 && null != _2) if (g >= 2 && m + g <= f2) {
          for (a2 = 255 == t4[r2 + m + g - 2] && t4[r2 + m + g - 1] == h2 ? new Uint8Array(g - 2) : new Uint8Array(g), s2 = 0; s2 < a2.length; s2++) a2[s2] = t4[r2 + m + s2];
          i2("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables");
        } else i2("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile");
        if (null == a2) {
          var k2 = 0, S2 = [];
          S2[k2++] = 255, S2[k2++] = h2;
          var A2 = e6.t519;
          if (null == A2) throw new Error("JPEGQTables tag is missing");
          for (s2 = 0; s2 < A2.length; s2++) for (S2[k2++] = 255, S2[k2++] = 219, S2[k2++] = 0, S2[k2++] = 67, S2[k2++] = s2, l2 = 0; l2 < 64; l2++) S2[k2++] = t4[r2 + A2[s2] + l2];
          for (u2 = 0; u2 < 2; u2++) {
            var I = e6[0 == u2 ? "t520" : "t521"];
            if (null == I) throw new Error((0 == u2 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing");
            for (s2 = 0; s2 < I.length; s2++) {
              S2[k2++] = 255, S2[k2++] = 196;
              var M2 = 19;
              for (l2 = 0; l2 < 16; l2++) M2 += t4[r2 + I[s2] + l2];
              for (S2[k2++] = M2 >>> 8, S2[k2++] = 255 & M2, S2[k2++] = s2 | u2 << 4, l2 = 0; l2 < 16; l2++) S2[k2++] = t4[r2 + I[s2] + l2];
              for (l2 = 0; l2 < M2; l2++) S2[k2++] = t4[r2 + I[s2] + 16 + l2];
            }
          }
          if (S2[k2++] = 255, S2[k2++] = 192, S2[k2++] = 0, S2[k2++] = 8 + 3 * x2, S2[k2++] = 8, S2[k2++] = e6.height >>> 8 & 255, S2[k2++] = 255 & e6.height, S2[k2++] = e6.width >>> 8 & 255, S2[k2++] = 255 & e6.width, S2[k2++] = x2, 1 == x2) S2[k2++] = 1, S2[k2++] = 17, S2[k2++] = 0;
          else for (s2 = 0; s2 < 3; s2++) S2[k2++] = s2 + 1, S2[k2++] = 0 != s2 ? 17 : (15 & w) << 4 | 15 & v2, S2[k2++] = s2;
          null != E2 && 0 != E2[0] && (S2[k2++] = 255, S2[k2++] = 221, S2[k2++] = 0, S2[k2++] = 4, S2[k2++] = E2[0] >>> 8 & 255, S2[k2++] = 255 & E2[0]), a2 = new Uint8Array(S2);
        }
        var T2 = -1;
        for (s2 = 0; s2 < a2.length - 1; ) {
          if (255 == a2[s2] && 192 == a2[s2 + 1]) {
            T2 = s2;
            break;
          }
          s2++;
        }
        if (-1 == T2) {
          var P = new Uint8Array(a2.length + 10 + 3 * x2);
          P.set(a2);
          var B2 = a2.length;
          if (T2 = a2.length, (a2 = P)[B2++] = 255, a2[B2++] = 192, a2[B2++] = 0, a2[B2++] = 8 + 3 * x2, a2[B2++] = 8, a2[B2++] = e6.height >>> 8 & 255, a2[B2++] = 255 & e6.height, a2[B2++] = e6.width >>> 8 & 255, a2[B2++] = 255 & e6.width, a2[B2++] = x2, 1 == x2) a2[B2++] = 1, a2[B2++] = 17, a2[B2++] = 0;
          else for (s2 = 0; s2 < 3; s2++) a2[B2++] = s2 + 1, a2[B2++] = 0 != s2 ? 17 : (15 & w) << 4 | 15 & v2, a2[B2++] = s2;
        }
        if (255 == t4[f2] && 218 == t4[f2 + 1]) {
          var C2 = t4[f2 + 2] << 8 | t4[f2 + 3];
          for ((o2 = new Uint8Array(C2 + 2))[0] = t4[f2], o2[1] = t4[f2 + 1], o2[2] = t4[f2 + 2], o2[3] = t4[f2 + 3], s2 = 0; s2 < C2 - 2; s2++) o2[s2 + 4] = t4[f2 + s2 + 4];
        } else {
          var R2 = 0;
          if ((o2 = new Uint8Array(8 + 2 * x2))[R2++] = 255, o2[R2++] = 218, o2[R2++] = 0, o2[R2++] = 6 + 2 * x2, o2[R2++] = x2, 1 == x2) o2[R2++] = 1, o2[R2++] = 0;
          else for (s2 = 0; s2 < 3; s2++) o2[R2++] = s2 + 1, o2[R2++] = s2 << 4 | s2;
          o2[R2++] = 0, o2[R2++] = 63, o2[R2++] = 0;
        }
        return { jpegOffset: r2, tables: a2, sosMarker: o2, sofPosition: T2 };
      }, e5.decode._decodeOldJPEG = function(t4, i3, r2, n2, a2, o2) {
        var s2, l2, u2, h2, c2 = e5.decode._decodeOldJPEGInit(t4, i3, r2, n2);
        if (null != c2.jpegOffset) for (s2 = r2 + n2 - c2.jpegOffset, u2 = new Uint8Array(s2), p2 = 0; p2 < s2; p2++) u2[p2] = i3[c2.jpegOffset + p2];
        else {
          for (l2 = c2.tables.length, (u2 = new Uint8Array(l2 + c2.sosMarker.length + n2 + 2)).set(c2.tables), h2 = l2, u2[c2.sofPosition + 5] = t4.height >>> 8 & 255, u2[c2.sofPosition + 6] = 255 & t4.height, u2[c2.sofPosition + 7] = t4.width >>> 8 & 255, u2[c2.sofPosition + 8] = 255 & t4.width, 255 == i3[r2] && i3[r2 + 1] == SOS || (u2.set(c2.sosMarker, h2), h2 += sosMarker.length), p2 = 0; p2 < n2; p2++) u2[h2++] = i3[r2 + p2];
          u2[h2++] = 255, u2[h2++] = EOI;
        }
        var f2 = new e5.JpegDecoder();
        f2.parse(u2);
        for (var d = f2.getData({ width: f2.width, height: f2.height, forceRGB: true, isSourcePDF: false }), p2 = 0; p2 < d.length; p2++) a2[o2 + p2] = d[p2];
        t4.t262 && 6 == t4.t262[0] && (t4.t262[0] = 2);
      }, e5.decode._decodePackBits = function(e6, t4, i3, r2, n2) {
        for (var a2 = new Int8Array(e6.buffer), o2 = new Int8Array(r2.buffer), s2 = t4 + i3; t4 < s2; ) {
          var l2 = a2[t4];
          if (t4++, l2 >= 0 && l2 < 128) for (var u2 = 0; u2 < l2 + 1; u2++) o2[n2] = a2[t4], n2++, t4++;
          if (l2 >= -127 && l2 < 0) {
            for (u2 = 0; u2 < 1 - l2; u2++) o2[n2] = a2[t4], n2++;
            t4++;
          }
        }
        return n2;
      }, e5.decode._decodeThunder = function(e6, t4, i3, r2, n2) {
        for (var a2 = [0, 1, 0, -1], o2 = [0, 1, 2, 3, 0, -3, -2, -1], s2 = t4 + i3, l2 = 2 * n2, u2 = 0; t4 < s2; ) {
          var h2 = e6[t4], c2 = h2 >>> 6, f2 = 63 & h2;
          if (t4++, 3 == c2 && (u2 = 15 & f2, r2[l2 >>> 1] |= u2 << 4 * (1 - l2 & 1), l2++), 0 == c2) for (var d = 0; d < f2; d++) r2[l2 >>> 1] |= u2 << 4 * (1 - l2 & 1), l2++;
          if (2 == c2) for (d = 0; d < 2; d++) {
            4 != (p2 = f2 >>> 3 * (1 - d) & 7) && (u2 += o2[p2], r2[l2 >>> 1] |= u2 << 4 * (1 - l2 & 1), l2++);
          }
          if (1 == c2) for (d = 0; d < 3; d++) {
            var p2;
            2 != (p2 = f2 >>> 2 * (2 - d) & 3) && (u2 += a2[p2], r2[l2 >>> 1] |= u2 << 4 * (1 - l2 & 1), l2++);
          }
        }
      }, e5.decode._dmap = { 1: 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 }, e5.decode._lens = function() {
        var e6 = function(e7, t5, i4, r3) {
          for (var n3 = 0; n3 < t5.length; n3++) e7[t5[n3]] = i4 + n3 * r3;
        }, t4 = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101,101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010,00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010,00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100", i3 = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000,0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001,000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111,000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111", r2 = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110,011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011", n2 = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100,0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010,0000001011011,0000001100100,0000001100101", a2 = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111";
        t4 = t4.split(","), i3 = i3.split(","), r2 = r2.split(","), n2 = n2.split(","), a2 = a2.split(",");
        var o2 = {}, s2 = {};
        return e6(o2, t4, 0, 1), e6(o2, r2, 64, 64), e6(o2, a2, 1792, 64), e6(s2, i3, 0, 1), e6(s2, n2, 64, 64), e6(s2, a2, 1792, 64), [o2, s2];
      }(), e5.decode._decodeG4 = function(t4, i3, r2, n2, a2, o2, s2) {
        for (var l2 = e5.decode, u2 = i3 << 3, h2 = 0, c2 = "", f2 = [], d = [], p2 = 0; p2 < o2; p2++) d.push(0);
        d = l2._makeDiff(d);
        for (var m = 0, _2 = 0, g = 0, b2 = 0, y2 = 0, w = 0, v2 = "", x2 = 0, E2 = 8 * Math.ceil(o2 / 8); u2 >>> 3 < i3 + r2; ) {
          g = l2._findDiff(d, m + (0 == m ? 0 : 1), 1 - y2), b2 = l2._findDiff(d, g, y2);
          var k2 = 0;
          if (1 == s2 && (k2 = t4[u2 >>> 3] >>> 7 - (7 & u2) & 1), 2 == s2 && (k2 = t4[u2 >>> 3] >>> (7 & u2) & 1), u2++, c2 += k2, "H" == v2) {
            if (null != l2._lens[y2][c2]) {
              var S2 = l2._lens[y2][c2];
              c2 = "", h2 += S2, S2 < 64 && (l2._addNtimes(f2, h2, y2), m += h2, y2 = 1 - y2, h2 = 0, 0 == --x2 && (v2 = ""));
            }
          } else "0001" == c2 && (c2 = "", l2._addNtimes(f2, b2 - m, y2), m = b2), "001" == c2 && (c2 = "", v2 = "H", x2 = 2), null != l2._dmap[c2] && (_2 = g + l2._dmap[c2], l2._addNtimes(f2, _2 - m, y2), m = _2, c2 = "", y2 = 1 - y2);
          f2.length == o2 && "" == v2 && (l2._writeBits(f2, n2, 8 * a2 + w * E2), y2 = 0, w++, m = 0, d = l2._makeDiff(f2), f2 = []);
        }
      }, e5.decode._findDiff = function(e6, t4, i3) {
        for (var r2 = 0; r2 < e6.length; r2 += 2) if (e6[r2] >= t4 && e6[r2 + 1] == i3) return e6[r2];
      }, e5.decode._makeDiff = function(e6) {
        var t4 = [];
        1 == e6[0] && t4.push(0, 1);
        for (var i3 = 1; i3 < e6.length; i3++) e6[i3 - 1] != e6[i3] && t4.push(i3, e6[i3]);
        return t4.push(e6.length, 0, e6.length, 1), t4;
      }, e5.decode._decodeG2 = function(t4, i3, r2, n2, a2, o2, s2) {
        for (var l2 = e5.decode, u2 = i3 << 3, h2 = 0, c2 = "", f2 = [], d = 0, p2 = 0, m = 8 * Math.ceil(o2 / 8); u2 >>> 3 < i3 + r2; ) {
          var _2 = 0;
          1 == s2 && (_2 = t4[u2 >>> 3] >>> 7 - (7 & u2) & 1), 2 == s2 && (_2 = t4[u2 >>> 3] >>> (7 & u2) & 1), u2++, c2 += _2, null != (h2 = l2._lens[d][c2]) && (l2._addNtimes(f2, h2, d), c2 = "", h2 < 64 && (d = 1 - d), f2.length == o2 && (l2._writeBits(f2, n2, 8 * a2 + p2 * m), f2 = [], p2++, d = 0, 7 & u2 && (u2 += 8 - (7 & u2)), h2 >= 64 && (u2 += 8)));
        }
      }, e5.decode._decodeG3 = function(t4, i3, r2, n2, a2, o2, s2, l2) {
        for (var u2 = e5.decode, h2 = i3 << 3, c2 = 0, f2 = "", d = [], p2 = [], m = 0; m < o2; m++) d.push(0);
        for (var _2 = 0, g = 0, b2 = 0, y2 = 0, w = 0, v2 = -1, x2 = "", E2 = 0, k2 = true, S2 = 8 * Math.ceil(o2 / 8); h2 >>> 3 < i3 + r2; ) {
          b2 = u2._findDiff(p2, _2 + (0 == _2 ? 0 : 1), 1 - w), y2 = u2._findDiff(p2, b2, w);
          var A2 = 0;
          if (1 == s2 && (A2 = t4[h2 >>> 3] >>> 7 - (7 & h2) & 1), 2 == s2 && (A2 = t4[h2 >>> 3] >>> (7 & h2) & 1), h2++, f2 += A2, k2) {
            if (null != u2._lens[w][f2]) {
              var I = u2._lens[w][f2];
              f2 = "", c2 += I, I < 64 && (u2._addNtimes(d, c2, w), w = 1 - w, c2 = 0);
            }
          } else if ("H" == x2) {
            if (null != u2._lens[w][f2]) {
              I = u2._lens[w][f2];
              f2 = "", c2 += I, I < 64 && (u2._addNtimes(d, c2, w), _2 += c2, w = 1 - w, c2 = 0, 0 == --E2 && (x2 = ""));
            }
          } else "0001" == f2 && (f2 = "", u2._addNtimes(d, y2 - _2, w), _2 = y2), "001" == f2 && (f2 = "", x2 = "H", E2 = 2), null != u2._dmap[f2] && (g = b2 + u2._dmap[f2], u2._addNtimes(d, g - _2, w), _2 = g, f2 = "", w = 1 - w);
          f2.endsWith("000000000001") && (v2 >= 0 && u2._writeBits(d, n2, 8 * a2 + v2 * S2), l2 && (1 == s2 && (k2 = 1 == (t4[h2 >>> 3] >>> 7 - (7 & h2) & 1)), 2 == s2 && (k2 = 1 == (t4[h2 >>> 3] >>> (7 & h2) & 1)), h2++), f2 = "", w = 0, v2++, _2 = 0, p2 = u2._makeDiff(d), d = []);
        }
        d.length == o2 && u2._writeBits(d, n2, 8 * a2 + v2 * S2);
      }, e5.decode._addNtimes = function(e6, t4, i3) {
        for (var r2 = 0; r2 < t4; r2++) e6.push(i3);
      }, e5.decode._writeBits = function(e6, t4, i3) {
        for (var r2 = 0; r2 < e6.length; r2++) t4[i3 + r2 >>> 3] |= e6[r2] << 7 - (i3 + r2 & 7);
      }, e5.decode._decodeLZW = e5.decode._decodeLZW = function() {
        var e6, t4, i3, r2, n2 = 0, a2 = 0, o2 = 0, s2 = 0, l2 = function() {
          var i4 = e6 >>> 3, r3 = (t4[i4] << 16 | t4[i4 + 1] << 8 | t4[i4 + 2]) >>> 24 - (7 & e6) - a2 & (1 << a2) - 1;
          return e6 += a2, r3;
        }, u2 = new Uint32Array(16384), h2 = 0, c2 = function(e7) {
          a2 = e7 + 1, n2 = s2 + 1;
        }, f2 = function(e7) {
          for (var t5 = e7 << 2, n3 = u2[t5 + 2], a3 = r2 + n3 - 1; 65535 != t5; ) i3[a3--] = u2[t5], t5 = u2[t5 + 1];
          r2 += n3;
        }, d = function(e7, t5) {
          var i4 = n2 << 2, r3 = e7 << 2;
          u2[i4] = u2[3 + (t5 << 2)], u2[i4 + 1] = r3, u2[i4 + 2] = u2[r3 + 2] + 1, u2[i4 + 3] = u2[r3 + 3], ++n2 + 1 == 1 << a2 && 12 != a2 && a2++;
        };
        return function(a3, p2, m, _2, g, b2) {
          e6 = p2 << 3, t4 = a3, i3 = _2, r2 = g;
          var y2 = p2 + m << 3, w = 0, v2 = 0;
          for (!function(e7) {
            if (e7 != h2) {
              h2 = e7, s2 = 1 + (o2 = 1 << e7);
              for (var t5 = 0; t5 < s2 + 1; t5++) u2[4 * t5] = u2[4 * t5 + 3] = t5, u2[4 * t5 + 1] = 65535, u2[4 * t5 + 2] = 1;
            }
          }(b2), c2(b2); e6 < y2 && (w = l2()) != s2; ) {
            if (w == o2) {
              if (c2(b2), (w = l2()) == s2) break;
              f2(w);
            } else w < n2 ? (f2(w), d(v2, w)) : (d(v2, v2), f2(n2 - 1));
            v2 = w;
          }
          return r2;
        };
      }(), e5.tags = {}, e5._types = function() {
        var e6 = new Array(250);
        e6.fill(0);
        return { basic: { main: e6 = e6.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), rest: { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 } }, gps: { main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9], rest: { 18: 2, 29: 2 } } };
      }(), e5._readIFD = function(t4, r2, n2, a2, o2, s2) {
        var l2 = t4.readUshort(r2, n2);
        n2 += 2;
        var u2 = {};
        s2.debug && i2("   ".repeat(o2), a2.length - 1, ">>>----------------");
        for (var h2 = 0; h2 < l2; h2++) {
          var c2 = t4.readUshort(r2, n2);
          n2 += 2;
          var f2 = t4.readUshort(r2, n2);
          n2 += 2;
          var d = t4.readUint(r2, n2);
          n2 += 4;
          var p2 = t4.readUint(r2, n2);
          n2 += 4;
          var m = [];
          if (1 == f2 || 7 == f2) {
            var _2 = d < 5 ? n2 - 4 : p2;
            _2 + d > r2.buffer.byteLength && (d = r2.buffer.byteLength - _2), m = new Uint8Array(r2.buffer, _2, d);
          }
          if (2 == f2) {
            var g = d < 5 ? n2 - 4 : p2, b2 = r2[g], y2 = Math.max(0, Math.min(d - 1, r2.length - g));
            b2 < 128 || 0 == y2 ? m.push(t4.readASCII(r2, g, y2)) : m = new Uint8Array(r2.buffer, g, y2);
          }
          if (3 == f2) for (var w = 0; w < d; w++) m.push(t4.readUshort(r2, (d < 3 ? n2 - 4 : p2) + 2 * w));
          if (4 == f2 || 13 == f2) for (w = 0; w < d; w++) m.push(t4.readUint(r2, (d < 2 ? n2 - 4 : p2) + 4 * w));
          if (5 == f2 || 10 == f2) {
            var v2 = 5 == f2 ? t4.readUint : t4.readInt;
            for (w = 0; w < d; w++) m.push([v2(r2, p2 + 8 * w), v2(r2, p2 + 8 * w + 4)]);
          }
          if (8 == f2) for (w = 0; w < d; w++) m.push(t4.readShort(r2, (d < 3 ? n2 - 4 : p2) + 2 * w));
          if (9 == f2) for (w = 0; w < d; w++) m.push(t4.readInt(r2, (d < 2 ? n2 - 4 : p2) + 4 * w));
          if (11 == f2) for (w = 0; w < d; w++) m.push(t4.readFloat(r2, p2 + 4 * w));
          if (12 == f2) for (w = 0; w < d; w++) m.push(t4.readDouble(r2, p2 + 8 * w));
          if (0 == d || 0 != m.length) {
            if (s2.debug && i2("   ".repeat(o2), c2, f2, e5.tags[c2], m), u2["t" + c2] = m, 330 == c2 && u2.t272 && "DSLR-A100" == u2.t272[0]) ;
            else if (330 == c2 || 34665 == c2 || 34853 == c2 || 50740 == c2 && t4.readUshort(r2, t4.readUint(m, 0)) < 300 || 61440 == c2) {
              var x2 = 50740 == c2 ? [t4.readUint(m, 0)] : m, E2 = [];
              for (w = 0; w < x2.length; w++) e5._readIFD(t4, r2, x2[w], E2, o2 + 1, s2);
              330 == c2 && (u2.subIFD = E2), 34665 == c2 && (u2.exifIFD = E2[0]), 34853 == c2 && (u2.gpsiIFD = E2[0]), 50740 == c2 && (u2.dngPrvt = E2[0]), 61440 == c2 && (u2.fujiIFD = E2[0]);
            }
            if (37500 == c2 && s2.parseMN) {
              var k2 = m;
              if ("Nikon" == t4.readASCII(k2, 0, 5)) u2.makerNote = e5.decode(k2.slice(10).buffer)[0];
              else if ("OLYMP" == t4.readASCII(k2, 0, 5) || "OM SYSTEM" == t4.readASCII(k2, 0, 9)) {
                var S2 = [8208, 8224, 8240, 8256, 8272], A2 = [];
                e5._readIFD(t4, k2, 77 == k2[1] ? 16 : 85 == k2[5] ? 12 : 8, A2, o2 + 1, s2);
                var I = u2.makerNote = A2.pop();
                for (w = 0; w < S2.length; w++) {
                  var M2 = "t" + S2[w];
                  null != I[M2] && (e5._readIFD(t4, k2, I[M2][0], A2, o2 + 1, s2), I[M2] = A2.pop());
                }
                I.t12288 && (e5._readIFD(t4, I.t12288, 0, A2, o2 + 1, s2), I.t12288 = A2.pop());
              } else if (t4.readUshort(r2, p2) < 300 && t4.readUshort(r2, p2 + 4) <= 12) {
                A2 = [];
                e5._readIFD(t4, r2, p2, A2, o2 + 1, s2), u2.makerNote = A2[0];
              }
            }
          } else if (i2(c2, "unknown TIFF tag type: ", f2, "num:", d), 0 == h2) return;
        }
        return a2.push(u2), s2.debug && i2("   ".repeat(o2), "<<<---------------"), n2;
      }, e5._writeIFD = function(t4, i3, r2, n2, a2) {
        var o2 = Object.keys(a2), s2 = o2.length;
        a2.exifIFD && s2--, a2.gpsiIFD && s2--, t4.writeUshort(r2, n2, s2);
        for (var l2 = (n2 += 2) + 12 * s2 + 4, u2 = 0; u2 < o2.length; u2++) {
          var h2 = o2[u2];
          if ("t34665" != h2 && "t34853" != h2) {
            "exifIFD" == h2 && (h2 = "t34665"), "gpsiIFD" == h2 && (h2 = "t34853");
            var c2 = parseInt(h2.slice(1)), f2 = i3.main[c2];
            if (null == f2 && (f2 = i3.rest[c2]), null == f2 || 0 == f2) throw new Error("unknown type of tag: " + c2);
            var d = a2[h2];
            if (34665 == c2) d = [l2], l2 = e5._writeIFD(t4, i3, r2, l2, a2.exifIFD)[1];
            if (34853 == c2) d = [l2], l2 = e5._writeIFD(t4, e5._types.gps, r2, l2, a2.gpsiIFD)[1];
            2 == f2 && (d = d[0] + "\0");
            var p2 = d.length;
            t4.writeUshort(r2, n2, c2), n2 += 2, t4.writeUshort(r2, n2, f2), n2 += 2, t4.writeUint(r2, n2, p2);
            var m = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][f2] * p2, _2 = n2 += 4;
            if (m > 4 && (t4.writeUint(r2, n2, l2), _2 = l2), 1 == f2 || 7 == f2) for (var g = 0; g < p2; g++) r2[_2 + g] = d[g];
            else if (2 == f2) t4.writeASCII(r2, _2, d);
            else if (3 == f2) for (g = 0; g < p2; g++) t4.writeUshort(r2, _2 + 2 * g, d[g]);
            else if (4 == f2) for (g = 0; g < p2; g++) t4.writeUint(r2, _2 + 4 * g, d[g]);
            else if (5 == f2 || 10 == f2) {
              var b2 = 5 == f2 ? t4.writeUint : t4.writeInt;
              for (g = 0; g < p2; g++) {
                var y2 = d[g], w = y2[0], v2 = y2[1];
                if (null == w) throw "e";
                b2(r2, _2 + 8 * g, w), b2(r2, _2 + 8 * g + 4, v2);
              }
            } else if (9 == f2) for (g = 0; g < p2; g++) t4.writeInt(r2, _2 + 4 * g, d[g]);
            else {
              if (12 != f2) throw f2;
              for (g = 0; g < p2; g++) t4.writeDouble(r2, _2 + 8 * g, d[g]);
            }
            m > 4 && (l2 += m += 1 & m), n2 += 4;
          }
        }
        return [n2, l2];
      }, e5.toRGBA8 = function(e6, t4) {
        function r2(e7) {
          return e7 < 31308e-7 ? 12.92 * e7 : 1.055 * Math.pow(e7, 1 / 2.4) - 0.055;
        }
        var n2 = e6.width, a2 = e6.height, o2 = n2 * a2, s2 = e6.data, l2 = new Uint8Array(4 * o2), u2 = e6.t262 ? e6.t262[0] : 2, h2 = e6.t258 ? Math.min(32, e6.t258[0]) : 1;
        null == e6.t262 && 1 == h2 && (u2 = 0);
        var c2 = e6.t277 ? e6.t277[0] : e6.t258 ? e6.t258.length : [1, 1, 3, 1, 1, 4, 3][u2], f2 = e6.t339 ? e6.t339[0] : null;
        if (1 == u2 && 32 == h2 && 3 != f2) throw "e";
        var d = Math.ceil(c2 * h2 * n2 / 8);
        if (0 == u2) {
          t4 = 1 / 256;
          for (var p2 = 0; p2 < a2; p2++) {
            var m = p2 * d, _2 = p2 * n2;
            if (1 == h2) for (var g = 0; g < n2; g++) {
              var b2 = _2 + g << 2, y2 = s2[m + (g >> 3)] >> 7 - (7 & g) & 1;
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = 255 * (1 - y2), l2[b2 + 3] = 255;
            }
            if (4 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[m + (g >> 1)] >> 4 - 4 * (1 & g) & 15;
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = 17 * (15 - y2), l2[b2 + 3] = 255;
            }
            if (8 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[m + g];
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = 255 - y2, l2[b2 + 3] = 255;
            }
            if (16 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[(v2 = m + 2 * g) + 1] << 8 | s2[v2];
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = Math.min(255, 255 - ~~(y2 * t4)), l2[b2 + 3] = 255;
            }
          }
        } else if (1 == u2) {
          null == t4 && (t4 = 1 / 256);
          var w = 3 & s2.length ? null : new Float32Array(s2.buffer);
          for (p2 = 0; p2 < a2; p2++) {
            m = p2 * d, _2 = p2 * n2;
            if (1 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[m + (g >> 3)] >> 7 - (7 & g) & 1;
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = 255 * y2, l2[b2 + 3] = 255;
            }
            if (2 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[m + (g >> 2)] >> 6 - 2 * (3 & g) & 3;
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = 85 * y2, l2[b2 + 3] = 255;
            }
            if (8 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[m + g * c2];
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = y2, l2[b2 + 3] = 255;
            }
            if (16 == h2) for (g = 0; g < n2; g++) {
              b2 = _2 + g << 2, y2 = s2[(v2 = m + 2 * g) + 1] << 8 | s2[v2];
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = Math.min(255, ~~(y2 * t4)), l2[b2 + 3] = 255;
            }
            if (32 == h2) for (g = 0; g < n2; g++) {
              var v2;
              b2 = _2 + g << 2, y2 = w[v2 = (m >>> 2) + g];
              l2[b2] = l2[b2 + 1] = l2[b2 + 2] = ~~(0.5 + 255 * y2), l2[b2 + 3] = 255;
            }
          }
        } else if (2 == u2) if (8 == h2) {
          if (1 == c2) for (g = 0; g < o2; g++) l2[4 * g] = l2[4 * g + 1] = l2[4 * g + 2] = s2[g], l2[4 * g + 3] = 255;
          if (3 == c2) for (g = 0; g < o2; g++) {
            var x2 = 3 * g;
            l2[b2 = g << 2] = s2[x2], l2[b2 + 1] = s2[x2 + 1], l2[b2 + 2] = s2[x2 + 2], l2[b2 + 3] = 255;
          }
          if (c2 >= 4) for (g = 0; g < o2; g++) {
            x2 = g * c2;
            l2[b2 = g << 2] = s2[x2], l2[b2 + 1] = s2[x2 + 1], l2[b2 + 2] = s2[x2 + 2], l2[b2 + 3] = s2[x2 + 3];
          }
        } else if (16 == h2) {
          if (4 == c2) for (g = 0; g < o2; g++) {
            x2 = 8 * g + 1;
            l2[b2 = g << 2] = s2[x2], l2[b2 + 1] = s2[x2 + 2], l2[b2 + 2] = s2[x2 + 4], l2[b2 + 3] = s2[x2 + 6];
          }
          if (3 == c2) for (g = 0; g < o2; g++) {
            x2 = 6 * g + 1;
            l2[b2 = g << 2] = s2[x2], l2[b2 + 1] = s2[x2 + 2], l2[b2 + 2] = s2[x2 + 4], l2[b2 + 3] = 255;
          }
        } else {
          if (32 != h2) throw h2;
          var E2 = new Float32Array(s2.buffer), k2 = 0;
          for (g = 0; g < E2.length; g++) k2 = Math.min(k2, E2[g]);
          if (k2 < 0) for (g = 0; g < s2.length; g += 4) {
            var S2 = s2[g];
            s2[g] = s2[g + 3], s2[g + 3] = S2, S2 = s2[g + 1], s2[g + 1] = s2[g + 2], s2[g + 2] = S2;
          }
          var A2 = [];
          for (g = 0; g < 65536; g++) A2.push(r2(g / 65535));
          for (g = 0; g < E2.length; g++) {
            var I = Math.max(0, Math.min(1, E2[g]));
            E2[g] = A2[~~(0.5 + 65535 * I)];
          }
          if (3 == c2) for (g = 0; g < o2; g++) {
            x2 = 3 * g;
            l2[b2 = g << 2] = ~~(0.5 + 255 * E2[x2]), l2[b2 + 1] = ~~(0.5 + 255 * E2[x2 + 1]), l2[b2 + 2] = ~~(0.5 + 255 * E2[x2 + 2]), l2[b2 + 3] = 255;
          }
          else {
            if (4 != c2) throw c2;
            for (g = 0; g < o2; g++) {
              x2 = 4 * g;
              l2[b2 = g << 2] = ~~(0.5 + 255 * E2[x2]), l2[b2 + 1] = ~~(0.5 + 255 * E2[x2 + 1]), l2[b2 + 2] = ~~(0.5 + 255 * E2[x2 + 2]), l2[b2 + 3] = ~~(0.5 + 255 * E2[x2 + 3]);
            }
          }
        }
        else if (3 == u2) {
          var M2 = e6.t320, T2 = 1 << h2, P = 8 == h2 && c2 > 1 && e6.t338 && 0 != e6.t338[0];
          for (p2 = 0; p2 < a2; p2++) for (var B2 = 0; B2 < n2; B2++) {
            b2 = (g = p2 * n2 + B2) << 2;
            var C2 = 0, R2 = p2 * d;
            if (1 == h2) C2 = s2[R2 + (B2 >>> 3)] >>> 7 - (7 & B2) & 1;
            else if (2 == h2) C2 = s2[R2 + (B2 >>> 2)] >>> 6 - 2 * (3 & B2) & 3;
            else if (4 == h2) C2 = s2[R2 + (B2 >>> 1)] >>> 4 - 4 * (1 & B2) & 15;
            else {
              if (8 != h2) throw h2;
              C2 = s2[R2 + B2 * c2];
            }
            l2[b2] = M2[C2] >> 8, l2[b2 + 1] = M2[T2 + C2] >> 8, l2[b2 + 2] = M2[T2 + T2 + C2] >> 8, l2[b2 + 3] = P ? s2[R2 + B2 * c2 + 1] : 255;
          }
        } else if (5 == u2) {
          var z2 = c2 > 4 ? 1 : 0;
          for (g = 0; g < o2; g++) {
            b2 = g << 2;
            var F = g * c2;
            if (window.UDOC) {
              var N2 = s2[F], O2 = s2[F + 1], D = s2[F + 2], $ = s2[F + 3], L2 = UDOC.C.cmykToRgb([N2 * (1 / 255), O2 * (1 / 255), D * (1 / 255), $ * (1 / 255)]);
              l2[b2] = ~~(0.5 + 255 * L2[0]), l2[b2 + 1] = ~~(0.5 + 255 * L2[1]), l2[b2 + 2] = ~~(0.5 + 255 * L2[2]);
            } else {
              N2 = 255 - s2[F], O2 = 255 - s2[F + 1], D = 255 - s2[F + 2], $ = (255 - s2[F + 3]) * (1 / 255);
              l2[b2] = ~~(N2 * $ + 0.5), l2[b2 + 1] = ~~(O2 * $ + 0.5), l2[b2 + 2] = ~~(D * $ + 0.5);
            }
            l2[b2 + 3] = 255 * (1 - z2) + s2[F + 4] * z2;
          }
        } else if (6 == u2 && e6.t278) {
          var U = e6.t278[0];
          for (p2 = 0; p2 < a2; p2 += U) {
            g = p2 * n2;
            for (var Z = U * n2, j = 0; j < Z; j++) {
              b2 = 4 * (g + j), D = s2[(F = 3 * g + 4 * (j >>> 1)) + (1 & j)];
              var G2 = s2[F + 2] - 128, H = s2[F + 3] - 128, Q = D + ((H >> 2) + (H >> 3) + (H >> 5)), W = D - ((G2 >> 2) + (G2 >> 4) + (G2 >> 5)) - ((H >> 1) + (H >> 3) + (H >> 4) + (H >> 5)), q = D + (G2 + (G2 >> 1) + (G2 >> 2) + (G2 >> 6));
              l2[b2] = Math.max(0, Math.min(255, Q)), l2[b2 + 1] = Math.max(0, Math.min(255, W)), l2[b2 + 2] = Math.max(0, Math.min(255, q)), l2[b2 + 3] = 255;
            }
          }
        } else if (32845 == u2) for (p2 = 0; p2 < a2; p2++) for (B2 = 0; B2 < n2; B2++) {
          b2 = 4 * (p2 * n2 + B2);
          var V = s2[(F = 6 * (p2 * n2 + B2)) + 1] << 8 | s2[F], Y2 = (V = Math.pow(2, (V + 0.5) / 256 - 64), (s2[F + 3] + 0.5) / 410), K = (s2[F + 5] + 0.5) / 410, J = 9 * Y2 / (6 * Y2 - 16 * K + 12), X = 4 * K / (6 * Y2 - 16 * K + 12), ee = J * V / X, te = (1 - J - X) * V / X;
          Q = 2.69 * ee - 1.276 * (D = V) - 0.414 * te, W = -1.022 * ee + 1.978 * D + 0.044 * te, q = 0.061 * ee - 0.224 * D + 1.163 * te;
          l2[b2] = 255 * r2(Math.min(Q, 1)), l2[b2 + 1] = 255 * r2(Math.min(W, 1)), l2[b2 + 2] = 255 * r2(Math.min(q, 1)), l2[b2 + 3] = 255;
        }
        else i2("Unknown Photometric interpretation: " + u2);
        return l2;
      }, e5.replaceIMG = function(t4) {
        null == t4 && (t4 = document.getElementsByTagName("img"));
        for (var i3 = ["tif", "tiff", "dng", "cr2", "nef"], r2 = 0; r2 < t4.length; r2++) {
          var n2 = t4[r2], a2 = n2.getAttribute("src");
          if (null != a2) {
            var o2 = a2.split(".").pop().toLowerCase();
            if (-1 != i3.indexOf(o2)) {
              var s2 = new XMLHttpRequest();
              e5._xhrs.push(s2), e5._imgs.push(n2), s2.open("GET", a2), s2.responseType = "arraybuffer", s2.onload = e5._imgLoaded, s2.send();
            }
          }
        }
      }, e5._xhrs = [], e5._imgs = [], e5._imgLoaded = function(t4) {
        var i3 = e5._xhrs.indexOf(t4.target), r2 = e5._imgs[i3];
        e5._xhrs.splice(i3, 1), e5._imgs.splice(i3, 1), r2.setAttribute("src", e5.bufferToURI(t4.target.response));
      }, e5.bufferToURI = function(t4) {
        var i3 = e5.decode(t4), r2 = i3, n2 = 0, a2 = r2[0];
        i3[0].subIFD && (r2 = r2.concat(i3[0].subIFD));
        for (var o2 = 0; o2 < r2.length; o2++) {
          var s2 = r2[o2];
          if (!(null == s2.t258 || s2.t258.length < 3)) {
            var l2 = s2.t256 * s2.t257;
            l2 > n2 && (n2 = l2, a2 = s2);
          }
        }
        e5.decodeImage(t4, a2, i3);
        var u2 = e5.toRGBA8(a2), h2 = a2.width, c2 = a2.height, f2 = document.createElement("canvas");
        f2.width = h2, f2.height = c2;
        var d = f2.getContext("2d"), p2 = new ImageData(new Uint8ClampedArray(u2.buffer), h2, c2);
        return d.putImageData(p2, 0, 0), f2.toDataURL();
      }, e5._binBE = { nextZero: function(e6, t4) {
        for (; 0 != e6[t4]; ) t4++;
        return t4;
      }, readUshort: function(e6, t4) {
        return e6[t4] << 8 | e6[t4 + 1];
      }, readShort: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 1], r2[1] = t4[i3 + 0], e5._binBE.i16[0];
      }, readInt: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 3], r2[1] = t4[i3 + 2], r2[2] = t4[i3 + 1], r2[3] = t4[i3 + 0], e5._binBE.i32[0];
      }, readUint: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 3], r2[1] = t4[i3 + 2], r2[2] = t4[i3 + 1], r2[3] = t4[i3 + 0], e5._binBE.ui32[0];
      }, readASCII: function(e6, t4, i3) {
        for (var r2 = "", n2 = 0; n2 < i3; n2++) r2 += String.fromCharCode(e6[t4 + n2]);
        return r2;
      }, readFloat: function(t4, i3) {
        for (var r2 = e5._binBE.ui8, n2 = 0; n2 < 4; n2++) r2[n2] = t4[i3 + 3 - n2];
        return e5._binBE.fl32[0];
      }, readDouble: function(t4, i3) {
        for (var r2 = e5._binBE.ui8, n2 = 0; n2 < 8; n2++) r2[n2] = t4[i3 + 7 - n2];
        return e5._binBE.fl64[0];
      }, writeUshort: function(e6, t4, i3) {
        e6[t4] = i3 >> 8 & 255, e6[t4 + 1] = 255 & i3;
      }, writeInt: function(t4, i3, r2) {
        var n2 = e5._binBE.ui8;
        e5._binBE.i32[0] = r2, t4[i3 + 3] = n2[0], t4[i3 + 2] = n2[1], t4[i3 + 1] = n2[2], t4[i3 + 0] = n2[3];
      }, writeUint: function(e6, t4, i3) {
        e6[t4] = i3 >> 24 & 255, e6[t4 + 1] = i3 >> 16 & 255, e6[t4 + 2] = i3 >> 8 & 255, e6[t4 + 3] = 255 & i3;
      }, writeASCII: function(e6, t4, i3) {
        for (var r2 = 0; r2 < i3.length; r2++) e6[t4 + r2] = i3.charCodeAt(r2);
      }, writeDouble: function(t4, i3, r2) {
        e5._binBE.fl64[0] = r2;
        for (var n2 = 0; n2 < 8; n2++) t4[i3 + n2] = e5._binBE.ui8[7 - n2];
      } }, e5._binBE.ui8 = new Uint8Array(8), e5._binBE.i16 = new Int16Array(e5._binBE.ui8.buffer), e5._binBE.i32 = new Int32Array(e5._binBE.ui8.buffer), e5._binBE.ui32 = new Uint32Array(e5._binBE.ui8.buffer), e5._binBE.fl32 = new Float32Array(e5._binBE.ui8.buffer), e5._binBE.fl64 = new Float64Array(e5._binBE.ui8.buffer), e5._binLE = { nextZero: e5._binBE.nextZero, readUshort: function(e6, t4) {
        return e6[t4 + 1] << 8 | e6[t4];
      }, readShort: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 0], r2[1] = t4[i3 + 1], e5._binBE.i16[0];
      }, readInt: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 0], r2[1] = t4[i3 + 1], r2[2] = t4[i3 + 2], r2[3] = t4[i3 + 3], e5._binBE.i32[0];
      }, readUint: function(t4, i3) {
        var r2 = e5._binBE.ui8;
        return r2[0] = t4[i3 + 0], r2[1] = t4[i3 + 1], r2[2] = t4[i3 + 2], r2[3] = t4[i3 + 3], e5._binBE.ui32[0];
      }, readASCII: e5._binBE.readASCII, readFloat: function(t4, i3) {
        for (var r2 = e5._binBE.ui8, n2 = 0; n2 < 4; n2++) r2[n2] = t4[i3 + n2];
        return e5._binBE.fl32[0];
      }, readDouble: function(t4, i3) {
        for (var r2 = e5._binBE.ui8, n2 = 0; n2 < 8; n2++) r2[n2] = t4[i3 + n2];
        return e5._binBE.fl64[0];
      }, writeUshort: function(e6, t4, i3) {
        e6[t4] = 255 & i3, e6[t4 + 1] = i3 >> 8 & 255;
      }, writeInt: function(t4, i3, r2) {
        var n2 = e5._binBE.ui8;
        e5._binBE.i32[0] = r2, t4[i3 + 0] = n2[0], t4[i3 + 1] = n2[1], t4[i3 + 2] = n2[2], t4[i3 + 3] = n2[3];
      }, writeUint: function(e6, t4, i3) {
        e6[t4] = i3 >>> 0 & 255, e6[t4 + 1] = i3 >>> 8 & 255, e6[t4 + 2] = i3 >>> 16 & 255, e6[t4 + 3] = i3 >>> 24 & 255;
      }, writeASCII: e5._binBE.writeASCII }, e5._copyTile = function(e6, t4, i3, r2, n2, a2, o2, s2) {
        for (var l2 = Math.min(t4, n2 - o2), u2 = Math.min(i3, a2 - s2), h2 = 0; h2 < u2; h2++) for (var c2 = (s2 + h2) * n2 + o2, f2 = h2 * t4, d = 0; d < l2; d++) r2[c2 + d] = e6[f2 + d];
      }, e5.LosslessJpegDecode = /* @__PURE__ */ function() {
        var e6, t4;
        function i3() {
          return e6[t4++];
        }
        function r2() {
          return e6[t4++] << 8 | e6[t4++];
        }
        function n2(e7) {
          for (var t5 = i3(), r3 = [0, 0, 0, 255], n3 = [], o3 = 0; o3 < 16; o3++) n3[o3] = i3();
          for (o3 = 0; o3 < 16; o3++) for (var s3 = 0; s3 < n3[o3]; s3++) {
            r3[a2(r3, 0, o3 + 1, 1) + 3] = i3();
          }
          var l3 = new Uint8Array(256);
          e7[t5] = [new Uint8Array(r3), l3];
          for (o3 = 0; o3 < 256; o3++) {
            for (var u3 = 8, h3 = o3, c3 = 0; 255 == r3[c3 + 3] && 0 != u3; ) c3 = r3[c3 + (h3 >> --u3 & 1)];
            l3[o3] = c3;
          }
        }
        function a2(e7, t5, i4, r3) {
          if (255 != e7[t5 + 3]) return 0;
          if (0 == i4) return t5;
          for (var n3 = 0; n3 < 2; n3++) {
            0 == e7[t5 + n3] && (e7[t5 + n3] = e7.length, e7.push(0, 0, r3, 255));
            var o3 = a2(e7, e7[t5 + n3], i4 - 1, r3 + 1);
            if (0 != o3) return o3;
          }
          return 0;
        }
        function o2(e7) {
          for (var t5 = e7.b, i4 = e7.f; t5 < 25 && e7.a < e7.d; ) {
            var r3 = e7.data[e7.a++];
            255 != r3 || e7.c || e7.a++, i4 = i4 << 8 | r3, t5 += 8;
          }
          if (t5 < 0) throw "e";
          e7.b = t5, e7.f = i4;
        }
        function s2(e7, t5) {
          return t5.b < e7 && o2(t5), t5.f >> (t5.b -= e7) & 65535 >> 16 - e7;
        }
        function l2(e7, t5) {
          var i4 = e7[0], r3 = 0, n3 = 255;
          t5.b < 16 && o2(t5);
          var a3 = t5.f >> t5.b - 8 & 255;
          for (n3 = i4[(r3 = e7[1][a3]) + 3], t5.b -= i4[r3 + 2]; 255 == n3; ) n3 = i4[(r3 = i4[r3 + (t5.f >> --t5.b & 1)]) + 3];
          return n3;
        }
        function u2(e7, t5) {
          return e7 < 32768 >> 16 - t5 && (e7 += 1 - (1 << t5)), e7;
        }
        function h2(e7, t5) {
          var i4 = l2(e7, t5);
          return 0 == i4 ? 0 : 16 == i4 ? -32768 : u2(s2(i4, t5), i4);
        }
        function c2(e7, t5, i4, r3, n3, a3) {
          for (var o3 = 0, s3 = 0; s3 < a3; s3++) {
            for (var l3 = s3 * t5, u3 = 0; u3 < t5; u3 += n3) {
              o3++;
              for (var c3 = 0; c3 < n3; c3++) e7[l3 + u3 + c3] = h2(r3[c3], i4);
            }
            if (0 != i4.e && o3 % i4.e == 0 && 0 != s3) {
              for (var f3 = i4.a, d2 = i4.data; 255 != d2[f3] || !(208 <= d2[f3 + 1] && d2[f3 + 1] <= 215); ) f3--;
              i4.a = f3 + 2, i4.f = 0, i4.b = 0;
            }
          }
        }
        function f2(e7, t5) {
          return u2(s2(e7, t5), e7);
        }
        function d(e7, t5, i4, r3, n3, a3, o3, s3) {
          for (var l3 = i4 * o3, u3 = n3; u3 < a3; u3++) e7[u3] += 1 << s3 - 1;
          for (var h3 = o3; h3 < l3; h3 += o3) for (u3 = n3; u3 < a3; u3++) e7[h3 + u3] += e7[h3 + u3 - o3];
          for (var c3 = 1; c3 < r3; c3++) {
            var f3 = c3 * l3;
            for (u3 = n3; u3 < a3; u3++) e7[f3 + u3] += e7[f3 + u3 - l3];
            for (h3 = o3; h3 < l3; h3 += o3) for (u3 = n3; u3 < a3; u3++) {
              var d2 = f3 + h3 + u3, p2 = d2 - l3, m = e7[d2 - o3], _2 = 0;
              if (0 == t5) _2 = 0;
              else if (1 == t5) _2 = m;
              else if (2 == t5) _2 = e7[p2];
              else if (3 == t5) _2 = e7[p2 - o3];
              else if (4 == t5) _2 = m + (e7[p2] - e7[p2 - o3]);
              else if (5 == t5) _2 = m + (e7[p2] - e7[p2 - o3] >>> 1);
              else if (6 == t5) _2 = e7[p2] + (m - e7[p2 - o3] >>> 1);
              else {
                if (7 != t5) throw t5;
                _2 = m + e7[p2] >>> 1;
              }
              e7[d2] += _2;
            }
          }
        }
        return function(a3) {
          if (e6 = a3, t4 = 0, 65496 != r2()) throw "e";
          for (var o3 = [], s3 = 0, u3 = 0, h3 = 0, p2 = [], m = [], _2 = [], g = 0, b2 = 0, y2 = 0; ; ) {
            var w = r2();
            if (65535 != w) {
              var v2 = r2();
              if (65475 == w) {
                u3 = i3(), b2 = r2(), y2 = r2(), g = i3();
                for (var x2 = 0; x2 < g; x2++) {
                  var E2 = i3(), k2 = i3();
                  if (0 != i3()) throw "e";
                  o3[E2] = [x2, k2 >> 4, 15 & k2];
                }
              } else if (65476 == w) for (var S2 = t4 + v2 - 2; t4 < S2; ) n2(m);
              else {
                if (65498 == w) {
                  t4++;
                  for (x2 = 0; x2 < g; x2++) {
                    var A2 = o3[i3()];
                    _2[A2[0]] = m[i3() >>> 4], p2[A2[0]] = A2.slice(1);
                  }
                  s3 = i3(), t4 += 2;
                  break;
                }
                65501 == w ? h3 = r2() : t4 += v2 - 2;
              }
            } else t4--;
          }
          var I = new (u3 > 8 ? Uint16Array : Uint8Array)(b2 * y2 * g), M2 = { b: 0, f: 0, c: 8 == s3, a: t4, data: e6, d: e6.length, e: h3 };
          if (M2.c) !function(i4, r3, n3, a4, o4) {
            for (var s4 = e6.length - t4, u4 = 0; u4 < s4; u4 += 4) {
              var h4 = e6[t4 + u4];
              e6[t4 + u4] = e6[t4 + u4 + 3], e6[t4 + u4 + 3] = h4, h4 = e6[t4 + u4 + 1], e6[t4 + u4 + 1] = e6[t4 + u4 + 2], e6[t4 + u4 + 2] = h4;
            }
            for (var c3 = 0; c3 < o4; c3++) for (var d2 = 32768, p3 = 32768, m2 = 0; m2 < r3; m2 += 2) {
              var _3 = l2(a4, n3), g2 = l2(a4, n3);
              0 != _3 && (d2 += f2(_3, n3)), 0 != g2 && (p3 += f2(g2, n3)), i4[c3 * r3 + m2] = 65535 & d2, i4[c3 * r3 + m2 + 1] = 65535 & p3;
            }
          }(I, y2 * g, M2, _2[0], b2);
          else {
            var T2 = [], P = 0, B2 = 0;
            for (x2 = 0; x2 < g; x2++) {
              var C2 = p2[x2];
              (Z = C2[0]) > P && (P = Z), (U = C2[1]) > B2 && (B2 = U), T2.push(Z * U);
            }
            if (1 != P || 1 != B2) {
              if (3 != g || 1 != T2[1] || 1 != T2[2]) throw "e";
              if (2 != P || 1 != B2 && 2 != B2) throw "e";
              var R2 = [], z2 = 0;
              for (x2 = 0; x2 < g; x2++) {
                for (var F = 0; F < T2[x2]; F++) R2.push(_2[x2]);
                z2 += T2[x2];
              }
              var N2 = y2 / P, O2 = b2 / B2, D = N2 * O2;
              c2(I, N2 * z2, M2, R2, z2, O2), d(I, s3, N2, O2, z2 - 2, z2, z2, u3);
              var $ = new Uint16Array(D * T2[0]);
              if (2 == P && 2 == B2) {
                for (x2 = 0; x2 < D; x2++) $[4 * x2] = I[6 * x2], $[4 * x2 + 1] = I[6 * x2 + 1], $[4 * x2 + 2] = I[6 * x2 + 2], $[4 * x2 + 3] = I[6 * x2 + 3];
                d($, s3, 4 * N2, O2, 0, 1, 1, u3);
                for (x2 = 0; x2 < D; x2++) I[6 * x2] = $[4 * x2], I[6 * x2 + 1] = $[4 * x2 + 1], I[6 * x2 + 2] = $[4 * x2 + 2], I[6 * x2 + 3] = $[4 * x2 + 3];
              }
              if (2 == P && 1 == B2) {
                for (x2 = 0; x2 < D; x2++) $[2 * x2] = I[4 * x2], $[2 * x2 + 1] = I[4 * x2 + 1];
                d($, s3, 2 * N2, O2, 0, 1, 1, u3);
                for (x2 = 0; x2 < D; x2++) I[4 * x2] = $[2 * x2], I[4 * x2 + 1] = $[2 * x2 + 1];
              }
              for (var L2 = I.slice(0), U = 0; U < b2; U++) if (2 == B2) for (var Z = 0; Z < y2; Z++) {
                var j = ((U >>> 1) * N2 + (Z >>> 1)) * z2, G2 = 2 * (1 & U) + (1 & Z);
                I[H = (U * y2 + Z) * g] = L2[j + G2], I[H + 1] = L2[j + 4], I[H + 2] = L2[j + 5];
              }
              else for (Z = 0; Z < y2; Z++) {
                var H;
                j = (U * N2 + (Z >>> 1)) * z2, G2 = 1 & Z;
                I[H = (U * y2 + Z) * g] = L2[j + G2], I[H + 1] = L2[j + 2], I[H + 2] = L2[j + 3];
              }
            } else if (c2(I, y2 * g, M2, _2, g, b2), 0 == h3) d(I, s3, y2, b2, 0, g, g, u3);
            else {
              var Q = Math.floor(h3 / y2);
              for (U = 0; U < b2; U += Q) {
                var W = I.slice(U * y2 * g, (U + Q) * y2 * g);
                d(W, s3, y2, Q, 0, g, g, u3), I.set(W, U * y2 * g);
              }
            }
          }
          return I;
        };
      }(), function() {
        var t4 = 2, i3 = 4, r2 = 5, n2 = 6, a2 = 7, o2 = 12, s2 = 13, l2 = 14, u2 = 15, h2 = 17;
        function c2(e6) {
          var t5 = { c: new Int8Array(2 << e6.u) };
          return function(e7, t6, i4) {
            var r3 = [t6, 3 * t6 + 18, 5 * t6 + 67, 7 * t6 + 276, i4];
            e7.o = t6, e7.w = (r3[4] + 2 * t6) / (2 * t6 + 1) + 1 | 0, e7.v = Math.ceil(Math.log2(e7.w)), e7.t = 9, function(e8, t7) {
              for (var i5 = -t7[4], r4 = 0; i5 <= t7[4]; r4++, i5++) e8[r4] = i5 <= -276 ? -4 : i5 <= -67 ? -3 : i5 <= -18 ? -2 : i5 < -0 ? -1 : i5 <= t7[0] ? 0 : i5 < t7[1] ? 1 : i5 < t7[2] ? 2 : i5 < t7[3] ? 3 : 4;
            }(e7.c, r3);
          }(t5, 0, e6.g), t5;
        }
        function f2(e6) {
          for (var t5 = [[], [], []], i4 = Math.max(2, e6.w + 32 >>> 6), r3 = 0; r3 < 3; r3++) for (var n3 = 0; n3 < 41; n3++) t5[r3][n3] = [i4, 1];
          return t5;
        }
        function d(e6, t5) {
          var i4 = 0, r3 = 8 - e6.a;
          if (e6.j, e6.a, t5) {
            if (t5 >= r3) do {
              i4 <<= r3, t5 -= r3, i4 |= e6[e6.j] & (1 << r3) - 1, e6.j++, r3 = 8;
            } while (t5 >= 8);
            t5 && (i4 <<= t5, r3 -= t5, i4 |= e6[e6.j] >>> r3 & (1 << t5) - 1), e6.a = 8 - r3;
          }
          return i4;
        }
        function p2(e6, t5, i4, r3, n3, a3, o3, s3) {
          null == s3 && (s3 = 0);
          var l3, u3, h3, c3, f3, p3, m2 = a3 + 1, _3 = m2 % 2, g2 = 0, b3 = r3[n3], y3 = r3[n3 - 1], w = r3[n3 - 2][m2], v2 = y3[m2 - 1], x2 = y3[m2], E2 = y3[m2 + 1], k2 = b3[m2 - 1], S2 = b3[m2 + 1], A2 = Math.abs;
          if (_3 && (h3 = A2(E2 - x2), c3 = A2(w - x2), f3 = A2(v2 - x2)), _3) {
            if (p3 = (p3 = h3 > f3 && c3 < h3 ? w + v2 : h3 < f3 && c3 < f3 ? w + E2 : E2 + v2) + 2 * x2 >>> 2, s3) return void (b3[m2] = p3);
            l3 = t5.t * t5.c[e6.g + x2 - w] + t5.c[e6.g + v2 - x2];
          } else p3 = x2 > v2 && x2 > E2 || x2 < v2 && x2 < E2 ? S2 + k2 + 2 * x2 >>> 2 : k2 + S2 >>> 1, l3 = t5.t * t5.c[e6.g + x2 - v2] + t5.c[e6.g + v2 - k2];
          u3 = A2(l3);
          var I = function(e7) {
            for (var t6 = -1, i5 = 0; !i5; t6++) i5 = e7[e7.j] >>> 7 - e7.a & 1, e7.a++, e7.a &= 7, e7.a || e7.j++;
            return t6;
          }(i4);
          if (I < e6.n - t5.v - 1) {
            var M2 = function(e7, t6) {
              var i5 = 0;
              if (t6 < e7) for (; i5 <= 14 && t6 << ++i5 < e7; ) ;
              return i5;
            }(o3[u3][0], o3[u3][1]);
            g2 = d(i4, M2) + (I << M2);
          } else g2 = d(i4, t5.v) + 1;
          g2 = 1 & g2 ? -1 - (g2 >>> 1) : g2 >>> 1, o3[u3][0] += A2(g2), o3[u3][1] == e6.f && (o3[u3][0] >>>= 1, o3[u3][1] >>>= 1), o3[u3][1]++, p3 = l3 < 0 ? p3 - g2 : p3 + g2, e6.i && (p3 < 0 ? p3 += t5.w : p3 > e6.g && (p3 -= t5.w)), b3[m2] = p3 >= 0 ? Math.min(p3, e6.g) : 0;
        }
        function m(e6, t5, i4) {
          for (var r3 = e6[0].length, n3 = t5; n3 <= i4; n3++) e6[n3][0] = e6[n3 - 1][1], e6[n3][r3 - 1] = e6[n3 - 1][r3 - 2];
        }
        function _2(e6) {
          m(e6, a2, o2), m(e6, t4, i3), m(e6, u2, h2);
        }
        function g(e6, t5, r3, n3, a3, o3, l3, u3, h3, c3, f3, d2, m2) {
          for (var g2 = 0, b3 = 1, y3 = a3 < s2 && a3 > i3; b3 < e6.m; ) g2 < e6.m && (p2(e6, t5, r3, n3, a3, g2, l3[h3], e6.h && (y3 && c3 || !y3 && (f3 || (g2 & d2) == m2))), p2(e6, t5, r3, n3, o3, g2, l3[h3], e6.h && (!y3 && c3 || y3 && (f3 || (g2 & d2) == m2))), g2 += 2), g2 > 8 && (p2(e6, t5, r3, n3, a3, b3, u3[h3]), p2(e6, t5, r3, n3, o3, b3, u3[h3]), b3 += 2);
          _2(n3);
        }
        function b2(e6, r3, n3, s3, l3, c3) {
          g(e6, r3, n3, s3, t4, a2, l3, c3, 0, 0, 1, 0, 8), g(e6, r3, n3, s3, 8, u2, l3, c3, 1, 0, 1, 0, 8), g(e6, r3, n3, s3, 3, 9, l3, c3, 2, 1, 0, 3, 0), g(e6, r3, n3, s3, 10, 16, l3, c3, 0, 0, 0, 3, 2), g(e6, r3, n3, s3, i3, 11, l3, c3, 1, 0, 0, 3, 2), g(e6, r3, n3, s3, o2, h2, l3, c3, 2, 1, 0, 3, 0);
        }
        function y2(e6, i4, r3, n3, o3, s3) {
          var l3 = s3.length, h3 = e6.l;
          o3 + 1 == e6.s && (h3 = e6.e - o3 * e6.l);
          for (var c3 = 6 * e6.e * n3 + o3 * e6.l, f3 = 0; f3 < 6; f3++) {
            for (var d2 = 0; d2 < h3; d2++) {
              var p3, m2 = s3[f3 % l3][d2 % l3];
              p3 = 0 == m2 ? t4 + (f3 >>> 1) : 2 == m2 ? u2 + (f3 >>> 1) : a2 + f3;
              var _3 = e6.h ? (2 * d2 / 3 & 2147483646 | d2 % 3 & 1) + (d2 % 3 >>> 1) : d2 >>> 1;
              i4[c3 + d2] = r3[p3][_3 + 1];
            }
            c3 += e6.e;
          }
        }
        e5._decompressRAF = function(a3, u3) {
          var d2 = function(t5) {
            var i4 = e5._binBE.readUshort, r3 = { b: i4(t5, 0), i: t5[2], C: t5[3], u: t5[4], q: i4(t5, 5), k: i4(t5, 7), e: i4(t5, 9), l: i4(t5, 11), s: t5[13], d: i4(t5, 14) };
            if (18771 != r3.b || r3.i > 1 || r3.q < 6 || r3.q % 6 || r3.e < 768 || r3.e % 24 || 768 != r3.l || r3.k < r3.l || r3.k % r3.l || r3.k - r3.e >= r3.l || r3.s > 16 || r3.s != r3.k / r3.l || r3.s != Math.ceil(r3.e / r3.l) || r3.d != r3.q / 6 || 12 != r3.u && 14 != r3.u && 16 != r3.u || 16 != r3.C && 0 != r3.C) throw "Invalid data";
            if (0 == r3.i) throw "Not implemented. We need this file!";
            return r3.h = 16 == r3.C, r3.m = 0 | (r3.h ? 2 * r3.l / 3 : r3.l >>> 1), r3.A = r3.m + 2, r3.f = 64, r3.g = (1 << r3.u) - 1, r3.n = 4 * r3.u, r3;
          }(a3), p3 = function(t5, i4) {
            var r3 = new Array(i4.s), n3 = 4 * i4.s, a4 = 16 + n3;
            12 & n3 && (a4 += 16 - (12 & n3));
            for (var o3 = 0, s3 = 16; o3 < i4.s; s3 += 4) {
              var l3 = e5._binBE.readUint(t5, s3);
              r3[o3] = t5.slice(a4, a4 + l3), r3[o3].j = 0, r3[o3].a = 0, a4 += l3, o3++;
            }
            if (a4 != t5.length) throw "Invalid data";
            return r3;
          }(a3, d2), m2 = c2(d2), g2 = new Int16Array(d2.e * d2.q);
          null == u3 && (u3 = d2.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]);
          for (var w = [[0, 3], [1, i3], [r2, 11], [n2, o2], [s2, 16], [l2, h2]], v2 = [], x2 = 0; x2 < 18; x2++) v2[x2] = new Uint16Array(d2.A);
          for (var E2 = 0; E2 < d2.s; E2++) {
            var k2 = f2(m2), S2 = f2(m2);
            for (x2 = 0; x2 < 18; x2++) for (var A2 = 0; A2 < d2.A; A2++) v2[x2][A2] = 0;
            for (var I = 0; I < d2.d; I++) {
              b2(d2, m2, p3[E2], v2, k2, S2);
              for (x2 = 0; x2 < 6; x2++) for (A2 = 0; A2 < d2.A; A2++) v2[w[x2][0]][A2] = v2[w[x2][1]][A2];
              y2(d2, g2, v2, I, E2, u3);
              for (x2 = t4; x2 < 18; x2++) if (-1 == [r2, n2, s2, l2].indexOf(x2)) for (A2 = 0; A2 < d2.A; A2++) v2[x2][A2] = 0;
              _2(v2);
            }
          }
          return g2;
        };
      }();
    }(t2, "function" == typeof commonjsRequire ? requirePako() : self.pako);
  }();
}(UTIF);
var UTIFExports = UTIF.exports, utif = getDefaultExportFromCjs(UTIFExports), util$1, objectUtil;
function getDimensionValue(e4) {
  return "number" == typeof e4 ? e4 : e4 instanceof Uint8Array ? e4[0] : "string" == typeof e4[0] ? parseInt(e4[0]) : e4[0];
}
function tiff() {
  return { mime: "image/tiff", encode: (e4) => {
    const t2 = utif.encodeImage(e4.data, e4.width, e4.height);
    return Buffer$1.from(t2);
  }, decode: (e4) => {
    const t2 = utif.decode(e4), i2 = t2[0];
    if (!i2) throw new Error("No page found in TIFF");
    if (!i2.t256) throw new Error("No image width found in TIFF");
    if (!i2.t257) throw new Error("No image height found in TIFF");
    t2.forEach((t3) => {
      utif.decodeImage(e4, t3);
    });
    const r2 = utif.toRGBA8(i2);
    return { data: Buffer$1.from(r2), width: getDimensionValue(i2.t256), height: getDimensionValue(i2.t257) };
  } };
}
!function(e4) {
  e4.assertEqual = (e5) => e5, e4.assertIs = function(e5) {
  }, e4.assertNever = function(e5) {
    throw new Error();
  }, e4.arrayToEnum = (e5) => {
    const t2 = {};
    for (const i2 of e5) t2[i2] = i2;
    return t2;
  }, e4.getValidEnumValues = (t2) => {
    const i2 = e4.objectKeys(t2).filter((e5) => "number" != typeof t2[t2[e5]]), r2 = {};
    for (const e5 of i2) r2[e5] = t2[e5];
    return e4.objectValues(r2);
  }, e4.objectValues = (t2) => e4.objectKeys(t2).map(function(e5) {
    return t2[e5];
  }), e4.objectKeys = "function" == typeof Object.keys ? (e5) => Object.keys(e5) : (e5) => {
    const t2 = [];
    for (const i2 in e5) Object.prototype.hasOwnProperty.call(e5, i2) && t2.push(i2);
    return t2;
  }, e4.find = (e5, t2) => {
    for (const i2 of e5) if (t2(i2)) return i2;
  }, e4.isInteger = "function" == typeof Number.isInteger ? (e5) => Number.isInteger(e5) : (e5) => "number" == typeof e5 && isFinite(e5) && Math.floor(e5) === e5, e4.joinValues = function(e5, t2 = " | ") {
    return e5.map((e6) => "string" == typeof e6 ? `'${e6}'` : e6).join(t2);
  }, e4.jsonStringifyReplacer = (e5, t2) => "bigint" == typeof t2 ? t2.toString() : t2;
}(util$1 || (util$1 = {})), function(e4) {
  e4.mergeShapes = (e5, t2) => ({ ...e5, ...t2 });
}(objectUtil || (objectUtil = {}));
const ZodParsedType = util$1.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]), getParsedType = (e4) => {
  switch (typeof e4) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return isNaN(e4) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      return Array.isArray(e4) ? ZodParsedType.array : null === e4 ? ZodParsedType.null : e4.then && "function" == typeof e4.then && e4.catch && "function" == typeof e4.catch ? ZodParsedType.promise : "undefined" != typeof Map && e4 instanceof Map ? ZodParsedType.map : "undefined" != typeof Set && e4 instanceof Set ? ZodParsedType.set : "undefined" != typeof Date && e4 instanceof Date ? ZodParsedType.date : ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
}, ZodIssueCode = util$1.arrayToEnum(["invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite"]), quotelessJson = (e4) => JSON.stringify(e4, null, 2).replace(/"([^"]+)":/g, "$1:");
class ZodError extends Error {
  constructor(e4) {
    super(), this.issues = [], this.addIssue = (e5) => {
      this.issues = [...this.issues, e5];
    }, this.addIssues = (e5 = []) => {
      this.issues = [...this.issues, ...e5];
    };
    const t2 = new.target.prototype;
    Object.setPrototypeOf ? Object.setPrototypeOf(this, t2) : this.__proto__ = t2, this.name = "ZodError", this.issues = e4;
  }
  get errors() {
    return this.issues;
  }
  format(e4) {
    const t2 = e4 || function(e5) {
      return e5.message;
    }, i2 = { _errors: [] }, r2 = (e5) => {
      for (const n2 of e5.issues) if ("invalid_union" === n2.code) n2.unionErrors.map(r2);
      else if ("invalid_return_type" === n2.code) r2(n2.returnTypeError);
      else if ("invalid_arguments" === n2.code) r2(n2.argumentsError);
      else if (0 === n2.path.length) i2._errors.push(t2(n2));
      else {
        let e6 = i2, r3 = 0;
        for (; r3 < n2.path.length; ) {
          const i3 = n2.path[r3];
          r3 === n2.path.length - 1 ? (e6[i3] = e6[i3] || { _errors: [] }, e6[i3]._errors.push(t2(n2))) : e6[i3] = e6[i3] || { _errors: [] }, e6 = e6[i3], r3++;
        }
      }
    };
    return r2(this), i2;
  }
  static assert(e4) {
    if (!(e4 instanceof ZodError)) throw new Error(`Not a ZodError: ${e4}`);
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util$1.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return 0 === this.issues.length;
  }
  flatten(e4 = (e5) => e5.message) {
    const t2 = {}, i2 = [];
    for (const r2 of this.issues) r2.path.length > 0 ? (t2[r2.path[0]] = t2[r2.path[0]] || [], t2[r2.path[0]].push(e4(r2))) : i2.push(e4(r2));
    return { formErrors: i2, fieldErrors: t2 };
  }
  get formErrors() {
    return this.flatten();
  }
}
ZodError.create = (e4) => new ZodError(e4);
const errorMap = (e4, t2) => {
  let i2;
  switch (e4.code) {
    case ZodIssueCode.invalid_type:
      i2 = e4.received === ZodParsedType.undefined ? "Required" : `Expected ${e4.expected}, received ${e4.received}`;
      break;
    case ZodIssueCode.invalid_literal:
      i2 = `Invalid literal value, expected ${JSON.stringify(e4.expected, util$1.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      i2 = `Unrecognized key(s) in object: ${util$1.joinValues(e4.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      i2 = "Invalid input";
      break;
    case ZodIssueCode.invalid_union_discriminator:
      i2 = `Invalid discriminator value. Expected ${util$1.joinValues(e4.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      i2 = `Invalid enum value. Expected ${util$1.joinValues(e4.options)}, received '${e4.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      i2 = "Invalid function arguments";
      break;
    case ZodIssueCode.invalid_return_type:
      i2 = "Invalid function return type";
      break;
    case ZodIssueCode.invalid_date:
      i2 = "Invalid date";
      break;
    case ZodIssueCode.invalid_string:
      "object" == typeof e4.validation ? "includes" in e4.validation ? (i2 = `Invalid input: must include "${e4.validation.includes}"`, "number" == typeof e4.validation.position && (i2 = `${i2} at one or more positions greater than or equal to ${e4.validation.position}`)) : "startsWith" in e4.validation ? i2 = `Invalid input: must start with "${e4.validation.startsWith}"` : "endsWith" in e4.validation ? i2 = `Invalid input: must end with "${e4.validation.endsWith}"` : util$1.assertNever(e4.validation) : i2 = "regex" !== e4.validation ? `Invalid ${e4.validation}` : "Invalid";
      break;
    case ZodIssueCode.too_small:
      i2 = "array" === e4.type ? `Array must contain ${e4.exact ? "exactly" : e4.inclusive ? "at least" : "more than"} ${e4.minimum} element(s)` : "string" === e4.type ? `String must contain ${e4.exact ? "exactly" : e4.inclusive ? "at least" : "over"} ${e4.minimum} character(s)` : "number" === e4.type ? `Number must be ${e4.exact ? "exactly equal to " : e4.inclusive ? "greater than or equal to " : "greater than "}${e4.minimum}` : "date" === e4.type ? `Date must be ${e4.exact ? "exactly equal to " : e4.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(e4.minimum))}` : "Invalid input";
      break;
    case ZodIssueCode.too_big:
      i2 = "array" === e4.type ? `Array must contain ${e4.exact ? "exactly" : e4.inclusive ? "at most" : "less than"} ${e4.maximum} element(s)` : "string" === e4.type ? `String must contain ${e4.exact ? "exactly" : e4.inclusive ? "at most" : "under"} ${e4.maximum} character(s)` : "number" === e4.type ? `Number must be ${e4.exact ? "exactly" : e4.inclusive ? "less than or equal to" : "less than"} ${e4.maximum}` : "bigint" === e4.type ? `BigInt must be ${e4.exact ? "exactly" : e4.inclusive ? "less than or equal to" : "less than"} ${e4.maximum}` : "date" === e4.type ? `Date must be ${e4.exact ? "exactly" : e4.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(e4.maximum))}` : "Invalid input";
      break;
    case ZodIssueCode.custom:
      i2 = "Invalid input";
      break;
    case ZodIssueCode.invalid_intersection_types:
      i2 = "Intersection results could not be merged";
      break;
    case ZodIssueCode.not_multiple_of:
      i2 = `Number must be a multiple of ${e4.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      i2 = "Number must be finite";
      break;
    default:
      i2 = t2.defaultError, util$1.assertNever(e4);
  }
  return { message: i2 };
};
let overrideErrorMap = errorMap;
function setErrorMap(e4) {
  overrideErrorMap = e4;
}
function getErrorMap() {
  return overrideErrorMap;
}
const makeIssue = (e4) => {
  const { data: t2, path: i2, errorMaps: r2, issueData: n2 } = e4, a2 = [...i2, ...n2.path || []], o2 = { ...n2, path: a2 };
  if (void 0 !== n2.message) return { ...n2, path: a2, message: n2.message };
  let s2 = "";
  const l2 = r2.filter((e5) => !!e5).slice().reverse();
  for (const e5 of l2) s2 = e5(o2, { data: t2, defaultError: s2 }).message;
  return { ...n2, path: a2, message: s2 };
}, EMPTY_PATH = [];
function addIssueToContext(e4, t2) {
  const i2 = getErrorMap(), r2 = makeIssue({ issueData: t2, data: e4.data, path: e4.path, errorMaps: [e4.common.contextualErrorMap, e4.schemaErrorMap, i2, i2 === errorMap ? void 0 : errorMap].filter((e5) => !!e5) });
  e4.common.issues.push(r2);
}
class ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    "valid" === this.value && (this.value = "dirty");
  }
  abort() {
    "aborted" !== this.value && (this.value = "aborted");
  }
  static mergeArray(e4, t2) {
    const i2 = [];
    for (const r2 of t2) {
      if ("aborted" === r2.status) return INVALID;
      "dirty" === r2.status && e4.dirty(), i2.push(r2.value);
    }
    return { status: e4.value, value: i2 };
  }
  static async mergeObjectAsync(e4, t2) {
    const i2 = [];
    for (const e5 of t2) {
      const t3 = await e5.key, r2 = await e5.value;
      i2.push({ key: t3, value: r2 });
    }
    return ParseStatus.mergeObjectSync(e4, i2);
  }
  static mergeObjectSync(e4, t2) {
    const i2 = {};
    for (const r2 of t2) {
      const { key: t3, value: n2 } = r2;
      if ("aborted" === t3.status) return INVALID;
      if ("aborted" === n2.status) return INVALID;
      "dirty" === t3.status && e4.dirty(), "dirty" === n2.status && e4.dirty(), "__proto__" === t3.value || void 0 === n2.value && !r2.alwaysSet || (i2[t3.value] = n2.value);
    }
    return { status: e4.value, value: i2 };
  }
}
const INVALID = Object.freeze({ status: "aborted" }), DIRTY = (e4) => ({ status: "dirty", value: e4 }), OK = (e4) => ({ status: "valid", value: e4 }), isAborted = (e4) => "aborted" === e4.status, isDirty = (e4) => "dirty" === e4.status, isValid = (e4) => "valid" === e4.status, isAsync = (e4) => "undefined" != typeof Promise && e4 instanceof Promise;
function __classPrivateFieldGet(e4, t2, i2, r2) {
  if ("function" == typeof t2 ? e4 !== t2 || true : !t2.has(e4)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return t2.get(e4);
}
function __classPrivateFieldSet(e4, t2, i2, r2, n2) {
  if ("function" == typeof t2 ? e4 !== t2 || true : !t2.has(e4)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return t2.set(e4, i2), i2;
}
var errorUtil, _ZodEnum_cache, _ZodNativeEnum_cache;
"function" == typeof SuppressedError && SuppressedError, function(e4) {
  e4.errToObj = (e5) => "string" == typeof e5 ? { message: e5 } : e5 || {}, e4.toString = (e5) => "string" == typeof e5 ? e5 : null == e5 ? void 0 : e5.message;
}(errorUtil || (errorUtil = {}));
class ParseInputLazyPath {
  constructor(e4, t2, i2, r2) {
    this._cachedPath = [], this.parent = e4, this.data = t2, this._path = i2, this._key = r2;
  }
  get path() {
    return this._cachedPath.length || (this._key instanceof Array ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
  }
}
const handleResult = (e4, t2) => {
  if (isValid(t2)) return { success: true, data: t2.value };
  if (!e4.common.issues.length) throw new Error("Validation failed but no issues detected.");
  return { success: false, get error() {
    if (this._error) return this._error;
    const t3 = new ZodError(e4.common.issues);
    return this._error = t3, this._error;
  } };
};
function processCreateParams(e4) {
  if (!e4) return {};
  const { errorMap: t2, invalid_type_error: i2, required_error: r2, description: n2 } = e4;
  if (t2 && (i2 || r2)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  if (t2) return { errorMap: t2, description: n2 };
  return { errorMap: (t3, n3) => {
    var a2, o2;
    const { message: s2 } = e4;
    return "invalid_enum_value" === t3.code ? { message: null != s2 ? s2 : n3.defaultError } : void 0 === n3.data ? { message: null !== (a2 = null != s2 ? s2 : r2) && void 0 !== a2 ? a2 : n3.defaultError } : "invalid_type" !== t3.code ? { message: n3.defaultError } : { message: null !== (o2 = null != s2 ? s2 : i2) && void 0 !== o2 ? o2 : n3.defaultError };
  }, description: n2 };
}
class ZodType {
  constructor(e4) {
    this.spa = this.safeParseAsync, this._def = e4, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this);
  }
  get description() {
    return this._def.description;
  }
  _getType(e4) {
    return getParsedType(e4.data);
  }
  _getOrReturnCtx(e4, t2) {
    return t2 || { common: e4.parent.common, data: e4.data, parsedType: getParsedType(e4.data), schemaErrorMap: this._def.errorMap, path: e4.path, parent: e4.parent };
  }
  _processInputParams(e4) {
    return { status: new ParseStatus(), ctx: { common: e4.parent.common, data: e4.data, parsedType: getParsedType(e4.data), schemaErrorMap: this._def.errorMap, path: e4.path, parent: e4.parent } };
  }
  _parseSync(e4) {
    const t2 = this._parse(e4);
    if (isAsync(t2)) throw new Error("Synchronous parse encountered promise.");
    return t2;
  }
  _parseAsync(e4) {
    const t2 = this._parse(e4);
    return Promise.resolve(t2);
  }
  parse(e4, t2) {
    const i2 = this.safeParse(e4, t2);
    if (i2.success) return i2.data;
    throw i2.error;
  }
  safeParse(e4, t2) {
    var i2;
    const r2 = { common: { issues: [], async: null !== (i2 = null == t2 ? void 0 : t2.async) && void 0 !== i2 && i2, contextualErrorMap: null == t2 ? void 0 : t2.errorMap }, path: (null == t2 ? void 0 : t2.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: e4, parsedType: getParsedType(e4) }, n2 = this._parseSync({ data: e4, path: r2.path, parent: r2 });
    return handleResult(r2, n2);
  }
  async parseAsync(e4, t2) {
    const i2 = await this.safeParseAsync(e4, t2);
    if (i2.success) return i2.data;
    throw i2.error;
  }
  async safeParseAsync(e4, t2) {
    const i2 = { common: { issues: [], contextualErrorMap: null == t2 ? void 0 : t2.errorMap, async: true }, path: (null == t2 ? void 0 : t2.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: e4, parsedType: getParsedType(e4) }, r2 = this._parse({ data: e4, path: i2.path, parent: i2 }), n2 = await (isAsync(r2) ? r2 : Promise.resolve(r2));
    return handleResult(i2, n2);
  }
  refine(e4, t2) {
    const i2 = (e5) => "string" == typeof t2 || void 0 === t2 ? { message: t2 } : "function" == typeof t2 ? t2(e5) : t2;
    return this._refinement((t3, r2) => {
      const n2 = e4(t3), a2 = () => r2.addIssue({ code: ZodIssueCode.custom, ...i2(t3) });
      return "undefined" != typeof Promise && n2 instanceof Promise ? n2.then((e5) => !!e5 || (a2(), false)) : !!n2 || (a2(), false);
    });
  }
  refinement(e4, t2) {
    return this._refinement((i2, r2) => !!e4(i2) || (r2.addIssue("function" == typeof t2 ? t2(i2, r2) : t2), false));
  }
  _refinement(e4) {
    return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement: e4 } });
  }
  superRefine(e4) {
    return this._refinement(e4);
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this, this._def);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(e4) {
    return ZodUnion.create([this, e4], this._def);
  }
  and(e4) {
    return ZodIntersection.create(this, e4, this._def);
  }
  transform(e4) {
    return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform: e4 } });
  }
  default(e4) {
    const t2 = "function" == typeof e4 ? e4 : () => e4;
    return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: t2, typeName: ZodFirstPartyTypeKind.ZodDefault });
  }
  brand() {
    return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) });
  }
  catch(e4) {
    const t2 = "function" == typeof e4 ? e4 : () => e4;
    return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: t2, typeName: ZodFirstPartyTypeKind.ZodCatch });
  }
  describe(e4) {
    return new this.constructor({ ...this._def, description: e4 });
  }
  pipe(e4) {
    return ZodPipeline.create(this, e4);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
const cuidRegex = /^c[^\s-]{8,}$/i, cuid2Regex = /^[0-9a-z]+$/, ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/, uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i, nanoidRegex = /^[a-z0-9_-]{21}$/i, durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/, emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i, _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, dateRegexSource = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))", dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(e4) {
  let t2 = "([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
  return e4.precision ? t2 = `${t2}\\.\\d{${e4.precision}}` : null == e4.precision && (t2 = `${t2}(\\.\\d+)?`), t2;
}
function timeRegex(e4) {
  return new RegExp(`^${timeRegexSource(e4)}$`);
}
function datetimeRegex(e4) {
  let t2 = `${dateRegexSource}T${timeRegexSource(e4)}`;
  const i2 = [];
  return i2.push(e4.local ? "Z?" : "Z"), e4.offset && i2.push("([+-]\\d{2}:?\\d{2})"), t2 = `${t2}(${i2.join("|")})`, new RegExp(`^${t2}$`);
}
function isValidIP(e4, t2) {
  return !("v4" !== t2 && t2 || !ipv4Regex.test(e4)) || !("v6" !== t2 && t2 || !ipv6Regex.test(e4));
}
class ZodString extends ZodType {
  _parse(e4) {
    this._def.coerce && (e4.data = String(e4.data));
    if (this._getType(e4) !== ZodParsedType.string) {
      const t3 = this._getOrReturnCtx(e4);
      return addIssueToContext(t3, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: t3.parsedType }), INVALID;
    }
    const t2 = new ParseStatus();
    let i2;
    for (const r2 of this._def.checks) if ("min" === r2.kind) e4.data.length < r2.value && (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.too_small, minimum: r2.value, type: "string", inclusive: true, exact: false, message: r2.message }), t2.dirty());
    else if ("max" === r2.kind) e4.data.length > r2.value && (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.too_big, maximum: r2.value, type: "string", inclusive: true, exact: false, message: r2.message }), t2.dirty());
    else if ("length" === r2.kind) {
      const n2 = e4.data.length > r2.value, a2 = e4.data.length < r2.value;
      (n2 || a2) && (i2 = this._getOrReturnCtx(e4, i2), n2 ? addIssueToContext(i2, { code: ZodIssueCode.too_big, maximum: r2.value, type: "string", inclusive: true, exact: true, message: r2.message }) : a2 && addIssueToContext(i2, { code: ZodIssueCode.too_small, minimum: r2.value, type: "string", inclusive: true, exact: true, message: r2.message }), t2.dirty());
    } else if ("email" === r2.kind) emailRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "email", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("emoji" === r2.kind) emojiRegex || (emojiRegex = new RegExp(_emojiRegex, "u")), emojiRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "emoji", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("uuid" === r2.kind) uuidRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "uuid", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("nanoid" === r2.kind) nanoidRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("cuid" === r2.kind) cuidRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "cuid", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("cuid2" === r2.kind) cuid2Regex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("ulid" === r2.kind) ulidRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "ulid", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    else if ("url" === r2.kind) try {
      new URL(e4.data);
    } catch (n2) {
      i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "url", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty();
    }
    else if ("regex" === r2.kind) {
      r2.regex.lastIndex = 0;
      r2.regex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "regex", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty());
    } else if ("trim" === r2.kind) e4.data = e4.data.trim();
    else if ("includes" === r2.kind) e4.data.includes(r2.value, r2.position) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: { includes: r2.value, position: r2.position }, message: r2.message }), t2.dirty());
    else if ("toLowerCase" === r2.kind) e4.data = e4.data.toLowerCase();
    else if ("toUpperCase" === r2.kind) e4.data = e4.data.toUpperCase();
    else if ("startsWith" === r2.kind) e4.data.startsWith(r2.value) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: { startsWith: r2.value }, message: r2.message }), t2.dirty());
    else if ("endsWith" === r2.kind) e4.data.endsWith(r2.value) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: { endsWith: r2.value }, message: r2.message }), t2.dirty());
    else if ("datetime" === r2.kind) {
      datetimeRegex(r2).test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: "datetime", message: r2.message }), t2.dirty());
    } else if ("date" === r2.kind) {
      dateRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: "date", message: r2.message }), t2.dirty());
    } else if ("time" === r2.kind) {
      timeRegex(r2).test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.invalid_string, validation: "time", message: r2.message }), t2.dirty());
    } else "duration" === r2.kind ? durationRegex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "duration", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty()) : "ip" === r2.kind ? isValidIP(e4.data, r2.version) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "ip", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty()) : "base64" === r2.kind ? base64Regex.test(e4.data) || (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { validation: "base64", code: ZodIssueCode.invalid_string, message: r2.message }), t2.dirty()) : util$1.assertNever(r2);
    return { status: t2.value, value: e4.data };
  }
  _regex(e4, t2, i2) {
    return this.refinement((t3) => e4.test(t3), { validation: t2, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(i2) });
  }
  _addCheck(e4) {
    return new ZodString({ ...this._def, checks: [...this._def.checks, e4] });
  }
  email(e4) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(e4) });
  }
  url(e4) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(e4) });
  }
  emoji(e4) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(e4) });
  }
  uuid(e4) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(e4) });
  }
  nanoid(e4) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(e4) });
  }
  cuid(e4) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(e4) });
  }
  cuid2(e4) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(e4) });
  }
  ulid(e4) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(e4) });
  }
  base64(e4) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(e4) });
  }
  ip(e4) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(e4) });
  }
  datetime(e4) {
    var t2, i2;
    return "string" == typeof e4 ? this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: e4 }) : this._addCheck({ kind: "datetime", precision: void 0 === (null == e4 ? void 0 : e4.precision) ? null : null == e4 ? void 0 : e4.precision, offset: null !== (t2 = null == e4 ? void 0 : e4.offset) && void 0 !== t2 && t2, local: null !== (i2 = null == e4 ? void 0 : e4.local) && void 0 !== i2 && i2, ...errorUtil.errToObj(null == e4 ? void 0 : e4.message) });
  }
  date(e4) {
    return this._addCheck({ kind: "date", message: e4 });
  }
  time(e4) {
    return "string" == typeof e4 ? this._addCheck({ kind: "time", precision: null, message: e4 }) : this._addCheck({ kind: "time", precision: void 0 === (null == e4 ? void 0 : e4.precision) ? null : null == e4 ? void 0 : e4.precision, ...errorUtil.errToObj(null == e4 ? void 0 : e4.message) });
  }
  duration(e4) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(e4) });
  }
  regex(e4, t2) {
    return this._addCheck({ kind: "regex", regex: e4, ...errorUtil.errToObj(t2) });
  }
  includes(e4, t2) {
    return this._addCheck({ kind: "includes", value: e4, position: null == t2 ? void 0 : t2.position, ...errorUtil.errToObj(null == t2 ? void 0 : t2.message) });
  }
  startsWith(e4, t2) {
    return this._addCheck({ kind: "startsWith", value: e4, ...errorUtil.errToObj(t2) });
  }
  endsWith(e4, t2) {
    return this._addCheck({ kind: "endsWith", value: e4, ...errorUtil.errToObj(t2) });
  }
  min(e4, t2) {
    return this._addCheck({ kind: "min", value: e4, ...errorUtil.errToObj(t2) });
  }
  max(e4, t2) {
    return this._addCheck({ kind: "max", value: e4, ...errorUtil.errToObj(t2) });
  }
  length(e4, t2) {
    return this._addCheck({ kind: "length", value: e4, ...errorUtil.errToObj(t2) });
  }
  nonempty(e4) {
    return this.min(1, errorUtil.errToObj(e4));
  }
  trim() {
    return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] });
  }
  toLowerCase() {
    return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] });
  }
  toUpperCase() {
    return new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] });
  }
  get isDatetime() {
    return !!this._def.checks.find((e4) => "datetime" === e4.kind);
  }
  get isDate() {
    return !!this._def.checks.find((e4) => "date" === e4.kind);
  }
  get isTime() {
    return !!this._def.checks.find((e4) => "time" === e4.kind);
  }
  get isDuration() {
    return !!this._def.checks.find((e4) => "duration" === e4.kind);
  }
  get isEmail() {
    return !!this._def.checks.find((e4) => "email" === e4.kind);
  }
  get isURL() {
    return !!this._def.checks.find((e4) => "url" === e4.kind);
  }
  get isEmoji() {
    return !!this._def.checks.find((e4) => "emoji" === e4.kind);
  }
  get isUUID() {
    return !!this._def.checks.find((e4) => "uuid" === e4.kind);
  }
  get isNANOID() {
    return !!this._def.checks.find((e4) => "nanoid" === e4.kind);
  }
  get isCUID() {
    return !!this._def.checks.find((e4) => "cuid" === e4.kind);
  }
  get isCUID2() {
    return !!this._def.checks.find((e4) => "cuid2" === e4.kind);
  }
  get isULID() {
    return !!this._def.checks.find((e4) => "ulid" === e4.kind);
  }
  get isIP() {
    return !!this._def.checks.find((e4) => "ip" === e4.kind);
  }
  get isBase64() {
    return !!this._def.checks.find((e4) => "base64" === e4.kind);
  }
  get minLength() {
    let e4 = null;
    for (const t2 of this._def.checks) "min" === t2.kind && (null === e4 || t2.value > e4) && (e4 = t2.value);
    return e4;
  }
  get maxLength() {
    let e4 = null;
    for (const t2 of this._def.checks) "max" === t2.kind && (null === e4 || t2.value < e4) && (e4 = t2.value);
    return e4;
  }
}
function floatSafeRemainder(e4, t2) {
  const i2 = (e4.toString().split(".")[1] || "").length, r2 = (t2.toString().split(".")[1] || "").length, n2 = i2 > r2 ? i2 : r2;
  return parseInt(e4.toFixed(n2).replace(".", "")) % parseInt(t2.toFixed(n2).replace(".", "")) / Math.pow(10, n2);
}
ZodString.create = (e4) => {
  var t2;
  return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: null !== (t2 = null == e4 ? void 0 : e4.coerce) && void 0 !== t2 && t2, ...processCreateParams(e4) });
};
class ZodNumber extends ZodType {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;
  }
  _parse(e4) {
    this._def.coerce && (e4.data = Number(e4.data));
    if (this._getType(e4) !== ZodParsedType.number) {
      const t3 = this._getOrReturnCtx(e4);
      return addIssueToContext(t3, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: t3.parsedType }), INVALID;
    }
    let t2;
    const i2 = new ParseStatus();
    for (const r2 of this._def.checks) if ("int" === r2.kind) util$1.isInteger(e4.data) || (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: r2.message }), i2.dirty());
    else if ("min" === r2.kind) {
      (r2.inclusive ? e4.data < r2.value : e4.data <= r2.value) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.too_small, minimum: r2.value, type: "number", inclusive: r2.inclusive, exact: false, message: r2.message }), i2.dirty());
    } else if ("max" === r2.kind) {
      (r2.inclusive ? e4.data > r2.value : e4.data >= r2.value) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.too_big, maximum: r2.value, type: "number", inclusive: r2.inclusive, exact: false, message: r2.message }), i2.dirty());
    } else "multipleOf" === r2.kind ? 0 !== floatSafeRemainder(e4.data, r2.value) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.not_multiple_of, multipleOf: r2.value, message: r2.message }), i2.dirty()) : "finite" === r2.kind ? Number.isFinite(e4.data) || (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.not_finite, message: r2.message }), i2.dirty()) : util$1.assertNever(r2);
    return { status: i2.value, value: e4.data };
  }
  gte(e4, t2) {
    return this.setLimit("min", e4, true, errorUtil.toString(t2));
  }
  gt(e4, t2) {
    return this.setLimit("min", e4, false, errorUtil.toString(t2));
  }
  lte(e4, t2) {
    return this.setLimit("max", e4, true, errorUtil.toString(t2));
  }
  lt(e4, t2) {
    return this.setLimit("max", e4, false, errorUtil.toString(t2));
  }
  setLimit(e4, t2, i2, r2) {
    return new ZodNumber({ ...this._def, checks: [...this._def.checks, { kind: e4, value: t2, inclusive: i2, message: errorUtil.toString(r2) }] });
  }
  _addCheck(e4) {
    return new ZodNumber({ ...this._def, checks: [...this._def.checks, e4] });
  }
  int(e4) {
    return this._addCheck({ kind: "int", message: errorUtil.toString(e4) });
  }
  positive(e4) {
    return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(e4) });
  }
  negative(e4) {
    return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(e4) });
  }
  nonpositive(e4) {
    return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(e4) });
  }
  nonnegative(e4) {
    return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(e4) });
  }
  multipleOf(e4, t2) {
    return this._addCheck({ kind: "multipleOf", value: e4, message: errorUtil.toString(t2) });
  }
  finite(e4) {
    return this._addCheck({ kind: "finite", message: errorUtil.toString(e4) });
  }
  safe(e4) {
    return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(e4) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(e4) });
  }
  get minValue() {
    let e4 = null;
    for (const t2 of this._def.checks) "min" === t2.kind && (null === e4 || t2.value > e4) && (e4 = t2.value);
    return e4;
  }
  get maxValue() {
    let e4 = null;
    for (const t2 of this._def.checks) "max" === t2.kind && (null === e4 || t2.value < e4) && (e4 = t2.value);
    return e4;
  }
  get isInt() {
    return !!this._def.checks.find((e4) => "int" === e4.kind || "multipleOf" === e4.kind && util$1.isInteger(e4.value));
  }
  get isFinite() {
    let e4 = null, t2 = null;
    for (const i2 of this._def.checks) {
      if ("finite" === i2.kind || "int" === i2.kind || "multipleOf" === i2.kind) return true;
      "min" === i2.kind ? (null === t2 || i2.value > t2) && (t2 = i2.value) : "max" === i2.kind && (null === e4 || i2.value < e4) && (e4 = i2.value);
    }
    return Number.isFinite(t2) && Number.isFinite(e4);
  }
}
ZodNumber.create = (e4) => new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (null == e4 ? void 0 : e4.coerce) || false, ...processCreateParams(e4) });
class ZodBigInt extends ZodType {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte;
  }
  _parse(e4) {
    this._def.coerce && (e4.data = BigInt(e4.data));
    if (this._getType(e4) !== ZodParsedType.bigint) {
      const t3 = this._getOrReturnCtx(e4);
      return addIssueToContext(t3, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: t3.parsedType }), INVALID;
    }
    let t2;
    const i2 = new ParseStatus();
    for (const r2 of this._def.checks) if ("min" === r2.kind) {
      (r2.inclusive ? e4.data < r2.value : e4.data <= r2.value) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.too_small, type: "bigint", minimum: r2.value, inclusive: r2.inclusive, message: r2.message }), i2.dirty());
    } else if ("max" === r2.kind) {
      (r2.inclusive ? e4.data > r2.value : e4.data >= r2.value) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.too_big, type: "bigint", maximum: r2.value, inclusive: r2.inclusive, message: r2.message }), i2.dirty());
    } else "multipleOf" === r2.kind ? e4.data % r2.value !== BigInt(0) && (t2 = this._getOrReturnCtx(e4, t2), addIssueToContext(t2, { code: ZodIssueCode.not_multiple_of, multipleOf: r2.value, message: r2.message }), i2.dirty()) : util$1.assertNever(r2);
    return { status: i2.value, value: e4.data };
  }
  gte(e4, t2) {
    return this.setLimit("min", e4, true, errorUtil.toString(t2));
  }
  gt(e4, t2) {
    return this.setLimit("min", e4, false, errorUtil.toString(t2));
  }
  lte(e4, t2) {
    return this.setLimit("max", e4, true, errorUtil.toString(t2));
  }
  lt(e4, t2) {
    return this.setLimit("max", e4, false, errorUtil.toString(t2));
  }
  setLimit(e4, t2, i2, r2) {
    return new ZodBigInt({ ...this._def, checks: [...this._def.checks, { kind: e4, value: t2, inclusive: i2, message: errorUtil.toString(r2) }] });
  }
  _addCheck(e4) {
    return new ZodBigInt({ ...this._def, checks: [...this._def.checks, e4] });
  }
  positive(e4) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(e4) });
  }
  negative(e4) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(e4) });
  }
  nonpositive(e4) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(e4) });
  }
  nonnegative(e4) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(e4) });
  }
  multipleOf(e4, t2) {
    return this._addCheck({ kind: "multipleOf", value: e4, message: errorUtil.toString(t2) });
  }
  get minValue() {
    let e4 = null;
    for (const t2 of this._def.checks) "min" === t2.kind && (null === e4 || t2.value > e4) && (e4 = t2.value);
    return e4;
  }
  get maxValue() {
    let e4 = null;
    for (const t2 of this._def.checks) "max" === t2.kind && (null === e4 || t2.value < e4) && (e4 = t2.value);
    return e4;
  }
}
ZodBigInt.create = (e4) => {
  var t2;
  return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: null !== (t2 = null == e4 ? void 0 : e4.coerce) && void 0 !== t2 && t2, ...processCreateParams(e4) });
};
class ZodBoolean extends ZodType {
  _parse(e4) {
    this._def.coerce && (e4.data = Boolean(e4.data));
    if (this._getType(e4) !== ZodParsedType.boolean) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: t2.parsedType }), INVALID;
    }
    return OK(e4.data);
  }
}
ZodBoolean.create = (e4) => new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (null == e4 ? void 0 : e4.coerce) || false, ...processCreateParams(e4) });
class ZodDate extends ZodType {
  _parse(e4) {
    this._def.coerce && (e4.data = new Date(e4.data));
    if (this._getType(e4) !== ZodParsedType.date) {
      const t3 = this._getOrReturnCtx(e4);
      return addIssueToContext(t3, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: t3.parsedType }), INVALID;
    }
    if (isNaN(e4.data.getTime())) {
      return addIssueToContext(this._getOrReturnCtx(e4), { code: ZodIssueCode.invalid_date }), INVALID;
    }
    const t2 = new ParseStatus();
    let i2;
    for (const r2 of this._def.checks) "min" === r2.kind ? e4.data.getTime() < r2.value && (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.too_small, message: r2.message, inclusive: true, exact: false, minimum: r2.value, type: "date" }), t2.dirty()) : "max" === r2.kind ? e4.data.getTime() > r2.value && (i2 = this._getOrReturnCtx(e4, i2), addIssueToContext(i2, { code: ZodIssueCode.too_big, message: r2.message, inclusive: true, exact: false, maximum: r2.value, type: "date" }), t2.dirty()) : util$1.assertNever(r2);
    return { status: t2.value, value: new Date(e4.data.getTime()) };
  }
  _addCheck(e4) {
    return new ZodDate({ ...this._def, checks: [...this._def.checks, e4] });
  }
  min(e4, t2) {
    return this._addCheck({ kind: "min", value: e4.getTime(), message: errorUtil.toString(t2) });
  }
  max(e4, t2) {
    return this._addCheck({ kind: "max", value: e4.getTime(), message: errorUtil.toString(t2) });
  }
  get minDate() {
    let e4 = null;
    for (const t2 of this._def.checks) "min" === t2.kind && (null === e4 || t2.value > e4) && (e4 = t2.value);
    return null != e4 ? new Date(e4) : null;
  }
  get maxDate() {
    let e4 = null;
    for (const t2 of this._def.checks) "max" === t2.kind && (null === e4 || t2.value < e4) && (e4 = t2.value);
    return null != e4 ? new Date(e4) : null;
  }
}
ZodDate.create = (e4) => new ZodDate({ checks: [], coerce: (null == e4 ? void 0 : e4.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(e4) });
class ZodSymbol extends ZodType {
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.symbol) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: t2.parsedType }), INVALID;
    }
    return OK(e4.data);
  }
}
ZodSymbol.create = (e4) => new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(e4) });
class ZodUndefined extends ZodType {
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.undefined) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: t2.parsedType }), INVALID;
    }
    return OK(e4.data);
  }
}
ZodUndefined.create = (e4) => new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(e4) });
class ZodNull extends ZodType {
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.null) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: t2.parsedType }), INVALID;
    }
    return OK(e4.data);
  }
}
ZodNull.create = (e4) => new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(e4) });
class ZodAny extends ZodType {
  constructor() {
    super(...arguments), this._any = true;
  }
  _parse(e4) {
    return OK(e4.data);
  }
}
ZodAny.create = (e4) => new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(e4) });
class ZodUnknown extends ZodType {
  constructor() {
    super(...arguments), this._unknown = true;
  }
  _parse(e4) {
    return OK(e4.data);
  }
}
ZodUnknown.create = (e4) => new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(e4) });
class ZodNever extends ZodType {
  _parse(e4) {
    const t2 = this._getOrReturnCtx(e4);
    return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: t2.parsedType }), INVALID;
  }
}
ZodNever.create = (e4) => new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(e4) });
class ZodVoid extends ZodType {
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.undefined) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: t2.parsedType }), INVALID;
    }
    return OK(e4.data);
  }
}
ZodVoid.create = (e4) => new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(e4) });
class ZodArray extends ZodType {
  _parse(e4) {
    const { ctx: t2, status: i2 } = this._processInputParams(e4), r2 = this._def;
    if (t2.parsedType !== ZodParsedType.array) return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: t2.parsedType }), INVALID;
    if (null !== r2.exactLength) {
      const e5 = t2.data.length > r2.exactLength.value, n3 = t2.data.length < r2.exactLength.value;
      (e5 || n3) && (addIssueToContext(t2, { code: e5 ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: n3 ? r2.exactLength.value : void 0, maximum: e5 ? r2.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: r2.exactLength.message }), i2.dirty());
    }
    if (null !== r2.minLength && t2.data.length < r2.minLength.value && (addIssueToContext(t2, { code: ZodIssueCode.too_small, minimum: r2.minLength.value, type: "array", inclusive: true, exact: false, message: r2.minLength.message }), i2.dirty()), null !== r2.maxLength && t2.data.length > r2.maxLength.value && (addIssueToContext(t2, { code: ZodIssueCode.too_big, maximum: r2.maxLength.value, type: "array", inclusive: true, exact: false, message: r2.maxLength.message }), i2.dirty()), t2.common.async) return Promise.all([...t2.data].map((e5, i3) => r2.type._parseAsync(new ParseInputLazyPath(t2, e5, t2.path, i3)))).then((e5) => ParseStatus.mergeArray(i2, e5));
    const n2 = [...t2.data].map((e5, i3) => r2.type._parseSync(new ParseInputLazyPath(t2, e5, t2.path, i3)));
    return ParseStatus.mergeArray(i2, n2);
  }
  get element() {
    return this._def.type;
  }
  min(e4, t2) {
    return new ZodArray({ ...this._def, minLength: { value: e4, message: errorUtil.toString(t2) } });
  }
  max(e4, t2) {
    return new ZodArray({ ...this._def, maxLength: { value: e4, message: errorUtil.toString(t2) } });
  }
  length(e4, t2) {
    return new ZodArray({ ...this._def, exactLength: { value: e4, message: errorUtil.toString(t2) } });
  }
  nonempty(e4) {
    return this.min(1, e4);
  }
}
function deepPartialify(e4) {
  if (e4 instanceof ZodObject) {
    const t2 = {};
    for (const i2 in e4.shape) {
      const r2 = e4.shape[i2];
      t2[i2] = ZodOptional.create(deepPartialify(r2));
    }
    return new ZodObject({ ...e4._def, shape: () => t2 });
  }
  return e4 instanceof ZodArray ? new ZodArray({ ...e4._def, type: deepPartialify(e4.element) }) : e4 instanceof ZodOptional ? ZodOptional.create(deepPartialify(e4.unwrap())) : e4 instanceof ZodNullable ? ZodNullable.create(deepPartialify(e4.unwrap())) : e4 instanceof ZodTuple ? ZodTuple.create(e4.items.map((e5) => deepPartialify(e5))) : e4;
}
ZodArray.create = (e4, t2) => new ZodArray({ type: e4, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(t2) });
class ZodObject extends ZodType {
  constructor() {
    super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
  }
  _getCached() {
    if (null !== this._cached) return this._cached;
    const e4 = this._def.shape(), t2 = util$1.objectKeys(e4);
    return this._cached = { shape: e4, keys: t2 };
  }
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.object) {
      const t3 = this._getOrReturnCtx(e4);
      return addIssueToContext(t3, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: t3.parsedType }), INVALID;
    }
    const { status: t2, ctx: i2 } = this._processInputParams(e4), { shape: r2, keys: n2 } = this._getCached(), a2 = [];
    if (!(this._def.catchall instanceof ZodNever && "strip" === this._def.unknownKeys)) for (const e5 in i2.data) n2.includes(e5) || a2.push(e5);
    const o2 = [];
    for (const e5 of n2) {
      const t3 = r2[e5], n3 = i2.data[e5];
      o2.push({ key: { status: "valid", value: e5 }, value: t3._parse(new ParseInputLazyPath(i2, n3, i2.path, e5)), alwaysSet: e5 in i2.data });
    }
    if (this._def.catchall instanceof ZodNever) {
      const e5 = this._def.unknownKeys;
      if ("passthrough" === e5) for (const e6 of a2) o2.push({ key: { status: "valid", value: e6 }, value: { status: "valid", value: i2.data[e6] } });
      else if ("strict" === e5) a2.length > 0 && (addIssueToContext(i2, { code: ZodIssueCode.unrecognized_keys, keys: a2 }), t2.dirty());
      else if ("strip" !== e5) throw new Error("Internal ZodObject error: invalid unknownKeys value.");
    } else {
      const e5 = this._def.catchall;
      for (const t3 of a2) {
        const r3 = i2.data[t3];
        o2.push({ key: { status: "valid", value: t3 }, value: e5._parse(new ParseInputLazyPath(i2, r3, i2.path, t3)), alwaysSet: t3 in i2.data });
      }
    }
    return i2.common.async ? Promise.resolve().then(async () => {
      const e5 = [];
      for (const t3 of o2) {
        const i3 = await t3.key, r3 = await t3.value;
        e5.push({ key: i3, value: r3, alwaysSet: t3.alwaysSet });
      }
      return e5;
    }).then((e5) => ParseStatus.mergeObjectSync(t2, e5)) : ParseStatus.mergeObjectSync(t2, o2);
  }
  get shape() {
    return this._def.shape();
  }
  strict(e4) {
    return errorUtil.errToObj, new ZodObject({ ...this._def, unknownKeys: "strict", ...void 0 !== e4 ? { errorMap: (t2, i2) => {
      var r2, n2, a2, o2;
      const s2 = null !== (a2 = null === (n2 = (r2 = this._def).errorMap) || void 0 === n2 ? void 0 : n2.call(r2, t2, i2).message) && void 0 !== a2 ? a2 : i2.defaultError;
      return "unrecognized_keys" === t2.code ? { message: null !== (o2 = errorUtil.errToObj(e4).message) && void 0 !== o2 ? o2 : s2 } : { message: s2 };
    } } : {} });
  }
  strip() {
    return new ZodObject({ ...this._def, unknownKeys: "strip" });
  }
  passthrough() {
    return new ZodObject({ ...this._def, unknownKeys: "passthrough" });
  }
  extend(e4) {
    return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...e4 }) });
  }
  merge(e4) {
    return new ZodObject({ unknownKeys: e4._def.unknownKeys, catchall: e4._def.catchall, shape: () => ({ ...this._def.shape(), ...e4._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject });
  }
  setKey(e4, t2) {
    return this.augment({ [e4]: t2 });
  }
  catchall(e4) {
    return new ZodObject({ ...this._def, catchall: e4 });
  }
  pick(e4) {
    const t2 = {};
    return util$1.objectKeys(e4).forEach((i2) => {
      e4[i2] && this.shape[i2] && (t2[i2] = this.shape[i2]);
    }), new ZodObject({ ...this._def, shape: () => t2 });
  }
  omit(e4) {
    const t2 = {};
    return util$1.objectKeys(this.shape).forEach((i2) => {
      e4[i2] || (t2[i2] = this.shape[i2]);
    }), new ZodObject({ ...this._def, shape: () => t2 });
  }
  deepPartial() {
    return deepPartialify(this);
  }
  partial(e4) {
    const t2 = {};
    return util$1.objectKeys(this.shape).forEach((i2) => {
      const r2 = this.shape[i2];
      e4 && !e4[i2] ? t2[i2] = r2 : t2[i2] = r2.optional();
    }), new ZodObject({ ...this._def, shape: () => t2 });
  }
  required(e4) {
    const t2 = {};
    return util$1.objectKeys(this.shape).forEach((i2) => {
      if (e4 && !e4[i2]) t2[i2] = this.shape[i2];
      else {
        let e5 = this.shape[i2];
        for (; e5 instanceof ZodOptional; ) e5 = e5._def.innerType;
        t2[i2] = e5;
      }
    }), new ZodObject({ ...this._def, shape: () => t2 });
  }
  keyof() {
    return createZodEnum(util$1.objectKeys(this.shape));
  }
}
ZodObject.create = (e4, t2) => new ZodObject({ shape: () => e4, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(t2) }), ZodObject.strictCreate = (e4, t2) => new ZodObject({ shape: () => e4, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(t2) }), ZodObject.lazycreate = (e4, t2) => new ZodObject({ shape: e4, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(t2) });
class ZodUnion extends ZodType {
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4), i2 = this._def.options;
    if (t2.common.async) return Promise.all(i2.map(async (e5) => {
      const i3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null };
      return { result: await e5._parseAsync({ data: t2.data, path: t2.path, parent: i3 }), ctx: i3 };
    })).then(function(e5) {
      for (const t3 of e5) if ("valid" === t3.result.status) return t3.result;
      for (const i4 of e5) if ("dirty" === i4.result.status) return t2.common.issues.push(...i4.ctx.common.issues), i4.result;
      const i3 = e5.map((e6) => new ZodError(e6.ctx.common.issues));
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_union, unionErrors: i3 }), INVALID;
    });
    {
      let e5;
      const r2 = [];
      for (const n3 of i2) {
        const i3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null }, a2 = n3._parseSync({ data: t2.data, path: t2.path, parent: i3 });
        if ("valid" === a2.status) return a2;
        "dirty" !== a2.status || e5 || (e5 = { result: a2, ctx: i3 }), i3.common.issues.length && r2.push(i3.common.issues);
      }
      if (e5) return t2.common.issues.push(...e5.ctx.common.issues), e5.result;
      const n2 = r2.map((e6) => new ZodError(e6));
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_union, unionErrors: n2 }), INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
}
ZodUnion.create = (e4, t2) => new ZodUnion({ options: e4, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(t2) });
const getDiscriminator = (e4) => e4 instanceof ZodLazy ? getDiscriminator(e4.schema) : e4 instanceof ZodEffects ? getDiscriminator(e4.innerType()) : e4 instanceof ZodLiteral ? [e4.value] : e4 instanceof ZodEnum ? e4.options : e4 instanceof ZodNativeEnum ? util$1.objectValues(e4.enum) : e4 instanceof ZodDefault ? getDiscriminator(e4._def.innerType) : e4 instanceof ZodUndefined ? [void 0] : e4 instanceof ZodNull ? [null] : e4 instanceof ZodOptional ? [void 0, ...getDiscriminator(e4.unwrap())] : e4 instanceof ZodNullable ? [null, ...getDiscriminator(e4.unwrap())] : e4 instanceof ZodBranded || e4 instanceof ZodReadonly ? getDiscriminator(e4.unwrap()) : e4 instanceof ZodCatch ? getDiscriminator(e4._def.innerType) : [];
class ZodDiscriminatedUnion extends ZodType {
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4);
    if (t2.parsedType !== ZodParsedType.object) return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: t2.parsedType }), INVALID;
    const i2 = this.discriminator, r2 = t2.data[i2], n2 = this.optionsMap.get(r2);
    return n2 ? t2.common.async ? n2._parseAsync({ data: t2.data, path: t2.path, parent: t2 }) : n2._parseSync({ data: t2.data, path: t2.path, parent: t2 }) : (addIssueToContext(t2, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [i2] }), INVALID);
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create(e4, t2, i2) {
    const r2 = /* @__PURE__ */ new Map();
    for (const i3 of t2) {
      const t3 = getDiscriminator(i3.shape[e4]);
      if (!t3.length) throw new Error(`A discriminator value for key \`${e4}\` could not be extracted from all schema options`);
      for (const n2 of t3) {
        if (r2.has(n2)) throw new Error(`Discriminator property ${String(e4)} has duplicate value ${String(n2)}`);
        r2.set(n2, i3);
      }
    }
    return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator: e4, options: t2, optionsMap: r2, ...processCreateParams(i2) });
  }
}
function mergeValues(e4, t2) {
  const i2 = getParsedType(e4), r2 = getParsedType(t2);
  if (e4 === t2) return { valid: true, data: e4 };
  if (i2 === ZodParsedType.object && r2 === ZodParsedType.object) {
    const i3 = util$1.objectKeys(t2), r3 = util$1.objectKeys(e4).filter((e5) => -1 !== i3.indexOf(e5)), n2 = { ...e4, ...t2 };
    for (const i4 of r3) {
      const r4 = mergeValues(e4[i4], t2[i4]);
      if (!r4.valid) return { valid: false };
      n2[i4] = r4.data;
    }
    return { valid: true, data: n2 };
  }
  if (i2 === ZodParsedType.array && r2 === ZodParsedType.array) {
    if (e4.length !== t2.length) return { valid: false };
    const i3 = [];
    for (let r3 = 0; r3 < e4.length; r3++) {
      const n2 = mergeValues(e4[r3], t2[r3]);
      if (!n2.valid) return { valid: false };
      i3.push(n2.data);
    }
    return { valid: true, data: i3 };
  }
  return i2 === ZodParsedType.date && r2 === ZodParsedType.date && +e4 == +t2 ? { valid: true, data: e4 } : { valid: false };
}
class ZodIntersection extends ZodType {
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4), r2 = (e5, r3) => {
      if (isAborted(e5) || isAborted(r3)) return INVALID;
      const n2 = mergeValues(e5.value, r3.value);
      return n2.valid ? ((isDirty(e5) || isDirty(r3)) && t2.dirty(), { status: t2.value, value: n2.data }) : (addIssueToContext(i2, { code: ZodIssueCode.invalid_intersection_types }), INVALID);
    };
    return i2.common.async ? Promise.all([this._def.left._parseAsync({ data: i2.data, path: i2.path, parent: i2 }), this._def.right._parseAsync({ data: i2.data, path: i2.path, parent: i2 })]).then(([e5, t3]) => r2(e5, t3)) : r2(this._def.left._parseSync({ data: i2.data, path: i2.path, parent: i2 }), this._def.right._parseSync({ data: i2.data, path: i2.path, parent: i2 }));
  }
}
ZodIntersection.create = (e4, t2, i2) => new ZodIntersection({ left: e4, right: t2, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(i2) });
class ZodTuple extends ZodType {
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4);
    if (i2.parsedType !== ZodParsedType.array) return addIssueToContext(i2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: i2.parsedType }), INVALID;
    if (i2.data.length < this._def.items.length) return addIssueToContext(i2, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }), INVALID;
    !this._def.rest && i2.data.length > this._def.items.length && (addIssueToContext(i2, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }), t2.dirty());
    const r2 = [...i2.data].map((e5, t3) => {
      const r3 = this._def.items[t3] || this._def.rest;
      return r3 ? r3._parse(new ParseInputLazyPath(i2, e5, i2.path, t3)) : null;
    }).filter((e5) => !!e5);
    return i2.common.async ? Promise.all(r2).then((e5) => ParseStatus.mergeArray(t2, e5)) : ParseStatus.mergeArray(t2, r2);
  }
  get items() {
    return this._def.items;
  }
  rest(e4) {
    return new ZodTuple({ ...this._def, rest: e4 });
  }
}
ZodTuple.create = (e4, t2) => {
  if (!Array.isArray(e4)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  return new ZodTuple({ items: e4, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(t2) });
};
class ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4);
    if (i2.parsedType !== ZodParsedType.object) return addIssueToContext(i2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: i2.parsedType }), INVALID;
    const r2 = [], n2 = this._def.keyType, a2 = this._def.valueType;
    for (const e5 in i2.data) r2.push({ key: n2._parse(new ParseInputLazyPath(i2, e5, i2.path, e5)), value: a2._parse(new ParseInputLazyPath(i2, i2.data[e5], i2.path, e5)), alwaysSet: e5 in i2.data });
    return i2.common.async ? ParseStatus.mergeObjectAsync(t2, r2) : ParseStatus.mergeObjectSync(t2, r2);
  }
  get element() {
    return this._def.valueType;
  }
  static create(e4, t2, i2) {
    return new ZodRecord(t2 instanceof ZodType ? { keyType: e4, valueType: t2, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(i2) } : { keyType: ZodString.create(), valueType: e4, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(t2) });
  }
}
class ZodMap extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4);
    if (i2.parsedType !== ZodParsedType.map) return addIssueToContext(i2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: i2.parsedType }), INVALID;
    const r2 = this._def.keyType, n2 = this._def.valueType, a2 = [...i2.data.entries()].map(([e5, t3], a3) => ({ key: r2._parse(new ParseInputLazyPath(i2, e5, i2.path, [a3, "key"])), value: n2._parse(new ParseInputLazyPath(i2, t3, i2.path, [a3, "value"])) }));
    if (i2.common.async) {
      const e5 = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const i3 of a2) {
          const r3 = await i3.key, n3 = await i3.value;
          if ("aborted" === r3.status || "aborted" === n3.status) return INVALID;
          "dirty" !== r3.status && "dirty" !== n3.status || t2.dirty(), e5.set(r3.value, n3.value);
        }
        return { status: t2.value, value: e5 };
      });
    }
    {
      const e5 = /* @__PURE__ */ new Map();
      for (const i3 of a2) {
        const r3 = i3.key, n3 = i3.value;
        if ("aborted" === r3.status || "aborted" === n3.status) return INVALID;
        "dirty" !== r3.status && "dirty" !== n3.status || t2.dirty(), e5.set(r3.value, n3.value);
      }
      return { status: t2.value, value: e5 };
    }
  }
}
ZodMap.create = (e4, t2, i2) => new ZodMap({ valueType: t2, keyType: e4, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(i2) });
class ZodSet extends ZodType {
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4);
    if (i2.parsedType !== ZodParsedType.set) return addIssueToContext(i2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: i2.parsedType }), INVALID;
    const r2 = this._def;
    null !== r2.minSize && i2.data.size < r2.minSize.value && (addIssueToContext(i2, { code: ZodIssueCode.too_small, minimum: r2.minSize.value, type: "set", inclusive: true, exact: false, message: r2.minSize.message }), t2.dirty()), null !== r2.maxSize && i2.data.size > r2.maxSize.value && (addIssueToContext(i2, { code: ZodIssueCode.too_big, maximum: r2.maxSize.value, type: "set", inclusive: true, exact: false, message: r2.maxSize.message }), t2.dirty());
    const n2 = this._def.valueType;
    function a2(e5) {
      const i3 = /* @__PURE__ */ new Set();
      for (const r3 of e5) {
        if ("aborted" === r3.status) return INVALID;
        "dirty" === r3.status && t2.dirty(), i3.add(r3.value);
      }
      return { status: t2.value, value: i3 };
    }
    const o2 = [...i2.data.values()].map((e5, t3) => n2._parse(new ParseInputLazyPath(i2, e5, i2.path, t3)));
    return i2.common.async ? Promise.all(o2).then((e5) => a2(e5)) : a2(o2);
  }
  min(e4, t2) {
    return new ZodSet({ ...this._def, minSize: { value: e4, message: errorUtil.toString(t2) } });
  }
  max(e4, t2) {
    return new ZodSet({ ...this._def, maxSize: { value: e4, message: errorUtil.toString(t2) } });
  }
  size(e4, t2) {
    return this.min(e4, t2).max(e4, t2);
  }
  nonempty(e4) {
    return this.min(1, e4);
  }
}
ZodSet.create = (e4, t2) => new ZodSet({ valueType: e4, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(t2) });
class ZodFunction extends ZodType {
  constructor() {
    super(...arguments), this.validate = this.implement;
  }
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4);
    if (t2.parsedType !== ZodParsedType.function) return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: t2.parsedType }), INVALID;
    function i2(e5, i3) {
      return makeIssue({ data: e5, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, getErrorMap(), errorMap].filter((e6) => !!e6), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: i3 } });
    }
    function r2(e5, i3) {
      return makeIssue({ data: e5, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, getErrorMap(), errorMap].filter((e6) => !!e6), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: i3 } });
    }
    const n2 = { errorMap: t2.common.contextualErrorMap }, a2 = t2.data;
    if (this._def.returns instanceof ZodPromise) {
      const e5 = this;
      return OK(async function(...t3) {
        const o2 = new ZodError([]), s2 = await e5._def.args.parseAsync(t3, n2).catch((e6) => {
          throw o2.addIssue(i2(t3, e6)), o2;
        }), l2 = await Reflect.apply(a2, this, s2), u2 = await e5._def.returns._def.type.parseAsync(l2, n2).catch((e6) => {
          throw o2.addIssue(r2(l2, e6)), o2;
        });
        return u2;
      });
    }
    {
      const e5 = this;
      return OK(function(...t3) {
        const o2 = e5._def.args.safeParse(t3, n2);
        if (!o2.success) throw new ZodError([i2(t3, o2.error)]);
        const s2 = Reflect.apply(a2, this, o2.data), l2 = e5._def.returns.safeParse(s2, n2);
        if (!l2.success) throw new ZodError([r2(s2, l2.error)]);
        return l2.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...e4) {
    return new ZodFunction({ ...this._def, args: ZodTuple.create(e4).rest(ZodUnknown.create()) });
  }
  returns(e4) {
    return new ZodFunction({ ...this._def, returns: e4 });
  }
  implement(e4) {
    return this.parse(e4);
  }
  strictImplement(e4) {
    return this.parse(e4);
  }
  static create(e4, t2, i2) {
    return new ZodFunction({ args: e4 || ZodTuple.create([]).rest(ZodUnknown.create()), returns: t2 || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(i2) });
  }
}
class ZodLazy extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4);
    return this._def.getter()._parse({ data: t2.data, path: t2.path, parent: t2 });
  }
}
ZodLazy.create = (e4, t2) => new ZodLazy({ getter: e4, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(t2) });
class ZodLiteral extends ZodType {
  _parse(e4) {
    if (e4.data !== this._def.value) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { received: t2.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }), INVALID;
    }
    return { status: "valid", value: e4.data };
  }
  get value() {
    return this._def.value;
  }
}
function createZodEnum(e4, t2) {
  return new ZodEnum({ values: e4, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(t2) });
}
ZodLiteral.create = (e4, t2) => new ZodLiteral({ value: e4, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(t2) });
class ZodEnum extends ZodType {
  constructor() {
    super(...arguments), _ZodEnum_cache.set(this, void 0);
  }
  _parse(e4) {
    if ("string" != typeof e4.data) {
      const t2 = this._getOrReturnCtx(e4), i2 = this._def.values;
      return addIssueToContext(t2, { expected: util$1.joinValues(i2), received: t2.parsedType, code: ZodIssueCode.invalid_type }), INVALID;
    }
    if (__classPrivateFieldGet(this, _ZodEnum_cache) || __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values)), !__classPrivateFieldGet(this, _ZodEnum_cache).has(e4.data)) {
      const t2 = this._getOrReturnCtx(e4), i2 = this._def.values;
      return addIssueToContext(t2, { received: t2.data, code: ZodIssueCode.invalid_enum_value, options: i2 }), INVALID;
    }
    return OK(e4.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const e4 = {};
    for (const t2 of this._def.values) e4[t2] = t2;
    return e4;
  }
  get Values() {
    const e4 = {};
    for (const t2 of this._def.values) e4[t2] = t2;
    return e4;
  }
  get Enum() {
    const e4 = {};
    for (const t2 of this._def.values) e4[t2] = t2;
    return e4;
  }
  extract(e4, t2 = this._def) {
    return ZodEnum.create(e4, { ...this._def, ...t2 });
  }
  exclude(e4, t2 = this._def) {
    return ZodEnum.create(this.options.filter((t3) => !e4.includes(t3)), { ...this._def, ...t2 });
  }
}
_ZodEnum_cache = /* @__PURE__ */ new WeakMap(), ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
  constructor() {
    super(...arguments), _ZodNativeEnum_cache.set(this, void 0);
  }
  _parse(e4) {
    const t2 = util$1.getValidEnumValues(this._def.values), i2 = this._getOrReturnCtx(e4);
    if (i2.parsedType !== ZodParsedType.string && i2.parsedType !== ZodParsedType.number) {
      const e5 = util$1.objectValues(t2);
      return addIssueToContext(i2, { expected: util$1.joinValues(e5), received: i2.parsedType, code: ZodIssueCode.invalid_type }), INVALID;
    }
    if (__classPrivateFieldGet(this, _ZodNativeEnum_cache) || __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util$1.getValidEnumValues(this._def.values))), !__classPrivateFieldGet(this, _ZodNativeEnum_cache).has(e4.data)) {
      const e5 = util$1.objectValues(t2);
      return addIssueToContext(i2, { received: i2.data, code: ZodIssueCode.invalid_enum_value, options: e5 }), INVALID;
    }
    return OK(e4.data);
  }
  get enum() {
    return this._def.values;
  }
}
_ZodNativeEnum_cache = /* @__PURE__ */ new WeakMap(), ZodNativeEnum.create = (e4, t2) => new ZodNativeEnum({ values: e4, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(t2) });
class ZodPromise extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4);
    if (t2.parsedType !== ZodParsedType.promise && false === t2.common.async) return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: t2.parsedType }), INVALID;
    const i2 = t2.parsedType === ZodParsedType.promise ? t2.data : Promise.resolve(t2.data);
    return OK(i2.then((e5) => this._def.type.parseAsync(e5, { path: t2.path, errorMap: t2.common.contextualErrorMap })));
  }
}
ZodPromise.create = (e4, t2) => new ZodPromise({ type: e4, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(t2) });
class ZodEffects extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4), r2 = this._def.effect || null, n2 = { addIssue: (e5) => {
      addIssueToContext(i2, e5), e5.fatal ? t2.abort() : t2.dirty();
    }, get path() {
      return i2.path;
    } };
    if (n2.addIssue = n2.addIssue.bind(n2), "preprocess" === r2.type) {
      const e5 = r2.transform(i2.data, n2);
      if (i2.common.async) return Promise.resolve(e5).then(async (e6) => {
        if ("aborted" === t2.value) return INVALID;
        const r3 = await this._def.schema._parseAsync({ data: e6, path: i2.path, parent: i2 });
        return "aborted" === r3.status ? INVALID : "dirty" === r3.status || "dirty" === t2.value ? DIRTY(r3.value) : r3;
      });
      {
        if ("aborted" === t2.value) return INVALID;
        const r3 = this._def.schema._parseSync({ data: e5, path: i2.path, parent: i2 });
        return "aborted" === r3.status ? INVALID : "dirty" === r3.status || "dirty" === t2.value ? DIRTY(r3.value) : r3;
      }
    }
    if ("refinement" === r2.type) {
      const e5 = (e6) => {
        const t3 = r2.refinement(e6, n2);
        if (i2.common.async) return Promise.resolve(t3);
        if (t3 instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        return e6;
      };
      if (false === i2.common.async) {
        const r3 = this._def.schema._parseSync({ data: i2.data, path: i2.path, parent: i2 });
        return "aborted" === r3.status ? INVALID : ("dirty" === r3.status && t2.dirty(), e5(r3.value), { status: t2.value, value: r3.value });
      }
      return this._def.schema._parseAsync({ data: i2.data, path: i2.path, parent: i2 }).then((i3) => "aborted" === i3.status ? INVALID : ("dirty" === i3.status && t2.dirty(), e5(i3.value).then(() => ({ status: t2.value, value: i3.value }))));
    }
    if ("transform" === r2.type) {
      if (false === i2.common.async) {
        const e5 = this._def.schema._parseSync({ data: i2.data, path: i2.path, parent: i2 });
        if (!isValid(e5)) return e5;
        const a2 = r2.transform(e5.value, n2);
        if (a2 instanceof Promise) throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
        return { status: t2.value, value: a2 };
      }
      return this._def.schema._parseAsync({ data: i2.data, path: i2.path, parent: i2 }).then((e5) => isValid(e5) ? Promise.resolve(r2.transform(e5.value, n2)).then((e6) => ({ status: t2.value, value: e6 })) : e5);
    }
    util$1.assertNever(r2);
  }
}
ZodEffects.create = (e4, t2, i2) => new ZodEffects({ schema: e4, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: t2, ...processCreateParams(i2) }), ZodEffects.createWithPreprocess = (e4, t2, i2) => new ZodEffects({ schema: t2, effect: { type: "preprocess", transform: e4 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(i2) });
class ZodOptional extends ZodType {
  _parse(e4) {
    return this._getType(e4) === ZodParsedType.undefined ? OK(void 0) : this._def.innerType._parse(e4);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodOptional.create = (e4, t2) => new ZodOptional({ innerType: e4, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(t2) });
class ZodNullable extends ZodType {
  _parse(e4) {
    return this._getType(e4) === ZodParsedType.null ? OK(null) : this._def.innerType._parse(e4);
  }
  unwrap() {
    return this._def.innerType;
  }
}
ZodNullable.create = (e4, t2) => new ZodNullable({ innerType: e4, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(t2) });
class ZodDefault extends ZodType {
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4);
    let i2 = t2.data;
    return t2.parsedType === ZodParsedType.undefined && (i2 = this._def.defaultValue()), this._def.innerType._parse({ data: i2, path: t2.path, parent: t2 });
  }
  removeDefault() {
    return this._def.innerType;
  }
}
ZodDefault.create = (e4, t2) => new ZodDefault({ innerType: e4, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: "function" == typeof t2.default ? t2.default : () => t2.default, ...processCreateParams(t2) });
class ZodCatch extends ZodType {
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4), i2 = { ...t2, common: { ...t2.common, issues: [] } }, r2 = this._def.innerType._parse({ data: i2.data, path: i2.path, parent: { ...i2 } });
    return isAsync(r2) ? r2.then((e5) => ({ status: "valid", value: "valid" === e5.status ? e5.value : this._def.catchValue({ get error() {
      return new ZodError(i2.common.issues);
    }, input: i2.data }) })) : { status: "valid", value: "valid" === r2.status ? r2.value : this._def.catchValue({ get error() {
      return new ZodError(i2.common.issues);
    }, input: i2.data }) };
  }
  removeCatch() {
    return this._def.innerType;
  }
}
ZodCatch.create = (e4, t2) => new ZodCatch({ innerType: e4, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: "function" == typeof t2.catch ? t2.catch : () => t2.catch, ...processCreateParams(t2) });
class ZodNaN extends ZodType {
  _parse(e4) {
    if (this._getType(e4) !== ZodParsedType.nan) {
      const t2 = this._getOrReturnCtx(e4);
      return addIssueToContext(t2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: t2.parsedType }), INVALID;
    }
    return { status: "valid", value: e4.data };
  }
}
ZodNaN.create = (e4) => new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(e4) });
const BRAND = Symbol("zod_brand");
class ZodBranded extends ZodType {
  _parse(e4) {
    const { ctx: t2 } = this._processInputParams(e4), i2 = t2.data;
    return this._def.type._parse({ data: i2, path: t2.path, parent: t2 });
  }
  unwrap() {
    return this._def.type;
  }
}
class ZodPipeline extends ZodType {
  _parse(e4) {
    const { status: t2, ctx: i2 } = this._processInputParams(e4);
    if (i2.common.async) {
      return (async () => {
        const e5 = await this._def.in._parseAsync({ data: i2.data, path: i2.path, parent: i2 });
        return "aborted" === e5.status ? INVALID : "dirty" === e5.status ? (t2.dirty(), DIRTY(e5.value)) : this._def.out._parseAsync({ data: e5.value, path: i2.path, parent: i2 });
      })();
    }
    {
      const e5 = this._def.in._parseSync({ data: i2.data, path: i2.path, parent: i2 });
      return "aborted" === e5.status ? INVALID : "dirty" === e5.status ? (t2.dirty(), { status: "dirty", value: e5.value }) : this._def.out._parseSync({ data: e5.value, path: i2.path, parent: i2 });
    }
  }
  static create(e4, t2) {
    return new ZodPipeline({ in: e4, out: t2, typeName: ZodFirstPartyTypeKind.ZodPipeline });
  }
}
class ZodReadonly extends ZodType {
  _parse(e4) {
    const t2 = this._def.innerType._parse(e4), i2 = (e5) => (isValid(e5) && (e5.value = Object.freeze(e5.value)), e5);
    return isAsync(t2) ? t2.then((e5) => i2(e5)) : i2(t2);
  }
  unwrap() {
    return this._def.innerType;
  }
}
function custom(e4, t2 = {}, i2) {
  return e4 ? ZodAny.create().superRefine((r2, n2) => {
    var a2, o2;
    if (!e4(r2)) {
      const e5 = "function" == typeof t2 ? t2(r2) : "string" == typeof t2 ? { message: t2 } : t2, s2 = null === (o2 = null !== (a2 = e5.fatal) && void 0 !== a2 ? a2 : i2) || void 0 === o2 || o2, l2 = "string" == typeof e5 ? { message: e5 } : e5;
      n2.addIssue({ code: "custom", ...l2, fatal: s2 });
    }
  }) : ZodAny.create();
}
ZodReadonly.create = (e4, t2) => new ZodReadonly({ innerType: e4, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(t2) });
const late = { object: ZodObject.lazycreate };
var ZodFirstPartyTypeKind;
!function(e4) {
  e4.ZodString = "ZodString", e4.ZodNumber = "ZodNumber", e4.ZodNaN = "ZodNaN", e4.ZodBigInt = "ZodBigInt", e4.ZodBoolean = "ZodBoolean", e4.ZodDate = "ZodDate", e4.ZodSymbol = "ZodSymbol", e4.ZodUndefined = "ZodUndefined", e4.ZodNull = "ZodNull", e4.ZodAny = "ZodAny", e4.ZodUnknown = "ZodUnknown", e4.ZodNever = "ZodNever", e4.ZodVoid = "ZodVoid", e4.ZodArray = "ZodArray", e4.ZodObject = "ZodObject", e4.ZodUnion = "ZodUnion", e4.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", e4.ZodIntersection = "ZodIntersection", e4.ZodTuple = "ZodTuple", e4.ZodRecord = "ZodRecord", e4.ZodMap = "ZodMap", e4.ZodSet = "ZodSet", e4.ZodFunction = "ZodFunction", e4.ZodLazy = "ZodLazy", e4.ZodLiteral = "ZodLiteral", e4.ZodEnum = "ZodEnum", e4.ZodEffects = "ZodEffects", e4.ZodNativeEnum = "ZodNativeEnum", e4.ZodOptional = "ZodOptional", e4.ZodNullable = "ZodNullable", e4.ZodDefault = "ZodDefault", e4.ZodCatch = "ZodCatch", e4.ZodPromise = "ZodPromise", e4.ZodBranded = "ZodBranded", e4.ZodPipeline = "ZodPipeline", e4.ZodReadonly = "ZodReadonly";
}(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
const instanceOfType = (e4, t2 = { message: `Input not instance of ${e4.name}` }) => custom((t3) => t3 instanceof e4, t2), stringType = ZodString.create, numberType = ZodNumber.create, nanType = ZodNaN.create, bigIntType = ZodBigInt.create, booleanType = ZodBoolean.create, dateType = ZodDate.create, symbolType = ZodSymbol.create, undefinedType = ZodUndefined.create, nullType = ZodNull.create, anyType = ZodAny.create, unknownType = ZodUnknown.create, neverType = ZodNever.create, voidType = ZodVoid.create, arrayType = ZodArray.create, objectType = ZodObject.create, strictObjectType = ZodObject.strictCreate, unionType = ZodUnion.create, discriminatedUnionType = ZodDiscriminatedUnion.create, intersectionType = ZodIntersection.create, tupleType = ZodTuple.create, recordType = ZodRecord.create, mapType = ZodMap.create, setType = ZodSet.create, functionType = ZodFunction.create, lazyType = ZodLazy.create, literalType = ZodLiteral.create, enumType = ZodEnum.create, nativeEnumType = ZodNativeEnum.create, promiseType = ZodPromise.create, effectsType = ZodEffects.create, optionalType = ZodOptional.create, nullableType = ZodNullable.create, preprocessType = ZodEffects.createWithPreprocess, pipelineType = ZodPipeline.create, ostring = () => stringType().optional(), onumber = () => numberType().optional(), oboolean = () => booleanType().optional(), coerce = { string: (e4) => ZodString.create({ ...e4, coerce: true }), number: (e4) => ZodNumber.create({ ...e4, coerce: true }), boolean: (e4) => ZodBoolean.create({ ...e4, coerce: true }), bigint: (e4) => ZodBigInt.create({ ...e4, coerce: true }), date: (e4) => ZodDate.create({ ...e4, coerce: true }) }, NEVER = INVALID;
var z = Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap, getErrorMap, makeIssue, EMPTY_PATH, addIssueToContext, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, get util() {
  return util$1;
}, get objectUtil() {
  return objectUtil;
}, ZodParsedType, getParsedType, ZodType, datetimeRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodTransformer: ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, Schema: ZodType, ZodSchema: ZodType, late, get ZodFirstPartyTypeKind() {
  return ZodFirstPartyTypeKind;
}, coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, enum: enumType, function: functionType, instanceof: instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, null: nullType, nullable: nullableType, number: numberType, object: objectType, oboolean, onumber, optional: optionalType, ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, undefined: undefinedType, union: unionType, unknown: unknownType, void: voidType, NEVER, ZodIssueCode, quotelessJson, ZodError }), Edge, Edge2;
Edge2 = Edge || (Edge = {}), Edge2[Edge2.EXTEND = 1] = "EXTEND", Edge2[Edge2.WRAP = 2] = "WRAP", Edge2[Edge2.CROP = 3] = "CROP";
const JimpClassSchema = z.object({ bitmap: z.object({ data: z.union([z.instanceof(Buffer$1), z.instanceof(Uint8Array)]), width: z.number(), height: z.number() }) }), BlitOptionsSchemaComplex = z.object({ src: JimpClassSchema, x: z.number().optional(), y: z.number().optional(), srcX: z.number().optional(), srcY: z.number().optional(), srcW: z.number().optional(), srcH: z.number().optional() }), BlitOptionsSchema = z.union([JimpClassSchema, BlitOptionsSchemaComplex]), methods$h = { blit(e4, t2) {
  const i2 = BlitOptionsSchema.parse(t2);
  let { src: r2, x: n2 = 0, y: a2 = 0, srcX: o2 = 0, srcY: s2 = 0, srcW: l2 = r2.bitmap.width, srcH: u2 = r2.bitmap.height } = "bitmap" in i2 ? { src: i2 } : i2;
  if (!("bitmap" in r2)) throw new Error("The source must be a Jimp image");
  if ("number" != typeof n2 || "number" != typeof a2) throw new Error("x and y must be numbers");
  n2 = Math.round(n2), a2 = Math.round(a2), o2 = Math.round(o2), s2 = Math.round(s2), l2 = Math.round(l2), u2 = Math.round(u2);
  const h2 = e4.bitmap.width, c2 = e4.bitmap.height;
  return scan(r2, o2, s2, l2, u2, function(t3, i3, l3) {
    const u3 = n2 + t3 - o2, f2 = a2 + i3 - s2;
    if (u3 >= 0 && f2 >= 0 && h2 - u3 > 0 && c2 - f2 > 0) {
      const t4 = e4.getPixelIndex(u3, f2), i4 = { r: r2.bitmap.data[l3] || 0, g: r2.bitmap.data[l3 + 1] || 0, b: r2.bitmap.data[l3 + 2] || 0, a: r2.bitmap.data[l3 + 3] || 0 }, n3 = { r: e4.bitmap.data[t4] || 0, g: e4.bitmap.data[t4 + 1] || 0, b: e4.bitmap.data[t4 + 2] || 0, a: e4.bitmap.data[t4 + 3] || 0 };
      e4.bitmap.data[t4] = (i4.a * (i4.r - n3.r) - n3.r + 255 >> 8) + n3.r, e4.bitmap.data[t4 + 1] = (i4.a * (i4.g - n3.g) - n3.g + 255 >> 8) + n3.g, e4.bitmap.data[t4 + 2] = (i4.a * (i4.b - n3.b) - n3.b + 255 >> 8) + n3.b, e4.bitmap.data[t4 + 3] = limit255(n3.a + i4.a);
    }
  }), e4;
} }, mulTable = [1, 57, 41, 21, 203, 34, 97, 73, 227, 91, 149, 62, 105, 45, 39, 137, 241, 107, 3, 173, 39, 71, 65, 238, 219, 101, 187, 87, 81, 151, 141, 133, 249, 117, 221, 209, 197, 187, 177, 169, 5, 153, 73, 139, 133, 127, 243, 233, 223, 107, 103, 99, 191, 23, 177, 171, 165, 159, 77, 149, 9, 139, 135, 131, 253, 245, 119, 231, 224, 109, 211, 103, 25, 195, 189, 23, 45, 175, 171, 83, 81, 79, 155, 151, 147, 9, 141, 137, 67, 131, 129, 251, 123, 30, 235, 115, 113, 221, 217, 53, 13, 51, 50, 49, 193, 189, 185, 91, 179, 175, 43, 169, 83, 163, 5, 79, 155, 19, 75, 147, 145, 143, 35, 69, 17, 67, 33, 65, 255, 251, 247, 243, 239, 59, 29, 229, 113, 111, 219, 27, 213, 105, 207, 51, 201, 199, 49, 193, 191, 47, 93, 183, 181, 179, 11, 87, 43, 85, 167, 165, 163, 161, 159, 157, 155, 77, 19, 75, 37, 73, 145, 143, 141, 35, 138, 137, 135, 67, 33, 131, 129, 255, 63, 250, 247, 61, 121, 239, 237, 117, 29, 229, 227, 225, 111, 55, 109, 216, 213, 211, 209, 207, 205, 203, 201, 199, 197, 195, 193, 48, 190, 47, 93, 185, 183, 181, 179, 178, 176, 175, 173, 171, 85, 21, 167, 165, 41, 163, 161, 5, 79, 157, 78, 154, 153, 19, 75, 149, 74, 147, 73, 144, 143, 71, 141, 140, 139, 137, 17, 135, 134, 133, 66, 131, 65, 129, 1], shgTable = [0, 9, 10, 10, 14, 12, 14, 14, 16, 15, 16, 15, 16, 15, 15, 17, 18, 17, 12, 18, 16, 17, 17, 19, 19, 18, 19, 18, 18, 19, 19, 19, 20, 19, 20, 20, 20, 20, 20, 20, 15, 20, 19, 20, 20, 20, 21, 21, 21, 20, 20, 20, 21, 18, 21, 21, 21, 21, 20, 21, 17, 21, 21, 21, 22, 22, 21, 22, 22, 21, 22, 21, 19, 22, 22, 19, 20, 22, 22, 21, 21, 21, 22, 22, 22, 18, 22, 22, 21, 22, 22, 23, 22, 20, 23, 22, 22, 23, 23, 21, 19, 21, 21, 21, 23, 23, 23, 22, 23, 23, 21, 23, 22, 23, 18, 22, 23, 20, 22, 23, 23, 23, 21, 22, 20, 22, 21, 22, 24, 24, 24, 24, 24, 22, 21, 24, 23, 23, 24, 21, 24, 23, 24, 22, 24, 24, 22, 24, 24, 22, 23, 24, 24, 24, 20, 23, 22, 23, 24, 24, 24, 24, 24, 24, 24, 23, 21, 23, 22, 23, 24, 24, 24, 22, 24, 24, 24, 23, 22, 24, 24, 25, 23, 25, 25, 23, 24, 25, 25, 24, 22, 25, 25, 25, 24, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 23, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 24, 22, 25, 25, 23, 25, 25, 20, 24, 25, 24, 25, 25, 22, 24, 25, 24, 25, 24, 25, 25, 24, 25, 25, 25, 25, 22, 25, 25, 25, 24, 25, 24, 25, 18], methods$g = { blur(e4, t2) {
  if ("number" != typeof t2) throw new Error("r must be a number");
  if (t2 < 1) throw new Error("r must be greater than 0");
  let i2, r2, n2, a2, o2, s2, l2, u2, h2, c2, f2, d, p2;
  const m = e4.bitmap.width - 1, _2 = e4.bitmap.height - 1, g = t2 + 1, b2 = mulTable[t2], y2 = shgTable[t2], w = [], v2 = [], x2 = [], E2 = [], k2 = [], S2 = [];
  let A2 = 2;
  for (; A2-- > 0; ) {
    for (d = 0, p2 = 0, s2 = 0; s2 < e4.bitmap.height; s2++) {
      for (i2 = e4.bitmap.data[p2] * g, r2 = e4.bitmap.data[p2 + 1] * g, n2 = e4.bitmap.data[p2 + 2] * g, a2 = e4.bitmap.data[p2 + 3] * g, l2 = 1; l2 <= t2; l2++) u2 = p2 + ((l2 > m ? m : l2) << 2), i2 += e4.bitmap.data[u2++], r2 += e4.bitmap.data[u2++], n2 += e4.bitmap.data[u2++], a2 += e4.bitmap.data[u2];
      for (o2 = 0; o2 < e4.bitmap.width; o2++) w[d] = i2, v2[d] = r2, x2[d] = n2, E2[d] = a2, 0 === s2 && (k2[o2] = ((u2 = o2 + g) < m ? u2 : m) << 2, S2[o2] = (u2 = o2 - t2) > 0 ? u2 << 2 : 0), h2 = p2 + k2[o2], c2 = p2 + S2[o2], i2 += e4.bitmap.data[h2++] - e4.bitmap.data[c2++], r2 += e4.bitmap.data[h2++] - e4.bitmap.data[c2++], n2 += e4.bitmap.data[h2++] - e4.bitmap.data[c2++], a2 += e4.bitmap.data[h2] - e4.bitmap.data[c2++], d++;
      p2 += e4.bitmap.width << 2;
    }
    for (o2 = 0; o2 < e4.bitmap.width; o2++) {
      for (f2 = o2, i2 = w[f2] * g, r2 = v2[f2] * g, n2 = x2[f2] * g, a2 = E2[f2] * g, l2 = 1; l2 <= t2; l2++) f2 += l2 > _2 ? 0 : e4.bitmap.width, i2 += w[f2], r2 += v2[f2], n2 += x2[f2], a2 += E2[f2];
      for (d = o2 << 2, s2 = 0; s2 < e4.bitmap.height; s2++) e4.bitmap.data[d] = limit255(i2 * b2 >>> y2), e4.bitmap.data[d + 1] = limit255(r2 * b2 >>> y2), e4.bitmap.data[d + 2] = limit255(n2 * b2 >>> y2), e4.bitmap.data[d + 3] = limit255(a2 * b2 >>> y2), 0 === o2 && (k2[s2] = ((u2 = s2 + g) < _2 ? u2 : _2) * e4.bitmap.width, S2[s2] = (u2 = s2 - t2) > 0 ? u2 * e4.bitmap.width : 0), h2 = o2 + k2[s2], c2 = o2 + S2[s2], i2 += w[h2] - w[c2], r2 += v2[h2] - v2[c2], n2 += x2[h2] - x2[c2], a2 += E2[h2] - E2[c2], d += e4.bitmap.width << 2;
    }
  }
  return e4;
}, gaussian(e4, t2) {
  if ("number" != typeof t2) throw new Error("r must be a number");
  if (t2 < 1) throw new Error("r must be greater than 0");
  const i2 = Math.ceil(2.57 * t2), r2 = 2 * i2 + 1, n2 = t2 * t2 * 2, a2 = n2 * Math.PI, o2 = [];
  for (let e5 = 0; e5 < r2; e5++) {
    const t3 = [];
    for (let o3 = 0; o3 < r2; o3++) {
      const r3 = (o3 - i2) ** 2 + (e5 - i2) ** 2;
      t3[o3] = Math.exp(-r3 / n2) / a2;
    }
    o2.push(t3);
  }
  for (let t3 = 0; t3 < e4.bitmap.height; t3++) for (let n3 = 0; n3 < e4.bitmap.width; n3++) {
    let a3 = 0, s2 = 0, l2 = 0, u2 = 0, h2 = 0;
    for (let c2 = 0; c2 < r2; c2++) {
      for (let f3 = 0; f3 < r2; f3++) {
        const r3 = Math.min(e4.bitmap.width - 1, Math.max(0, f3 + n3 - i2)), d = Math.min(e4.bitmap.height - 1, Math.max(0, c2 + t3 - i2)), p2 = o2[c2][f3], m = d * e4.bitmap.width + r3 << 2;
        a3 += e4.bitmap.data[m] * p2, s2 += e4.bitmap.data[m + 1] * p2, l2 += e4.bitmap.data[m + 2] * p2, u2 += e4.bitmap.data[m + 3] * p2, h2 += p2;
      }
      const f2 = t3 * e4.bitmap.width + n3 << 2;
      e4.bitmap.data[f2] = Math.round(a3 / h2), e4.bitmap.data[f2 + 1] = Math.round(s2 / h2), e4.bitmap.data[f2 + 2] = Math.round(l2 / h2), e4.bitmap.data[f2 + 3] = Math.round(u2 / h2);
    }
  }
  return e4;
} }, CircleOptionsSchema = z.object({ x: z.number().optional(), y: z.number().optional(), radius: z.number().min(0).optional() }), methods$f = { circle(e4, t2 = {}) {
  const i2 = CircleOptionsSchema.parse(t2), r2 = i2.radius || (e4.bitmap.width > e4.bitmap.height ? e4.bitmap.height : e4.bitmap.width) / 2, n2 = "number" == typeof i2.x ? i2.x : e4.bitmap.width / 2, a2 = "number" == typeof i2.y ? i2.y : e4.bitmap.height / 2;
  return e4.scan((t3, i3, o2) => {
    const s2 = Math.sqrt(Math.pow(t3 - n2, 2) + Math.pow(i3 - a2, 2));
    r2 - s2 <= 0 ? e4.bitmap.data[o2 + 3] = 0 : r2 - s2 < 1 && (e4.bitmap.data[o2 + 3] = 255 * (r2 - s2));
  }), e4;
} }, ConvolutionMatrixSchema = z.array(z.number()).min(1).array(), ConvolutionComplexOptionsSchema = z.object({ kernel: ConvolutionMatrixSchema, edgeHandling: z.nativeEnum(Edge).optional() }), ConvolutionOptionsSchema = z.union([ConvolutionMatrixSchema, ConvolutionComplexOptionsSchema]), ConvoluteComplexOptionsSchema = z.object({ kernel: ConvolutionMatrixSchema, x: z.number().optional(), y: z.number().optional(), w: z.number().optional(), h: z.number().optional() }), ConvoluteOptionsSchema = z.union([ConvolutionMatrixSchema, ConvoluteComplexOptionsSchema]), PixelateSize = z.number().min(1).max(1 / 0), PixelateComplexOptionsSchema = z.object({ size: PixelateSize, x: z.number().optional(), y: z.number().optional(), w: z.number().optional(), h: z.number().optional() }), PixelateOptionsSchema = z.union([PixelateSize, PixelateComplexOptionsSchema]);
function applyKernel(e4, t2, i2, r2) {
  const n2 = [0, 0, 0, 0], a2 = (t2.length - 1) / 2;
  for (let o2 = 0; o2 < t2.length; o2 += 1) for (let s2 = 0; s2 < t2[o2].length; s2 += 1) {
    const l2 = e4.getPixelIndex(i2 + o2 - a2, r2 + s2 - a2);
    n2[0] += e4.bitmap.data[l2] * t2[o2][s2], n2[1] += e4.bitmap.data[l2 + 1] * t2[o2][s2], n2[2] += e4.bitmap.data[l2 + 2] * t2[o2][s2], n2[3] += e4.bitmap.data[l2 + 3] * t2[o2][s2];
  }
  return n2;
}
function mix(e4, t2, i2 = 50) {
  return { r: (t2.r - e4.r) * (i2 / 100) + e4.r, g: (t2.g - e4.g) * (i2 / 100) + e4.g, b: (t2.b - e4.b) * (i2 / 100) + e4.b };
}
const HueActionSchema = z.object({ apply: z.literal("hue"), params: z.tuple([z.number().min(-360).max(360)]) }), SpinActionSchema = z.object({ apply: z.literal("spin"), params: z.tuple([z.number().min(-360).max(360)]) }), LightenActionSchema = z.object({ apply: z.literal("lighten"), params: z.tuple([z.number().min(0).max(100)]).optional() }), RGBColorSchema = z.object({ r: z.number().min(0).max(255), g: z.number().min(0).max(255), b: z.number().min(0).max(255) }), MixActionSchema = z.object({ apply: z.literal("mix"), params: z.union([z.tuple([RGBColorSchema]), z.tuple([RGBColorSchema, z.number().min(0).max(100)])]) }), TintActionSchema = z.object({ apply: z.literal("tint"), params: z.tuple([z.number().min(0).max(100)]).optional() }), ShadeActionSchema = z.object({ apply: z.literal("shade"), params: z.tuple([z.number().min(0).max(100)]).optional() }), XorActionSchema = z.object({ apply: z.literal("xor"), params: z.tuple([RGBColorSchema]) }), RedActionSchema = z.object({ apply: z.literal("red"), params: z.tuple([z.number().min(-255).max(255)]) }), GreenActionSchema = z.object({ apply: z.literal("green"), params: z.tuple([z.number().min(-255).max(255)]) }), BlueActionSchema = z.object({ apply: z.literal("blue"), params: z.tuple([z.number().min(-255).max(255)]) }), BrightenActionSchema = z.object({ apply: z.literal("brighten"), params: z.tuple([z.number().min(0).max(100)]).optional() }), DarkenActionSchema = z.object({ apply: z.literal("darken"), params: z.tuple([z.number().min(0).max(100)]).optional() }), DesaturateActionSchema = z.object({ apply: z.literal("desaturate"), params: z.tuple([z.number().min(0).max(100)]).optional() }), SaturateActionSchema = z.object({ apply: z.literal("saturate"), params: z.tuple([z.number().min(0).max(100)]).optional() }), GrayscaleActionSchema = z.object({ apply: z.literal("greyscale"), params: z.tuple([]).optional() }), ColorActionNameSchema = z.union([HueActionSchema, SpinActionSchema, LightenActionSchema, MixActionSchema, TintActionSchema, ShadeActionSchema, XorActionSchema, RedActionSchema, GreenActionSchema, BlueActionSchema, BrightenActionSchema, DarkenActionSchema, DesaturateActionSchema, SaturateActionSchema, GrayscaleActionSchema]);
function histogram(e4) {
  const t2 = { r: new Array(256).fill(0), g: new Array(256).fill(0), b: new Array(256).fill(0) };
  return e4.scan((i2, r2, n2) => {
    t2.r[e4.bitmap.data[n2 + 0]]++, t2.g[e4.bitmap.data[n2 + 1]]++, t2.b[e4.bitmap.data[n2 + 2]]++;
  }), t2;
}
const normalizeValue = function(e4, t2, i2) {
  return 255 * (e4 - t2) / (i2 - t2);
}, getBounds = function(e4) {
  return [e4.findIndex((e5) => e5 > 0), 255 - e4.slice().reverse().findIndex((e5) => e5 > 0)];
}, methods$e = { normalize(e4) {
  const t2 = histogram(e4), i2 = { r: getBounds(t2.r), g: getBounds(t2.g), b: getBounds(t2.b) };
  return e4.scan((t3, r2, n2) => {
    const a2 = e4.bitmap.data[n2 + 0], o2 = e4.bitmap.data[n2 + 1], s2 = e4.bitmap.data[n2 + 2];
    e4.bitmap.data[n2 + 0] = normalizeValue(a2, i2.r[0], i2.r[1]), e4.bitmap.data[n2 + 1] = normalizeValue(o2, i2.g[0], i2.g[1]), e4.bitmap.data[n2 + 2] = normalizeValue(s2, i2.b[0], i2.b[1]);
  }), e4;
}, invert: (e4) => (e4.scan((t2, i2, r2) => {
  e4.bitmap.data[r2] = 255 - e4.bitmap.data[r2], e4.bitmap.data[r2 + 1] = 255 - e4.bitmap.data[r2 + 1], e4.bitmap.data[r2 + 2] = 255 - e4.bitmap.data[r2 + 2];
}), e4), brightness(e4, t2) {
  if ("number" != typeof t2) throw new Error("val must be numbers");
  return e4.scan((i2, r2, n2) => {
    e4.bitmap.data[n2] = limit255(e4.bitmap.data[n2] * t2), e4.bitmap.data[n2 + 1] = limit255(e4.bitmap.data[n2 + 1] * t2), e4.bitmap.data[n2 + 2] = limit255(e4.bitmap.data[n2 + 2] * t2);
  }), e4;
}, contrast(e4, t2) {
  if ("number" != typeof t2) throw new Error("val must be numbers");
  if (t2 < -1 || t2 > 1) throw new Error("val must be a number between -1 and +1");
  const i2 = (t2 + 1) / (1 - t2);
  function r2(e5) {
    return (e5 = Math.floor(i2 * (e5 - 127) + 127)) < 0 ? 0 : e5 > 255 ? 255 : e5;
  }
  return e4.scan((t3, i3, n2) => {
    e4.bitmap.data[n2] = r2(e4.bitmap.data[n2]), e4.bitmap.data[n2 + 1] = r2(e4.bitmap.data[n2 + 1]), e4.bitmap.data[n2 + 2] = r2(e4.bitmap.data[n2 + 2]);
  }), e4;
}, posterize(e4, t2) {
  if ("number" != typeof t2) throw new Error("n must be numbers");
  return t2 < 2 && (t2 = 2), e4.scan((i2, r2, n2) => {
    const a2 = e4.bitmap.data[n2], o2 = e4.bitmap.data[n2 + 1], s2 = e4.bitmap.data[n2 + 2];
    e4.bitmap.data[n2] = Math.floor(a2 / 255 * (t2 - 1)) / (t2 - 1) * 255, e4.bitmap.data[n2 + 1] = Math.floor(o2 / 255 * (t2 - 1)) / (t2 - 1) * 255, e4.bitmap.data[n2 + 2] = Math.floor(s2 / 255 * (t2 - 1)) / (t2 - 1) * 255;
  }), e4;
}, greyscale: (e4) => (e4.scan((t2, i2, r2) => {
  const n2 = 0.2126 * e4.bitmap.data[r2] + 0.7152 * e4.bitmap.data[r2 + 1] + 0.0722 * e4.bitmap.data[r2 + 2];
  e4.bitmap.data[r2] = n2, e4.bitmap.data[r2 + 1] = n2, e4.bitmap.data[r2 + 2] = n2;
}), e4), opacity(e4, t2) {
  if ("number" != typeof t2) throw new Error("f must be a number");
  if (t2 < 0 || t2 > 1) throw new Error("f must be a number from 0 to 1");
  return e4.scan((i2, r2, n2) => {
    const a2 = e4.bitmap.data[n2 + 3] * t2;
    e4.bitmap.data[n2 + 3] = a2;
  }), e4;
}, sepia: (e4) => (e4.scan((t2, i2, r2) => {
  let n2 = e4.bitmap.data[r2], a2 = e4.bitmap.data[r2 + 1], o2 = e4.bitmap.data[r2 + 2];
  n2 = 0.393 * n2 + 0.769 * a2 + 0.189 * o2, a2 = 0.349 * n2 + 0.686 * a2 + 0.168 * o2, o2 = 0.272 * n2 + 0.534 * a2 + 0.131 * o2, e4.bitmap.data[r2] = n2 < 255 ? n2 : 255, e4.bitmap.data[r2 + 1] = a2 < 255 ? a2 : 255, e4.bitmap.data[r2 + 2] = o2 < 255 ? o2 : 255;
}), e4), fade(e4, t2) {
  if ("number" != typeof t2) throw new Error("f must be a number");
  if (t2 < 0 || t2 > 1) throw new Error("f must be a number from 0 to 1");
  return this.opacity(e4, 1 - t2);
}, convolution(e4, t2) {
  const i2 = ConvolutionOptionsSchema.parse(t2), { kernel: r2, edgeHandling: n2 = Edge.EXTEND } = "kernel" in i2 ? i2 : { kernel: i2, edgeHandling: void 0 };
  if (!r2[0]) throw new Error("kernel must be a matrix");
  const a2 = Buffer$1.from(e4.bitmap.data), o2 = r2.length, s2 = r2[0].length, l2 = Math.floor(o2 / 2), u2 = Math.floor(s2 / 2), h2 = -l2, c2 = -u2;
  let f2, d, p2, m, _2, g, b2, y2, w, v2;
  return e4.scan((t3, i3, o3) => {
    m = 0, p2 = 0, d = 0;
    for (let a3 = h2; a3 <= l2; a3++) for (let o4 = c2; o4 <= u2; o4++) y2 = t3 + o4, w = i3 + a3, f2 = r2[a3 + l2][o4 + u2], v2 = e4.getPixelIndex(y2, w, n2), -1 === v2 ? (b2 = 0, g = 0, _2 = 0) : (_2 = e4.bitmap.data[v2 + 0], g = e4.bitmap.data[v2 + 1], b2 = e4.bitmap.data[v2 + 2]), d += f2 * _2, p2 += f2 * g, m += f2 * b2;
    d < 0 && (d = 0), p2 < 0 && (p2 = 0), m < 0 && (m = 0), d > 255 && (d = 255), p2 > 255 && (p2 = 255), m > 255 && (m = 255), a2[o3 + 0] = d, a2[o3 + 1] = p2, a2[o3 + 2] = m;
  }), e4.bitmap.data = a2, e4;
}, opaque: (e4) => (e4.scan((t2, i2, r2) => {
  e4.bitmap.data[r2 + 3] = 255;
}), e4), pixelate(e4, t2) {
  const i2 = PixelateOptionsSchema.parse(t2), { size: r2, x: n2 = 0, y: a2 = 0, w: o2 = e4.bitmap.width - n2, h: s2 = e4.bitmap.height - a2 } = "number" == typeof i2 ? { size: i2 } : i2, l2 = [[1 / 16, 2 / 16, 1 / 16], [2 / 16, 0.25, 2 / 16], [1 / 16, 2 / 16, 1 / 16]], u2 = clone(e4);
  return scan(u2, n2, a2, o2, s2, (t3, i3, n3) => {
    t3 = r2 * Math.floor(t3 / r2), i3 = r2 * Math.floor(i3 / r2);
    const a3 = applyKernel(u2, l2, t3, i3);
    e4.bitmap.data[n3] = a3[0], e4.bitmap.data[n3 + 1] = a3[1], e4.bitmap.data[n3 + 2] = a3[2], e4.bitmap.data[n3 + 3] = a3[3];
  }), e4;
}, convolute(e4, t2) {
  const i2 = ConvoluteOptionsSchema.parse(t2), { kernel: r2, x: n2 = 0, y: a2 = 0, w: o2 = e4.bitmap.width - n2, h: s2 = e4.bitmap.height - a2 } = "kernel" in i2 ? i2 : { kernel: i2 }, l2 = clone(e4);
  return scan(l2, n2, a2, o2, s2, (t3, i3, n3) => {
    const a3 = applyKernel(l2, r2, t3, i3);
    e4.bitmap.data[n3] = limit255(a3[0]), e4.bitmap.data[n3 + 1] = limit255(a3[1]), e4.bitmap.data[n3 + 2] = limit255(a3[2]), e4.bitmap.data[n3 + 3] = limit255(a3[3]);
  }), e4;
}, color(e4, t2) {
  if (!t2 || !Array.isArray(t2)) throw new Error("actions must be an array");
  return t2.forEach((e5) => ColorActionNameSchema.parse(e5)), t2 = t2.map((e5) => ("xor" !== e5.apply && "mix" !== e5.apply || (e5.params[0] = tinycolor(e5.params[0]).toRgb()), e5)), e4.scan((i2, r2, n2) => {
    let a2 = { r: e4.bitmap.data[n2], g: e4.bitmap.data[n2 + 1], b: e4.bitmap.data[n2 + 2] };
    const o2 = (e5, t3) => limit255(a2[e5] + t3);
    t2.forEach((e5) => {
      var _a3, _b2;
      if ("mix" === e5.apply) a2 = mix(a2, e5.params[0], e5.params[1]);
      else if ("tint" === e5.apply) a2 = mix(a2, { r: 255, g: 255, b: 255 }, (_a3 = e5.params) == null ? void 0 : _a3[0]);
      else if ("shade" === e5.apply) a2 = mix(a2, { r: 0, g: 0, b: 0 }, (_b2 = e5.params) == null ? void 0 : _b2[0]);
      else if ("xor" === e5.apply) a2 = { r: a2.r ^ e5.params[0].r, g: a2.g ^ e5.params[0].g, b: a2.b ^ e5.params[0].b };
      else if ("red" === e5.apply) a2.r = o2("r", e5.params[0]);
      else if ("green" === e5.apply) a2.g = o2("g", e5.params[0]);
      else if ("blue" === e5.apply) a2.b = o2("b", e5.params[0]);
      else {
        "hue" === e5.apply && (e5.apply = "spin");
        const t3 = tinycolor(a2), i3 = t3[e5.apply].bind(t3);
        if (!i3) throw new Error("action " + e5.apply + " not supported");
        a2 = i3(...e5.params || []).toRgb();
      }
    }), e4.bitmap.data[n2] = a2.r, e4.bitmap.data[n2 + 1] = a2.g, e4.bitmap.data[n2 + 2] = a2.b;
  }), e4;
} };
var lib$1 = {}, ieee754 = {
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  read: function(e4, t2, i2, r2, n2) {
    var a2, o2, s2 = 8 * n2 - r2 - 1, l2 = (1 << s2) - 1, u2 = l2 >> 1, h2 = -7, c2 = i2 ? n2 - 1 : 0, f2 = i2 ? -1 : 1, d = e4[t2 + c2];
    for (c2 += f2, a2 = d & (1 << -h2) - 1, d >>= -h2, h2 += s2; h2 > 0; a2 = 256 * a2 + e4[t2 + c2], c2 += f2, h2 -= 8) ;
    for (o2 = a2 & (1 << -h2) - 1, a2 >>= -h2, h2 += r2; h2 > 0; o2 = 256 * o2 + e4[t2 + c2], c2 += f2, h2 -= 8) ;
    if (0 === a2) a2 = 1 - u2;
    else {
      if (a2 === l2) return o2 ? NaN : 1 / 0 * (d ? -1 : 1);
      o2 += Math.pow(2, r2), a2 -= u2;
    }
    return (d ? -1 : 1) * o2 * Math.pow(2, a2 - r2);
  },
  write: function(e4, t2, i2, r2, n2, a2) {
    var o2, s2, l2, u2 = 8 * a2 - n2 - 1, h2 = (1 << u2) - 1, c2 = h2 >> 1, f2 = 23 === n2 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = r2 ? 0 : a2 - 1, p2 = r2 ? 1 : -1, m = t2 < 0 || 0 === t2 && 1 / t2 < 0 ? 1 : 0;
    for (t2 = Math.abs(t2), isNaN(t2) || t2 === 1 / 0 ? (s2 = isNaN(t2) ? 1 : 0, o2 = h2) : (o2 = Math.floor(Math.log(t2) / Math.LN2), t2 * (l2 = Math.pow(2, -o2)) < 1 && (o2--, l2 *= 2), (t2 += o2 + c2 >= 1 ? f2 / l2 : f2 * Math.pow(2, 1 - c2)) * l2 >= 2 && (o2++, l2 /= 2), o2 + c2 >= h2 ? (s2 = 0, o2 = h2) : o2 + c2 >= 1 ? (s2 = (t2 * l2 - 1) * Math.pow(2, n2), o2 += c2) : (s2 = t2 * Math.pow(2, c2 - 1) * Math.pow(2, n2), o2 = 0)); n2 >= 8; e4[i2 + d] = 255 & s2, d += p2, s2 /= 256, n2 -= 8) ;
    for (o2 = o2 << n2 | s2, u2 += n2; u2 > 0; e4[i2 + d] = 255 & o2, d += p2, o2 /= 256, u2 -= 8) ;
    e4[i2 + d - p2] |= 128 * m;
  }
};
!function(e4) {
  Object.defineProperty(e4, "__esModule", { value: true }), e4.AnsiStringType = e4.StringType = e4.BufferType = e4.Uint8ArrayType = e4.IgnoreType = e4.Float80_LE = e4.Float80_BE = e4.Float64_LE = e4.Float64_BE = e4.Float32_LE = e4.Float32_BE = e4.Float16_LE = e4.Float16_BE = e4.INT64_BE = e4.UINT64_BE = e4.INT64_LE = e4.UINT64_LE = e4.INT32_LE = e4.INT32_BE = e4.INT24_BE = e4.INT24_LE = e4.INT16_LE = e4.INT16_BE = e4.INT8 = e4.UINT32_BE = e4.UINT32_LE = e4.UINT24_BE = e4.UINT24_LE = e4.UINT16_BE = e4.UINT16_LE = e4.UINT8 = void 0;
  const t2 = ieee754;
  function i2(e5) {
    return new DataView(e5.buffer, e5.byteOffset);
  }
  e4.UINT8 = { len: 1, get: (e5, t3) => i2(e5).getUint8(t3), put: (e5, t3, r3) => (i2(e5).setUint8(t3, r3), t3 + 1) }, e4.UINT16_LE = { len: 2, get: (e5, t3) => i2(e5).getUint16(t3, true), put: (e5, t3, r3) => (i2(e5).setUint16(t3, r3, true), t3 + 2) }, e4.UINT16_BE = { len: 2, get: (e5, t3) => i2(e5).getUint16(t3), put: (e5, t3, r3) => (i2(e5).setUint16(t3, r3), t3 + 2) }, e4.UINT24_LE = { len: 3, get(e5, t3) {
    const r3 = i2(e5);
    return r3.getUint8(t3) + (r3.getUint16(t3 + 1, true) << 8);
  }, put(e5, t3, r3) {
    const n2 = i2(e5);
    return n2.setUint8(t3, 255 & r3), n2.setUint16(t3 + 1, r3 >> 8, true), t3 + 3;
  } }, e4.UINT24_BE = { len: 3, get(e5, t3) {
    const r3 = i2(e5);
    return (r3.getUint16(t3) << 8) + r3.getUint8(t3 + 2);
  }, put(e5, t3, r3) {
    const n2 = i2(e5);
    return n2.setUint16(t3, r3 >> 8), n2.setUint8(t3 + 2, 255 & r3), t3 + 3;
  } }, e4.UINT32_LE = { len: 4, get: (e5, t3) => i2(e5).getUint32(t3, true), put: (e5, t3, r3) => (i2(e5).setUint32(t3, r3, true), t3 + 4) }, e4.UINT32_BE = { len: 4, get: (e5, t3) => i2(e5).getUint32(t3), put: (e5, t3, r3) => (i2(e5).setUint32(t3, r3), t3 + 4) }, e4.INT8 = { len: 1, get: (e5, t3) => i2(e5).getInt8(t3), put: (e5, t3, r3) => (i2(e5).setInt8(t3, r3), t3 + 1) }, e4.INT16_BE = { len: 2, get: (e5, t3) => i2(e5).getInt16(t3), put: (e5, t3, r3) => (i2(e5).setInt16(t3, r3), t3 + 2) }, e4.INT16_LE = { len: 2, get: (e5, t3) => i2(e5).getInt16(t3, true), put: (e5, t3, r3) => (i2(e5).setInt16(t3, r3, true), t3 + 2) }, e4.INT24_LE = { len: 3, get(t3, i3) {
    const r3 = e4.UINT24_LE.get(t3, i3);
    return r3 > 8388607 ? r3 - 16777216 : r3;
  }, put(e5, t3, r3) {
    const n2 = i2(e5);
    return n2.setUint8(t3, 255 & r3), n2.setUint16(t3 + 1, r3 >> 8, true), t3 + 3;
  } }, e4.INT24_BE = { len: 3, get(t3, i3) {
    const r3 = e4.UINT24_BE.get(t3, i3);
    return r3 > 8388607 ? r3 - 16777216 : r3;
  }, put(e5, t3, r3) {
    const n2 = i2(e5);
    return n2.setUint16(t3, r3 >> 8), n2.setUint8(t3 + 2, 255 & r3), t3 + 3;
  } }, e4.INT32_BE = { len: 4, get: (e5, t3) => i2(e5).getInt32(t3), put: (e5, t3, r3) => (i2(e5).setInt32(t3, r3), t3 + 4) }, e4.INT32_LE = { len: 4, get: (e5, t3) => i2(e5).getInt32(t3, true), put: (e5, t3, r3) => (i2(e5).setInt32(t3, r3, true), t3 + 4) }, e4.UINT64_LE = { len: 8, get: (e5, t3) => i2(e5).getBigUint64(t3, true), put: (e5, t3, r3) => (i2(e5).setBigUint64(t3, r3, true), t3 + 8) }, e4.INT64_LE = { len: 8, get: (e5, t3) => i2(e5).getBigInt64(t3, true), put: (e5, t3, r3) => (i2(e5).setBigInt64(t3, r3, true), t3 + 8) }, e4.UINT64_BE = { len: 8, get: (e5, t3) => i2(e5).getBigUint64(t3), put: (e5, t3, r3) => (i2(e5).setBigUint64(t3, r3), t3 + 8) }, e4.INT64_BE = { len: 8, get: (e5, t3) => i2(e5).getBigInt64(t3), put: (e5, t3, r3) => (i2(e5).setBigInt64(t3, r3), t3 + 8) }, e4.Float16_BE = { len: 2, get(e5, i3) {
    return t2.read(e5, i3, false, 10, this.len);
  }, put(e5, i3, r3) {
    return t2.write(e5, r3, i3, false, 10, this.len), i3 + this.len;
  } }, e4.Float16_LE = { len: 2, get(e5, i3) {
    return t2.read(e5, i3, true, 10, this.len);
  }, put(e5, i3, r3) {
    return t2.write(e5, r3, i3, true, 10, this.len), i3 + this.len;
  } }, e4.Float32_BE = { len: 4, get: (e5, t3) => i2(e5).getFloat32(t3), put: (e5, t3, r3) => (i2(e5).setFloat32(t3, r3), t3 + 4) }, e4.Float32_LE = { len: 4, get: (e5, t3) => i2(e5).getFloat32(t3, true), put: (e5, t3, r3) => (i2(e5).setFloat32(t3, r3, true), t3 + 4) }, e4.Float64_BE = { len: 8, get: (e5, t3) => i2(e5).getFloat64(t3), put: (e5, t3, r3) => (i2(e5).setFloat64(t3, r3), t3 + 8) }, e4.Float64_LE = { len: 8, get: (e5, t3) => i2(e5).getFloat64(t3, true), put: (e5, t3, r3) => (i2(e5).setFloat64(t3, r3, true), t3 + 8) }, e4.Float80_BE = { len: 10, get(e5, i3) {
    return t2.read(e5, i3, false, 63, this.len);
  }, put(e5, i3, r3) {
    return t2.write(e5, r3, i3, false, 63, this.len), i3 + this.len;
  } }, e4.Float80_LE = { len: 10, get(e5, i3) {
    return t2.read(e5, i3, true, 63, this.len);
  }, put(e5, i3, r3) {
    return t2.write(e5, r3, i3, true, 63, this.len), i3 + this.len;
  } };
  e4.IgnoreType = class {
    constructor(e5) {
      this.len = e5;
    }
    get(e5, t3) {
    }
  };
  e4.Uint8ArrayType = class {
    constructor(e5) {
      this.len = e5;
    }
    get(e5, t3) {
      return e5.subarray(t3, t3 + this.len);
    }
  };
  e4.BufferType = class {
    constructor(e5) {
      this.len = e5;
    }
    get(e5, t3) {
      return Buffer$1.from(e5.subarray(t3, t3 + this.len));
    }
  };
  e4.StringType = class {
    constructor(e5, t3) {
      this.len = e5, this.encoding = t3;
    }
    get(e5, t3) {
      return Buffer$1.from(e5).toString(this.encoding, t3, t3 + this.len);
    }
  };
  class r2 {
    constructor(e5) {
      this.len = e5;
    }
    static decode(e5, t3, i3) {
      let n2 = "";
      for (let a2 = t3; a2 < i3; ++a2) n2 += r2.codePointToString(r2.singleByteDecoder(e5[a2]));
      return n2;
    }
    static inRange(e5, t3, i3) {
      return t3 <= e5 && e5 <= i3;
    }
    static codePointToString(e5) {
      return e5 <= 65535 ? String.fromCharCode(e5) : (e5 -= 65536, String.fromCharCode(55296 + (e5 >> 10), 56320 + (1023 & e5)));
    }
    static singleByteDecoder(e5) {
      if (r2.inRange(e5, 0, 127)) return e5;
      const t3 = r2.windows1252[e5 - 128];
      if (null === t3) throw Error("invaliding encoding");
      return t3;
    }
    get(e5, t3 = 0) {
      return r2.decode(e5, t3, t3 + this.len);
    }
  }
  e4.AnsiStringType = r2, r2.windows1252 = [8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255];
}(lib$1);
var core$1 = {}, ReadStreamTokenizer$1 = {}, AbstractTokenizer$1 = {}, lib = {}, EndOfFileStream = {};
!function(e4) {
  Object.defineProperty(e4, "__esModule", { value: true }), e4.EndOfStreamError = e4.defaultMessages = void 0, e4.defaultMessages = "End-Of-Stream";
  class t2 extends Error {
    constructor() {
      super(e4.defaultMessages);
    }
  }
  e4.EndOfStreamError = t2;
}(EndOfFileStream);
var StreamReader = {}, Deferred$1 = {};
Object.defineProperty(Deferred$1, "__esModule", { value: true }), Deferred$1.Deferred = void 0;
class Deferred {
  constructor() {
    this.resolve = () => null, this.reject = () => null, this.promise = new Promise((e4, t2) => {
      this.reject = t2, this.resolve = e4;
    });
  }
}
Deferred$1.Deferred = Deferred, function(e4) {
  Object.defineProperty(e4, "__esModule", { value: true }), e4.StreamReader = e4.EndOfStreamError = void 0;
  const t2 = EndOfFileStream, i2 = Deferred$1;
  var r2 = EndOfFileStream;
  Object.defineProperty(e4, "EndOfStreamError", { enumerable: true, get: function() {
    return r2.EndOfStreamError;
  } });
  e4.StreamReader = class {
    constructor(e5) {
      if (this.s = e5, this.deferred = null, this.endOfStream = false, this.peekQueue = [], !e5.read || !e5.once) throw new Error("Expected an instance of stream.Readable");
      this.s.once("end", () => this.reject(new t2.EndOfStreamError())), this.s.once("error", (e6) => this.reject(e6)), this.s.once("close", () => this.reject(new Error("Stream closed")));
    }
    async peek(e5, t3, i3) {
      const r3 = await this.read(e5, t3, i3);
      return this.peekQueue.push(e5.subarray(t3, t3 + r3)), r3;
    }
    async read(e5, i3, r3) {
      if (0 === r3) return 0;
      if (0 === this.peekQueue.length && this.endOfStream) throw new t2.EndOfStreamError();
      let n2 = r3, a2 = 0;
      for (; this.peekQueue.length > 0 && n2 > 0; ) {
        const t3 = this.peekQueue.pop();
        if (!t3) throw new Error("peekData should be defined");
        const r4 = Math.min(t3.length, n2);
        e5.set(t3.subarray(0, r4), i3 + a2), a2 += r4, n2 -= r4, r4 < t3.length && this.peekQueue.push(t3.subarray(r4));
      }
      for (; n2 > 0 && !this.endOfStream; ) {
        const t3 = Math.min(n2, 1048576), r4 = await this.readFromStream(e5, i3 + a2, t3);
        if (a2 += r4, r4 < t3) break;
        n2 -= r4;
      }
      return a2;
    }
    async readFromStream(e5, t3, r3) {
      const n2 = this.s.read(r3);
      if (n2) return e5.set(n2, t3), n2.length;
      {
        const n3 = { buffer: e5, offset: t3, length: r3, deferred: new i2.Deferred() };
        return this.deferred = n3.deferred, this.s.once("readable", () => {
          this.readDeferred(n3);
        }), n3.deferred.promise;
      }
    }
    readDeferred(e5) {
      const t3 = this.s.read(e5.length);
      t3 ? (e5.buffer.set(t3, e5.offset), e5.deferred.resolve(t3.length), this.deferred = null) : this.s.once("readable", () => {
        this.readDeferred(e5);
      });
    }
    reject(e5) {
      this.endOfStream = true, this.deferred && (this.deferred.reject(e5), this.deferred = null);
    }
  };
}(StreamReader), function(e4) {
  Object.defineProperty(e4, "__esModule", { value: true }), e4.StreamReader = e4.EndOfStreamError = void 0;
  var t2 = EndOfFileStream;
  Object.defineProperty(e4, "EndOfStreamError", { enumerable: true, get: function() {
    return t2.EndOfStreamError;
  } });
  var i2 = StreamReader;
  Object.defineProperty(e4, "StreamReader", { enumerable: true, get: function() {
    return i2.StreamReader;
  } });
}(lib), Object.defineProperty(AbstractTokenizer$1, "__esModule", { value: true }), AbstractTokenizer$1.AbstractTokenizer = void 0;
const peek_readable_1$2 = lib;
class AbstractTokenizer {
  constructor(e4) {
    this.position = 0, this.numBuffer = new Uint8Array(8), this.fileInfo = e4 || {};
  }
  async readToken(e4, t2 = this.position) {
    const i2 = Buffer$1.alloc(e4.len);
    if (await this.readBuffer(i2, { position: t2 }) < e4.len) throw new peek_readable_1$2.EndOfStreamError();
    return e4.get(i2, 0);
  }
  async peekToken(e4, t2 = this.position) {
    const i2 = Buffer$1.alloc(e4.len);
    if (await this.peekBuffer(i2, { position: t2 }) < e4.len) throw new peek_readable_1$2.EndOfStreamError();
    return e4.get(i2, 0);
  }
  async readNumber(e4) {
    if (await this.readBuffer(this.numBuffer, { length: e4.len }) < e4.len) throw new peek_readable_1$2.EndOfStreamError();
    return e4.get(this.numBuffer, 0);
  }
  async peekNumber(e4) {
    if (await this.peekBuffer(this.numBuffer, { length: e4.len }) < e4.len) throw new peek_readable_1$2.EndOfStreamError();
    return e4.get(this.numBuffer, 0);
  }
  async ignore(e4) {
    if (void 0 !== this.fileInfo.size) {
      const t2 = this.fileInfo.size - this.position;
      if (e4 > t2) return this.position += t2, t2;
    }
    return this.position += e4, e4;
  }
  async close() {
  }
  normalizeOptions(e4, t2) {
    if (t2 && void 0 !== t2.position && t2.position < this.position) throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
    return t2 ? { mayBeLess: true === t2.mayBeLess, offset: t2.offset ? t2.offset : 0, length: t2.length ? t2.length : e4.length - (t2.offset ? t2.offset : 0), position: t2.position ? t2.position : this.position } : { mayBeLess: false, offset: 0, length: e4.length, position: this.position };
  }
}
AbstractTokenizer$1.AbstractTokenizer = AbstractTokenizer, Object.defineProperty(ReadStreamTokenizer$1, "__esModule", { value: true }), ReadStreamTokenizer$1.ReadStreamTokenizer = void 0;
const AbstractTokenizer_1$1 = AbstractTokenizer$1, peek_readable_1$1 = lib, maxBufferSize = 256e3;
class ReadStreamTokenizer extends AbstractTokenizer_1$1.AbstractTokenizer {
  constructor(e4, t2) {
    super(t2), this.streamReader = new peek_readable_1$1.StreamReader(e4);
  }
  async getFileInfo() {
    return this.fileInfo;
  }
  async readBuffer(e4, t2) {
    const i2 = this.normalizeOptions(e4, t2), r2 = i2.position - this.position;
    if (r2 > 0) return await this.ignore(r2), this.readBuffer(e4, t2);
    if (r2 < 0) throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
    if (0 === i2.length) return 0;
    const n2 = await this.streamReader.read(e4, i2.offset, i2.length);
    if (this.position += n2, (!t2 || !t2.mayBeLess) && n2 < i2.length) throw new peek_readable_1$1.EndOfStreamError();
    return n2;
  }
  async peekBuffer(e4, t2) {
    const i2 = this.normalizeOptions(e4, t2);
    let r2 = 0;
    if (i2.position) {
      const t3 = i2.position - this.position;
      if (t3 > 0) {
        const n2 = new Uint8Array(i2.length + t3);
        return r2 = await this.peekBuffer(n2, { mayBeLess: i2.mayBeLess }), e4.set(n2.subarray(t3), i2.offset), r2 - t3;
      }
      if (t3 < 0) throw new Error("Cannot peek from a negative offset in a stream");
    }
    if (i2.length > 0) {
      try {
        r2 = await this.streamReader.peek(e4, i2.offset, i2.length);
      } catch (e5) {
        if (t2 && t2.mayBeLess && e5 instanceof peek_readable_1$1.EndOfStreamError) return 0;
        throw e5;
      }
      if (!i2.mayBeLess && r2 < i2.length) throw new peek_readable_1$1.EndOfStreamError();
    }
    return r2;
  }
  async ignore(e4) {
    const t2 = Math.min(maxBufferSize, e4), i2 = new Uint8Array(t2);
    let r2 = 0;
    for (; r2 < e4; ) {
      const n2 = e4 - r2, a2 = await this.readBuffer(i2, { length: Math.min(t2, n2) });
      if (a2 < 0) return a2;
      r2 += a2;
    }
    return r2;
  }
}
ReadStreamTokenizer$1.ReadStreamTokenizer = ReadStreamTokenizer;
var BufferTokenizer$1 = {};
Object.defineProperty(BufferTokenizer$1, "__esModule", { value: true }), BufferTokenizer$1.BufferTokenizer = void 0;
const peek_readable_1 = lib, AbstractTokenizer_1 = AbstractTokenizer$1;
class BufferTokenizer extends AbstractTokenizer_1.AbstractTokenizer {
  constructor(e4, t2) {
    super(t2), this.uint8Array = e4, this.fileInfo.size = this.fileInfo.size ? this.fileInfo.size : e4.length;
  }
  async readBuffer(e4, t2) {
    if (t2 && t2.position) {
      if (t2.position < this.position) throw new Error("`options.position` must be equal or greater than `tokenizer.position`");
      this.position = t2.position;
    }
    const i2 = await this.peekBuffer(e4, t2);
    return this.position += i2, i2;
  }
  async peekBuffer(e4, t2) {
    const i2 = this.normalizeOptions(e4, t2), r2 = Math.min(this.uint8Array.length - i2.position, i2.length);
    if (!i2.mayBeLess && r2 < i2.length) throw new peek_readable_1.EndOfStreamError();
    return e4.set(this.uint8Array.subarray(i2.position, i2.position + r2), i2.offset), r2;
  }
  async close() {
  }
}
BufferTokenizer$1.BufferTokenizer = BufferTokenizer, function(e4) {
  Object.defineProperty(e4, "__esModule", { value: true }), e4.fromBuffer = e4.fromStream = e4.EndOfStreamError = void 0;
  const t2 = ReadStreamTokenizer$1, i2 = BufferTokenizer$1;
  var r2 = lib;
  Object.defineProperty(e4, "EndOfStreamError", { enumerable: true, get: function() {
    return r2.EndOfStreamError;
  } }), e4.fromStream = function(e5, i3) {
    return i3 = i3 || {}, new t2.ReadStreamTokenizer(e5, i3);
  }, e4.fromBuffer = function(e5, t3) {
    return new i2.BufferTokenizer(e5, t3);
  };
}(core$1);
var util = { stringToBytes: (e4) => [...e4].map((e5) => e5.charCodeAt(0)), tarHeaderChecksumMatches: (e4, t2 = 0) => {
  const i2 = parseInt(e4.toString("utf8", 148, 154).replace(/\0.*$/, "").trim(), 8);
  if (isNaN(i2)) return false;
  let r2 = 256;
  for (let i3 = t2; i3 < t2 + 148; i3++) r2 += e4[i3];
  for (let i3 = t2 + 156; i3 < t2 + 512; i3++) r2 += e4[i3];
  return i2 === r2;
}, uint32SyncSafeToken: { get: (e4, t2) => 127 & e4[t2 + 3] | e4[t2 + 2] << 7 | e4[t2 + 1] << 14 | e4[t2] << 21, len: 4 } }, supported$1 = { extensions: ["jpg", "png", "apng", "gif", "webp", "flif", "xcf", "cr2", "cr3", "orf", "arw", "dng", "nef", "rw2", "raf", "tif", "bmp", "icns", "jxr", "psd", "indd", "zip", "tar", "rar", "gz", "bz2", "7z", "dmg", "mp4", "mid", "mkv", "webm", "mov", "avi", "mpg", "mp2", "mp3", "m4a", "oga", "ogg", "ogv", "opus", "flac", "wav", "spx", "amr", "pdf", "epub", "exe", "swf", "rtf", "wasm", "woff", "woff2", "eot", "ttf", "otf", "ico", "flv", "ps", "xz", "sqlite", "nes", "crx", "xpi", "cab", "deb", "ar", "rpm", "Z", "lz", "cfb", "mxf", "mts", "blend", "bpg", "docx", "pptx", "xlsx", "3gp", "3g2", "jp2", "jpm", "jpx", "mj2", "aif", "qcp", "odt", "ods", "odp", "xml", "mobi", "heic", "cur", "ktx", "ape", "wv", "dcm", "ics", "glb", "pcap", "dsf", "lnk", "alias", "voc", "ac3", "m4v", "m4p", "m4b", "f4v", "f4p", "f4b", "f4a", "mie", "asf", "ogm", "ogx", "mpc", "arrow", "shp", "aac", "mp1", "it", "s3m", "xm", "ai", "skp", "avif", "eps", "lzh", "pgp", "asar", "stl", "chm", "3mf", "zst", "jxl", "vcf"], mimeTypes: ["image/jpeg", "image/png", "image/gif", "image/webp", "image/flif", "image/x-xcf", "image/x-canon-cr2", "image/x-canon-cr3", "image/tiff", "image/bmp", "image/vnd.ms-photo", "image/vnd.adobe.photoshop", "application/x-indesign", "application/epub+zip", "application/x-xpinstall", "application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.presentation", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/zip", "application/x-tar", "application/x-rar-compressed", "application/gzip", "application/x-bzip2", "application/x-7z-compressed", "application/x-apple-diskimage", "application/x-apache-arrow", "video/mp4", "audio/midi", "video/x-matroska", "video/webm", "video/quicktime", "video/vnd.avi", "audio/vnd.wave", "audio/qcelp", "audio/x-ms-asf", "video/x-ms-asf", "application/vnd.ms-asf", "video/mpeg", "video/3gpp", "audio/mpeg", "audio/mp4", "audio/opus", "video/ogg", "audio/ogg", "application/ogg", "audio/x-flac", "audio/ape", "audio/wavpack", "audio/amr", "application/pdf", "application/x-msdownload", "application/x-shockwave-flash", "application/rtf", "application/wasm", "font/woff", "font/woff2", "application/vnd.ms-fontobject", "font/ttf", "font/otf", "image/x-icon", "video/x-flv", "application/postscript", "application/eps", "application/x-xz", "application/x-sqlite3", "application/x-nintendo-nes-rom", "application/x-google-chrome-extension", "application/vnd.ms-cab-compressed", "application/x-deb", "application/x-unix-archive", "application/x-rpm", "application/x-compress", "application/x-lzip", "application/x-cfb", "application/x-mie", "application/mxf", "video/mp2t", "application/x-blender", "image/bpg", "image/jp2", "image/jpx", "image/jpm", "image/mj2", "audio/aiff", "application/xml", "application/x-mobipocket-ebook", "image/heif", "image/heif-sequence", "image/heic", "image/heic-sequence", "image/icns", "image/ktx", "application/dicom", "audio/x-musepack", "text/calendar", "text/vcard", "model/gltf-binary", "application/vnd.tcpdump.pcap", "audio/x-dsf", "application/x.ms.shortcut", "application/x.apple.alias", "audio/x-voc", "audio/vnd.dolby.dd-raw", "audio/x-m4a", "image/apng", "image/x-olympus-orf", "image/x-sony-arw", "image/x-adobe-dng", "image/x-nikon-nef", "image/x-panasonic-rw2", "image/x-fujifilm-raf", "video/x-m4v", "video/3gpp2", "application/x-esri-shape", "audio/aac", "audio/x-it", "audio/x-s3m", "audio/x-xm", "video/MP1S", "video/MP2P", "application/vnd.sketchup.skp", "image/avif", "application/x-lzh-compressed", "application/pgp-encrypted", "application/x-asar", "model/stl", "application/vnd.ms-htmlhelp", "model/3mf", "image/jxl", "application/zstd"] };
const Token = lib$1, strtok3 = core$1, { stringToBytes, tarHeaderChecksumMatches, uint32SyncSafeToken } = util, supported = supported$1, minimumBytes = 4100;
async function fromStream(e4) {
  const t2 = await strtok3.fromStream(e4);
  try {
    return await fromTokenizer(t2);
  } finally {
    await t2.close();
  }
}
async function fromBuffer(e4) {
  if (!(e4 instanceof Uint8Array || e4 instanceof ArrayBuffer || Buffer$1.isBuffer(e4))) throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof e4}\``);
  const t2 = e4 instanceof Buffer$1 ? e4 : Buffer$1.from(e4);
  if (!(t2 && t2.length > 1)) return;
  return fromTokenizer(strtok3.fromBuffer(t2));
}
function _check(e4, t2, i2) {
  i2 = { offset: 0, ...i2 };
  for (const [r2, n2] of t2.entries()) if (i2.mask) {
    if (n2 !== (i2.mask[r2] & e4[r2 + i2.offset])) return false;
  } else if (n2 !== e4[r2 + i2.offset]) return false;
  return true;
}
async function fromTokenizer(e4) {
  try {
    return _fromTokenizer(e4);
  } catch (e5) {
    if (!(e5 instanceof strtok3.EndOfStreamError)) throw e5;
  }
}
async function _fromTokenizer(e4) {
  let t2 = Buffer$1.alloc(minimumBytes);
  const i2 = (e5, i3) => _check(t2, e5, i3), r2 = (e5, t3) => i2(stringToBytes(e5), t3);
  if (e4.fileInfo.size || (e4.fileInfo.size = Number.MAX_SAFE_INTEGER), await e4.peekBuffer(t2, { length: 12, mayBeLess: true }), i2([66, 77])) return { ext: "bmp", mime: "image/bmp" };
  if (i2([11, 119])) return { ext: "ac3", mime: "audio/vnd.dolby.dd-raw" };
  if (i2([120, 1])) return { ext: "dmg", mime: "application/x-apple-diskimage" };
  if (i2([77, 90])) return { ext: "exe", mime: "application/x-msdownload" };
  if (i2([37, 33])) return await e4.peekBuffer(t2, { length: 24, mayBeLess: true }), r2("PS-Adobe-", { offset: 2 }) && r2(" EPSF-", { offset: 14 }) ? { ext: "eps", mime: "application/eps" } : { ext: "ps", mime: "application/postscript" };
  if (i2([31, 160]) || i2([31, 157])) return { ext: "Z", mime: "application/x-compress" };
  if (i2([255, 216, 255])) return { ext: "jpg", mime: "image/jpeg" };
  if (i2([73, 73, 188])) return { ext: "jxr", mime: "image/vnd.ms-photo" };
  if (i2([31, 139, 8])) return { ext: "gz", mime: "application/gzip" };
  if (i2([66, 90, 104])) return { ext: "bz2", mime: "application/x-bzip2" };
  if (r2("ID3")) {
    await e4.ignore(6);
    const n2 = await e4.readToken(uint32SyncSafeToken);
    return e4.position + n2 > e4.fileInfo.size ? { ext: "mp3", mime: "audio/mpeg" } : (await e4.ignore(n2), fromTokenizer(e4));
  }
  if (r2("MP+")) return { ext: "mpc", mime: "audio/x-musepack" };
  if ((67 === t2[0] || 70 === t2[0]) && i2([87, 83], { offset: 1 })) return { ext: "swf", mime: "application/x-shockwave-flash" };
  if (i2([71, 73, 70])) return { ext: "gif", mime: "image/gif" };
  if (r2("FLIF")) return { ext: "flif", mime: "image/flif" };
  if (r2("8BPS")) return { ext: "psd", mime: "image/vnd.adobe.photoshop" };
  if (r2("WEBP", { offset: 8 })) return { ext: "webp", mime: "image/webp" };
  if (r2("MPCK")) return { ext: "mpc", mime: "audio/x-musepack" };
  if (r2("FORM")) return { ext: "aif", mime: "audio/aiff" };
  if (r2("icns", { offset: 0 })) return { ext: "icns", mime: "image/icns" };
  if (i2([80, 75, 3, 4])) {
    try {
      for (; e4.position + 30 < e4.fileInfo.size; ) {
        await e4.readBuffer(t2, { length: 30 });
        const a2 = { compressedSize: t2.readUInt32LE(18), uncompressedSize: t2.readUInt32LE(22), filenameLength: t2.readUInt16LE(26), extraFieldLength: t2.readUInt16LE(28) };
        if (a2.filename = await e4.readToken(new Token.StringType(a2.filenameLength, "utf-8")), await e4.ignore(a2.extraFieldLength), "META-INF/mozilla.rsa" === a2.filename) return { ext: "xpi", mime: "application/x-xpinstall" };
        if (a2.filename.endsWith(".rels") || a2.filename.endsWith(".xml")) {
          switch (a2.filename.split("/")[0]) {
            case "_rels":
            default:
              break;
            case "word":
              return { ext: "docx", mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" };
            case "ppt":
              return { ext: "pptx", mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation" };
            case "xl":
              return { ext: "xlsx", mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" };
          }
        }
        if (a2.filename.startsWith("xl/")) return { ext: "xlsx", mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" };
        if (a2.filename.startsWith("3D/") && a2.filename.endsWith(".model")) return { ext: "3mf", mime: "model/3mf" };
        if ("mimetype" === a2.filename && a2.compressedSize === a2.uncompressedSize) {
          switch (await e4.readToken(new Token.StringType(a2.compressedSize, "utf-8"))) {
            case "application/epub+zip":
              return { ext: "epub", mime: "application/epub+zip" };
            case "application/vnd.oasis.opendocument.text":
              return { ext: "odt", mime: "application/vnd.oasis.opendocument.text" };
            case "application/vnd.oasis.opendocument.spreadsheet":
              return { ext: "ods", mime: "application/vnd.oasis.opendocument.spreadsheet" };
            case "application/vnd.oasis.opendocument.presentation":
              return { ext: "odp", mime: "application/vnd.oasis.opendocument.presentation" };
          }
        }
        if (0 === a2.compressedSize) {
          let o2 = -1;
          for (; o2 < 0 && e4.position < e4.fileInfo.size; ) await e4.peekBuffer(t2, { mayBeLess: true }), o2 = t2.indexOf("504B0304", 0, "hex"), await e4.ignore(o2 >= 0 ? o2 : t2.length);
        } else await e4.ignore(a2.compressedSize);
      }
    } catch (s2) {
      if (!(s2 instanceof strtok3.EndOfStreamError)) throw s2;
    }
    return { ext: "zip", mime: "application/zip" };
  }
  if (r2("OggS")) {
    await e4.ignore(28);
    const l2 = Buffer$1.alloc(8);
    return await e4.readBuffer(l2), _check(l2, [79, 112, 117, 115, 72, 101, 97, 100]) ? { ext: "opus", mime: "audio/opus" } : _check(l2, [128, 116, 104, 101, 111, 114, 97]) ? { ext: "ogv", mime: "video/ogg" } : _check(l2, [1, 118, 105, 100, 101, 111, 0]) ? { ext: "ogm", mime: "video/ogg" } : _check(l2, [127, 70, 76, 65, 67]) ? { ext: "oga", mime: "audio/ogg" } : _check(l2, [83, 112, 101, 101, 120, 32, 32]) ? { ext: "spx", mime: "audio/ogg" } : _check(l2, [1, 118, 111, 114, 98, 105, 115]) ? { ext: "ogg", mime: "audio/ogg" } : { ext: "ogx", mime: "application/ogg" };
  }
  if (i2([80, 75]) && (3 === t2[2] || 5 === t2[2] || 7 === t2[2]) && (4 === t2[3] || 6 === t2[3] || 8 === t2[3])) return { ext: "zip", mime: "application/zip" };
  if (r2("ftyp", { offset: 4 }) && 96 & t2[8]) {
    const u2 = t2.toString("binary", 8, 12).replace("\0", " ").trim();
    switch (u2) {
      case "avif":
        return { ext: "avif", mime: "image/avif" };
      case "mif1":
        return { ext: "heic", mime: "image/heif" };
      case "msf1":
        return { ext: "heic", mime: "image/heif-sequence" };
      case "heic":
      case "heix":
        return { ext: "heic", mime: "image/heic" };
      case "hevc":
      case "hevx":
        return { ext: "heic", mime: "image/heic-sequence" };
      case "qt":
        return { ext: "mov", mime: "video/quicktime" };
      case "M4V":
      case "M4VH":
      case "M4VP":
        return { ext: "m4v", mime: "video/x-m4v" };
      case "M4P":
        return { ext: "m4p", mime: "video/mp4" };
      case "M4B":
        return { ext: "m4b", mime: "audio/mp4" };
      case "M4A":
        return { ext: "m4a", mime: "audio/x-m4a" };
      case "F4V":
        return { ext: "f4v", mime: "video/mp4" };
      case "F4P":
        return { ext: "f4p", mime: "video/mp4" };
      case "F4A":
        return { ext: "f4a", mime: "audio/mp4" };
      case "F4B":
        return { ext: "f4b", mime: "audio/mp4" };
      case "crx":
        return { ext: "cr3", mime: "image/x-canon-cr3" };
      default:
        return u2.startsWith("3g") ? u2.startsWith("3g2") ? { ext: "3g2", mime: "video/3gpp2" } : { ext: "3gp", mime: "video/3gpp" } : { ext: "mp4", mime: "video/mp4" };
    }
  }
  if (r2("MThd")) return { ext: "mid", mime: "audio/midi" };
  if (r2("wOFF") && (i2([0, 1, 0, 0], { offset: 4 }) || r2("OTTO", { offset: 4 }))) return { ext: "woff", mime: "font/woff" };
  if (r2("wOF2") && (i2([0, 1, 0, 0], { offset: 4 }) || r2("OTTO", { offset: 4 }))) return { ext: "woff2", mime: "font/woff2" };
  if (i2([212, 195, 178, 161]) || i2([161, 178, 195, 212])) return { ext: "pcap", mime: "application/vnd.tcpdump.pcap" };
  if (r2("DSD ")) return { ext: "dsf", mime: "audio/x-dsf" };
  if (r2("LZIP")) return { ext: "lz", mime: "application/x-lzip" };
  if (r2("fLaC")) return { ext: "flac", mime: "audio/x-flac" };
  if (i2([66, 80, 71, 251])) return { ext: "bpg", mime: "image/bpg" };
  if (r2("wvpk")) return { ext: "wv", mime: "audio/wavpack" };
  if (r2("%PDF")) {
    await e4.ignore(1350);
    const h2 = 10485760, c2 = Buffer$1.alloc(Math.min(h2, e4.fileInfo.size));
    return await e4.readBuffer(c2, { mayBeLess: true }), c2.includes(Buffer$1.from("AIPrivateData")) ? { ext: "ai", mime: "application/postscript" } : { ext: "pdf", mime: "application/pdf" };
  }
  if (i2([0, 97, 115, 109])) return { ext: "wasm", mime: "application/wasm" };
  if (i2([73, 73, 42, 0])) return r2("CR", { offset: 8 }) ? { ext: "cr2", mime: "image/x-canon-cr2" } : i2([28, 0, 254, 0], { offset: 8 }) || i2([31, 0, 11, 0], { offset: 8 }) ? { ext: "nef", mime: "image/x-nikon-nef" } : i2([8, 0, 0, 0], { offset: 4 }) && (i2([45, 0, 254, 0], { offset: 8 }) || i2([39, 0, 254, 0], { offset: 8 })) ? { ext: "dng", mime: "image/x-adobe-dng" } : (t2 = Buffer$1.alloc(24), await e4.peekBuffer(t2), (i2([16, 251, 134, 1], { offset: 4 }) || i2([8, 0, 0, 0], { offset: 4 })) && i2([0, 254, 0, 4, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 1], { offset: 9 }) ? { ext: "arw", mime: "image/x-sony-arw" } : { ext: "tif", mime: "image/tiff" });
  if (i2([77, 77, 0, 42])) return { ext: "tif", mime: "image/tiff" };
  if (r2("MAC ")) return { ext: "ape", mime: "audio/ape" };
  if (i2([26, 69, 223, 163])) {
    async function f2() {
      const t3 = await e4.peekNumber(Token.UINT8);
      let i3 = 128, r3 = 0;
      for (; !(t3 & i3) && 0 !== i3; ) ++r3, i3 >>= 1;
      const n2 = Buffer$1.alloc(r3 + 1);
      return await e4.readBuffer(n2), n2;
    }
    async function d() {
      const e5 = await f2(), t3 = await f2();
      t3[0] ^= 128 >> t3.length - 1;
      const i3 = Math.min(6, t3.length);
      return { id: e5.readUIntBE(0, e5.length), len: t3.readUIntBE(t3.length - i3, i3) };
    }
    async function p2(t3, i3) {
      for (; i3 > 0; ) {
        const t4 = await d();
        if (17026 === t4.id) return e4.readToken(new Token.StringType(t4.len, "utf-8"));
        await e4.ignore(t4.len), --i3;
      }
    }
    const m = await d();
    switch (await p2(0, m.len)) {
      case "webm":
        return { ext: "webm", mime: "video/webm" };
      case "matroska":
        return { ext: "mkv", mime: "video/x-matroska" };
      default:
        return;
    }
  }
  if (i2([82, 73, 70, 70])) {
    if (i2([65, 86, 73], { offset: 8 })) return { ext: "avi", mime: "video/vnd.avi" };
    if (i2([87, 65, 86, 69], { offset: 8 })) return { ext: "wav", mime: "audio/vnd.wave" };
    if (i2([81, 76, 67, 77], { offset: 8 })) return { ext: "qcp", mime: "audio/qcelp" };
  }
  if (r2("SQLi")) return { ext: "sqlite", mime: "application/x-sqlite3" };
  if (i2([78, 69, 83, 26])) return { ext: "nes", mime: "application/x-nintendo-nes-rom" };
  if (r2("Cr24")) return { ext: "crx", mime: "application/x-google-chrome-extension" };
  if (r2("MSCF") || r2("ISc(")) return { ext: "cab", mime: "application/vnd.ms-cab-compressed" };
  if (i2([237, 171, 238, 219])) return { ext: "rpm", mime: "application/x-rpm" };
  if (i2([197, 208, 211, 198])) return { ext: "eps", mime: "application/eps" };
  if (i2([40, 181, 47, 253])) return { ext: "zst", mime: "application/zstd" };
  if (i2([79, 84, 84, 79, 0])) return { ext: "otf", mime: "font/otf" };
  if (r2("#!AMR")) return { ext: "amr", mime: "audio/amr" };
  if (r2("{\\rtf")) return { ext: "rtf", mime: "application/rtf" };
  if (i2([70, 76, 86, 1])) return { ext: "flv", mime: "video/x-flv" };
  if (r2("IMPM")) return { ext: "it", mime: "audio/x-it" };
  if (r2("-lh0-", { offset: 2 }) || r2("-lh1-", { offset: 2 }) || r2("-lh2-", { offset: 2 }) || r2("-lh3-", { offset: 2 }) || r2("-lh4-", { offset: 2 }) || r2("-lh5-", { offset: 2 }) || r2("-lh6-", { offset: 2 }) || r2("-lh7-", { offset: 2 }) || r2("-lzs-", { offset: 2 }) || r2("-lz4-", { offset: 2 }) || r2("-lz5-", { offset: 2 }) || r2("-lhd-", { offset: 2 })) return { ext: "lzh", mime: "application/x-lzh-compressed" };
  if (i2([0, 0, 1, 186])) {
    if (i2([33], { offset: 4, mask: [241] })) return { ext: "mpg", mime: "video/MP1S" };
    if (i2([68], { offset: 4, mask: [196] })) return { ext: "mpg", mime: "video/MP2P" };
  }
  if (r2("ITSF")) return { ext: "chm", mime: "application/vnd.ms-htmlhelp" };
  if (i2([253, 55, 122, 88, 90, 0])) return { ext: "xz", mime: "application/x-xz" };
  if (r2("<?xml ")) return { ext: "xml", mime: "application/xml" };
  if (i2([55, 122, 188, 175, 39, 28])) return { ext: "7z", mime: "application/x-7z-compressed" };
  if (i2([82, 97, 114, 33, 26, 7]) && (0 === t2[6] || 1 === t2[6])) return { ext: "rar", mime: "application/x-rar-compressed" };
  if (r2("solid ")) return { ext: "stl", mime: "model/stl" };
  if (r2("BLENDER")) return { ext: "blend", mime: "application/x-blender" };
  if (r2("!<arch>")) {
    await e4.ignore(8);
    return "debian-binary" === await e4.readToken(new Token.StringType(13, "ascii")) ? { ext: "deb", mime: "application/x-deb" } : { ext: "ar", mime: "application/x-unix-archive" };
  }
  if (i2([137, 80, 78, 71, 13, 10, 26, 10])) {
    async function _2() {
      return { length: await e4.readToken(Token.INT32_BE), type: await e4.readToken(new Token.StringType(4, "binary")) };
    }
    await e4.ignore(8);
    do {
      const g = await _2();
      if (g.length < 0) return;
      switch (g.type) {
        case "IDAT":
          return { ext: "png", mime: "image/png" };
        case "acTL":
          return { ext: "apng", mime: "image/apng" };
        default:
          await e4.ignore(g.length + 4);
      }
    } while (e4.position + 8 < e4.fileInfo.size);
    return { ext: "png", mime: "image/png" };
  }
  if (i2([65, 82, 82, 79, 87, 49, 0, 0])) return { ext: "arrow", mime: "application/x-apache-arrow" };
  if (i2([103, 108, 84, 70, 2, 0, 0, 0])) return { ext: "glb", mime: "model/gltf-binary" };
  if (i2([102, 114, 101, 101], { offset: 4 }) || i2([109, 100, 97, 116], { offset: 4 }) || i2([109, 111, 111, 118], { offset: 4 }) || i2([119, 105, 100, 101], { offset: 4 })) return { ext: "mov", mime: "video/quicktime" };
  if (i2([73, 73, 82, 79, 8, 0, 0, 0, 24])) return { ext: "orf", mime: "image/x-olympus-orf" };
  if (r2("gimp xcf ")) return { ext: "xcf", mime: "image/x-xcf" };
  if (i2([73, 73, 85, 0, 24, 0, 0, 0, 136, 231, 116, 216])) return { ext: "rw2", mime: "image/x-panasonic-rw2" };
  if (i2([48, 38, 178, 117, 142, 102, 207, 17, 166, 217])) {
    async function b2() {
      const t3 = Buffer$1.alloc(16);
      return await e4.readBuffer(t3), { id: t3, size: Number(await e4.readToken(Token.UINT64_LE)) };
    }
    for (await e4.ignore(30); e4.position + 24 < e4.fileInfo.size; ) {
      const y2 = await b2();
      let w = y2.size - 24;
      if (_check(y2.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) {
        const v2 = Buffer$1.alloc(16);
        if (w -= await e4.readBuffer(v2), _check(v2, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) return { ext: "asf", mime: "audio/x-ms-asf" };
        if (_check(v2, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) return { ext: "asf", mime: "video/x-ms-asf" };
        break;
      }
      await e4.ignore(w);
    }
    return { ext: "asf", mime: "application/vnd.ms-asf" };
  }
  if (i2([171, 75, 84, 88, 32, 49, 49, 187, 13, 10, 26, 10])) return { ext: "ktx", mime: "image/ktx" };
  if ((i2([126, 16, 4]) || i2([126, 24, 4])) && i2([48, 77, 73, 69], { offset: 4 })) return { ext: "mie", mime: "application/x-mie" };
  if (i2([39, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], { offset: 2 })) return { ext: "shp", mime: "application/x-esri-shape" };
  if (i2([0, 0, 0, 12, 106, 80, 32, 32, 13, 10, 135, 10])) {
    await e4.ignore(20);
    switch (await e4.readToken(new Token.StringType(4, "ascii"))) {
      case "jp2 ":
        return { ext: "jp2", mime: "image/jp2" };
      case "jpx ":
        return { ext: "jpx", mime: "image/jpx" };
      case "jpm ":
        return { ext: "jpm", mime: "image/jpm" };
      case "mjp2":
        return { ext: "mj2", mime: "image/mj2" };
      default:
        return;
    }
  }
  if (i2([255, 10]) || i2([0, 0, 0, 12, 74, 88, 76, 32, 13, 10, 135, 10])) return { ext: "jxl", mime: "image/jxl" };
  if (i2([0, 0, 1, 186]) || i2([0, 0, 1, 179])) return { ext: "mpg", mime: "video/mpeg" };
  if (i2([0, 1, 0, 0, 0])) return { ext: "ttf", mime: "font/ttf" };
  if (i2([0, 0, 1, 0])) return { ext: "ico", mime: "image/x-icon" };
  if (i2([0, 0, 2, 0])) return { ext: "cur", mime: "image/x-icon" };
  if (i2([208, 207, 17, 224, 161, 177, 26, 225])) return { ext: "cfb", mime: "application/x-cfb" };
  if (await e4.peekBuffer(t2, { length: Math.min(256, e4.fileInfo.size), mayBeLess: true }), r2("BEGIN:")) {
    if (r2("VCARD", { offset: 6 })) return { ext: "vcf", mime: "text/vcard" };
    if (r2("VCALENDAR", { offset: 6 })) return { ext: "ics", mime: "text/calendar" };
  }
  if (r2("FUJIFILMCCD-RAW")) return { ext: "raf", mime: "image/x-fujifilm-raf" };
  if (r2("Extended Module:")) return { ext: "xm", mime: "audio/x-xm" };
  if (r2("Creative Voice File")) return { ext: "voc", mime: "audio/x-voc" };
  if (i2([4, 0, 0, 0]) && t2.length >= 16) {
    const x2 = t2.readUInt32LE(12);
    if (x2 > 12 && t2.length >= x2 + 16) try {
      const E2 = t2.slice(16, x2 + 16).toString();
      if (JSON.parse(E2).files) return { ext: "asar", mime: "application/x-asar" };
    } catch (k2) {
    }
  }
  if (i2([6, 14, 43, 52, 2, 5, 1, 1, 13, 1, 2, 1, 1, 2])) return { ext: "mxf", mime: "application/mxf" };
  if (r2("SCRM", { offset: 44 })) return { ext: "s3m", mime: "audio/x-s3m" };
  if (i2([71], { offset: 4 }) && (i2([71], { offset: 192 }) || i2([71], { offset: 196 }))) return { ext: "mts", mime: "video/mp2t" };
  if (i2([66, 79, 79, 75, 77, 79, 66, 73], { offset: 60 })) return { ext: "mobi", mime: "application/x-mobipocket-ebook" };
  if (i2([68, 73, 67, 77], { offset: 128 })) return { ext: "dcm", mime: "application/dicom" };
  if (i2([76, 0, 0, 0, 1, 20, 2, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 70])) return { ext: "lnk", mime: "application/x.ms.shortcut" };
  if (i2([98, 111, 111, 107, 0, 0, 0, 0, 109, 97, 114, 107, 0, 0, 0, 0])) return { ext: "alias", mime: "application/x.apple.alias" };
  if (i2([76, 80], { offset: 34 }) && (i2([0, 0, 1], { offset: 8 }) || i2([1, 0, 2], { offset: 8 }) || i2([2, 0, 2], { offset: 8 }))) return { ext: "eot", mime: "application/vnd.ms-fontobject" };
  if (i2([6, 6, 237, 245, 216, 29, 70, 229, 189, 49, 239, 231, 254, 116, 183, 29])) return { ext: "indd", mime: "application/x-indesign" };
  if (await e4.peekBuffer(t2, { length: Math.min(512, e4.fileInfo.size), mayBeLess: true }), tarHeaderChecksumMatches(t2)) return { ext: "tar", mime: "application/x-tar" };
  if (i2([255, 254, 255, 14, 83, 0, 107, 0, 101, 0, 116, 0, 99, 0, 104, 0, 85, 0, 112, 0, 32, 0, 77, 0, 111, 0, 100, 0, 101, 0, 108, 0])) return { ext: "skp", mime: "application/vnd.sketchup.skp" };
  if (r2("-----BEGIN PGP MESSAGE-----")) return { ext: "pgp", mime: "application/pgp-encrypted" };
  if (t2.length >= 2 && i2([255, 224], { offset: 0, mask: [255, 224] })) {
    if (i2([16], { offset: 1, mask: [22] })) return i2([8], { offset: 1, mask: [8] }), { ext: "aac", mime: "audio/aac" };
    if (i2([2], { offset: 1, mask: [6] })) return { ext: "mp3", mime: "audio/mpeg" };
    if (i2([4], { offset: 1, mask: [6] })) return { ext: "mp2", mime: "audio/mpeg" };
    if (i2([6], { offset: 1, mask: [6] })) return { ext: "mp1", mime: "audio/mpeg" };
  }
}
const stream = (readableStream) => new Promise((resolve, reject) => {
  const stream = eval("require")("stream");
  readableStream.on("error", reject), readableStream.once("readable", async () => {
    const e4 = new stream.PassThrough();
    let t2;
    t2 = stream.pipeline ? stream.pipeline(readableStream, e4, () => {
    }) : readableStream.pipe(e4);
    const i2 = readableStream.read(minimumBytes) || readableStream.read() || Buffer$1.alloc(0);
    try {
      const t3 = await fromBuffer(i2);
      e4.fileType = t3;
    } catch (e5) {
      reject(e5);
    }
    resolve(t2);
  });
}), fileType = { fromStream, fromTokenizer, fromBuffer, stream };
Object.defineProperty(fileType, "extensions", { get: () => new Set(supported.extensions) }), Object.defineProperty(fileType, "mimeTypes", { get: () => new Set(supported.mimeTypes) });
var core = fileType, fileType$1 = getDefaultExportFromCjs(core);
function to(e4, t2) {
  return e4.then(function(e5) {
    return [null, e5];
  }).catch(function(e5) {
    return [e5, void 0];
  });
}
const writeFile = async () => {
  throw new Error("Not supported");
};
function Mime$1() {
  this._types = /* @__PURE__ */ Object.create(null), this._extensions = /* @__PURE__ */ Object.create(null);
  for (let e4 = 0; e4 < arguments.length; e4++) this.define(arguments[e4]);
  this.define = this.define.bind(this), this.getType = this.getType.bind(this), this.getExtension = this.getExtension.bind(this);
}
Mime$1.prototype.define = function(e4, t2) {
  for (let i2 in e4) {
    let r2 = e4[i2].map(function(e5) {
      return e5.toLowerCase();
    });
    i2 = i2.toLowerCase();
    for (let e5 = 0; e5 < r2.length; e5++) {
      const n2 = r2[e5];
      if ("*" !== n2[0]) {
        if (!t2 && n2 in this._types) throw new Error('Attempt to change mapping for "' + n2 + '" extension from "' + this._types[n2] + '" to "' + i2 + '". Pass `force=true` to allow this, otherwise remove "' + n2 + '" from the list of extensions for "' + i2 + '".');
        this._types[n2] = i2;
      }
    }
    if (t2 || !this._extensions[i2]) {
      const e5 = r2[0];
      this._extensions[i2] = "*" !== e5[0] ? e5 : e5.substr(1);
    }
  }
}, Mime$1.prototype.getType = function(e4) {
  let t2 = (e4 = String(e4)).replace(/^.*[/\\]/, "").toLowerCase(), i2 = t2.replace(/^.*\./, "").toLowerCase(), r2 = t2.length < e4.length;
  return (i2.length < t2.length - 1 || !r2) && this._types[i2] || null;
}, Mime$1.prototype.getExtension = function(e4) {
  return (e4 = /^\s*([^;\s]*)/.test(e4) && RegExp.$1) && this._extensions[e4.toLowerCase()] || null;
};
var Mime_1 = Mime$1, standard = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
let Mime = Mime_1;
var lite = new Mime(standard), mime = getDefaultExportFromCjs(lite), HorizontalAlign, HorizontalAlign2, VerticalAlign, VerticalAlign2, BlendMode, BlendMode2;
function srcOver(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a;
  return { r: (e4.r * e4.a + t2.r * t2.a * (1 - e4.a)) / r2, g: (e4.g * e4.a + t2.g * t2.a * (1 - e4.a)) / r2, b: (e4.b * e4.a + t2.b * t2.a * (1 - e4.a)) / r2, a: r2 };
}
function dstOver(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a;
  return { r: (t2.r * t2.a + e4.r * e4.a * (1 - t2.a)) / r2, g: (t2.g * t2.a + e4.g * e4.a * (1 - t2.a)) / r2, b: (t2.b * t2.a + e4.b * e4.a * (1 - t2.a)) / r2, a: r2 };
}
function multiply(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (n2 * s2 + n2 * (1 - t2.a) + s2 * (1 - e4.a)) / r2, g: (a2 * l2 + a2 * (1 - t2.a) + l2 * (1 - e4.a)) / r2, b: (o2 * u2 + o2 * (1 - t2.a) + u2 * (1 - e4.a)) / r2, a: r2 };
}
function add(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a;
  return { r: (n2 + t2.r * t2.a) / r2, g: (a2 + t2.g * t2.a) / r2, b: (o2 + t2.b * t2.a) / r2, a: r2 };
}
function screen$1(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (n2 * t2.a + s2 * e4.a - n2 * s2 + n2 * (1 - t2.a) + s2 * (1 - e4.a)) / r2, g: (a2 * t2.a + l2 * e4.a - a2 * l2 + a2 * (1 - t2.a) + l2 * (1 - e4.a)) / r2, b: (o2 * t2.a + u2 * e4.a - o2 * u2 + o2 * (1 - t2.a) + u2 * (1 - e4.a)) / r2, a: r2 };
}
function overlay(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (2 * s2 <= t2.a ? 2 * n2 * s2 + n2 * (1 - t2.a) + s2 * (1 - e4.a) : n2 * (1 + t2.a) + s2 * (1 + e4.a) - 2 * s2 * n2 - t2.a * e4.a) / r2, g: (2 * l2 <= t2.a ? 2 * a2 * l2 + a2 * (1 - t2.a) + l2 * (1 - e4.a) : a2 * (1 + t2.a) + l2 * (1 + e4.a) - 2 * l2 * a2 - t2.a * e4.a) / r2, b: (2 * u2 <= t2.a ? 2 * o2 * u2 + o2 * (1 - t2.a) + u2 * (1 - e4.a) : o2 * (1 + t2.a) + u2 * (1 + e4.a) - 2 * u2 * o2 - t2.a * e4.a) / r2, a: r2 };
}
function darken(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (Math.min(n2 * t2.a, s2 * e4.a) + n2 * (1 - t2.a) + s2 * (1 - e4.a)) / r2, g: (Math.min(a2 * t2.a, l2 * e4.a) + a2 * (1 - t2.a) + l2 * (1 - e4.a)) / r2, b: (Math.min(o2 * t2.a, u2 * e4.a) + o2 * (1 - t2.a) + u2 * (1 - e4.a)) / r2, a: r2 };
}
function lighten(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (Math.max(n2 * t2.a, s2 * e4.a) + n2 * (1 - t2.a) + s2 * (1 - e4.a)) / r2, g: (Math.max(a2 * t2.a, l2 * e4.a) + a2 * (1 - t2.a) + l2 * (1 - e4.a)) / r2, b: (Math.max(o2 * t2.a, u2 * e4.a) + o2 * (1 - t2.a) + u2 * (1 - e4.a)) / r2, a: r2 };
}
function hardLight(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (2 * n2 <= e4.a ? 2 * n2 * s2 + n2 * (1 - t2.a) + s2 * (1 - e4.a) : n2 * (1 + t2.a) + s2 * (1 + e4.a) - 2 * s2 * n2 - t2.a * e4.a) / r2, g: (2 * a2 <= e4.a ? 2 * a2 * l2 + a2 * (1 - t2.a) + l2 * (1 - e4.a) : a2 * (1 + t2.a) + l2 * (1 + e4.a) - 2 * l2 * a2 - t2.a * e4.a) / r2, b: (2 * o2 <= e4.a ? 2 * o2 * u2 + o2 * (1 - t2.a) + u2 * (1 - e4.a) : o2 * (1 + t2.a) + u2 * (1 + e4.a) - 2 * u2 * o2 - t2.a * e4.a) / r2, a: r2 };
}
function difference(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (n2 + s2 - 2 * Math.min(n2 * t2.a, s2 * e4.a)) / r2, g: (a2 + l2 - 2 * Math.min(a2 * t2.a, l2 * e4.a)) / r2, b: (o2 + u2 - 2 * Math.min(o2 * t2.a, u2 * e4.a)) / r2, a: r2 };
}
function exclusion(e4, t2, i2 = 1) {
  e4.a *= i2;
  const r2 = t2.a + e4.a - t2.a * e4.a, n2 = e4.r * e4.a, a2 = e4.g * e4.a, o2 = e4.b * e4.a, s2 = t2.r * t2.a, l2 = t2.g * t2.a, u2 = t2.b * t2.a;
  return { r: (n2 * t2.a + s2 * e4.a - 2 * n2 * s2 + n2 * (1 - t2.a) + s2 * (1 - e4.a)) / r2, g: (a2 * t2.a + l2 * e4.a - 2 * a2 * l2 + a2 * (1 - t2.a) + l2 * (1 - e4.a)) / r2, b: (o2 * t2.a + u2 * e4.a - 2 * o2 * u2 + o2 * (1 - t2.a) + u2 * (1 - e4.a)) / r2, a: r2 };
}
HorizontalAlign2 = HorizontalAlign || (HorizontalAlign = {}), HorizontalAlign2[HorizontalAlign2.LEFT = 1] = "LEFT", HorizontalAlign2[HorizontalAlign2.CENTER = 2] = "CENTER", HorizontalAlign2[HorizontalAlign2.RIGHT = 4] = "RIGHT", VerticalAlign2 = VerticalAlign || (VerticalAlign = {}), VerticalAlign2[VerticalAlign2.TOP = 8] = "TOP", VerticalAlign2[VerticalAlign2.MIDDLE = 16] = "MIDDLE", VerticalAlign2[VerticalAlign2.BOTTOM = 32] = "BOTTOM", BlendMode2 = BlendMode || (BlendMode = {}), BlendMode2.SRC_OVER = "srcOver", BlendMode2.DST_OVER = "dstOver", BlendMode2.MULTIPLY = "multiply", BlendMode2.ADD = "add", BlendMode2.SCREEN = "screen", BlendMode2.OVERLAY = "overlay", BlendMode2.DARKEN = "darken", BlendMode2.LIGHTEN = "lighten", BlendMode2.HARD_LIGHT = "hardLight", BlendMode2.DIFFERENCE = "difference", BlendMode2.EXCLUSION = "exclusion";
const names = [srcOver, dstOver, multiply, add, screen$1, overlay, darken, lighten, hardLight, difference, exclusion];
var compositeModes = Object.freeze({ __proto__: null, add, darken, difference, dstOver, exclusion, hardLight, lighten, multiply, names, overlay, screen: screen$1, srcOver });
function composite(e4, t2, i2 = 0, r2 = 0, n2 = {}) {
  if (!(t2 instanceof e4.constructor)) throw new Error("The source must be a Jimp image");
  if ("number" != typeof i2 || "number" != typeof r2) throw new Error("x and y must be numbers");
  const { mode: a2 = BlendMode.SRC_OVER } = n2;
  let { opacitySource: o2 = 1, opacityDest: s2 = 1 } = n2;
  ("number" != typeof o2 || o2 < 0 || o2 > 1) && (o2 = 1), ("number" != typeof s2 || s2 < 0 || s2 > 1) && (s2 = 1);
  const l2 = compositeModes[a2];
  return i2 = Math.round(i2), r2 = Math.round(r2), 1 !== s2 && e4.scan((t3, i3, r3) => {
    const n3 = e4.bitmap.data[r3 + 3] * s2;
    e4.bitmap.data[r3 + 3] = n3;
  }), t2.scan((n3, a3, s3) => {
    const u2 = e4.getPixelIndex(i2 + n3, r2 + a3, Edge.CROP);
    if (-1 === u2) return;
    const h2 = l2({ r: t2.bitmap.data[s3 + 0] / 255, g: t2.bitmap.data[s3 + 1] / 255, b: t2.bitmap.data[s3 + 2] / 255, a: t2.bitmap.data[s3 + 3] / 255 }, { r: e4.bitmap.data[u2 + 0] / 255, g: e4.bitmap.data[u2 + 1] / 255, b: e4.bitmap.data[u2 + 2] / 255, a: e4.bitmap.data[u2 + 3] / 255 }, o2);
    e4.bitmap.data[u2 + 0] = limit255(255 * h2.r), e4.bitmap.data[u2 + 1] = limit255(255 * h2.g), e4.bitmap.data[u2 + 2] = limit255(255 * h2.b), e4.bitmap.data[u2 + 3] = limit255(255 * h2.a);
  }), e4;
}
var jpeg$1 = { parseSections: function(e4, t2) {
  var i2, r2;
  for (e4.setBigEndian(true); e4.remainingLength() > 0 && 218 !== r2; ) {
    if (255 !== e4.nextUInt8()) throw new Error("Invalid JPEG section offset");
    i2 = (r2 = e4.nextUInt8()) >= 208 && r2 <= 217 || 218 === r2 ? 0 : e4.nextUInt16() - 2, t2(r2, e4.branch(0, i2)), e4.skip(i2);
  }
}, getSizeFromSOFSection: function(e4) {
  return e4.skip(1), { height: e4.nextUInt16(), width: e4.nextUInt16() };
}, getSectionName: function(e4) {
  var t2, i2;
  switch (e4) {
    case 216:
      t2 = "SOI";
      break;
    case 196:
      t2 = "DHT";
      break;
    case 219:
      t2 = "DQT";
      break;
    case 221:
      t2 = "DRI";
      break;
    case 218:
      t2 = "SOS";
      break;
    case 254:
      t2 = "COM";
      break;
    case 217:
      t2 = "EOI";
      break;
    default:
      e4 >= 224 && e4 <= 239 ? (t2 = "APP", i2 = e4 - 224) : e4 >= 192 && e4 <= 207 && 196 !== e4 && 200 !== e4 && 204 !== e4 ? (t2 = "SOF", i2 = e4 - 192) : e4 >= 208 && e4 <= 215 && (t2 = "RST", i2 = e4 - 208);
  }
  var r2 = { name: t2 };
  return "number" == typeof i2 && (r2.index = i2), r2;
} };
function readExifValue(e4, t2) {
  switch (e4) {
    case 1:
      return t2.nextUInt8();
    case 3:
    case 8:
      return t2.nextUInt16();
    case 4:
    case 9:
      return t2.nextUInt32();
    case 5:
      return [t2.nextUInt32(), t2.nextUInt32()];
    case 6:
      return t2.nextInt8();
    case 10:
      return [t2.nextInt32(), t2.nextInt32()];
    case 11:
      return t2.nextFloat();
    case 12:
      return t2.nextDouble();
    default:
      throw new Error("Invalid format while decoding: " + e4);
  }
}
function getBytesPerComponent(e4) {
  switch (e4) {
    case 1:
    case 2:
    case 6:
    case 7:
      return 1;
    case 3:
    case 8:
      return 2;
    case 4:
    case 9:
    case 11:
      return 4;
    case 5:
    case 10:
    case 12:
      return 8;
    default:
      return 0;
  }
}
function readExifTag(e4, t2) {
  var i2, r2, n2 = t2.nextUInt16(), a2 = t2.nextUInt16(), o2 = getBytesPerComponent(a2), s2 = t2.nextUInt32(), l2 = o2 * s2;
  if (l2 > 4 && (t2 = e4.openWithOffset(t2.nextUInt32())), 2 === a2) {
    var u2 = (i2 = t2.nextString(s2)).indexOf("\0");
    -1 !== u2 && (i2 = i2.substr(0, u2));
  } else if (7 === a2) i2 = t2.nextBuffer(s2);
  else if (0 !== a2) for (i2 = [], r2 = 0; r2 < s2; ++r2) i2.push(readExifValue(a2, t2));
  return l2 < 4 && t2.skip(4 - l2), [n2, i2, a2];
}
function readIFDSection(e4, t2, i2) {
  var r2, n2, a2 = t2.nextUInt16();
  for (n2 = 0; n2 < a2; ++n2) i2((r2 = readExifTag(e4, t2))[0], r2[1], r2[2]);
}
function readHeader(e4) {
  if ("Exif\0\0" !== e4.nextString(6)) throw new Error("Invalid EXIF header");
  var t2 = e4.mark(), i2 = e4.nextUInt16();
  if (18761 === i2) e4.setBigEndian(false);
  else {
    if (19789 !== i2) throw new Error("Invalid TIFF header");
    e4.setBigEndian(true);
  }
  if (42 !== e4.nextUInt16()) throw new Error("Invalid TIFF data");
  return t2;
}
var exif$2 = { IFD0: 1, IFD1: 2, GPSIFD: 3, SubIFD: 4, InteropIFD: 5, parseTags: function(e4, t2) {
  var i2, r2, n2, a2;
  try {
    i2 = readHeader(e4);
  } catch (e5) {
    return false;
  }
  var o2 = i2.openWithOffset(e4.nextUInt32()), s2 = this.IFD0;
  readIFDSection(i2, o2, function(e5, i3, a3) {
    switch (e5) {
      case 34853:
        n2 = i3[0];
        break;
      case 34665:
        r2 = i3[0];
        break;
      default:
        t2(s2, e5, i3, a3);
    }
  });
  var l2 = o2.nextUInt32();
  if (0 !== l2) {
    var u2 = i2.openWithOffset(l2);
    readIFDSection(i2, u2, t2.bind(null, this.IFD1));
  }
  if (n2) {
    var h2 = i2.openWithOffset(n2);
    readIFDSection(i2, h2, t2.bind(null, this.GPSIFD));
  }
  if (r2) {
    var c2 = i2.openWithOffset(r2), f2 = this.InteropIFD;
    readIFDSection(i2, c2, function(e5, i3, r3) {
      40965 === e5 ? a2 = i3[0] : t2(f2, e5, i3, r3);
    });
  }
  if (a2) {
    var d = i2.openWithOffset(a2);
    readIFDSection(i2, d, t2.bind(null, this.InteropIFD));
  }
  return true;
} };
function parseNumber(e4) {
  return parseInt(e4, 10);
}
var hours = 3600, minutes = 60;
function parseDateTimeParts(e4, t2) {
  e4 = e4.map(parseNumber), t2 = t2.map(parseNumber);
  var i2 = e4[0], r2 = e4[1] - 1, n2 = e4[2], a2 = t2[0], o2 = t2[1], s2 = t2[2];
  return Date.UTC(i2, r2, n2, a2, o2, s2, 0) / 1e3;
}
function parseDateWithTimezoneFormat(e4) {
  var t2 = e4.substr(0, 10).split("-"), i2 = e4.substr(11, 8).split(":"), r2 = e4.substr(19, 6).split(":").map(parseNumber), n2 = r2[0] * hours + r2[1] * minutes, a2 = parseDateTimeParts(t2, i2);
  if ("number" == typeof (a2 -= n2) && !isNaN(a2)) return a2;
}
function parseDateWithSpecFormat(e4) {
  var t2 = e4.split(" "), i2 = parseDateTimeParts(t2[0].split(":"), t2[1].split(":"));
  if ("number" == typeof i2 && !isNaN(i2)) return i2;
}
function parseExifDate(e4) {
  var t2 = 19 === e4.length && ":" === e4.charAt(4);
  return 25 === e4.length && "T" === e4.charAt(10) ? parseDateWithTimezoneFormat(e4) : t2 ? parseDateWithSpecFormat(e4) : void 0;
}
var date$1 = { parseDateWithSpecFormat, parseDateWithTimezoneFormat, parseExifDate }, exif$1 = exif$2, date = date$1, degreeTags = [{ section: exif$1.GPSIFD, type: 2, name: "GPSLatitude", refType: 1, refName: "GPSLatitudeRef", posVal: "N" }, { section: exif$1.GPSIFD, type: 4, name: "GPSLongitude", refType: 3, refName: "GPSLongitudeRef", posVal: "E" }], dateTags = [{ section: exif$1.SubIFD, type: 306, name: "ModifyDate" }, { section: exif$1.SubIFD, type: 36867, name: "DateTimeOriginal" }, { section: exif$1.SubIFD, type: 36868, name: "CreateDate" }, { section: exif$1.SubIFD, type: 306, name: "ModifyDate" }], simplify$1 = { castDegreeValues: function(e4, t2) {
  degreeTags.forEach(function(i2) {
    var r2 = e4(i2);
    if (r2) {
      var n2 = e4({ section: i2.section, type: i2.refType, name: i2.refName }) === i2.posVal ? 1 : -1, a2 = (r2[0] + r2[1] / 60 + r2[2] / 3600) * n2;
      t2(i2, a2);
    }
  });
}, castDateValues: function(e4, t2) {
  dateTags.forEach(function(i2) {
    var r2 = e4(i2);
    if (r2) {
      var n2 = date.parseExifDate(r2);
      void 0 !== n2 && t2(i2, n2);
    }
  });
}, simplifyValue: function(e4, t2) {
  return Array.isArray(e4) && 1 === (e4 = e4.map(function(e5) {
    return 10 === t2 || 5 === t2 ? e5[0] / e5[1] : e5;
  })).length && (e4 = e4[0]), e4;
} }, exifTags, hasRequiredExifTags;
function requireExifTags() {
  return hasRequiredExifTags ? exifTags : (hasRequiredExifTags = 1, exifTags = { exif: { 1: "InteropIndex", 2: "InteropVersion", 11: "ProcessingSoftware", 254: "SubfileType", 255: "OldSubfileType", 256: "ImageWidth", 257: "ImageHeight", 258: "BitsPerSample", 259: "Compression", 262: "PhotometricInterpretation", 263: "Thresholding", 264: "CellWidth", 265: "CellLength", 266: "FillOrder", 269: "DocumentName", 270: "ImageDescription", 271: "Make", 272: "Model", 273: "StripOffsets", 274: "Orientation", 277: "SamplesPerPixel", 278: "RowsPerStrip", 279: "StripByteCounts", 280: "MinSampleValue", 281: "MaxSampleValue", 282: "XResolution", 283: "YResolution", 284: "PlanarConfiguration", 285: "PageName", 286: "XPosition", 287: "YPosition", 288: "FreeOffsets", 289: "FreeByteCounts", 290: "GrayResponseUnit", 291: "GrayResponseCurve", 292: "T4Options", 293: "T6Options", 296: "ResolutionUnit", 297: "PageNumber", 300: "ColorResponseUnit", 301: "TransferFunction", 305: "Software", 306: "ModifyDate", 315: "Artist", 316: "HostComputer", 317: "Predictor", 318: "WhitePoint", 319: "PrimaryChromaticities", 320: "ColorMap", 321: "HalftoneHints", 322: "TileWidth", 323: "TileLength", 324: "TileOffsets", 325: "TileByteCounts", 326: "BadFaxLines", 327: "CleanFaxData", 328: "ConsecutiveBadFaxLines", 330: "SubIFD", 332: "InkSet", 333: "InkNames", 334: "NumberofInks", 336: "DotRange", 337: "TargetPrinter", 338: "ExtraSamples", 339: "SampleFormat", 340: "SMinSampleValue", 341: "SMaxSampleValue", 342: "TransferRange", 343: "ClipPath", 344: "XClipPathUnits", 345: "YClipPathUnits", 346: "Indexed", 347: "JPEGTables", 351: "OPIProxy", 400: "GlobalParametersIFD", 401: "ProfileType", 402: "FaxProfile", 403: "CodingMethods", 404: "VersionYear", 405: "ModeNumber", 433: "Decode", 434: "DefaultImageColor", 435: "T82Options", 437: "JPEGTables", 512: "JPEGProc", 513: "ThumbnailOffset", 514: "ThumbnailLength", 515: "JPEGRestartInterval", 517: "JPEGLosslessPredictors", 518: "JPEGPointTransforms", 519: "JPEGQTables", 520: "JPEGDCTables", 521: "JPEGACTables", 529: "YCbCrCoefficients", 530: "YCbCrSubSampling", 531: "YCbCrPositioning", 532: "ReferenceBlackWhite", 559: "StripRowCounts", 700: "ApplicationNotes", 999: "USPTOMiscellaneous", 4096: "RelatedImageFileFormat", 4097: "RelatedImageWidth", 4098: "RelatedImageHeight", 18246: "Rating", 18247: "XP_DIP_XML", 18248: "StitchInfo", 18249: "RatingPercent", 32781: "ImageID", 32931: "WangTag1", 32932: "WangAnnotation", 32933: "WangTag3", 32934: "WangTag4", 32995: "Matteing", 32996: "DataType", 32997: "ImageDepth", 32998: "TileDepth", 33405: "Model2", 33421: "CFARepeatPatternDim", 33422: "CFAPattern2", 33423: "BatteryLevel", 33424: "KodakIFD", 33432: "Copyright", 33434: "ExposureTime", 33437: "FNumber", 33445: "MDFileTag", 33446: "MDScalePixel", 33447: "MDColorTable", 33448: "MDLabName", 33449: "MDSampleInfo", 33450: "MDPrepDate", 33451: "MDPrepTime", 33452: "MDFileUnits", 33550: "PixelScale", 33589: "AdventScale", 33590: "AdventRevision", 33628: "UIC1Tag", 33629: "UIC2Tag", 33630: "UIC3Tag", 33631: "UIC4Tag", 33723: "IPTC-NAA", 33918: "IntergraphPacketData", 33919: "IntergraphFlagRegisters", 33920: "IntergraphMatrix", 33921: "INGRReserved", 33922: "ModelTiePoint", 34016: "Site", 34017: "ColorSequence", 34018: "IT8Header", 34019: "RasterPadding", 34020: "BitsPerRunLength", 34021: "BitsPerExtendedRunLength", 34022: "ColorTable", 34023: "ImageColorIndicator", 34024: "BackgroundColorIndicator", 34025: "ImageColorValue", 34026: "BackgroundColorValue", 34027: "PixelIntensityRange", 34028: "TransparencyIndicator", 34029: "ColorCharacterization", 34030: "HCUsage", 34031: "TrapIndicator", 34032: "CMYKEquivalent", 34118: "SEMInfo", 34152: "AFCP_IPTC", 34232: "PixelMagicJBIGOptions", 34264: "ModelTransform", 34306: "WB_GRGBLevels", 34310: "LeafData", 34377: "PhotoshopSettings", 34665: "ExifOffset", 34675: "ICC_Profile", 34687: "TIFF_FXExtensions", 34688: "MultiProfiles", 34689: "SharedData", 34690: "T88Options", 34732: "ImageLayer", 34735: "GeoTiffDirectory", 34736: "GeoTiffDoubleParams", 34737: "GeoTiffAsciiParams", 34850: "ExposureProgram", 34852: "SpectralSensitivity", 34853: "GPSInfo", 34855: "ISO", 34856: "Opto-ElectricConvFactor", 34857: "Interlace", 34858: "TimeZoneOffset", 34859: "SelfTimerMode", 34864: "SensitivityType", 34865: "StandardOutputSensitivity", 34866: "RecommendedExposureIndex", 34867: "ISOSpeed", 34868: "ISOSpeedLatitudeyyy", 34869: "ISOSpeedLatitudezzz", 34908: "FaxRecvParams", 34909: "FaxSubAddress", 34910: "FaxRecvTime", 34954: "LeafSubIFD", 36864: "ExifVersion", 36867: "DateTimeOriginal", 36868: "CreateDate", 37121: "ComponentsConfiguration", 37122: "CompressedBitsPerPixel", 37377: "ShutterSpeedValue", 37378: "ApertureValue", 37379: "BrightnessValue", 37380: "ExposureCompensation", 37381: "MaxApertureValue", 37382: "SubjectDistance", 37383: "MeteringMode", 37384: "LightSource", 37385: "Flash", 37386: "FocalLength", 37387: "FlashEnergy", 37388: "SpatialFrequencyResponse", 37389: "Noise", 37390: "FocalPlaneXResolution", 37391: "FocalPlaneYResolution", 37392: "FocalPlaneResolutionUnit", 37393: "ImageNumber", 37394: "SecurityClassification", 37395: "ImageHistory", 37396: "SubjectArea", 37397: "ExposureIndex", 37398: "TIFF-EPStandardID", 37399: "SensingMethod", 37434: "CIP3DataFile", 37435: "CIP3Sheet", 37436: "CIP3Side", 37439: "StoNits", 37500: "MakerNote", 37510: "UserComment", 37520: "SubSecTime", 37521: "SubSecTimeOriginal", 37522: "SubSecTimeDigitized", 37679: "MSDocumentText", 37680: "MSPropertySetStorage", 37681: "MSDocumentTextPosition", 37724: "ImageSourceData", 40091: "XPTitle", 40092: "XPComment", 40093: "XPAuthor", 40094: "XPKeywords", 40095: "XPSubject", 40960: "FlashpixVersion", 40961: "ColorSpace", 40962: "ExifImageWidth", 40963: "ExifImageHeight", 40964: "RelatedSoundFile", 40965: "InteropOffset", 41483: "FlashEnergy", 41484: "SpatialFrequencyResponse", 41485: "Noise", 41486: "FocalPlaneXResolution", 41487: "FocalPlaneYResolution", 41488: "FocalPlaneResolutionUnit", 41489: "ImageNumber", 41490: "SecurityClassification", 41491: "ImageHistory", 41492: "SubjectLocation", 41493: "ExposureIndex", 41494: "TIFF-EPStandardID", 41495: "SensingMethod", 41728: "FileSource", 41729: "SceneType", 41730: "CFAPattern", 41985: "CustomRendered", 41986: "ExposureMode", 41987: "WhiteBalance", 41988: "DigitalZoomRatio", 41989: "FocalLengthIn35mmFormat", 41990: "SceneCaptureType", 41991: "GainControl", 41992: "Contrast", 41993: "Saturation", 41994: "Sharpness", 41995: "DeviceSettingDescription", 41996: "SubjectDistanceRange", 42016: "ImageUniqueID", 42032: "OwnerName", 42033: "SerialNumber", 42034: "LensInfo", 42035: "LensMake", 42036: "LensModel", 42037: "LensSerialNumber", 42112: "GDALMetadata", 42113: "GDALNoData", 42240: "Gamma", 44992: "ExpandSoftware", 44993: "ExpandLens", 44994: "ExpandFilm", 44995: "ExpandFilterLens", 44996: "ExpandScanner", 44997: "ExpandFlashLamp", 48129: "PixelFormat", 48130: "Transformation", 48131: "Uncompressed", 48132: "ImageType", 48256: "ImageWidth", 48257: "ImageHeight", 48258: "WidthResolution", 48259: "HeightResolution", 48320: "ImageOffset", 48321: "ImageByteCount", 48322: "AlphaOffset", 48323: "AlphaByteCount", 48324: "ImageDataDiscard", 48325: "AlphaDataDiscard", 50215: "OceScanjobDesc", 50216: "OceApplicationSelector", 50217: "OceIDNumber", 50218: "OceImageLogic", 50255: "Annotations", 50341: "PrintIM", 50560: "USPTOOriginalContentType", 50706: "DNGVersion", 50707: "DNGBackwardVersion", 50708: "UniqueCameraModel", 50709: "LocalizedCameraModel", 50710: "CFAPlaneColor", 50711: "CFALayout", 50712: "LinearizationTable", 50713: "BlackLevelRepeatDim", 50714: "BlackLevel", 50715: "BlackLevelDeltaH", 50716: "BlackLevelDeltaV", 50717: "WhiteLevel", 50718: "DefaultScale", 50719: "DefaultCropOrigin", 50720: "DefaultCropSize", 50721: "ColorMatrix1", 50722: "ColorMatrix2", 50723: "CameraCalibration1", 50724: "CameraCalibration2", 50725: "ReductionMatrix1", 50726: "ReductionMatrix2", 50727: "AnalogBalance", 50728: "AsShotNeutral", 50729: "AsShotWhiteXY", 50730: "BaselineExposure", 50731: "BaselineNoise", 50732: "BaselineSharpness", 50733: "BayerGreenSplit", 50734: "LinearResponseLimit", 50735: "CameraSerialNumber", 50736: "DNGLensInfo", 50737: "ChromaBlurRadius", 50738: "AntiAliasStrength", 50739: "ShadowScale", 50740: "DNGPrivateData", 50741: "MakerNoteSafety", 50752: "RawImageSegmentation", 50778: "CalibrationIlluminant1", 50779: "CalibrationIlluminant2", 50780: "BestQualityScale", 50781: "RawDataUniqueID", 50784: "AliasLayerMetadata", 50827: "OriginalRawFileName", 50828: "OriginalRawFileData", 50829: "ActiveArea", 50830: "MaskedAreas", 50831: "AsShotICCProfile", 50832: "AsShotPreProfileMatrix", 50833: "CurrentICCProfile", 50834: "CurrentPreProfileMatrix", 50879: "ColorimetricReference", 50898: "PanasonicTitle", 50899: "PanasonicTitle2", 50931: "CameraCalibrationSig", 50932: "ProfileCalibrationSig", 50933: "ProfileIFD", 50934: "AsShotProfileName", 50935: "NoiseReductionApplied", 50936: "ProfileName", 50937: "ProfileHueSatMapDims", 50938: "ProfileHueSatMapData1", 50939: "ProfileHueSatMapData2", 50940: "ProfileToneCurve", 50941: "ProfileEmbedPolicy", 50942: "ProfileCopyright", 50964: "ForwardMatrix1", 50965: "ForwardMatrix2", 50966: "PreviewApplicationName", 50967: "PreviewApplicationVersion", 50968: "PreviewSettingsName", 50969: "PreviewSettingsDigest", 50970: "PreviewColorSpace", 50971: "PreviewDateTime", 50972: "RawImageDigest", 50973: "OriginalRawFileDigest", 50974: "SubTileBlockSize", 50975: "RowInterleaveFactor", 50981: "ProfileLookTableDims", 50982: "ProfileLookTableData", 51008: "OpcodeList1", 51009: "OpcodeList2", 51022: "OpcodeList3", 51041: "NoiseProfile", 51043: "TimeCodes", 51044: "FrameRate", 51058: "TStop", 51081: "ReelName", 51089: "OriginalDefaultFinalSize", 51090: "OriginalBestQualitySize", 51091: "OriginalDefaultCropSize", 51105: "CameraLabel", 51107: "ProfileHueSatMapEncoding", 51108: "ProfileLookTableEncoding", 51109: "BaselineExposureOffset", 51110: "DefaultBlackRender", 51111: "NewRawImageDigest", 51112: "RawToPreviewGain", 51125: "DefaultUserCrop", 59932: "Padding", 59933: "OffsetSchema", 65e3: "OwnerName", 65001: "SerialNumber", 65002: "Lens", 65024: "KDC_IFD", 65100: "RawFile", 65101: "Converter", 65102: "WhiteBalance", 65105: "Exposure", 65106: "Shadows", 65107: "Brightness", 65108: "Contrast", 65109: "Saturation", 65110: "Sharpness", 65111: "Smoothness", 65112: "MoireFilter" }, gps: { 0: "GPSVersionID", 1: "GPSLatitudeRef", 2: "GPSLatitude", 3: "GPSLongitudeRef", 4: "GPSLongitude", 5: "GPSAltitudeRef", 6: "GPSAltitude", 7: "GPSTimeStamp", 8: "GPSSatellites", 9: "GPSStatus", 10: "GPSMeasureMode", 11: "GPSDOP", 12: "GPSSpeedRef", 13: "GPSSpeed", 14: "GPSTrackRef", 15: "GPSTrack", 16: "GPSImgDirectionRef", 17: "GPSImgDirection", 18: "GPSMapDatum", 19: "GPSDestLatitudeRef", 20: "GPSDestLatitude", 21: "GPSDestLongitudeRef", 22: "GPSDestLongitude", 23: "GPSDestBearingRef", 24: "GPSDestBearing", 25: "GPSDestDistanceRef", 26: "GPSDestDistance", 27: "GPSProcessingMethod", 28: "GPSAreaInformation", 29: "GPSDateStamp", 30: "GPSDifferential", 31: "GPSHPositioningError" } });
}
var jpeg = jpeg$1, exif = exif$2, simplify = simplify$1;
function ExifResult(e4, t2, i2, r2, n2, a2, o2) {
  this.startMarker = e4, this.tags = t2, this.imageSize = i2, this.thumbnailOffset = r2, this.thumbnailLength = n2, this.thumbnailType = a2, this.app1Offset = o2;
}
function Parser$1(e4) {
  this.stream = e4, this.flags = { readBinaryTags: false, resolveTagNames: true, simplifyValues: true, imageSize: true, hidePointers: true, returnTags: true };
}
ExifResult.prototype = { hasThumbnail: function(e4) {
  return !(!this.thumbnailOffset || !this.thumbnailLength) && ("string" != typeof e4 || ("image/jpeg" === e4.toLowerCase().trim() ? 6 === this.thumbnailType : "image/tiff" === e4.toLowerCase().trim() && 1 === this.thumbnailType));
}, getThumbnailOffset: function() {
  return this.app1Offset + 6 + this.thumbnailOffset;
}, getThumbnailLength: function() {
  return this.thumbnailLength;
}, getThumbnailBuffer: function() {
  return this._getThumbnailStream().nextBuffer(this.thumbnailLength);
}, _getThumbnailStream: function() {
  return this.startMarker.openWithOffset(this.getThumbnailOffset());
}, getImageSize: function() {
  return this.imageSize;
}, getThumbnailSize: function() {
  var e4, t2 = this._getThumbnailStream();
  return jpeg.parseSections(t2, function(t3, i2) {
    "SOF" === jpeg.getSectionName(t3).name && (e4 = jpeg.getSizeFromSOFSection(i2));
  }), e4;
} }, Parser$1.prototype = { enableBinaryFields: function(e4) {
  return this.flags.readBinaryTags = !!e4, this;
}, enablePointers: function(e4) {
  return this.flags.hidePointers = !e4, this;
}, enableTagNames: function(e4) {
  return this.flags.resolveTagNames = !!e4, this;
}, enableImageSize: function(e4) {
  return this.flags.imageSize = !!e4, this;
}, enableReturnTags: function(e4) {
  return this.flags.returnTags = !!e4, this;
}, enableSimpleValues: function(e4) {
  return this.flags.simplifyValues = !!e4, this;
}, parse: function() {
  var e4, t2, i2, r2, n2, a2, o2, s2, l2, u2 = this.stream.mark(), h2 = u2.openWithOffset(0), c2 = this.flags;
  return c2.resolveTagNames && (o2 = requireExifTags()), c2.resolveTagNames ? (e4 = {}, s2 = function(t3) {
    return e4[t3.name];
  }, l2 = function(t3, i3) {
    e4[t3.name] = i3;
  }) : (e4 = [], s2 = function(t3) {
    var i3;
    for (i3 = 0; i3 < e4.length; ++i3) if (e4[i3].type === t3.type && e4[i3].section === t3.section) return e4.value;
  }, l2 = function(t3, i3) {
    var r3;
    for (r3 = 0; r3 < e4.length; ++r3) if (e4[r3].type === t3.type && e4[r3].section === t3.section) return void (e4.value = i3);
  }), jpeg.parseSections(h2, function(s3, l3) {
    var h3 = l3.offsetFrom(u2);
    225 === s3 ? exif.parseTags(l3, function(t3, a3, s4, l4) {
      if (c2.readBinaryTags || 7 !== l4) {
        if (513 === a3) {
          if (i2 = s4[0], c2.hidePointers) return;
        } else if (514 === a3) {
          if (r2 = s4[0], c2.hidePointers) return;
        } else if (259 === a3 && (n2 = s4[0], c2.hidePointers)) return;
        if (c2.returnTags) if (c2.simplifyValues && (s4 = simplify.simplifyValue(s4, l4)), c2.resolveTagNames) {
          var u3 = (t3 === exif.GPSIFD ? o2.gps : o2.exif)[a3];
          u3 || (u3 = o2.exif[a3]), e4.hasOwnProperty(u3) || (e4[u3] = s4);
        } else e4.push({ section: t3, type: a3, value: s4 });
      }
    }) && (a2 = h3) : c2.imageSize && "SOF" === jpeg.getSectionName(s3).name && (t2 = jpeg.getSizeFromSOFSection(l3));
  }), c2.simplifyValues && (simplify.castDegreeValues(s2, l2), simplify.castDateValues(s2, l2)), new ExifResult(u2, e4, t2, i2, r2, n2, a2);
} };
var parser = Parser$1, domBufferstream, hasRequiredDomBufferstream, bufferstream, hasRequiredBufferstream;
function requireDomBufferstream() {
  if (hasRequiredDomBufferstream) return domBufferstream;
  function e4(e5, t2, i2, r2, n2, a2) {
    this.global = n2, t2 = t2 || 0, i2 = i2 || e5.byteLength - t2, this.arrayBuffer = e5.slice(t2, t2 + i2), this.view = new n2.DataView(this.arrayBuffer, 0, this.arrayBuffer.byteLength), this.setBigEndian(r2), this.offset = 0, this.parentOffset = (a2 || 0) + t2;
  }
  return hasRequiredDomBufferstream = 1, e4.prototype = { setBigEndian: function(e5) {
    this.littleEndian = !e5;
  }, nextUInt8: function() {
    var e5 = this.view.getUint8(this.offset);
    return this.offset += 1, e5;
  }, nextInt8: function() {
    var e5 = this.view.getInt8(this.offset);
    return this.offset += 1, e5;
  }, nextUInt16: function() {
    var e5 = this.view.getUint16(this.offset, this.littleEndian);
    return this.offset += 2, e5;
  }, nextUInt32: function() {
    var e5 = this.view.getUint32(this.offset, this.littleEndian);
    return this.offset += 4, e5;
  }, nextInt16: function() {
    var e5 = this.view.getInt16(this.offset, this.littleEndian);
    return this.offset += 2, e5;
  }, nextInt32: function() {
    var e5 = this.view.getInt32(this.offset, this.littleEndian);
    return this.offset += 4, e5;
  }, nextFloat: function() {
    var e5 = this.view.getFloat32(this.offset, this.littleEndian);
    return this.offset += 4, e5;
  }, nextDouble: function() {
    var e5 = this.view.getFloat64(this.offset, this.littleEndian);
    return this.offset += 8, e5;
  }, nextBuffer: function(e5) {
    var t2 = this.arrayBuffer.slice(this.offset, this.offset + e5);
    return this.offset += e5, t2;
  }, remainingLength: function() {
    return this.arrayBuffer.byteLength - this.offset;
  }, nextString: function(e5) {
    var t2 = this.arrayBuffer.slice(this.offset, this.offset + e5);
    return t2 = String.fromCharCode.apply(null, new this.global.Uint8Array(t2)), this.offset += e5, t2;
  }, mark: function() {
    var t2 = this;
    return { openWithOffset: function(i2) {
      return i2 = (i2 || 0) + this.offset, new e4(t2.arrayBuffer, i2, t2.arrayBuffer.byteLength - i2, !t2.littleEndian, t2.global, t2.parentOffset);
    }, offset: this.offset, getParentOffset: function() {
      return t2.parentOffset;
    } };
  }, offsetFrom: function(e5) {
    return this.parentOffset + this.offset - (e5.offset + e5.getParentOffset());
  }, skip: function(e5) {
    this.offset += e5;
  }, branch: function(t2, i2) {
    return i2 = "number" == typeof i2 ? i2 : this.arrayBuffer.byteLength - (this.offset + t2), new e4(this.arrayBuffer, this.offset + t2, i2, !this.littleEndian, this.global, this.parentOffset);
  } }, domBufferstream = e4;
}
function requireBufferstream() {
  if (hasRequiredBufferstream) return bufferstream;
  function e4(e5, t2, i2, r2) {
    this.buffer = e5, this.offset = t2 || 0, i2 = "number" == typeof i2 ? i2 : e5.length, this.endPosition = this.offset + i2, this.setBigEndian(r2);
  }
  return hasRequiredBufferstream = 1, e4.prototype = { setBigEndian: function(e5) {
    this.bigEndian = !!e5;
  }, nextUInt8: function() {
    var e5 = this.buffer.readUInt8(this.offset);
    return this.offset += 1, e5;
  }, nextInt8: function() {
    var e5 = this.buffer.readInt8(this.offset);
    return this.offset += 1, e5;
  }, nextUInt16: function() {
    var e5 = this.bigEndian ? this.buffer.readUInt16BE(this.offset) : this.buffer.readUInt16LE(this.offset);
    return this.offset += 2, e5;
  }, nextUInt32: function() {
    var e5 = this.bigEndian ? this.buffer.readUInt32BE(this.offset) : this.buffer.readUInt32LE(this.offset);
    return this.offset += 4, e5;
  }, nextInt16: function() {
    var e5 = this.bigEndian ? this.buffer.readInt16BE(this.offset) : this.buffer.readInt16LE(this.offset);
    return this.offset += 2, e5;
  }, nextInt32: function() {
    var e5 = this.bigEndian ? this.buffer.readInt32BE(this.offset) : this.buffer.readInt32LE(this.offset);
    return this.offset += 4, e5;
  }, nextFloat: function() {
    var e5 = this.bigEndian ? this.buffer.readFloatBE(this.offset) : this.buffer.readFloatLE(this.offset);
    return this.offset += 4, e5;
  }, nextDouble: function() {
    var e5 = this.bigEndian ? this.buffer.readDoubleBE(this.offset) : this.buffer.readDoubleLE(this.offset);
    return this.offset += 8, e5;
  }, nextBuffer: function(e5) {
    var t2 = this.buffer.slice(this.offset, this.offset + e5);
    return this.offset += e5, t2;
  }, remainingLength: function() {
    return this.endPosition - this.offset;
  }, nextString: function(e5) {
    var t2 = this.buffer.toString("utf8", this.offset, this.offset + e5);
    return this.offset += e5, t2;
  }, mark: function() {
    var t2 = this;
    return { openWithOffset: function(i2) {
      return i2 = (i2 || 0) + this.offset, new e4(t2.buffer, i2, t2.endPosition - i2, t2.bigEndian);
    }, offset: this.offset };
  }, offsetFrom: function(e5) {
    return this.offset - e5.offset;
  }, skip: function(e5) {
    this.offset += e5;
  }, branch: function(t2, i2) {
    return i2 = "number" == typeof i2 ? i2 : this.endPosition - (this.offset + t2), new e4(this.buffer, this.offset + t2, i2, this.bigEndian);
  } }, bufferstream = e4;
}
var Parser = parser;
function getGlobal() {
  return (0, eval)("this");
}
var exifParser = { create: function(e4, t2) {
  if (e4 instanceof (t2 = t2 || getGlobal()).ArrayBuffer) {
    var i2 = requireDomBufferstream();
    return new Parser(new i2(e4, 0, e4.byteLength, true, t2));
  }
  var r2 = requireBufferstream();
  return new Parser(new r2(e4, 0, e4.length, true));
} }, EXIFParser = getDefaultExportFromCjs(exifParser);
function getExifOrientation(e4) {
  const t2 = e4._exif;
  return t2 && t2.tags && t2.tags.Orientation || 1;
}
function getExifOrientationTransformation(e4) {
  const t2 = e4.bitmap.width, i2 = e4.bitmap.height;
  switch (getExifOrientation(e4)) {
    case 1:
    default:
      return null;
    case 2:
      return function(e5, i3) {
        return [t2 - e5 - 1, i3];
      };
    case 3:
      return function(e5, r2) {
        return [t2 - e5 - 1, i2 - r2 - 1];
      };
    case 4:
      return function(e5, t3) {
        return [e5, i2 - t3 - 1];
      };
    case 5:
      return function(e5, t3) {
        return [t3, e5];
      };
    case 6:
      return function(e5, t3) {
        return [t3, i2 - e5 - 1];
      };
    case 7:
      return function(e5, r2) {
        return [t2 - r2 - 1, i2 - e5 - 1];
      };
    case 8:
      return function(e5, i3) {
        return [t2 - i3 - 1, e5];
      };
  }
}
function transformBitmap(e4, t2, i2, r2) {
  const n2 = e4.bitmap.data, a2 = e4.bitmap.width, o2 = Buffer$1.alloc(n2.length);
  for (let e5 = 0; e5 < t2; e5++) for (let s2 = 0; s2 < i2; s2++) {
    const [i3, l2] = r2(e5, s2), u2 = t2 * s2 + e5 << 2, h2 = a2 * l2 + i3 << 2, c2 = n2.readUInt32BE(h2);
    o2.writeUInt32BE(c2, u2);
  }
  e4.bitmap.data = o2, e4.bitmap.width = t2, e4.bitmap.height = i2, e4._exif.tags.Orientation = 1;
}
function exifRotate(e4) {
  if (getExifOrientation(e4) < 2) return;
  const t2 = getExifOrientationTransformation(e4), i2 = getExifOrientation(e4) > 4, r2 = i2 ? e4.bitmap.height : e4.bitmap.width, n2 = i2 ? e4.bitmap.width : e4.bitmap.height;
  t2 && transformBitmap(e4, r2, n2, t2);
}
async function attemptExifRotate(e4, t2) {
  try {
    e4._exif = EXIFParser.create(t2).parse(), exifRotate(e4);
  } catch {
  }
}
var __defProp$2 = Object.defineProperty, __defNormalProp$2 = (e4, t2, i2) => t2 in e4 ? __defProp$2(e4, t2, { enumerable: true, configurable: true, writable: true, value: i2 }) : e4[t2] = i2, __publicField$2 = (e4, t2, i2) => __defNormalProp$2(e4, "symbol" != typeof t2 ? t2 + "" : t2, i2);
const emptyBitmap = { data: Buffer$1.alloc(0), width: 0, height: 0 };
function bufferFromArrayBuffer(e4) {
  const t2 = Buffer$1.alloc(e4.byteLength), i2 = new Uint8Array(e4);
  for (let e5 = 0; e5 < t2.length; ++e5) t2[e5] = i2[e5];
  return t2;
}
function createJimp({ plugins: e4, formats: t2 } = {}) {
  const i2 = e4 || [], r2 = (t2 || []).map((e5) => e5()), n2 = class {
    constructor(e5 = emptyBitmap) {
      if (__publicField$2(this, "bitmap", emptyBitmap), __publicField$2(this, "background", 0), __publicField$2(this, "formats", []), __publicField$2(this, "mime"), this.formats = r2, "data" in e5) this.bitmap = e5;
      else if (this.bitmap = { data: Buffer$1.alloc(e5.width * e5.height * 4), width: e5.width, height: e5.height }, e5.color) {
        this.background = "string" == typeof e5.color ? cssColorToHex(e5.color) : e5.color;
        for (let e6 = 0; e6 < this.bitmap.data.length; e6 += 4) this.bitmap.data.writeUInt32BE(this.background, e6);
      }
      for (const e6 of i2) for (const t3 in e6) this[t3] = (...i3) => {
        var _a3;
        const r3 = (_a3 = e6[t3]) == null ? void 0 : _a3.call(e6, this, ...i3);
        return "object" == typeof r3 && "bitmap" in r3 ? (this.bitmap = r3.bitmap, this) : r3;
      };
    }
    static async read(e5, t3) {
      if (Buffer$1.isBuffer(e5) || e5 instanceof ArrayBuffer) return this.fromBuffer(e5);
      const [i3, r3] = await to(fetch(e5));
      if (i3) throw new Error(`Could not load Buffer from URL: ${e5}`);
      if (!r3.ok) throw new Error(`HTTP Status ${r3.status} for url ${e5}`);
      const [n3, a2] = await to(r3.arrayBuffer());
      if (n3) throw new Error(`Could not load Buffer from ${e5}`);
      const o2 = bufferFromArrayBuffer(a2);
      return this.fromBuffer(o2, t3);
    }
    static fromBitmap(e5) {
      let t3;
      if (e5.data instanceof Buffer$1 && (t3 = Buffer$1.from(e5.data)), (e5.data instanceof Uint8Array || e5.data instanceof Uint8ClampedArray) && (t3 = Buffer$1.from(e5.data.buffer)), Array.isArray(e5.data) && (t3 = Buffer$1.concat(e5.data.map((e6) => Buffer$1.from(e6.toString(16).padStart(8, "0"), "hex")))), !t3) throw new Error("data must be a Buffer");
      if ("number" != typeof e5.height || "number" != typeof e5.width) throw new Error("bitmap must have width and height");
      return new n2({ height: e5.height, width: e5.width, data: t3 });
    }
    static async fromBuffer(e5, t3) {
      const i3 = e5 instanceof ArrayBuffer ? bufferFromArrayBuffer(e5) : e5, a2 = await fileType$1.fromBuffer(i3);
      if (!a2 || !a2.mime) throw new Error("Could not find MIME for Buffer");
      const o2 = r2.find((e6) => e6.mime === a2.mime);
      if (!o2 || !o2.decode) throw new Error(`Mime type ${a2.mime} does not support decoding`);
      const s2 = new n2(await o2.decode(i3, t3 == null ? void 0 : t3[o2.mime]));
      return s2.mime = a2.mime, attemptExifRotate(s2, i3), s2;
    }
    inspect() {
      return "<Jimp " + (this.bitmap === emptyBitmap ? "pending..." : this.bitmap.width + "x" + this.bitmap.height) + ">";
    }
    toString() {
      return "[object Jimp]";
    }
    get width() {
      return this.bitmap.width;
    }
    get height() {
      return this.bitmap.height;
    }
    async getBuffer(e5, t3) {
      const i3 = this.formats.find((t4) => t4.mime === e5);
      if (!i3 || !i3.encode) throw new Error(`Unsupported MIME type: ${e5}`);
      let r3;
      return i3.hasAlpha ? r3 = this : (r3 = new n2({ width: this.bitmap.width, height: this.bitmap.height, color: this.background }), composite(r3, this)), i3.encode(r3.bitmap, t3);
    }
    async getBase64(e5, t3) {
      return "data:" + e5 + ";base64," + (await this.getBuffer(e5, t3)).toString("base64");
    }
    async write(e5, t3) {
      const i3 = mime.getType(e5);
      await writeFile(e5, await this.getBuffer(i3, t3));
    }
    clone() {
      return new n2({ ...this.bitmap, data: Buffer$1.from(this.bitmap.data) });
    }
    getPixelIndex(e5, t3, i3) {
      let r3, n3;
      if (i3 || (i3 = Edge.EXTEND), "number" != typeof e5 || "number" != typeof t3) throw new Error("x and y must be numbers");
      r3 = e5 = Math.round(e5), n3 = t3 = Math.round(t3), i3 === Edge.EXTEND && (e5 < 0 && (r3 = 0), e5 >= this.bitmap.width && (r3 = this.bitmap.width - 1), t3 < 0 && (n3 = 0), t3 >= this.bitmap.height && (n3 = this.bitmap.height - 1)), i3 === Edge.WRAP && (e5 < 0 && (r3 = this.bitmap.width + e5), e5 >= this.bitmap.width && (r3 = e5 % this.bitmap.width), t3 < 0 && (n3 = this.bitmap.height + t3), t3 >= this.bitmap.height && (n3 = t3 % this.bitmap.height));
      let a2 = this.bitmap.width * n3 + r3 << 2;
      return (r3 < 0 || r3 >= this.bitmap.width) && (a2 = -1), (n3 < 0 || n3 >= this.bitmap.height) && (a2 = -1), a2;
    }
    getPixelColor(e5, t3) {
      if ("number" != typeof e5 || "number" != typeof t3) throw new Error("x and y must be numbers");
      const i3 = this.getPixelIndex(e5, t3);
      return this.bitmap.data.readUInt32BE(i3);
    }
    setPixelColor(e5, t3, i3) {
      if ("number" != typeof e5 || "number" != typeof t3 || "number" != typeof i3) throw new Error("hex, x and y must be numbers");
      const r3 = this.getPixelIndex(t3, i3);
      return this.bitmap.data.writeUInt32BE(e5, r3), this;
    }
    hasAlpha() {
      const { width: e5, height: t3, data: i3 } = this.bitmap, r3 = e5 * t3 << 2;
      for (let e6 = 3; e6 < r3; e6 += 4) if (255 !== i3[e6]) return true;
      return false;
    }
    composite(e5, t3 = 0, i3 = 0, r3 = {}) {
      return composite(this, e5, t3, i3, r3);
    }
    scan(e5, t3, i3, r3, n3) {
      return scan(this, e5, t3, i3, r3, n3);
    }
    scanIterator(e5 = 0, t3 = 0, i3 = this.bitmap.width, r3 = this.bitmap.height) {
      if ("number" != typeof e5 || "number" != typeof t3) throw new Error("x and y must be numbers");
      if ("number" != typeof i3 || "number" != typeof r3) throw new Error("w and h must be numbers");
      return scanIterator(this, e5, t3, i3, r3);
    }
  };
  return n2;
}
var ResizeStrategy, ResizeStrategy2;
function Resize(e4, t2, i2, r2, n2, a2, o2) {
  this.widthOriginal = Math.abs(Math.floor(e4) || 0), this.heightOriginal = Math.abs(Math.floor(t2) || 0), this.targetWidth = Math.abs(Math.floor(i2) || 0), this.targetHeight = Math.abs(Math.floor(r2) || 0), this.colorChannels = n2 ? 4 : 3, this.interpolationPass = Boolean(a2), this.resizeCallback = "function" == typeof o2 ? o2 : function() {
  }, this.targetWidthMultipliedByChannels = this.targetWidth * this.colorChannels, this.originalWidthMultipliedByChannels = this.widthOriginal * this.colorChannels, this.originalHeightMultipliedByChannels = this.heightOriginal * this.colorChannels, this.widthPassResultSize = this.targetWidthMultipliedByChannels * this.heightOriginal, this.finalResultSize = this.targetWidthMultipliedByChannels * this.targetHeight, this.initialize();
}
ResizeStrategy2 = ResizeStrategy || (ResizeStrategy = {}), ResizeStrategy2.NEAREST_NEIGHBOR = "nearestNeighbor", ResizeStrategy2.BILINEAR = "bilinearInterpolation", ResizeStrategy2.BICUBIC = "bicubicInterpolation", ResizeStrategy2.HERMITE = "hermiteInterpolation", ResizeStrategy2.BEZIER = "bezierInterpolation", Resize.prototype.initialize = function() {
  if (!(this.widthOriginal > 0 && this.heightOriginal > 0 && this.targetWidth > 0 && this.targetHeight > 0)) throw console.log(this), new Error("Invalid settings specified for the resizer.");
  this.configurePasses();
}, Resize.prototype.configurePasses = function() {
  this.widthOriginal === this.targetWidth ? this.resizeWidth = this.bypassResizer : (this.ratioWeightWidthPass = this.widthOriginal / this.targetWidth, this.ratioWeightWidthPass < 1 && this.interpolationPass ? (this.initializeFirstPassBuffers(true), this.resizeWidth = 4 === this.colorChannels ? this.resizeWidthInterpolatedRGBA : this.resizeWidthInterpolatedRGB) : (this.initializeFirstPassBuffers(false), this.resizeWidth = 4 === this.colorChannels ? this.resizeWidthRGBA : this.resizeWidthRGB)), this.heightOriginal === this.targetHeight ? this.resizeHeight = this.bypassResizer : (this.ratioWeightHeightPass = this.heightOriginal / this.targetHeight, this.ratioWeightHeightPass < 1 && this.interpolationPass ? (this.initializeSecondPassBuffers(true), this.resizeHeight = this.resizeHeightInterpolated) : (this.initializeSecondPassBuffers(false), this.resizeHeight = 4 === this.colorChannels ? this.resizeHeightRGBA : this.resizeHeightRGB));
}, Resize.prototype._resizeWidthInterpolatedRGBChannels = function(e4, t2) {
  const i2 = t2 ? 4 : 3, r2 = this.ratioWeightWidthPass, n2 = this.widthBuffer;
  let a2, o2, s2 = 0, l2 = 0, u2 = 0, h2 = 0, c2 = 0;
  for (a2 = 0; s2 < 1 / 3; a2 += i2, s2 += r2) for (l2 = a2, u2 = 0; l2 < this.widthPassResultSize; u2 += this.originalWidthMultipliedByChannels, l2 += this.targetWidthMultipliedByChannels) n2[l2] = e4[u2], n2[l2 + 1] = e4[u2 + 1], n2[l2 + 2] = e4[u2 + 2], t2 && (n2[l2 + 3] = e4[u2 + 3]);
  for (s2 -= 1 / 3, o2 = this.widthOriginal - 1; s2 < o2; a2 += i2, s2 += r2) for (c2 = s2 % 1, h2 = 1 - c2, l2 = a2, u2 = Math.floor(s2) * i2; l2 < this.widthPassResultSize; u2 += this.originalWidthMultipliedByChannels, l2 += this.targetWidthMultipliedByChannels) n2[l2 + 0] = e4[u2 + 0] * h2 + e4[u2 + i2 + 0] * c2, n2[l2 + 1] = e4[u2 + 1] * h2 + e4[u2 + i2 + 1] * c2, n2[l2 + 2] = e4[u2 + 2] * h2 + e4[u2 + i2 + 2] * c2, t2 && (n2[l2 + 3] = e4[u2 + 3] * h2 + e4[u2 + i2 + 3] * c2);
  for (o2 = this.originalWidthMultipliedByChannels - i2; a2 < this.targetWidthMultipliedByChannels; a2 += i2) for (l2 = a2, u2 = o2; l2 < this.widthPassResultSize; u2 += this.originalWidthMultipliedByChannels, l2 += this.targetWidthMultipliedByChannels) n2[l2] = e4[u2], n2[l2 + 1] = e4[u2 + 1], n2[l2 + 2] = e4[u2 + 2], t2 && (n2[l2 + 3] = e4[u2 + 3]);
  return n2;
}, Resize.prototype._resizeWidthRGBChannels = function(e4, t2) {
  const i2 = t2 ? 4 : 3, r2 = this.ratioWeightWidthPass, n2 = 1 / r2, a2 = this.originalWidthMultipliedByChannels - i2 + 1, o2 = this.targetWidthMultipliedByChannels - i2 + 1, s2 = this.outputWidthWorkBench, l2 = this.widthBuffer, u2 = this.outputWidthWorkBenchOpaquePixelsCount;
  let h2 = 0, c2 = 0, f2 = 0, d = 0, p2 = 0, m = 0, _2 = 0, g = 1, b2 = 0, y2 = 0, w = 0, v2 = 0;
  do {
    for (p2 = 0; p2 < this.originalHeightMultipliedByChannels; ) s2[p2++] = 0, s2[p2++] = 0, s2[p2++] = 0, t2 && (s2[p2++] = 0, u2[p2 / i2 - 1] = 0);
    h2 = r2;
    do {
      for (c2 = 1 + f2 - d, g = Math.min(h2, c2), p2 = 0, m = f2; p2 < this.originalHeightMultipliedByChannels; m += a2) b2 = e4[m], y2 = e4[++m], w = e4[++m], v2 = t2 ? e4[++m] : 255, s2[p2++] += (v2 ? b2 : 0) * g, s2[p2++] += (v2 ? y2 : 0) * g, s2[p2++] += (v2 ? w : 0) * g, t2 && (s2[p2++] += v2 * g, u2[p2 / i2 - 1] += v2 ? g : 0);
      if (!(h2 >= c2)) {
        d += h2;
        break;
      }
      f2 += i2, d = f2, h2 -= c2;
    } while (h2 > 0 && f2 < this.originalWidthMultipliedByChannels);
    for (p2 = 0, m = _2; p2 < this.originalHeightMultipliedByChannels; m += o2) h2 = t2 ? u2[p2 / i2] : 1, g = t2 ? h2 ? 1 / h2 : 0 : n2, l2[m] = s2[p2++] * g, l2[++m] = s2[p2++] * g, l2[++m] = s2[p2++] * g, t2 && (l2[++m] = s2[p2++] * n2);
    _2 += i2;
  } while (_2 < this.targetWidthMultipliedByChannels);
  return l2;
}, Resize.prototype._resizeHeightRGBChannels = function(e4, t2) {
  const i2 = this.ratioWeightHeightPass, r2 = 1 / i2, n2 = this.outputHeightWorkBench, a2 = this.heightBuffer, o2 = this.outputHeightWorkBenchOpaquePixelsCount;
  let s2 = 0, l2 = 0, u2 = 0, h2 = 0, c2 = 0, f2 = 0, d = 0, p2 = 1, m = 0, _2 = 0, g = 0, b2 = 0;
  do {
    for (c2 = 0; c2 < this.targetWidthMultipliedByChannels; ) n2[c2++] = 0, n2[c2++] = 0, n2[c2++] = 0, t2 && (n2[c2++] = 0, o2[c2 / 4 - 1] = 0);
    s2 = i2;
    do {
      for (l2 = 1 + u2 - h2, p2 = Math.min(s2, l2), d = u2, c2 = 0; c2 < this.targetWidthMultipliedByChannels; ) m = e4[d++], _2 = e4[d++], g = e4[d++], b2 = t2 ? e4[d++] : 255, n2[c2++] += (b2 ? m : 0) * p2, n2[c2++] += (b2 ? _2 : 0) * p2, n2[c2++] += (b2 ? g : 0) * p2, t2 && (n2[c2++] += b2 * p2, o2[c2 / 4 - 1] += b2 ? p2 : 0);
      if (!(s2 >= l2)) {
        h2 += s2;
        break;
      }
      u2 = d, h2 = u2, s2 -= l2;
    } while (s2 > 0 && u2 < this.widthPassResultSize);
    for (c2 = 0; c2 < this.targetWidthMultipliedByChannels; ) s2 = t2 ? o2[c2 / 4] : 1, p2 = t2 ? s2 ? 1 / s2 : 0 : r2, a2[f2++] = Math.round(n2[c2++] * p2), a2[f2++] = Math.round(n2[c2++] * p2), a2[f2++] = Math.round(n2[c2++] * p2), t2 && (a2[f2++] = Math.round(n2[c2++] * r2));
  } while (f2 < this.finalResultSize);
  return a2;
}, Resize.prototype.resizeWidthInterpolatedRGB = function(e4) {
  return this._resizeWidthInterpolatedRGBChannels(e4, false);
}, Resize.prototype.resizeWidthInterpolatedRGBA = function(e4) {
  return this._resizeWidthInterpolatedRGBChannels(e4, true);
}, Resize.prototype.resizeWidthRGB = function(e4) {
  return this._resizeWidthRGBChannels(e4, false);
}, Resize.prototype.resizeWidthRGBA = function(e4) {
  return this._resizeWidthRGBChannels(e4, true);
}, Resize.prototype.resizeHeightInterpolated = function(e4) {
  const t2 = this.ratioWeightHeightPass, i2 = this.heightBuffer;
  let r2, n2 = 0, a2 = 0, o2 = 0, s2 = 0, l2 = 0, u2 = 0, h2 = 0;
  for (; n2 < 1 / 3; n2 += t2) for (o2 = 0; o2 < this.targetWidthMultipliedByChannels; ) i2[a2++] = Math.round(e4[o2++]);
  for (n2 -= 1 / 3, r2 = this.heightOriginal - 1; n2 < r2; n2 += t2) for (h2 = n2 % 1, u2 = 1 - h2, s2 = Math.floor(n2) * this.targetWidthMultipliedByChannels, l2 = s2 + this.targetWidthMultipliedByChannels, o2 = 0; o2 < this.targetWidthMultipliedByChannels; ++o2) i2[a2++] = Math.round(e4[s2++] * u2 + e4[l2++] * h2);
  for (; a2 < this.finalResultSize; ) for (o2 = 0, s2 = r2 * this.targetWidthMultipliedByChannels; o2 < this.targetWidthMultipliedByChannels; ++o2) i2[a2++] = Math.round(e4[s2++]);
  return i2;
}, Resize.prototype.resizeHeightRGB = function(e4) {
  return this._resizeHeightRGBChannels(e4, false);
}, Resize.prototype.resizeHeightRGBA = function(e4) {
  return this._resizeHeightRGBChannels(e4, true);
}, Resize.prototype.resize = function(e4) {
  this.resizeCallback(this.resizeHeight(this.resizeWidth(e4)));
}, Resize.prototype.bypassResizer = function(e4) {
  return e4;
}, Resize.prototype.initializeFirstPassBuffers = function(e4) {
  this.widthBuffer = this.generateFloatBuffer(this.widthPassResultSize), e4 || (this.outputWidthWorkBench = this.generateFloatBuffer(this.originalHeightMultipliedByChannels), this.colorChannels > 3 && (this.outputWidthWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.heightOriginal)));
}, Resize.prototype.initializeSecondPassBuffers = function(e4) {
  this.heightBuffer = this.generateUint8Buffer(this.finalResultSize), e4 || (this.outputHeightWorkBench = this.generateFloatBuffer(this.targetWidthMultipliedByChannels), this.colorChannels > 3 && (this.outputHeightWorkBenchOpaquePixelsCount = this.generateFloat64Buffer(this.targetWidth)));
}, Resize.prototype.generateFloatBuffer = function(e4) {
  try {
    return new Float32Array(e4);
  } catch (e5) {
    return console.error(e5), [];
  }
}, Resize.prototype.generateFloat64Buffer = function(e4) {
  try {
    return new Float64Array(e4);
  } catch (e5) {
    return console.error(e5), [];
  }
}, Resize.prototype.generateUint8Buffer = function(e4) {
  try {
    return new Uint8Array(e4);
  } catch (e5) {
    return console.error(e5), [];
  }
};
const operations = { nearestNeighbor(e4, t2) {
  const i2 = e4.width, r2 = e4.height, n2 = t2.width, a2 = t2.height, o2 = e4.data, s2 = t2.data;
  for (let e5 = 0; e5 < a2; e5++) for (let t3 = 0; t3 < n2; t3++) {
    let l2 = 4 * (e5 * n2 + t3);
    let u2 = 4 * (Math.floor(e5 * r2 / a2) * i2 + Math.floor(t3 * i2 / n2));
    s2[l2++] = o2[u2++], s2[l2++] = o2[u2++], s2[l2++] = o2[u2++], s2[l2++] = o2[u2++];
  }
}, bilinearInterpolation(e4, t2) {
  const i2 = e4.width, r2 = e4.height, n2 = t2.width, a2 = t2.height, o2 = e4.data, s2 = t2.data, l2 = function(e5, t3, i3, r3, n3) {
    return t3 === r3 ? i3 : Math.round((e5 - t3) * n3 + (r3 - e5) * i3);
  }, u2 = function(e5, t3, r3, n3, a3, u3, h2, c2) {
    let f2 = 4 * (h2 * i2 + n3) + t3, d = 4 * (h2 * i2 + a3) + t3;
    const p2 = l2(r3, n3, o2[f2], a3, o2[d]);
    if (c2 === h2) s2[e5 + t3] = p2;
    else {
      f2 = 4 * (c2 * i2 + n3) + t3, d = 4 * (c2 * i2 + a3) + t3;
      const m = l2(r3, n3, o2[f2], a3, o2[d]);
      s2[e5 + t3] = l2(u3, h2, p2, c2, m);
    }
  };
  for (let e5 = 0; e5 < a2; e5++) for (let t3 = 0; t3 < n2; t3++) {
    const o3 = 4 * (e5 * n2 + t3), s3 = t3 * i2 / n2, l3 = Math.floor(s3), h2 = Math.min(Math.ceil(s3), i2 - 1), c2 = e5 * r2 / a2, f2 = Math.floor(c2), d = Math.min(Math.ceil(c2), r2 - 1);
    u2(o3, 0, s3, l3, h2, c2, f2, d), u2(o3, 1, s3, l3, h2, c2, f2, d), u2(o3, 2, s3, l3, h2, c2, f2, d), u2(o3, 3, s3, l3, h2, c2, f2, d);
  }
}, _interpolate2D(e4, t2, i2, r2) {
  const n2 = e4.data, a2 = t2.data, o2 = e4.width, s2 = e4.height, l2 = t2.width, u2 = t2.height, h2 = Math.max(1, Math.floor(o2 / l2)), c2 = l2 * h2, f2 = Math.max(1, Math.floor(s2 / u2)), d = u2 * f2, p2 = Buffer$1.alloc(c2 * s2 * 4);
  for (let e5 = 0; e5 < s2; e5++) for (let t3 = 0; t3 < c2; t3++) {
    const i3 = t3 * (o2 - 1) / c2, a3 = Math.floor(i3), s3 = i3 - a3, l3 = 4 * (e5 * o2 + a3), u3 = 4 * (e5 * c2 + t3);
    for (let e6 = 0; e6 < 4; e6++) {
      const t4 = l3 + e6, i4 = a3 > 0 ? n2[t4 - 4] : 2 * n2[t4] - n2[t4 + 4], h3 = n2[t4], c3 = n2[t4 + 4], f3 = a3 < o2 - 2 ? n2[t4 + 8] : 2 * n2[t4 + 4] - n2[t4];
      p2[u3 + e6] = r2(i4, h3, c3, f3, s3);
    }
  }
  const m = Buffer$1.alloc(c2 * d * 4);
  for (let e5 = 0; e5 < d; e5++) for (let t3 = 0; t3 < c2; t3++) {
    const i3 = e5 * (s2 - 1) / d, n3 = Math.floor(i3), a3 = i3 - n3, o3 = 4 * (n3 * c2 + t3), l3 = 4 * (e5 * c2 + t3);
    for (let e6 = 0; e6 < 4; e6++) {
      const t4 = o3 + e6, i4 = n3 > 0 ? p2[t4 - 4 * c2] : 2 * p2[t4] - p2[t4 + 4 * c2], u3 = p2[t4], h3 = p2[t4 + 4 * c2], f3 = n3 < s2 - 2 ? p2[t4 + 8 * c2] : 2 * p2[t4 + 4 * c2] - p2[t4];
      m[l3 + e6] = r2(i4, u3, h3, f3, a3);
    }
  }
  const _2 = h2 * f2;
  if (_2 > 1) for (let e5 = 0; e5 < u2; e5++) for (let t3 = 0; t3 < l2; t3++) {
    let i3 = 0, r3 = 0, n3 = 0, o3 = 0, s3 = 0;
    for (let a3 = 0; a3 < f2; a3++) {
      const l3 = e5 * f2 + a3;
      for (let e6 = 0; e6 < h2; e6++) {
        const a4 = 4 * (l3 * c2 + (t3 * h2 + e6)), u4 = m[a4 + 3];
        u4 && (i3 += m[a4], r3 += m[a4 + 1], n3 += m[a4 + 2], s3++), o3 += u4;
      }
    }
    const u3 = 4 * (e5 * l2 + t3);
    a2[u3] = s3 ? Math.round(i3 / s3) : 0, a2[u3 + 1] = s3 ? Math.round(r3 / s3) : 0, a2[u3 + 2] = s3 ? Math.round(n3 / s3) : 0, a2[u3 + 3] = Math.round(o3 / _2);
  }
  else t2.data = m;
}, bicubicInterpolation(e4, t2, i2) {
  return this._interpolate2D(e4, t2, i2, function(e5, t3, i3, r2, n2) {
    const a2 = r2 - i3 - e5 + t3, o2 = e5 - t3 - a2, s2 = i3 - e5, l2 = t3;
    return Math.max(0, Math.min(255, a2 * (n2 * n2 * n2) + o2 * (n2 * n2) + s2 * n2 + l2));
  });
}, hermiteInterpolation(e4, t2, i2) {
  return this._interpolate2D(e4, t2, i2, function(e5, t3, i3, r2, n2) {
    const a2 = t3, o2 = 0.5 * (i3 - e5), s2 = e5 - 2.5 * t3 + 2 * i3 - 0.5 * r2, l2 = 0.5 * (r2 - e5) + 1.5 * (t3 - i3);
    return Math.max(0, Math.min(255, Math.round(((l2 * n2 + s2) * n2 + o2) * n2 + a2)));
  });
}, bezierInterpolation(e4, t2, i2) {
  return this._interpolate2D(e4, t2, i2, function(e5, t3, i3, r2, n2) {
    const a2 = 1 - n2, o2 = t3 * a2 * a2 * a2, s2 = 3 * (t3 + (i3 - e5) / 4) * a2 * a2 * n2, l2 = 3 * (i3 - (r2 - t3) / 4) * a2 * n2 * n2, u2 = i3 * n2 * n2 * n2;
    return Math.max(0, Math.min(255, Math.round(o2 + s2 + l2 + u2)));
  });
} }, ResizeOptionsSchema = z.union([z.object({ w: z.number().min(0), h: z.number().min(0).optional(), mode: z.nativeEnum(ResizeStrategy).optional() }), z.object({ w: z.number().min(0).optional(), h: z.number().min(0), mode: z.nativeEnum(ResizeStrategy).optional() })]), ScaleToFitOptionsSchema = z.object({ w: z.number().min(0), h: z.number().min(0), mode: z.nativeEnum(ResizeStrategy).optional() }), ScaleComplexOptionsSchema = z.object({ f: z.number().min(0), mode: z.nativeEnum(ResizeStrategy).optional() }), methods$d = { resize(e4, t2) {
  const { mode: i2 } = ResizeOptionsSchema.parse(t2);
  let r2, n2;
  if ("number" == typeof t2.w) r2 = t2.w, n2 = t2.h ?? e4.bitmap.height * (r2 / e4.bitmap.width);
  else {
    if ("number" != typeof t2.h) throw new Error("w must be a number");
    n2 = t2.h, r2 = t2.w ?? e4.bitmap.width * (n2 / e4.bitmap.height);
  }
  if (r2 = Math.round(r2) || 1, n2 = Math.round(n2) || 1, i2 && "function" == typeof operations[i2]) {
    const t3 = { data: Buffer$1.alloc(r2 * n2 * 4), width: r2, height: n2 };
    operations[i2](e4.bitmap, t3), e4.bitmap = t3;
  } else {
    new Resize(e4.bitmap.width, e4.bitmap.height, r2, n2, true, true, (t3) => {
      e4.bitmap.data = Buffer$1.from(t3), e4.bitmap.width = r2, e4.bitmap.height = n2;
    }).resize(e4.bitmap.data);
  }
  return e4;
}, scale(e4, t2) {
  const { f: i2, mode: r2 } = "number" == typeof t2 ? { f: t2 } : ScaleComplexOptionsSchema.parse(t2), n2 = e4.bitmap.width * i2, a2 = e4.bitmap.height * i2;
  return this.resize(e4, { w: n2, h: a2, mode: r2 });
}, scaleToFit(e4, t2) {
  const { h: i2, w: r2, mode: n2 } = ScaleToFitOptionsSchema.parse(t2), a2 = r2 / i2 > e4.bitmap.width / e4.bitmap.height ? i2 / e4.bitmap.height : r2 / e4.bitmap.width;
  return this.scale(e4, { f: a2, mode: n2 });
} }, ContainOptionsSchema = z.object({ w: z.number(), h: z.number(), align: z.number().optional(), mode: z.nativeEnum(ResizeStrategy).optional() }), methods$c = { contain(e4, t2) {
  const { w: i2, h: r2, align: n2 = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode: a2 } = ContainOptionsSchema.parse(t2), o2 = 7 & n2, s2 = n2 >> 3;
  if ((0 === o2 || o2 & o2 - 1) && (0 === s2 || s2 & s2 - 1)) throw new Error("only use one flag per alignment direction");
  const l2 = o2 >> 1, u2 = s2 >> 1, h2 = i2 / r2 > e4.bitmap.width / e4.bitmap.height ? r2 / e4.bitmap.height : i2 / e4.bitmap.width, c2 = methods$d.scale(clone(e4), { f: h2, mode: a2 });
  return (e4 = methods$d.resize(e4, { w: i2, h: r2, mode: a2 })).scan((t3, i3, r3) => {
    e4.bitmap.data.writeUInt32BE(e4.background, r3);
  }), e4 = methods$h.blit(e4, { src: c2, x: (e4.bitmap.width - c2.bitmap.width) / 2 * l2, y: (e4.bitmap.height - c2.bitmap.height) / 2 * u2 });
} }, CropOptionsSchema = z.object({ x: z.number(), y: z.number(), w: z.number(), h: z.number() }), AutocropComplexOptionsSchema = z.object({ tolerance: z.number().min(0).max(1).optional(), cropOnlyFrames: z.boolean().optional(), cropSymmetric: z.boolean().optional(), leaveBorder: z.number().optional(), ignoreSides: z.object({ north: z.boolean().optional(), south: z.boolean().optional(), east: z.boolean().optional(), west: z.boolean().optional() }).optional() }), methods$b = { crop(e4, t2) {
  let { x: i2, y: r2, w: n2, h: a2 } = CropOptionsSchema.parse(t2);
  if (i2 = Math.round(i2), r2 = Math.round(r2), n2 = Math.round(n2), a2 = Math.round(a2), 0 === i2 && n2 === e4.bitmap.width) {
    const t3 = n2 * r2 + i2 << 2, o2 = t3 + (a2 * n2 << 2);
    e4.bitmap.data = e4.bitmap.data.slice(t3, o2);
  } else {
    const t3 = Buffer$1.allocUnsafe(n2 * a2 * 4);
    let o2 = 0;
    scan(e4, i2, r2, n2, a2, function(i3, r3, n3) {
      const a3 = e4.bitmap.data.readUInt32BE(n3);
      t3.writeUInt32BE(a3, o2), o2 += 4;
    }), e4.bitmap.data = t3;
  }
  return e4.bitmap.width = n2, e4.bitmap.height = a2, e4;
}, autocrop(e4, t2 = {}) {
  const { tolerance: i2 = 2e-4, cropOnlyFrames: r2 = true, cropSymmetric: n2 = false, leaveBorder: a2 = 0, ignoreSides: o2 } = "number" == typeof t2 ? { tolerance: t2 } : AutocropComplexOptionsSchema.parse(t2), s2 = e4.bitmap.width, l2 = e4.bitmap.height, u2 = { north: false, south: false, east: false, west: false, ...o2 };
  let h2 = e4.getPixelColor(0, 0);
  const c2 = intToRGBA$1(h2);
  let f2 = 0, d = 0, p2 = 0, m = 0;
  if (h2 = e4.getPixelColor(0, 0), !u2.north) e: for (let t3 = 0; t3 < l2 - 1; t3++) {
    for (let r3 = 0; r3 < s2; r3++) {
      if (colorDiff(c2, intToRGBA$1(e4.getPixelColor(r3, t3))) > i2) break e;
    }
    f2++;
  }
  if (h2 = e4.getPixelColor(s2, 0), !u2.west) e: for (let t3 = 0; t3 < s2 - 1; t3++) {
    for (let r3 = 0 + f2; r3 < l2; r3++) {
      if (colorDiff(c2, intToRGBA$1(e4.getPixelColor(t3, r3))) > i2) break e;
    }
    m++;
  }
  if (h2 = e4.getPixelColor(0, l2), !u2.south) e: for (let t3 = l2 - 1; t3 >= f2 + 1; t3--) {
    for (let r3 = s2 - d - 1; r3 >= 0; r3--) {
      if (colorDiff(c2, intToRGBA$1(e4.getPixelColor(r3, t3))) > i2) break e;
    }
    p2++;
  }
  if (h2 = e4.getPixelColor(s2, l2), !u2.east) e: for (let t3 = s2 - 1; t3 >= 0 + m + 1; t3--) {
    for (let r3 = l2 - 1; r3 >= 0 + f2; r3--) {
      if (colorDiff(c2, intToRGBA$1(e4.getPixelColor(t3, r3))) > i2) break e;
    }
    d++;
  }
  let _2 = false;
  if (m -= a2, d -= a2, f2 -= a2, p2 -= a2, n2) {
    const e5 = Math.min(d, m), t3 = Math.min(f2, p2);
    m = e5, d = e5, f2 = t3, p2 = t3;
  }
  m = m >= 0 ? m : 0, d = d >= 0 ? d : 0, f2 = f2 >= 0 ? f2 : 0, p2 = p2 >= 0 ? p2 : 0;
  const g = s2 - (m + d), b2 = l2 - (p2 + f2);
  return _2 = r2 ? 0 !== d && 0 !== f2 && 0 !== m && 0 !== p2 : 0 !== d || 0 !== f2 || 0 !== m || 0 !== p2, _2 && this.crop(e4, { x: m, y: f2, w: g, h: b2 }), e4;
} }, CoverOptionsSchema = z.object({ w: z.number(), h: z.number(), align: z.number().optional(), mode: z.nativeEnum(ResizeStrategy).optional() }), methods$a = { cover(e4, t2) {
  const { w: i2, h: r2, align: n2 = HorizontalAlign.CENTER | VerticalAlign.MIDDLE, mode: a2 } = CoverOptionsSchema.parse(t2), o2 = 7 & n2, s2 = n2 >> 3;
  if ((0 === o2 || o2 & o2 - 1) && (0 === s2 || s2 & s2 - 1)) throw new Error("only use one flag per alignment direction");
  const l2 = o2 >> 1, u2 = s2 >> 1, h2 = i2 / r2 > e4.bitmap.width / e4.bitmap.height ? i2 / e4.bitmap.width : r2 / e4.bitmap.height;
  return e4 = methods$d.scale(e4, { f: h2, mode: a2 }), e4 = methods$b.crop(e4, { x: (e4.bitmap.width - i2) / 2 * l2, y: (e4.bitmap.height - r2) / 2 * u2, w: i2, h: r2 });
} }, DisplaceOptionsSchema = z.object({ map: JimpClassSchema, offset: z.number() }), methods$9 = { displace(e4, t2) {
  const { map: i2, offset: r2 } = DisplaceOptionsSchema.parse(t2), n2 = clone(e4);
  return e4.scan((t3, a2, o2) => {
    let s2 = i2.bitmap.data[o2] / 256 * r2;
    s2 = Math.round(s2);
    const l2 = e4.getPixelIndex(t3 + s2, a2);
    e4.bitmap.data[l2] = n2.bitmap.data[o2], e4.bitmap.data[l2 + 1] = n2.bitmap.data[o2 + 1], e4.bitmap.data[l2 + 2] = n2.bitmap.data[o2 + 2];
  }), e4;
} }, methods$8 = { dither(e4) {
  const t2 = [1, 9, 3, 11, 13, 5, 15, 7, 4, 12, 2, 10, 16, 8, 14, 6];
  return e4.scan((i2, r2, n2) => {
    const a2 = t2[((3 & r2) << 2) + i2 % 4];
    e4.bitmap.data[n2] = Math.min(e4.bitmap.data[n2] + a2, 255), e4.bitmap.data[n2 + 1] = Math.min(e4.bitmap.data[n2 + 1] + a2, 255), e4.bitmap.data[n2 + 2] = Math.min(e4.bitmap.data[n2 + 2] + a2, 255);
  }), e4;
} }, FisheyeOptionsSchema = z.object({ radius: z.number().min(0).optional() }), methods$7 = { fisheye(e4, t2 = {}) {
  const { radius: i2 = 2.5 } = FisheyeOptionsSchema.parse(t2), r2 = clone(e4), { width: n2, height: a2 } = r2.bitmap;
  return r2.scan((t3, o2) => {
    const s2 = t3 / n2, l2 = o2 / a2, u2 = Math.sqrt(Math.pow(s2 - 0.5, 2) + Math.pow(l2 - 0.5, 2)), h2 = 2 * Math.pow(u2, i2), c2 = (s2 - 0.5) / u2, f2 = (l2 - 0.5) / u2, d = Math.round((h2 * c2 + 0.5) * n2), p2 = Math.round((h2 * f2 + 0.5) * a2), m = r2.getPixelColor(d, p2);
    e4.setPixelColor(m, t3, o2);
  }), e4.setPixelColor(r2.getPixelColor(n2 / 2, a2 / 2), n2 / 2, a2 / 2), e4;
} }, FlipOptionsSchema = z.object({ horizontal: z.boolean().optional(), vertical: z.boolean().optional() }), methods$6 = { flip(e4, t2) {
  const { horizontal: i2, vertical: r2 } = FlipOptionsSchema.parse(t2), n2 = Buffer$1.alloc(e4.bitmap.data.length);
  return e4.scan((t3, a2, o2) => {
    const s2 = i2 ? e4.bitmap.width - 1 - t3 : t3, l2 = r2 ? e4.bitmap.height - 1 - a2 : a2, u2 = e4.bitmap.width * l2 + s2 << 2, h2 = e4.bitmap.data.readUInt32BE(o2);
    n2.writeUInt32BE(h2, u2);
  }), e4.bitmap.data = Buffer$1.from(n2), e4;
} };
function Converter$1(e4, t2) {
  if (!(e4 && t2 && e4.length && t2.length)) throw new Error("Bad alphabet");
  this.srcAlphabet = e4, this.dstAlphabet = t2;
}
Converter$1.prototype.convert = function(e4) {
  var t2, i2, r2, n2 = {}, a2 = this.srcAlphabet.length, o2 = this.dstAlphabet.length, s2 = e4.length, l2 = "string" == typeof e4 ? "" : [];
  if (!this.isValid(e4)) throw new Error('Number "' + e4 + '" contains of non-alphabetic digits (' + this.srcAlphabet + ")");
  if (this.srcAlphabet === this.dstAlphabet) return e4;
  for (t2 = 0; t2 < s2; t2++) n2[t2] = this.srcAlphabet.indexOf(e4[t2]);
  do {
    for (i2 = 0, r2 = 0, t2 = 0; t2 < s2; t2++) (i2 = i2 * a2 + n2[t2]) >= o2 ? (n2[r2++] = parseInt(i2 / o2, 10), i2 %= o2) : r2 > 0 && (n2[r2++] = 0);
    s2 = r2, l2 = this.dstAlphabet.slice(i2, i2 + 1).concat(l2);
  } while (0 !== r2);
  return l2;
}, Converter$1.prototype.isValid = function(e4) {
  for (var t2 = 0; t2 < e4.length; ++t2) if (-1 === this.srcAlphabet.indexOf(e4[t2])) return false;
  return true;
};
var converter = Converter$1, Converter = converter;
function anyBase(e4, t2) {
  var i2 = new Converter(e4, t2);
  return function(e5) {
    return i2.convert(e5);
  };
}
anyBase.BIN = "01", anyBase.OCT = "01234567", anyBase.DEC = "0123456789", anyBase.HEX = "0123456789abcdef";
var anyBase_1 = anyBase, anyBase$1 = getDefaultExportFromCjs(anyBase_1), __defProp$1 = Object.defineProperty, __defNormalProp$1 = (e4, t2, i2) => t2 in e4 ? __defProp$1(e4, t2, { enumerable: true, configurable: true, writable: true, value: i2 }) : e4[t2] = i2, __publicField$1 = (e4, t2, i2) => __defNormalProp$1(e4, "symbol" != typeof t2 ? t2 + "" : t2, i2);
class ImagePHash {
  constructor(e4, t2) {
    __publicField$1(this, "size"), __publicField$1(this, "smallerSize"), this.size = e4 || 32, this.smallerSize = t2 || 8, initCoefficients(this.size);
  }
  distance(e4, t2) {
    let i2 = 0;
    for (let r2 = 0; r2 < e4.length; r2++) e4[r2] !== t2[r2] && i2++;
    return i2 / e4.length;
  }
  getHash(e4) {
    e4 = methods$d.resize(clone(e4), { w: this.size, h: this.size }), e4 = methods$e.greyscale(e4);
    const t2 = [];
    for (let i3 = 0; i3 < e4.bitmap.width; i3++) {
      const r3 = [];
      for (let t3 = 0; t3 < e4.bitmap.height; t3++) r3[t3] = intToRGBA(e4.getPixelColor(i3, t3)).b;
      t2[i3] = r3;
    }
    const i2 = applyDCT(t2, this.size);
    let r2 = 0;
    for (let e5 = 0; e5 < this.smallerSize; e5++) for (let t3 = 0; t3 < this.smallerSize; t3++) r2 += i2[e5][t3];
    const n2 = r2 / (this.smallerSize * this.smallerSize);
    let a2 = "";
    for (let e5 = 0; e5 < this.smallerSize; e5++) for (let t3 = 0; t3 < this.smallerSize; t3++) a2 += i2[e5][t3] > n2 ? "1" : "0";
    return a2;
  }
}
function intToRGBA(e4) {
  const t2 = 255 & e4, i2 = 255 & (e4 >>>= 8), r2 = 255 & (e4 >>>= 8);
  return { r: 255 & (e4 >>>= 8), g: r2, b: i2, a: t2 };
}
const c$1 = [];
function initCoefficients(e4) {
  for (let t2 = 1; t2 < e4; t2++) c$1[t2] = 1;
  c$1[0] = 1 / Math.sqrt(2);
}
function applyDCT(e4, t2) {
  const i2 = t2, r2 = [];
  for (let t3 = 0; t3 < i2; t3++) {
    const n2 = [];
    for (let a2 = 0; a2 < i2; a2++) {
      let o2 = 0;
      for (let r3 = 0; r3 < i2; r3++) for (let n3 = 0; n3 < i2; n3++) o2 += Math.cos((2 * r3 + 1) / (2 * i2) * t3 * Math.PI) * Math.cos((2 * n3 + 1) / (2 * i2) * a2 * Math.PI) * e4[r3][n3];
      o2 *= c$1[t3] * c$1[a2] / 4, n2[a2] = o2, r2[t3] = n2;
    }
  }
  return r2;
}
const alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_", maxHashLength = [NaN, NaN];
for (let e4 = 2; e4 < 65; e4++) {
  const t2 = anyBase$1(anyBase$1.BIN, alphabet.slice(0, e4))(new Array(65).join("1"));
  maxHashLength.push(t2.length);
}
const methods$5 = { pHash: (e4) => new ImagePHash().getHash(e4), hash(e4, t2 = 64) {
  if (t2 < 2 || t2 > 64) throw new Error("base must be a number between 2 and 64");
  const i2 = alphabet.slice(0, t2), r2 = this.pHash(e4), n2 = maxHashLength[t2];
  return anyBase$1(anyBase$1.BIN, i2)(r2).padStart(n2, "0");
}, distanceFromHash(e4, t2) {
  const i2 = new ImagePHash(), r2 = i2.getHash(e4);
  return i2.distance(r2, t2);
} };
const MaskOptionsObjectSchema = z.object({ src: JimpClassSchema, x: z.number().optional(), y: z.number().optional() }), MaskOptionsSchema = z.union([JimpClassSchema, MaskOptionsObjectSchema]), methods$4 = { mask(e4, t2) {
  let i2, r2, n2;
  MaskOptionsSchema.parse(t2), "bitmap" in t2 ? (i2 = t2, r2 = 0, n2 = 0) : (i2 = t2.src, r2 = t2.x ?? 0, n2 = t2.y ?? 0), r2 = Math.round(r2), n2 = Math.round(n2);
  const a2 = e4.bitmap.width, o2 = e4.bitmap.height;
  return i2.scan(function(t3, s2, l2) {
    const u2 = r2 + t3, h2 = n2 + s2;
    if (u2 >= 0 && h2 >= 0 && u2 < a2 && h2 < o2) {
      const t4 = e4.getPixelIndex(u2, h2), { data: r3 } = i2.bitmap, n3 = (r3[l2 + 0] + r3[l2 + 1] + r3[l2 + 2]) / 3;
      e4.bitmap.data[t4 + 3] *= n3 / 255;
    }
  }), e4;
} };
function measureText(e4, t2) {
  let i2 = 0;
  for (let r2 = 0; r2 < t2.length; r2++) {
    const n2 = t2[r2], a2 = e4.chars[n2];
    if (a2) {
      const o2 = e4.kernings[n2], s2 = t2[r2 + 1], l2 = o2 && s2 && o2[s2] && o2[s2] || 0;
      i2 += (a2.xadvance || 0) + l2;
    }
  }
  return i2;
}
function splitLines(e4, t2, i2) {
  const r2 = t2.replace(/[\r\n]+/g, " \n").split(" "), n2 = [];
  let a2 = [], o2 = 0;
  return r2.forEach((t3) => {
    if (measureText(e4, t3 + (r2.length > 1 ? " " : "")) > i2) {
      const r3 = t3[Symbol.iterator]();
      let o3 = "";
      for (const t4 of r3) {
        const r4 = [...a2, o3 + t4].join(" "), s3 = measureText(e4, r4);
        s3 < i2 ? o3 += t4 : s3 > i2 ? (n2.push([...a2, o3]), a2 = [], o3 = t4) : (n2.push([...a2, o3 + t4]), a2 = [], o3 = "");
      }
      return;
    }
    const s2 = [...a2, t3].join(" "), l2 = measureText(e4, s2);
    l2 <= i2 && !t3.includes("\n") ? (l2 > o2 && (o2 = l2), a2.push(t3)) : (n2.push(a2), a2 = [t3.replace("\n", "")]);
  }), n2.push(a2), { lines: n2, longestLine: o2 };
}
function measureTextHeight(e4, t2, i2) {
  const { lines: r2 } = splitLines(e4, t2, i2);
  return r2.length * e4.common.lineHeight;
}
const PrintOptionsSchema = z.object({ x: z.number(), y: z.number(), text: z.union([z.union([z.string(), z.number()]), z.object({ text: z.union([z.string(), z.number()]), alignmentX: z.nativeEnum(HorizontalAlign).optional(), alignmentY: z.nativeEnum(VerticalAlign).optional() })]), maxWidth: z.number().optional(), maxHeight: z.number().optional(), cb: z.function(z.tuple([z.object({ x: z.number(), y: z.number() })])).optional() });
function xOffsetBasedOnAlignment(e4, t2, i2, r2) {
  return r2 === HorizontalAlign.LEFT ? 0 : r2 === HorizontalAlign.CENTER ? (i2 - measureText(e4, t2)) / 2 : i2 - measureText(e4, t2);
}
function drawCharacter(e4, t2, i2, r2, n2) {
  if (n2.width > 0 && n2.height > 0) {
    const a2 = t2.pages[n2.page];
    a2 && (e4 = methods$h.blit(e4, { src: a2, x: i2 + n2.xoffset, y: r2 + n2.yoffset, srcX: n2.x, srcY: n2.y, srcW: n2.width, srcH: n2.height }));
  }
  return e4;
}
function printText(e4, t2, i2, r2, n2, a2) {
  for (let o2 = 0; o2 < n2.length; o2++) {
    const s2 = n2[o2];
    let l2;
    l2 = t2.chars[s2] ? s2 : /\s/.test(s2) ? "" : "?";
    const u2 = t2.chars[l2] || { xadvance: void 0 }, h2 = t2.kernings[l2];
    u2 && drawCharacter(e4, t2, i2, r2, u2);
    const c2 = n2[o2 + 1];
    i2 += (h2 && c2 && h2[c2] && h2[c2] || 0) + (u2.xadvance || a2);
  }
}
const methods$3 = { print(e4, { font: t2, ...i2 }) {
  var _a3;
  let r2, n2, { x: a2, y: o2, text: s2, maxWidth: l2 = 1 / 0, maxHeight: u2 = 1 / 0, cb: h2 = () => {
  } } = PrintOptionsSchema.parse(i2);
  "object" == typeof s2 && null !== s2.text && void 0 !== s2.text ? (r2 = s2.alignmentX || HorizontalAlign.LEFT, n2 = s2.alignmentY || VerticalAlign.TOP, { text: s2 } = s2) : (r2 = HorizontalAlign.LEFT, n2 = VerticalAlign.TOP, s2 = s2.toString()), "number" == typeof s2 && (s2 = s2.toString()), u2 !== 1 / 0 && n2 === VerticalAlign.BOTTOM ? o2 += u2 - measureTextHeight(t2, s2, l2) : u2 !== 1 / 0 && n2 === VerticalAlign.MIDDLE && (o2 += u2 / 2 - measureTextHeight(t2, s2, l2) / 2);
  const c2 = (_a3 = Object.entries(t2.chars).find((e5) => e5[1].xadvance)) == null ? void 0 : _a3[1].xadvance;
  if ("number" != typeof c2) throw new Error("Could not find default character width");
  const { lines: f2, longestLine: d } = splitLines(t2, s2, l2);
  return f2.forEach((i3) => {
    const n3 = i3.join(" "), s3 = xOffsetBasedOnAlignment(t2, n3, l2, r2);
    printText(e4, t2, a2 + s3, o2, n3, c2), o2 += t2.common.lineHeight;
  }), h2.bind(e4)({ x: a2 + d, y: o2 }), e4;
} }, RotateOptionsSchema = z.union([z.number(), z.object({ deg: z.number(), mode: z.union([z.boolean(), z.nativeEnum(ResizeStrategy)]).optional() })]);
function createIdxTranslationFunction(e4) {
  return function(t2, i2) {
    return i2 * e4 + t2 << 2;
  };
}
function matrixRotate(e4, t2) {
  if (Math.abs(t2) % 90 != 0) throw new Error("Unsupported matrix rotation degree");
  const i2 = e4.bitmap.width, r2 = e4.bitmap.height;
  let n2;
  switch (t2) {
    case 90:
    case -270:
      n2 = 90;
      break;
    case 180:
    case -180:
      n2 = 180;
      break;
    case 270:
    case -90:
      n2 = -90;
      break;
    default:
      throw new Error("Unsupported matrix rotation degree");
  }
  const a2 = 180 === n2 ? i2 : r2, o2 = 180 === n2 ? r2 : i2, s2 = Buffer$1.alloc(e4.bitmap.data.length), l2 = createIdxTranslationFunction(i2), u2 = createIdxTranslationFunction(a2);
  for (let t3 = 0; t3 < i2; t3++) for (let a3 = 0; a3 < r2; a3++) {
    const o3 = l2(t3, a3), h2 = e4.bitmap.data.readUInt32BE(o3);
    let c2;
    switch (n2) {
      case 90:
        c2 = u2(a3, i2 - t3 - 1);
        break;
      case -90:
        c2 = u2(r2 - a3 - 1, t3);
        break;
      case 180:
        c2 = u2(i2 - t3 - 1, r2 - a3 - 1);
        break;
      default:
        throw new Error("Unsupported matrix rotation angle");
    }
    s2.writeUInt32BE(h2, c2);
  }
  e4.bitmap.data = s2, e4.bitmap.width = a2, e4.bitmap.height = o2;
}
function createTranslationFunction(e4, t2) {
  return function(i2, r2) {
    return { x: i2 + e4, y: r2 + t2 };
  };
}
function advancedRotate(e4, t2, i2) {
  const r2 = t2 * Math.PI / 180, n2 = Math.cos(r2), a2 = Math.sin(r2);
  let o2 = e4.bitmap.width, s2 = e4.bitmap.height;
  if (true === i2 || "string" == typeof i2) {
    o2 = Math.ceil(Math.abs(e4.bitmap.width * n2) + Math.abs(e4.bitmap.height * a2)) + 1, s2 = Math.ceil(Math.abs(e4.bitmap.width * a2) + Math.abs(e4.bitmap.height * n2)) + 1, o2 % 2 != 0 && o2++, s2 % 2 != 0 && s2++;
    const t3 = clone(e4);
    e4.scan((t4, i3, r4) => {
      e4.bitmap.data.writeUInt32BE(e4.background, r4);
    });
    const r3 = Math.max(o2, s2, e4.bitmap.width, e4.bitmap.height);
    e4 = composite(e4 = methods$d.resize(e4, { h: r3, w: r3, mode: true === i2 ? void 0 : i2 }), t3, e4.bitmap.width / 2 - t3.bitmap.width / 2, e4.bitmap.height / 2 - t3.bitmap.height / 2);
  }
  const l2 = e4.bitmap.width, u2 = e4.bitmap.height, h2 = Buffer$1.alloc(e4.bitmap.data.length), c2 = createTranslationFunction(-l2 / 2, -u2 / 2), f2 = createTranslationFunction(l2 / 2 + 0.5, u2 / 2 + 0.5);
  for (let t3 = 1; t3 <= u2; t3++) for (let i3 = 1; i3 <= l2; i3++) {
    const r3 = c2(i3, t3), o3 = f2(n2 * r3.x - a2 * r3.y, n2 * r3.y + a2 * r3.x), s3 = l2 * (t3 - 1) + i3 - 1 << 2;
    if (o3.x >= 0 && o3.x < l2 && o3.y >= 0 && o3.y < u2) {
      const t4 = l2 * (0 | o3.y) + o3.x << 2, i4 = e4.bitmap.data.readUInt32BE(t4);
      h2.writeUInt32BE(i4, s3);
    } else h2.writeUInt32BE(e4.background, s3);
  }
  if (e4.bitmap.data = h2, true === i2 || "string" == typeof i2) {
    const t3 = Math.max(l2 / 2 - o2 / 2, 0), i3 = Math.max(u2 / 2 - s2 / 2, 0);
    e4 = methods$b.crop(e4, { x: t3, y: i3, w: o2, h: s2 });
  }
}
const methods$2 = { rotate(e4, t2) {
  const i2 = RotateOptionsSchema.parse(t2), r2 = "number" == typeof i2 ? { deg: i2 } : i2, { mode: n2 = true } = r2;
  let { deg: a2 } = r2;
  if (a2 %= 360, a2 % 360 == 0) return e4;
  return a2 % 90 == 0 && (n2 || e4.bitmap.width === e4.bitmap.height || a2 % 180 == 0) ? matrixRotate(e4, a2) : advancedRotate(e4, a2, n2), e4;
} }, ThresholdOptionsSchema = z.object({ max: z.number().min(0).max(255), replace: z.number().min(0).max(255).optional(), autoGreyscale: z.boolean().optional() }), methods$1 = { threshold(e4, t2) {
  let { max: i2, replace: r2 = 255, autoGreyscale: n2 = true } = ThresholdOptionsSchema.parse(t2);
  return i2 = limit255(i2), r2 = limit255(r2), n2 && methods$e.greyscale(e4), e4.scan((t3, n3, a2) => {
    const o2 = e4.bitmap.data[a2] < i2 ? e4.bitmap.data[a2] : r2;
    e4.bitmap.data[a2] = o2, e4.bitmap.data[a2 + 1] = o2, e4.bitmap.data[a2 + 2] = o2;
  }), e4;
} };
var __defProp = Object.defineProperty, __defNormalProp = (e4, t2, i2) => t2 in e4 ? __defProp(e4, t2, { enumerable: true, configurable: true, writable: true, value: i2 }) : e4[t2] = i2, __export = (e4, t2) => {
  for (var i2 in t2) __defProp(e4, i2, { get: t2[i2], enumerable: true });
}, __publicField = (e4, t2, i2) => (__defNormalProp(e4, "symbol" != typeof t2 ? t2 + "" : t2, i2), i2), constants_exports = {};
__export(constants_exports, { bt709: () => bt709_exports });
var bt709_exports = {};
__export(bt709_exports, { Y: () => Y, x: () => x$1, y: () => y$1 });
var Y = ((e4) => (e4[e4.RED = 0.2126] = "RED", e4[e4.GREEN = 0.7152] = "GREEN", e4[e4.BLUE = 0.0722] = "BLUE", e4[e4.WHITE = 1] = "WHITE", e4))(Y || {}), x$1 = ((e4) => (e4[e4.RED = 0.64] = "RED", e4[e4.GREEN = 0.3] = "GREEN", e4[e4.BLUE = 0.15] = "BLUE", e4[e4.WHITE = 0.3127] = "WHITE", e4))(x$1 || {}), y$1 = ((e4) => (e4[e4.RED = 0.33] = "RED", e4[e4.GREEN = 0.6] = "GREEN", e4[e4.BLUE = 0.06] = "BLUE", e4[e4.WHITE = 0.329] = "WHITE", e4))(y$1 || {}), conversion_exports = {};
function correctGamma(e4) {
  return e4 > 0.04045 ? ((e4 + 0.055) / 1.055) ** 2.4 : e4 / 12.92;
}
function rgb2xyz(e4, t2, i2) {
  return { x: 0.4124 * (e4 = correctGamma(e4 / 255)) + 0.3576 * (t2 = correctGamma(t2 / 255)) + 0.1805 * (i2 = correctGamma(i2 / 255)), y: 0.2126 * e4 + 0.7152 * t2 + 0.0722 * i2, z: 0.0193 * e4 + 0.1192 * t2 + 0.9505 * i2 };
}
__export(conversion_exports, { lab2rgb: () => lab2rgb, lab2xyz: () => lab2xyz, rgb2hsl: () => rgb2hsl, rgb2lab: () => rgb2lab, rgb2xyz: () => rgb2xyz, xyz2lab: () => xyz2lab, xyz2rgb: () => xyz2rgb });
var arithmetic_exports = {};
function degrees2radians(e4) {
  return e4 * (Math.PI / 180);
}
function max3(e4, t2, i2) {
  let r2 = e4;
  return r2 < t2 && (r2 = t2), r2 < i2 && (r2 = i2), r2;
}
function min3(e4, t2, i2) {
  let r2 = e4;
  return r2 > t2 && (r2 = t2), r2 > i2 && (r2 = i2), r2;
}
function intInRange(e4, t2, i2) {
  return e4 > i2 && (e4 = i2), e4 < t2 && (e4 = t2), 0 | e4;
}
function inRange0to255Rounded(e4) {
  return (e4 = Math.round(e4)) > 255 ? e4 = 255 : e4 < 0 && (e4 = 0), e4;
}
function inRange0to255(e4) {
  return e4 > 255 ? e4 = 255 : e4 < 0 && (e4 = 0), e4;
}
function stableSort(e4, t2) {
  const i2 = typeof e4[0];
  let r2;
  if ("number" === i2 || "string" === i2) {
    const i3 = /* @__PURE__ */ Object.create(null);
    for (let t3 = 0, r3 = e4.length; t3 < r3; t3++) {
      const r4 = e4[t3];
      i3[r4] || 0 === i3[r4] || (i3[r4] = t3);
    }
    r2 = e4.sort((e5, r3) => t2(e5, r3) || i3[e5] - i3[r3]);
  } else {
    const i3 = e4.slice(0);
    r2 = e4.sort((e5, r3) => t2(e5, r3) || i3.indexOf(e5) - i3.indexOf(r3));
  }
  return r2;
}
function rgb2hsl(e4, t2, i2) {
  const r2 = min3(e4, t2, i2), n2 = max3(e4, t2, i2), a2 = n2 - r2, o2 = (r2 + n2) / 510;
  let s2 = 0;
  o2 > 0 && o2 < 1 && (s2 = a2 / (o2 < 0.5 ? n2 + r2 : 510 - n2 - r2));
  let l2 = 0;
  return a2 > 0 && (l2 = n2 === e4 ? (t2 - i2) / a2 : n2 === t2 ? 2 + (i2 - e4) / a2 : 4 + (e4 - t2) / a2, l2 *= 60, l2 < 0 && (l2 += 360)), { h: l2, s: s2, l: o2 };
}
__export(arithmetic_exports, { degrees2radians: () => degrees2radians, inRange0to255: () => inRange0to255, inRange0to255Rounded: () => inRange0to255Rounded, intInRange: () => intInRange, max3: () => max3, min3: () => min3, stableSort: () => stableSort });
var refX = 0.95047, refY = 1, refZ = 1.08883;
function pivot(e4) {
  return e4 > 8856e-6 ? e4 ** (1 / 3) : 7.787 * e4 + 16 / 116;
}
function xyz2lab(e4, t2, i2) {
  if (e4 = pivot(e4 / refX), t2 = pivot(t2 / refY), i2 = pivot(i2 / refZ), 116 * t2 - 16 < 0) throw new Error("xxx");
  return { L: Math.max(0, 116 * t2 - 16), a: 500 * (e4 - t2), b: 200 * (t2 - i2) };
}
function rgb2lab(e4, t2, i2) {
  const r2 = rgb2xyz(e4, t2, i2);
  return xyz2lab(r2.x, r2.y, r2.z);
}
var refX2 = 0.95047, refY2 = 1, refZ2 = 1.08883;
function pivot2(e4) {
  return e4 > 0.206893034 ? e4 ** 3 : (e4 - 16 / 116) / 7.787;
}
function lab2xyz(e4, t2, i2) {
  const r2 = (e4 + 16) / 116, n2 = r2 - i2 / 200;
  return { x: refX2 * pivot2(t2 / 500 + r2), y: refY2 * pivot2(r2), z: refZ2 * pivot2(n2) };
}
function correctGamma2(e4) {
  return e4 > 31308e-7 ? 1.055 * e4 ** (1 / 2.4) - 0.055 : 12.92 * e4;
}
function xyz2rgb(e4, t2, i2) {
  const r2 = correctGamma2(3.2406 * e4 + -1.5372 * t2 + -0.4986 * i2), n2 = correctGamma2(-0.9689 * e4 + 1.8758 * t2 + 0.0415 * i2), a2 = correctGamma2(0.0557 * e4 + -0.204 * t2 + 1.057 * i2);
  return { r: inRange0to255Rounded(255 * r2), g: inRange0to255Rounded(255 * n2), b: inRange0to255Rounded(255 * a2) };
}
function lab2rgb(e4, t2, i2) {
  const r2 = lab2xyz(e4, t2, i2);
  return xyz2rgb(r2.x, r2.y, r2.z);
}
var distance_exports = {};
__export(distance_exports, { AbstractDistanceCalculator: () => AbstractDistanceCalculator, AbstractEuclidean: () => AbstractEuclidean, AbstractManhattan: () => AbstractManhattan, CIE94GraphicArts: () => CIE94GraphicArts, CIE94Textiles: () => CIE94Textiles, CIEDE2000: () => CIEDE2000, CMetric: () => CMetric, Euclidean: () => Euclidean, EuclideanBT709: () => EuclideanBT709, EuclideanBT709NoAlpha: () => EuclideanBT709NoAlpha, Manhattan: () => Manhattan, ManhattanBT709: () => ManhattanBT709, ManhattanNommyde: () => ManhattanNommyde, PNGQuant: () => PNGQuant });
var AbstractDistanceCalculator = class {
  constructor() {
    __publicField(this, "_maxDistance"), __publicField(this, "_whitePoint"), this._setDefaults(), this.setWhitePoint(255, 255, 255, 255);
  }
  setWhitePoint(e4, t2, i2, r2) {
    this._whitePoint = { r: e4 > 0 ? 255 / e4 : 0, g: t2 > 0 ? 255 / t2 : 0, b: i2 > 0 ? 255 / i2 : 0, a: r2 > 0 ? 255 / r2 : 0 }, this._maxDistance = this.calculateRaw(e4, t2, i2, r2, 0, 0, 0, 0);
  }
  calculateNormalized(e4, t2) {
    return this.calculateRaw(e4.r, e4.g, e4.b, e4.a, t2.r, t2.g, t2.b, t2.a) / this._maxDistance;
  }
}, AbstractCIE94 = class extends AbstractDistanceCalculator {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = rgb2lab(inRange0to255(e4 * this._whitePoint.r), inRange0to255(t2 * this._whitePoint.g), inRange0to255(i2 * this._whitePoint.b)), u2 = rgb2lab(inRange0to255(n2 * this._whitePoint.r), inRange0to255(a2 * this._whitePoint.g), inRange0to255(o2 * this._whitePoint.b)), h2 = l2.L - u2.L, c2 = l2.a - u2.a, f2 = l2.b - u2.b, d = Math.sqrt(l2.a * l2.a + l2.b * l2.b), p2 = d - Math.sqrt(u2.a * u2.a + u2.b * u2.b);
    let m = c2 * c2 + f2 * f2 - p2 * p2;
    m = m < 0 ? 0 : Math.sqrt(m);
    const _2 = (s2 - r2) * this._whitePoint.a * this._kA;
    return Math.sqrt((h2 / this._Kl) ** 2 + (p2 / (1 + this._K1 * d)) ** 2 + (m / (1 + this._K2 * d)) ** 2 + _2 ** 2);
  }
}, CIE94Textiles = class extends AbstractCIE94 {
  _setDefaults() {
    this._Kl = 2, this._K1 = 0.048, this._K2 = 0.014, this._kA = 12.5 / 255;
  }
}, CIE94GraphicArts = class extends AbstractCIE94 {
  _setDefaults() {
    this._Kl = 1, this._K1 = 0.045, this._K2 = 0.015, this._kA = 25 / 255;
  }
}, _CIEDE2000 = class extends AbstractDistanceCalculator {
  _setDefaults() {
  }
  static _calculatehp(e4, t2) {
    const i2 = Math.atan2(e4, t2);
    return i2 >= 0 ? i2 : i2 + _CIEDE2000._deg360InRad;
  }
  static _calculateRT(e4, t2) {
    const i2 = t2 ** 7, r2 = 2 * Math.sqrt(i2 / (i2 + _CIEDE2000._pow25to7)), n2 = _CIEDE2000._deg30InRad * Math.exp(-(((e4 - _CIEDE2000._deg275InRad) / _CIEDE2000._deg25InRad) ** 2));
    return -Math.sin(2 * n2) * r2;
  }
  static _calculateT(e4) {
    return 1 - 0.17 * Math.cos(e4 - _CIEDE2000._deg30InRad) + 0.24 * Math.cos(2 * e4) + 0.32 * Math.cos(3 * e4 + _CIEDE2000._deg6InRad) - 0.2 * Math.cos(4 * e4 - _CIEDE2000._deg63InRad);
  }
  static _calculate_ahp(e4, t2, i2, r2) {
    const n2 = i2 + r2;
    return 0 === e4 ? n2 : t2 <= _CIEDE2000._deg180InRad ? n2 / 2 : n2 < _CIEDE2000._deg360InRad ? (n2 + _CIEDE2000._deg360InRad) / 2 : (n2 - _CIEDE2000._deg360InRad) / 2;
  }
  static _calculate_dHp(e4, t2, i2, r2) {
    let n2;
    return n2 = 0 === e4 ? 0 : t2 <= _CIEDE2000._deg180InRad ? i2 - r2 : i2 <= r2 ? i2 - r2 + _CIEDE2000._deg360InRad : i2 - r2 - _CIEDE2000._deg360InRad, 2 * Math.sqrt(e4) * Math.sin(n2 / 2);
  }
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = rgb2lab(inRange0to255(e4 * this._whitePoint.r), inRange0to255(t2 * this._whitePoint.g), inRange0to255(i2 * this._whitePoint.b)), u2 = rgb2lab(inRange0to255(n2 * this._whitePoint.r), inRange0to255(a2 * this._whitePoint.g), inRange0to255(o2 * this._whitePoint.b)), h2 = (s2 - r2) * this._whitePoint.a * _CIEDE2000._kA, c2 = this.calculateRawInLab(l2, u2);
    return Math.sqrt(c2 + h2 * h2);
  }
  calculateRawInLab(e4, t2) {
    const i2 = e4.L, r2 = e4.a, n2 = e4.b, a2 = t2.L, o2 = t2.a, s2 = t2.b, l2 = ((Math.sqrt(r2 * r2 + n2 * n2) + Math.sqrt(o2 * o2 + s2 * s2)) / 2) ** 7, u2 = 0.5 * (1 - Math.sqrt(l2 / (l2 + _CIEDE2000._pow25to7))), h2 = (1 + u2) * r2, c2 = (1 + u2) * o2, f2 = Math.sqrt(h2 * h2 + n2 * n2), d = Math.sqrt(c2 * c2 + s2 * s2), p2 = f2 * d, m = _CIEDE2000._calculatehp(n2, h2), _2 = _CIEDE2000._calculatehp(s2, c2), g = Math.abs(m - _2), b2 = a2 - i2, y2 = d - f2, w = _CIEDE2000._calculate_dHp(p2, g, _2, m), v2 = _CIEDE2000._calculate_ahp(p2, g, m, _2), x2 = (f2 + d) / 2, E2 = ((i2 + a2) / 2 - 50) ** 2, k2 = y2 / (1 + 0.045 * x2), S2 = w / (1 + 0.015 * _CIEDE2000._calculateT(v2) * x2);
    return (b2 / (1 + 0.015 * E2 / Math.sqrt(20 + E2))) ** 2 + k2 ** 2 + S2 ** 2 + _CIEDE2000._calculateRT(v2, x2) * k2 * S2;
  }
}, CIEDE2000 = _CIEDE2000;
__publicField(CIEDE2000, "_kA", 25 / 255), __publicField(CIEDE2000, "_pow25to7", 25 ** 7), __publicField(CIEDE2000, "_deg360InRad", degrees2radians(360)), __publicField(CIEDE2000, "_deg180InRad", degrees2radians(180)), __publicField(CIEDE2000, "_deg30InRad", degrees2radians(30)), __publicField(CIEDE2000, "_deg6InRad", degrees2radians(6)), __publicField(CIEDE2000, "_deg63InRad", degrees2radians(63)), __publicField(CIEDE2000, "_deg275InRad", degrees2radians(275)), __publicField(CIEDE2000, "_deg25InRad", degrees2radians(25));
var CMetric = class extends AbstractDistanceCalculator {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = (e4 + n2) / 2 * this._whitePoint.r, u2 = (e4 - n2) * this._whitePoint.r, h2 = (t2 - a2) * this._whitePoint.g, c2 = (i2 - o2) * this._whitePoint.b, f2 = ((512 + l2) * u2 * u2 >> 8) + 4 * h2 * h2 + ((767 - l2) * c2 * c2 >> 8), d = (s2 - r2) * this._whitePoint.a;
    return Math.sqrt(f2 + d * d);
  }
  _setDefaults() {
  }
}, AbstractEuclidean = class extends AbstractDistanceCalculator {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = n2 - e4, u2 = a2 - t2, h2 = o2 - i2, c2 = s2 - r2;
    return Math.sqrt(this._kR * l2 * l2 + this._kG * u2 * u2 + this._kB * h2 * h2 + this._kA * c2 * c2);
  }
}, Euclidean = class extends AbstractEuclidean {
  _setDefaults() {
    this._kR = 1, this._kG = 1, this._kB = 1, this._kA = 1;
  }
}, EuclideanBT709 = class extends AbstractEuclidean {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 1;
  }
}, EuclideanBT709NoAlpha = class extends AbstractEuclidean {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 0;
  }
}, AbstractManhattan = class extends AbstractDistanceCalculator {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    let l2 = n2 - e4, u2 = a2 - t2, h2 = o2 - i2, c2 = s2 - r2;
    return l2 < 0 && (l2 = 0 - l2), u2 < 0 && (u2 = 0 - u2), h2 < 0 && (h2 = 0 - h2), c2 < 0 && (c2 = 0 - c2), this._kR * l2 + this._kG * u2 + this._kB * h2 + this._kA * c2;
  }
}, Manhattan = class extends AbstractManhattan {
  _setDefaults() {
    this._kR = 1, this._kG = 1, this._kB = 1, this._kA = 1;
  }
}, ManhattanNommyde = class extends AbstractManhattan {
  _setDefaults() {
    this._kR = 0.4984, this._kG = 0.8625, this._kB = 0.2979, this._kA = 1;
  }
}, ManhattanBT709 = class extends AbstractManhattan {
  _setDefaults() {
    this._kR = 0.2126, this._kG = 0.7152, this._kB = 0.0722, this._kA = 1;
  }
}, PNGQuant = class extends AbstractDistanceCalculator {
  calculateRaw(e4, t2, i2, r2, n2, a2, o2, s2) {
    const l2 = (s2 - r2) * this._whitePoint.a;
    return this._colordifferenceCh(e4 * this._whitePoint.r, n2 * this._whitePoint.r, l2) + this._colordifferenceCh(t2 * this._whitePoint.g, a2 * this._whitePoint.g, l2) + this._colordifferenceCh(i2 * this._whitePoint.b, o2 * this._whitePoint.b, l2);
  }
  _colordifferenceCh(e4, t2, i2) {
    const r2 = e4 - t2, n2 = r2 + i2;
    return r2 * r2 + n2 * n2;
  }
  _setDefaults() {
  }
}, palette_exports = {};
__export(palette_exports, { AbstractPaletteQuantizer: () => AbstractPaletteQuantizer, ColorHistogram: () => ColorHistogram, NeuQuant: () => NeuQuant, NeuQuantFloat: () => NeuQuantFloat, RGBQuant: () => RGBQuant, WuColorCube: () => WuColorCube, WuQuant: () => WuQuant });
var AbstractPaletteQuantizer = class {
  quantizeSync() {
    for (const e4 of this.quantize()) if (e4.palette) return e4.palette;
    throw new Error("unreachable");
  }
}, Point = class {
  constructor() {
    __publicField(this, "r"), __publicField(this, "g"), __publicField(this, "b"), __publicField(this, "a"), __publicField(this, "uint32"), __publicField(this, "rgba"), this.uint32 = -1 >>> 0, this.r = this.g = this.b = this.a = 0, this.rgba = new Array(4), this.rgba[0] = 0, this.rgba[1] = 0, this.rgba[2] = 0, this.rgba[3] = 0;
  }
  static createByQuadruplet(e4) {
    const t2 = new Point();
    return t2.r = 0 | e4[0], t2.g = 0 | e4[1], t2.b = 0 | e4[2], t2.a = 0 | e4[3], t2._loadUINT32(), t2._loadQuadruplet(), t2;
  }
  static createByRGBA(e4, t2, i2, r2) {
    const n2 = new Point();
    return n2.r = 0 | e4, n2.g = 0 | t2, n2.b = 0 | i2, n2.a = 0 | r2, n2._loadUINT32(), n2._loadQuadruplet(), n2;
  }
  static createByUint32(e4) {
    const t2 = new Point();
    return t2.uint32 = e4 >>> 0, t2._loadRGBA(), t2._loadQuadruplet(), t2;
  }
  from(e4) {
    this.r = e4.r, this.g = e4.g, this.b = e4.b, this.a = e4.a, this.uint32 = e4.uint32, this.rgba[0] = e4.r, this.rgba[1] = e4.g, this.rgba[2] = e4.b, this.rgba[3] = e4.a;
  }
  getLuminosity(e4) {
    let t2 = this.r, i2 = this.g, r2 = this.b;
    return e4 && (t2 = Math.min(255, 255 - this.a + this.a * t2 / 255), i2 = Math.min(255, 255 - this.a + this.a * i2 / 255), r2 = Math.min(255, 255 - this.a + this.a * r2 / 255)), 0.2126 * t2 + 0.7152 * i2 + 0.0722 * r2;
  }
  _loadUINT32() {
    this.uint32 = (this.a << 24 | this.b << 16 | this.g << 8 | this.r) >>> 0;
  }
  _loadRGBA() {
    this.r = 255 & this.uint32, this.g = this.uint32 >>> 8 & 255, this.b = this.uint32 >>> 16 & 255, this.a = this.uint32 >>> 24 & 255;
  }
  _loadQuadruplet() {
    this.rgba[0] = this.r, this.rgba[1] = this.g, this.rgba[2] = this.b, this.rgba[3] = this.a;
  }
}, PointContainer = class {
  constructor() {
    __publicField(this, "_pointArray"), __publicField(this, "_width"), __publicField(this, "_height"), this._width = 0, this._height = 0, this._pointArray = [];
  }
  getWidth() {
    return this._width;
  }
  getHeight() {
    return this._height;
  }
  setWidth(e4) {
    this._width = e4;
  }
  setHeight(e4) {
    this._height = e4;
  }
  getPointArray() {
    return this._pointArray;
  }
  clone() {
    const e4 = new PointContainer();
    e4._width = this._width, e4._height = this._height;
    for (let t2 = 0, i2 = this._pointArray.length; t2 < i2; t2++) e4._pointArray[t2] = Point.createByUint32(0 | this._pointArray[t2].uint32);
    return e4;
  }
  toUint32Array() {
    const e4 = this._pointArray.length, t2 = new Uint32Array(e4);
    for (let i2 = 0; i2 < e4; i2++) t2[i2] = this._pointArray[i2].uint32;
    return t2;
  }
  toUint8Array() {
    return new Uint8Array(this.toUint32Array().buffer);
  }
  static fromHTMLImageElement(e4) {
    const t2 = e4.naturalWidth, i2 = e4.naturalHeight, r2 = document.createElement("canvas");
    r2.width = t2, r2.height = i2;
    return r2.getContext("2d").drawImage(e4, 0, 0, t2, i2, 0, 0, t2, i2), PointContainer.fromHTMLCanvasElement(r2);
  }
  static fromHTMLCanvasElement(e4) {
    const t2 = e4.width, i2 = e4.height, r2 = e4.getContext("2d").getImageData(0, 0, t2, i2);
    return PointContainer.fromImageData(r2);
  }
  static fromImageData(e4) {
    const t2 = e4.width, i2 = e4.height;
    return PointContainer.fromUint8Array(e4.data, t2, i2);
  }
  static fromUint8Array(e4, t2, i2) {
    switch (Object.prototype.toString.call(e4)) {
      case "[object Uint8ClampedArray]":
      case "[object Uint8Array]":
        break;
      default:
        e4 = new Uint8Array(e4);
    }
    const r2 = new Uint32Array(e4.buffer);
    return PointContainer.fromUint32Array(r2, t2, i2);
  }
  static fromUint32Array(e4, t2, i2) {
    const r2 = new PointContainer();
    r2._width = t2, r2._height = i2;
    for (let t3 = 0, i3 = e4.length; t3 < i3; t3++) r2._pointArray[t3] = Point.createByUint32(0 | e4[t3]);
    return r2;
  }
  static fromBuffer(e4, t2, i2) {
    const r2 = new Uint32Array(e4.buffer, e4.byteOffset, e4.byteLength / Uint32Array.BYTES_PER_ELEMENT);
    return PointContainer.fromUint32Array(r2, t2, i2);
  }
}, hueGroups = 10;
function hueGroup(e4, t2) {
  const i2 = 360 / t2;
  for (let r2 = 1, n2 = i2 - i2 / 2; r2 < t2; r2++, n2 += i2) if (e4 >= n2 && e4 < n2 + i2) return r2;
  return 0;
}
var Palette = class {
  constructor() {
    __publicField(this, "_pointContainer"), __publicField(this, "_pointArray", []), __publicField(this, "_i32idx", {}), this._pointContainer = new PointContainer(), this._pointContainer.setHeight(1), this._pointArray = this._pointContainer.getPointArray();
  }
  add(e4) {
    this._pointArray.push(e4), this._pointContainer.setWidth(this._pointArray.length);
  }
  has(e4) {
    for (let t2 = this._pointArray.length - 1; t2 >= 0; t2--) if (e4.uint32 === this._pointArray[t2].uint32) return true;
    return false;
  }
  getNearestColor(e4, t2) {
    return this._pointArray[0 | this._getNearestIndex(e4, t2)];
  }
  getPointContainer() {
    return this._pointContainer;
  }
  _nearestPointFromCache(e4) {
    return "number" == typeof this._i32idx[e4] ? this._i32idx[e4] : -1;
  }
  _getNearestIndex(e4, t2) {
    let i2 = this._nearestPointFromCache("" + t2.uint32);
    if (i2 >= 0) return i2;
    let r2 = Number.MAX_VALUE;
    i2 = 0;
    for (let n2 = 0, a2 = this._pointArray.length; n2 < a2; n2++) {
      const a3 = this._pointArray[n2], o2 = e4.calculateRaw(t2.r, t2.g, t2.b, t2.a, a3.r, a3.g, a3.b, a3.a);
      o2 < r2 && (r2 = o2, i2 = n2);
    }
    return this._i32idx[t2.uint32] = i2, i2;
  }
  sort() {
    this._i32idx = {}, this._pointArray.sort((e4, t2) => {
      const i2 = rgb2hsl(e4.r, e4.g, e4.b), r2 = rgb2hsl(t2.r, t2.g, t2.b), n2 = e4.r === e4.g && e4.g === e4.b ? 0 : 1 + hueGroup(i2.h, hueGroups), a2 = (t2.r === t2.g && t2.g === t2.b ? 0 : 1 + hueGroup(r2.h, hueGroups)) - n2;
      if (a2) return -a2;
      const o2 = e4.getLuminosity(true), s2 = t2.getLuminosity(true);
      if (s2 - o2 != 0) return s2 - o2;
      const l2 = (100 * r2.s | 0) - (100 * i2.s | 0);
      return l2 ? -l2 : 0;
    });
  }
}, utils_exports = {};
__export(utils_exports, { HueStatistics: () => HueStatistics, Palette: () => Palette, Point: () => Point, PointContainer: () => PointContainer, ProgressTracker: () => ProgressTracker, arithmetic: () => arithmetic_exports });
var HueGroup = class {
  constructor() {
    __publicField(this, "num", 0), __publicField(this, "cols", []);
  }
}, HueStatistics = class {
  constructor(e4, t2) {
    __publicField(this, "_numGroups"), __publicField(this, "_minCols"), __publicField(this, "_stats"), __publicField(this, "_groupsFull"), this._numGroups = e4, this._minCols = t2, this._stats = [];
    for (let t3 = 0; t3 <= e4; t3++) this._stats[t3] = new HueGroup();
    this._groupsFull = 0;
  }
  check(e4) {
    this._groupsFull === this._numGroups + 1 && (this.check = () => {
    });
    const t2 = 255 & e4, i2 = e4 >>> 8 & 255, r2 = e4 >>> 16 & 255, n2 = t2 === i2 && i2 === r2 ? 0 : 1 + hueGroup(rgb2hsl(t2, i2, r2).h, this._numGroups), a2 = this._stats[n2], o2 = this._minCols;
    a2.num++, a2.num > o2 || (a2.num === o2 && this._groupsFull++, a2.num <= o2 && this._stats[n2].cols.push(e4));
  }
  injectIntoDictionary(e4) {
    for (let t2 = 0; t2 <= this._numGroups; t2++) this._stats[t2].num <= this._minCols && this._stats[t2].cols.forEach((t3) => {
      e4[t3] ? e4[t3]++ : e4[t3] = 1;
    });
  }
  injectIntoArray(e4) {
    for (let t2 = 0; t2 <= this._numGroups; t2++) this._stats[t2].num <= this._minCols && this._stats[t2].cols.forEach((t3) => {
      -1 === e4.indexOf(t3) && e4.push(t3);
    });
  }
}, _ProgressTracker = class {
  constructor(e4, t2) {
    __publicField(this, "progress"), __publicField(this, "_step"), __publicField(this, "_range"), __publicField(this, "_last"), __publicField(this, "_progressRange"), this._range = e4, this._progressRange = t2, this._step = Math.max(1, this._range / (_ProgressTracker.steps + 1) | 0), this._last = -this._step, this.progress = 0;
  }
  shouldNotify(e4) {
    return e4 - this._last >= this._step && (this._last = e4, this.progress = Math.min(this._progressRange * this._last / this._range, this._progressRange), true);
  }
}, ProgressTracker = _ProgressTracker;
__publicField(ProgressTracker, "steps", 100);
var networkBiasShift = 3, Neuron = class {
  constructor(e4) {
    __publicField(this, "r"), __publicField(this, "g"), __publicField(this, "b"), __publicField(this, "a"), this.r = this.g = this.b = this.a = e4;
  }
  toPoint() {
    return Point.createByRGBA(this.r >> networkBiasShift, this.g >> networkBiasShift, this.b >> networkBiasShift, this.a >> networkBiasShift);
  }
  subtract(e4, t2, i2, r2) {
    this.r -= 0 | e4, this.g -= 0 | t2, this.b -= 0 | i2, this.a -= 0 | r2;
  }
}, _NeuQuant = class extends AbstractPaletteQuantizer {
  constructor(e4, t2 = 256) {
    super(), __publicField(this, "_pointArray"), __publicField(this, "_networkSize"), __publicField(this, "_network"), __publicField(this, "_sampleFactor"), __publicField(this, "_radPower"), __publicField(this, "_freq"), __publicField(this, "_bias"), __publicField(this, "_distance"), this._distance = e4, this._pointArray = [], this._sampleFactor = 1, this._networkSize = t2, this._distance.setWhitePoint(255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift, 255 << networkBiasShift);
  }
  sample(e4) {
    this._pointArray = this._pointArray.concat(e4.getPointArray());
  }
  *quantize() {
    this._init(), yield* this._learn(), yield { palette: this._buildPalette(), progress: 100 };
  }
  _init() {
    this._freq = [], this._bias = [], this._radPower = [], this._network = [];
    for (let e4 = 0; e4 < this._networkSize; e4++) this._network[e4] = new Neuron((e4 << networkBiasShift + 8) / this._networkSize | 0), this._freq[e4] = _NeuQuant._initialBias / this._networkSize | 0, this._bias[e4] = 0;
  }
  *_learn() {
    let e4 = this._sampleFactor;
    const t2 = this._pointArray.length;
    t2 < _NeuQuant._minpicturebytes && (e4 = 1);
    const i2 = 30 + (e4 - 1) / 3 | 0, r2 = t2 / e4 | 0;
    let n2, a2 = r2 / _NeuQuant._nCycles | 0, o2 = _NeuQuant._initAlpha, s2 = (this._networkSize >> 3) * _NeuQuant._radiusBias, l2 = s2 >> _NeuQuant._radiusBiasShift;
    l2 <= 1 && (l2 = 0);
    for (let e5 = 0; e5 < l2; e5++) this._radPower[e5] = o2 * ((l2 * l2 - e5 * e5) * _NeuQuant._radBias / (l2 * l2)) >>> 0;
    n2 = t2 < _NeuQuant._minpicturebytes ? 1 : t2 % _NeuQuant._prime1 != 0 ? _NeuQuant._prime1 : t2 % _NeuQuant._prime2 != 0 ? _NeuQuant._prime2 : t2 % _NeuQuant._prime3 != 0 ? _NeuQuant._prime3 : _NeuQuant._prime4;
    const u2 = new ProgressTracker(r2, 99);
    for (let e5 = 0, h2 = 0; e5 < r2; ) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress });
      const r3 = this._pointArray[h2], c2 = r3.b << networkBiasShift, f2 = r3.g << networkBiasShift, d = r3.r << networkBiasShift, p2 = r3.a << networkBiasShift, m = this._contest(c2, f2, d, p2);
      if (this._alterSingle(o2, m, c2, f2, d, p2), 0 !== l2 && this._alterNeighbour(l2, m, c2, f2, d, p2), h2 += n2, h2 >= t2 && (h2 -= t2), e5++, 0 === a2 && (a2 = 1), e5 % a2 == 0) {
        o2 -= o2 / i2 | 0, s2 -= s2 / _NeuQuant._radiusDecrease | 0, l2 = s2 >> _NeuQuant._radiusBiasShift, l2 <= 1 && (l2 = 0);
        for (let e6 = 0; e6 < l2; e6++) this._radPower[e6] = o2 * ((l2 * l2 - e6 * e6) * _NeuQuant._radBias / (l2 * l2)) >>> 0;
      }
    }
  }
  _buildPalette() {
    const e4 = new Palette();
    return this._network.forEach((t2) => {
      e4.add(t2.toPoint());
    }), e4.sort(), e4;
  }
  _alterNeighbour(e4, t2, i2, r2, n2, a2) {
    let o2 = t2 - e4;
    o2 < -1 && (o2 = -1);
    let s2 = t2 + e4;
    s2 > this._networkSize && (s2 = this._networkSize);
    let l2 = t2 + 1, u2 = t2 - 1, h2 = 1;
    for (; l2 < s2 || u2 > o2; ) {
      const e5 = this._radPower[h2++] / _NeuQuant._alphaRadBias;
      if (l2 < s2) {
        const t3 = this._network[l2++];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
      if (u2 > o2) {
        const t3 = this._network[u2--];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
    }
  }
  _alterSingle(e4, t2, i2, r2, n2, a2) {
    e4 /= _NeuQuant._initAlpha;
    const o2 = this._network[t2];
    o2.subtract(e4 * (o2.r - n2), e4 * (o2.g - r2), e4 * (o2.b - i2), e4 * (o2.a - a2));
  }
  _contest(e4, t2, i2, r2) {
    const n2 = 1020 << networkBiasShift;
    let a2 = 2147483647, o2 = a2, s2 = -1, l2 = s2;
    for (let u2 = 0; u2 < this._networkSize; u2++) {
      const h2 = this._network[u2], c2 = this._distance.calculateNormalized(h2, { r: i2, g: t2, b: e4, a: r2 }) * n2 | 0;
      c2 < a2 && (a2 = c2, s2 = u2);
      const f2 = c2 - (this._bias[u2] >> _NeuQuant._initialBiasShift - networkBiasShift);
      f2 < o2 && (o2 = f2, l2 = u2);
      const d = this._freq[u2] >> _NeuQuant._betaShift;
      this._freq[u2] -= d, this._bias[u2] += d << _NeuQuant._gammaShift;
    }
    return this._freq[s2] += _NeuQuant._beta, this._bias[s2] -= _NeuQuant._betaGamma, l2;
  }
}, NeuQuant = _NeuQuant;
__publicField(NeuQuant, "_prime1", 499), __publicField(NeuQuant, "_prime2", 491), __publicField(NeuQuant, "_prime3", 487), __publicField(NeuQuant, "_prime4", 503), __publicField(NeuQuant, "_minpicturebytes", _NeuQuant._prime4), __publicField(NeuQuant, "_nCycles", 100), __publicField(NeuQuant, "_initialBiasShift", 16), __publicField(NeuQuant, "_initialBias", 1 << _NeuQuant._initialBiasShift), __publicField(NeuQuant, "_gammaShift", 10), __publicField(NeuQuant, "_betaShift", 10), __publicField(NeuQuant, "_beta", _NeuQuant._initialBias >> _NeuQuant._betaShift), __publicField(NeuQuant, "_betaGamma", _NeuQuant._initialBias << _NeuQuant._gammaShift - _NeuQuant._betaShift), __publicField(NeuQuant, "_radiusBiasShift", 6), __publicField(NeuQuant, "_radiusBias", 1 << _NeuQuant._radiusBiasShift), __publicField(NeuQuant, "_radiusDecrease", 30), __publicField(NeuQuant, "_alphaBiasShift", 10), __publicField(NeuQuant, "_initAlpha", 1 << _NeuQuant._alphaBiasShift), __publicField(NeuQuant, "_radBiasShift", 8), __publicField(NeuQuant, "_radBias", 1 << _NeuQuant._radBiasShift), __publicField(NeuQuant, "_alphaRadBiasShift", _NeuQuant._alphaBiasShift + _NeuQuant._radBiasShift), __publicField(NeuQuant, "_alphaRadBias", 1 << _NeuQuant._alphaRadBiasShift);
var networkBiasShift2 = 3, NeuronFloat = class {
  constructor(e4) {
    __publicField(this, "r"), __publicField(this, "g"), __publicField(this, "b"), __publicField(this, "a"), this.r = this.g = this.b = this.a = e4;
  }
  toPoint() {
    return Point.createByRGBA(this.r >> networkBiasShift2, this.g >> networkBiasShift2, this.b >> networkBiasShift2, this.a >> networkBiasShift2);
  }
  subtract(e4, t2, i2, r2) {
    this.r -= e4, this.g -= t2, this.b -= i2, this.a -= r2;
  }
}, _NeuQuantFloat = class extends AbstractPaletteQuantizer {
  constructor(e4, t2 = 256) {
    super(), __publicField(this, "_pointArray"), __publicField(this, "_networkSize"), __publicField(this, "_network"), __publicField(this, "_sampleFactor"), __publicField(this, "_radPower"), __publicField(this, "_freq"), __publicField(this, "_bias"), __publicField(this, "_distance"), this._distance = e4, this._pointArray = [], this._sampleFactor = 1, this._networkSize = t2, this._distance.setWhitePoint(255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2, 255 << networkBiasShift2);
  }
  sample(e4) {
    this._pointArray = this._pointArray.concat(e4.getPointArray());
  }
  *quantize() {
    this._init(), yield* this._learn(), yield { palette: this._buildPalette(), progress: 100 };
  }
  _init() {
    this._freq = [], this._bias = [], this._radPower = [], this._network = [];
    for (let e4 = 0; e4 < this._networkSize; e4++) this._network[e4] = new NeuronFloat((e4 << networkBiasShift2 + 8) / this._networkSize), this._freq[e4] = _NeuQuantFloat._initialBias / this._networkSize, this._bias[e4] = 0;
  }
  *_learn() {
    let e4 = this._sampleFactor;
    const t2 = this._pointArray.length;
    t2 < _NeuQuantFloat._minpicturebytes && (e4 = 1);
    const i2 = 30 + (e4 - 1) / 3, r2 = t2 / e4;
    let n2, a2 = r2 / _NeuQuantFloat._nCycles | 0, o2 = _NeuQuantFloat._initAlpha, s2 = (this._networkSize >> 3) * _NeuQuantFloat._radiusBias, l2 = s2 >> _NeuQuantFloat._radiusBiasShift;
    l2 <= 1 && (l2 = 0);
    for (let e5 = 0; e5 < l2; e5++) this._radPower[e5] = o2 * ((l2 * l2 - e5 * e5) * _NeuQuantFloat._radBias / (l2 * l2));
    n2 = t2 < _NeuQuantFloat._minpicturebytes ? 1 : t2 % _NeuQuantFloat._prime1 != 0 ? _NeuQuantFloat._prime1 : t2 % _NeuQuantFloat._prime2 != 0 ? _NeuQuantFloat._prime2 : t2 % _NeuQuantFloat._prime3 != 0 ? _NeuQuantFloat._prime3 : _NeuQuantFloat._prime4;
    const u2 = new ProgressTracker(r2, 99);
    for (let e5 = 0, h2 = 0; e5 < r2; ) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress });
      const r3 = this._pointArray[h2], c2 = r3.b << networkBiasShift2, f2 = r3.g << networkBiasShift2, d = r3.r << networkBiasShift2, p2 = r3.a << networkBiasShift2, m = this._contest(c2, f2, d, p2);
      if (this._alterSingle(o2, m, c2, f2, d, p2), 0 !== l2 && this._alterNeighbour(l2, m, c2, f2, d, p2), h2 += n2, h2 >= t2 && (h2 -= t2), e5++, 0 === a2 && (a2 = 1), e5 % a2 == 0) {
        o2 -= o2 / i2, s2 -= s2 / _NeuQuantFloat._radiusDecrease, l2 = s2 >> _NeuQuantFloat._radiusBiasShift, l2 <= 1 && (l2 = 0);
        for (let e6 = 0; e6 < l2; e6++) this._radPower[e6] = o2 * ((l2 * l2 - e6 * e6) * _NeuQuantFloat._radBias / (l2 * l2));
      }
    }
  }
  _buildPalette() {
    const e4 = new Palette();
    return this._network.forEach((t2) => {
      e4.add(t2.toPoint());
    }), e4.sort(), e4;
  }
  _alterNeighbour(e4, t2, i2, r2, n2, a2) {
    let o2 = t2 - e4;
    o2 < -1 && (o2 = -1);
    let s2 = t2 + e4;
    s2 > this._networkSize && (s2 = this._networkSize);
    let l2 = t2 + 1, u2 = t2 - 1, h2 = 1;
    for (; l2 < s2 || u2 > o2; ) {
      const e5 = this._radPower[h2++] / _NeuQuantFloat._alphaRadBias;
      if (l2 < s2) {
        const t3 = this._network[l2++];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
      if (u2 > o2) {
        const t3 = this._network[u2--];
        t3.subtract(e5 * (t3.r - n2), e5 * (t3.g - r2), e5 * (t3.b - i2), e5 * (t3.a - a2));
      }
    }
  }
  _alterSingle(e4, t2, i2, r2, n2, a2) {
    e4 /= _NeuQuantFloat._initAlpha;
    const o2 = this._network[t2];
    o2.subtract(e4 * (o2.r - n2), e4 * (o2.g - r2), e4 * (o2.b - i2), e4 * (o2.a - a2));
  }
  _contest(e4, t2, i2, r2) {
    const n2 = 1020 << networkBiasShift2;
    let a2 = 2147483647, o2 = a2, s2 = -1, l2 = s2;
    for (let u2 = 0; u2 < this._networkSize; u2++) {
      const h2 = this._network[u2], c2 = this._distance.calculateNormalized(h2, { r: i2, g: t2, b: e4, a: r2 }) * n2;
      c2 < a2 && (a2 = c2, s2 = u2);
      const f2 = c2 - (this._bias[u2] >> _NeuQuantFloat._initialBiasShift - networkBiasShift2);
      f2 < o2 && (o2 = f2, l2 = u2);
      const d = this._freq[u2] >> _NeuQuantFloat._betaShift;
      this._freq[u2] -= d, this._bias[u2] += d << _NeuQuantFloat._gammaShift;
    }
    return this._freq[s2] += _NeuQuantFloat._beta, this._bias[s2] -= _NeuQuantFloat._betaGamma, l2;
  }
}, NeuQuantFloat = _NeuQuantFloat;
__publicField(NeuQuantFloat, "_prime1", 499), __publicField(NeuQuantFloat, "_prime2", 491), __publicField(NeuQuantFloat, "_prime3", 487), __publicField(NeuQuantFloat, "_prime4", 503), __publicField(NeuQuantFloat, "_minpicturebytes", _NeuQuantFloat._prime4), __publicField(NeuQuantFloat, "_nCycles", 100), __publicField(NeuQuantFloat, "_initialBiasShift", 16), __publicField(NeuQuantFloat, "_initialBias", 1 << _NeuQuantFloat._initialBiasShift), __publicField(NeuQuantFloat, "_gammaShift", 10), __publicField(NeuQuantFloat, "_betaShift", 10), __publicField(NeuQuantFloat, "_beta", _NeuQuantFloat._initialBias >> _NeuQuantFloat._betaShift), __publicField(NeuQuantFloat, "_betaGamma", _NeuQuantFloat._initialBias << _NeuQuantFloat._gammaShift - _NeuQuantFloat._betaShift), __publicField(NeuQuantFloat, "_radiusBiasShift", 6), __publicField(NeuQuantFloat, "_radiusBias", 1 << _NeuQuantFloat._radiusBiasShift), __publicField(NeuQuantFloat, "_radiusDecrease", 30), __publicField(NeuQuantFloat, "_alphaBiasShift", 10), __publicField(NeuQuantFloat, "_initAlpha", 1 << _NeuQuantFloat._alphaBiasShift), __publicField(NeuQuantFloat, "_radBiasShift", 8), __publicField(NeuQuantFloat, "_radBias", 1 << _NeuQuantFloat._radBiasShift), __publicField(NeuQuantFloat, "_alphaRadBiasShift", _NeuQuantFloat._alphaBiasShift + _NeuQuantFloat._radBiasShift), __publicField(NeuQuantFloat, "_alphaRadBias", 1 << _NeuQuantFloat._alphaRadBiasShift);
var _ColorHistogram = class {
  constructor(e4, t2) {
    __publicField(this, "_method"), __publicField(this, "_hueStats"), __publicField(this, "_histogram"), __publicField(this, "_initColors"), __publicField(this, "_minHueCols"), this._method = e4, this._minHueCols = t2 << 2, this._initColors = t2 << 2, this._hueStats = new HueStatistics(_ColorHistogram._hueGroups, this._minHueCols), this._histogram = /* @__PURE__ */ Object.create(null);
  }
  sample(e4) {
    switch (this._method) {
      case 1:
        this._colorStats1D(e4);
        break;
      case 2:
        this._colorStats2D(e4);
    }
  }
  getImportanceSortedColorsIDXI32() {
    const e4 = stableSort(Object.keys(this._histogram), (e5, t3) => this._histogram[t3] - this._histogram[e5]);
    if (0 === e4.length) return [];
    let t2;
    switch (this._method) {
      case 1:
        const i2 = Math.min(e4.length, this._initColors), r2 = e4[i2 - 1], n2 = this._histogram[r2];
        t2 = e4.slice(0, i2);
        let a2 = i2;
        const o2 = e4.length;
        for (; a2 < o2 && this._histogram[e4[a2]] === n2; ) t2.push(e4[a2++]);
        this._hueStats.injectIntoArray(t2);
        break;
      case 2:
        t2 = e4;
        break;
      default:
        throw new Error("Incorrect method");
    }
    return t2.map((e5) => +e5);
  }
  _colorStats1D(e4) {
    const t2 = this._histogram, i2 = e4.getPointArray(), r2 = i2.length;
    for (let e5 = 0; e5 < r2; e5++) {
      const r3 = i2[e5].uint32;
      this._hueStats.check(r3), r3 in t2 ? t2[r3]++ : t2[r3] = 1;
    }
  }
  _colorStats2D(e4) {
    const t2 = e4.getWidth(), i2 = e4.getHeight(), r2 = e4.getPointArray(), n2 = _ColorHistogram._boxSize[0], a2 = _ColorHistogram._boxSize[1], o2 = n2 * a2, s2 = this._makeBoxes(t2, i2, n2, a2), l2 = this._histogram;
    s2.forEach((e5) => {
      let i3 = Math.round(e5.w * e5.h / o2) * _ColorHistogram._boxPixels;
      i3 < 2 && (i3 = 2);
      const n3 = {};
      this._iterateBox(e5, t2, (e6) => {
        const t3 = r2[e6].uint32;
        this._hueStats.check(t3), t3 in l2 ? l2[t3]++ : t3 in n3 ? ++n3[t3] >= i3 && (l2[t3] = n3[t3]) : n3[t3] = 1;
      });
    }), this._hueStats.injectIntoDictionary(l2);
  }
  _iterateBox(e4, t2, i2) {
    const r2 = e4, n2 = r2.y * t2 + r2.x, a2 = (r2.y + r2.h - 1) * t2 + (r2.x + r2.w - 1), o2 = t2 - r2.w + 1;
    let s2 = 0, l2 = n2;
    do {
      i2.call(this, l2), l2 += ++s2 % r2.w == 0 ? o2 : 1;
    } while (l2 <= a2);
  }
  _makeBoxes(e4, t2, i2, r2) {
    const n2 = e4 % i2, a2 = t2 % r2, o2 = e4 - n2, s2 = t2 - a2, l2 = [];
    for (let u2 = 0; u2 < t2; u2 += r2) for (let t3 = 0; t3 < e4; t3 += i2) l2.push({ x: t3, y: u2, w: t3 === o2 ? n2 : i2, h: u2 === s2 ? a2 : r2 });
    return l2;
  }
}, ColorHistogram = _ColorHistogram;
__publicField(ColorHistogram, "_boxSize", [64, 64]), __publicField(ColorHistogram, "_boxPixels", 2), __publicField(ColorHistogram, "_hueGroups", 10);
var RemovedColor = class {
  constructor(e4, t2, i2) {
    __publicField(this, "index"), __publicField(this, "color"), __publicField(this, "distance"), this.index = e4, this.color = t2, this.distance = i2;
  }
}, RGBQuant = class extends AbstractPaletteQuantizer {
  constructor(e4, t2 = 256, i2 = 2) {
    super(), __publicField(this, "_colors"), __publicField(this, "_initialDistance"), __publicField(this, "_distanceIncrement"), __publicField(this, "_histogram"), __publicField(this, "_distance"), this._distance = e4, this._colors = t2, this._histogram = new ColorHistogram(i2, t2), this._initialDistance = 0.01, this._distanceIncrement = 5e-3;
  }
  sample(e4) {
    this._histogram.sample(e4);
  }
  *quantize() {
    const e4 = this._histogram.getImportanceSortedColorsIDXI32();
    if (0 === e4.length) throw new Error("No colors in image");
    yield* this._buildPalette(e4);
  }
  *_buildPalette(e4) {
    const t2 = new Palette(), i2 = t2.getPointContainer().getPointArray(), r2 = new Array(e4.length);
    for (let t3 = 0; t3 < e4.length; t3++) i2.push(Point.createByUint32(e4[t3])), r2[t3] = 1;
    const n2 = i2.length, a2 = [];
    let o2 = n2, s2 = this._initialDistance;
    const l2 = new ProgressTracker(o2 - this._colors, 99);
    for (; o2 > this._colors; ) {
      a2.length = 0;
      for (let e5 = 0; e5 < n2; e5++) {
        if (l2.shouldNotify(n2 - o2) && (yield { progress: l2.progress }), 0 === r2[e5]) continue;
        const t3 = i2[e5];
        for (let l3 = e5 + 1; l3 < n2; l3++) {
          if (0 === r2[l3]) continue;
          const e6 = i2[l3], n3 = this._distance.calculateNormalized(t3, e6);
          n3 < s2 && (a2.push(new RemovedColor(l3, e6, n3)), r2[l3] = 0, o2--);
        }
      }
      s2 += o2 > 3 * this._colors ? this._initialDistance : this._distanceIncrement;
    }
    if (o2 < this._colors) {
      stableSort(a2, (e6, t3) => t3.distance - e6.distance);
      let e5 = 0;
      for (; o2 < this._colors && e5 < a2.length; ) {
        r2[a2[e5].index] = 1, o2++, e5++;
      }
    }
    let u2 = i2.length;
    for (let e5 = u2 - 1; e5 >= 0; e5--) 0 === r2[e5] && (e5 !== u2 - 1 && (i2[e5] = i2[u2 - 1]), --u2);
    i2.length = u2, t2.sort(), yield { palette: t2, progress: 100 };
  }
};
function createArray1D(e4) {
  const t2 = [];
  for (let i2 = 0; i2 < e4; i2++) t2[i2] = 0;
  return t2;
}
function createArray4D(e4, t2, i2, r2) {
  const n2 = new Array(e4);
  for (let a2 = 0; a2 < e4; a2++) {
    n2[a2] = new Array(t2);
    for (let e5 = 0; e5 < t2; e5++) {
      n2[a2][e5] = new Array(i2);
      for (let t3 = 0; t3 < i2; t3++) {
        n2[a2][e5][t3] = new Array(r2);
        for (let i3 = 0; i3 < r2; i3++) n2[a2][e5][t3][i3] = 0;
      }
    }
  }
  return n2;
}
function createArray3D(e4, t2, i2) {
  const r2 = new Array(e4);
  for (let n2 = 0; n2 < e4; n2++) {
    r2[n2] = new Array(t2);
    for (let e5 = 0; e5 < t2; e5++) {
      r2[n2][e5] = new Array(i2);
      for (let t3 = 0; t3 < i2; t3++) r2[n2][e5][t3] = 0;
    }
  }
  return r2;
}
function fillArray3D(e4, t2, i2, r2, n2) {
  for (let a2 = 0; a2 < t2; a2++) {
    e4[a2] = [];
    for (let t3 = 0; t3 < i2; t3++) {
      e4[a2][t3] = [];
      for (let i3 = 0; i3 < r2; i3++) e4[a2][t3][i3] = n2;
    }
  }
}
function fillArray1D(e4, t2, i2) {
  for (let r2 = 0; r2 < t2; r2++) e4[r2] = i2;
}
var WuColorCube = class {
  constructor() {
    __publicField(this, "redMinimum"), __publicField(this, "redMaximum"), __publicField(this, "greenMinimum"), __publicField(this, "greenMaximum"), __publicField(this, "blueMinimum"), __publicField(this, "blueMaximum"), __publicField(this, "volume"), __publicField(this, "alphaMinimum"), __publicField(this, "alphaMaximum");
  }
}, _WuQuant = class extends AbstractPaletteQuantizer {
  constructor(e4, t2 = 256, i2 = 5) {
    super(), __publicField(this, "_reds"), __publicField(this, "_greens"), __publicField(this, "_blues"), __publicField(this, "_alphas"), __publicField(this, "_sums"), __publicField(this, "_weights"), __publicField(this, "_momentsRed"), __publicField(this, "_momentsGreen"), __publicField(this, "_momentsBlue"), __publicField(this, "_momentsAlpha"), __publicField(this, "_moments"), __publicField(this, "_table"), __publicField(this, "_pixels"), __publicField(this, "_cubes"), __publicField(this, "_colors"), __publicField(this, "_significantBitsPerChannel"), __publicField(this, "_maxSideIndex"), __publicField(this, "_alphaMaxSideIndex"), __publicField(this, "_sideSize"), __publicField(this, "_alphaSideSize"), __publicField(this, "_distance"), this._distance = e4, this._setQuality(i2), this._initialize(t2);
  }
  sample(e4) {
    const t2 = e4.getPointArray();
    for (let e5 = 0, i2 = t2.length; e5 < i2; e5++) this._addColor(t2[e5]);
    this._pixels = this._pixels.concat(t2);
  }
  *quantize() {
    yield* this._preparePalette();
    const e4 = new Palette();
    for (let t2 = 0; t2 < this._colors; t2++) if (this._sums[t2] > 0) {
      const i2 = this._sums[t2], r2 = this._reds[t2] / i2, n2 = this._greens[t2] / i2, a2 = this._blues[t2] / i2, o2 = this._alphas[t2] / i2, s2 = Point.createByRGBA(0 | r2, 0 | n2, 0 | a2, 0 | o2);
      e4.add(s2);
    }
    e4.sort(), yield { palette: e4, progress: 100 };
  }
  *_preparePalette() {
    yield* this._calculateMoments();
    let e4 = 0;
    const t2 = createArray1D(this._colors);
    for (let i3 = 1; i3 < this._colors; ++i3) {
      this._cut(this._cubes[e4], this._cubes[i3]) ? (t2[e4] = this._cubes[e4].volume > 1 ? this._calculateVariance(this._cubes[e4]) : 0, t2[i3] = this._cubes[i3].volume > 1 ? this._calculateVariance(this._cubes[i3]) : 0) : (t2[e4] = 0, i3--), e4 = 0;
      let r3 = t2[0];
      for (let n3 = 1; n3 <= i3; ++n3) t2[n3] > r3 && (r3 = t2[n3], e4 = n3);
      if (r3 <= 0) {
        this._colors = i3 + 1;
        break;
      }
    }
    const i2 = [], r2 = [], n2 = [], a2 = [];
    for (let e5 = 0; e5 < this._colors; ++e5) {
      const t3 = _WuQuant._volume(this._cubes[e5], this._weights);
      t3 > 0 ? (i2[e5] = _WuQuant._volume(this._cubes[e5], this._momentsRed) / t3 | 0, r2[e5] = _WuQuant._volume(this._cubes[e5], this._momentsGreen) / t3 | 0, n2[e5] = _WuQuant._volume(this._cubes[e5], this._momentsBlue) / t3 | 0, a2[e5] = _WuQuant._volume(this._cubes[e5], this._momentsAlpha) / t3 | 0) : (i2[e5] = 0, r2[e5] = 0, n2[e5] = 0, a2[e5] = 0);
    }
    this._reds = createArray1D(this._colors + 1), this._greens = createArray1D(this._colors + 1), this._blues = createArray1D(this._colors + 1), this._alphas = createArray1D(this._colors + 1), this._sums = createArray1D(this._colors + 1);
    for (let e5 = 0, t3 = this._pixels.length; e5 < t3; e5++) {
      const t4 = this._pixels[e5];
      let o2 = -1, s2 = Number.MAX_VALUE;
      for (let e6 = 0; e6 < this._colors; e6++) {
        const l2 = i2[e6], u2 = r2[e6], h2 = n2[e6], c2 = a2[e6], f2 = this._distance.calculateRaw(l2, u2, h2, c2, t4.r, t4.g, t4.b, t4.a);
        f2 < s2 && (s2 = f2, o2 = e6);
      }
      this._reds[o2] += t4.r, this._greens[o2] += t4.g, this._blues[o2] += t4.b, this._alphas[o2] += t4.a, this._sums[o2]++;
    }
  }
  _addColor(e4) {
    const t2 = 8 - this._significantBitsPerChannel, i2 = 1 + (e4.r >> t2), r2 = 1 + (e4.g >> t2), n2 = 1 + (e4.b >> t2), a2 = 1 + (e4.a >> t2);
    this._weights[a2][i2][r2][n2]++, this._momentsRed[a2][i2][r2][n2] += e4.r, this._momentsGreen[a2][i2][r2][n2] += e4.g, this._momentsBlue[a2][i2][r2][n2] += e4.b, this._momentsAlpha[a2][i2][r2][n2] += e4.a, this._moments[a2][i2][r2][n2] += this._table[e4.r] + this._table[e4.g] + this._table[e4.b] + this._table[e4.a];
  }
  *_calculateMoments() {
    const e4 = [], t2 = [], i2 = [], r2 = [], n2 = [], a2 = [], o2 = createArray3D(this._sideSize, this._sideSize, this._sideSize), s2 = createArray3D(this._sideSize, this._sideSize, this._sideSize), l2 = createArray3D(this._sideSize, this._sideSize, this._sideSize), u2 = createArray3D(this._sideSize, this._sideSize, this._sideSize), h2 = createArray3D(this._sideSize, this._sideSize, this._sideSize), c2 = createArray3D(this._sideSize, this._sideSize, this._sideSize);
    let f2 = 0;
    const d = new ProgressTracker(this._alphaMaxSideIndex * this._maxSideIndex, 99);
    for (let p2 = 1; p2 <= this._alphaMaxSideIndex; ++p2) {
      fillArray3D(o2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D(s2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D(l2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D(u2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D(h2, this._sideSize, this._sideSize, this._sideSize, 0), fillArray3D(c2, this._sideSize, this._sideSize, this._sideSize, 0);
      for (let m = 1; m <= this._maxSideIndex; ++m, ++f2) {
        d.shouldNotify(f2) && (yield { progress: d.progress }), fillArray1D(e4, this._sideSize, 0), fillArray1D(t2, this._sideSize, 0), fillArray1D(i2, this._sideSize, 0), fillArray1D(r2, this._sideSize, 0), fillArray1D(n2, this._sideSize, 0), fillArray1D(a2, this._sideSize, 0);
        for (let f3 = 1; f3 <= this._maxSideIndex; ++f3) {
          let d2 = 0, _2 = 0, g = 0, b2 = 0, y2 = 0, w = 0;
          for (let v2 = 1; v2 <= this._maxSideIndex; ++v2) d2 += this._weights[p2][m][f3][v2], _2 += this._momentsRed[p2][m][f3][v2], g += this._momentsGreen[p2][m][f3][v2], b2 += this._momentsBlue[p2][m][f3][v2], y2 += this._momentsAlpha[p2][m][f3][v2], w += this._moments[p2][m][f3][v2], e4[v2] += d2, t2[v2] += _2, i2[v2] += g, r2[v2] += b2, n2[v2] += y2, a2[v2] += w, o2[m][f3][v2] = o2[m - 1][f3][v2] + e4[v2], s2[m][f3][v2] = s2[m - 1][f3][v2] + t2[v2], l2[m][f3][v2] = l2[m - 1][f3][v2] + i2[v2], u2[m][f3][v2] = u2[m - 1][f3][v2] + r2[v2], h2[m][f3][v2] = h2[m - 1][f3][v2] + n2[v2], c2[m][f3][v2] = c2[m - 1][f3][v2] + a2[v2], this._weights[p2][m][f3][v2] = this._weights[p2 - 1][m][f3][v2] + o2[m][f3][v2], this._momentsRed[p2][m][f3][v2] = this._momentsRed[p2 - 1][m][f3][v2] + s2[m][f3][v2], this._momentsGreen[p2][m][f3][v2] = this._momentsGreen[p2 - 1][m][f3][v2] + l2[m][f3][v2], this._momentsBlue[p2][m][f3][v2] = this._momentsBlue[p2 - 1][m][f3][v2] + u2[m][f3][v2], this._momentsAlpha[p2][m][f3][v2] = this._momentsAlpha[p2 - 1][m][f3][v2] + h2[m][f3][v2], this._moments[p2][m][f3][v2] = this._moments[p2 - 1][m][f3][v2] + c2[m][f3][v2];
        }
      }
    }
  }
  static _volumeFloat(e4, t2) {
    return t2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] - t2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - t2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + t2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - t2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] + t2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + t2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - t2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (t2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - t2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - t2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + t2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - t2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + t2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + t2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] - t2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
  }
  static _volume(e4, t2) {
    return 0 | _WuQuant._volumeFloat(e4, t2);
  }
  static _top(e4, t2, i2, r2) {
    let n2;
    switch (t2) {
      case _WuQuant._alpha:
        n2 = r2[i2][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] - r2[i2][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - r2[i2][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + r2[i2][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (r2[i2][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] - r2[i2][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - r2[i2][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + r2[i2][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
        break;
      case _WuQuant._red:
        n2 = r2[e4.alphaMaximum][i2][e4.greenMaximum][e4.blueMaximum] - r2[e4.alphaMaximum][i2][e4.greenMinimum][e4.blueMaximum] - r2[e4.alphaMinimum][i2][e4.greenMaximum][e4.blueMaximum] + r2[e4.alphaMinimum][i2][e4.greenMinimum][e4.blueMaximum] - (r2[e4.alphaMaximum][i2][e4.greenMaximum][e4.blueMinimum] - r2[e4.alphaMaximum][i2][e4.greenMinimum][e4.blueMinimum] - r2[e4.alphaMinimum][i2][e4.greenMaximum][e4.blueMinimum] + r2[e4.alphaMinimum][i2][e4.greenMinimum][e4.blueMinimum]);
        break;
      case _WuQuant._green:
        n2 = r2[e4.alphaMaximum][e4.redMaximum][i2][e4.blueMaximum] - r2[e4.alphaMaximum][e4.redMinimum][i2][e4.blueMaximum] - r2[e4.alphaMinimum][e4.redMaximum][i2][e4.blueMaximum] + r2[e4.alphaMinimum][e4.redMinimum][i2][e4.blueMaximum] - (r2[e4.alphaMaximum][e4.redMaximum][i2][e4.blueMinimum] - r2[e4.alphaMaximum][e4.redMinimum][i2][e4.blueMinimum] - r2[e4.alphaMinimum][e4.redMaximum][i2][e4.blueMinimum] + r2[e4.alphaMinimum][e4.redMinimum][i2][e4.blueMinimum]);
        break;
      case _WuQuant._blue:
        n2 = r2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][i2] - r2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][i2] - r2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][i2] + r2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][i2] - (r2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][i2] - r2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][i2] - r2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][i2] + r2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][i2]);
        break;
      default:
        throw new Error("impossible");
    }
    return 0 | n2;
  }
  static _bottom(e4, t2, i2) {
    switch (t2) {
      case _WuQuant._alpha:
        return -i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant._red:
        return -i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant._green:
        return -i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMaximum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMaximum] - (-i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      case _WuQuant._blue:
        return -i2[e4.alphaMaximum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMaximum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMaximum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum] - (-i2[e4.alphaMinimum][e4.redMaximum][e4.greenMaximum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMaximum][e4.greenMinimum][e4.blueMinimum] + i2[e4.alphaMinimum][e4.redMinimum][e4.greenMaximum][e4.blueMinimum] - i2[e4.alphaMinimum][e4.redMinimum][e4.greenMinimum][e4.blueMinimum]);
      default:
        return 0;
    }
  }
  _calculateVariance(e4) {
    const t2 = _WuQuant._volume(e4, this._momentsRed), i2 = _WuQuant._volume(e4, this._momentsGreen), r2 = _WuQuant._volume(e4, this._momentsBlue), n2 = _WuQuant._volume(e4, this._momentsAlpha);
    return _WuQuant._volumeFloat(e4, this._moments) - (t2 * t2 + i2 * i2 + r2 * r2 + n2 * n2) / _WuQuant._volume(e4, this._weights);
  }
  _maximize(e4, t2, i2, r2, n2, a2, o2, s2, l2) {
    const u2 = 0 | _WuQuant._bottom(e4, t2, this._momentsRed), h2 = 0 | _WuQuant._bottom(e4, t2, this._momentsGreen), c2 = 0 | _WuQuant._bottom(e4, t2, this._momentsBlue), f2 = 0 | _WuQuant._bottom(e4, t2, this._momentsAlpha), d = 0 | _WuQuant._bottom(e4, t2, this._weights);
    let p2 = 0, m = -1;
    for (let _2 = i2; _2 < r2; ++_2) {
      let i3 = u2 + _WuQuant._top(e4, t2, _2, this._momentsRed), r3 = h2 + _WuQuant._top(e4, t2, _2, this._momentsGreen), g = c2 + _WuQuant._top(e4, t2, _2, this._momentsBlue), b2 = f2 + _WuQuant._top(e4, t2, _2, this._momentsAlpha), y2 = d + _WuQuant._top(e4, t2, _2, this._weights);
      if (0 !== y2) {
        let e5 = i3 * i3 + r3 * r3 + g * g + b2 * b2, t3 = e5 / y2;
        i3 = n2 - i3, r3 = a2 - r3, g = o2 - g, b2 = s2 - b2, y2 = l2 - y2, 0 !== y2 && (e5 = i3 * i3 + r3 * r3 + g * g + b2 * b2, t3 += e5 / y2, t3 > p2 && (p2 = t3, m = _2));
      }
    }
    return { max: p2, position: m };
  }
  _cut(e4, t2) {
    let i2;
    const r2 = _WuQuant._volume(e4, this._momentsRed), n2 = _WuQuant._volume(e4, this._momentsGreen), a2 = _WuQuant._volume(e4, this._momentsBlue), o2 = _WuQuant._volume(e4, this._momentsAlpha), s2 = _WuQuant._volume(e4, this._weights), l2 = this._maximize(e4, _WuQuant._red, e4.redMinimum + 1, e4.redMaximum, r2, n2, a2, o2, s2), u2 = this._maximize(e4, _WuQuant._green, e4.greenMinimum + 1, e4.greenMaximum, r2, n2, a2, o2, s2), h2 = this._maximize(e4, _WuQuant._blue, e4.blueMinimum + 1, e4.blueMaximum, r2, n2, a2, o2, s2), c2 = this._maximize(e4, _WuQuant._alpha, e4.alphaMinimum + 1, e4.alphaMaximum, r2, n2, a2, o2, s2);
    if (c2.max >= l2.max && c2.max >= u2.max && c2.max >= h2.max) {
      if (i2 = _WuQuant._alpha, c2.position < 0) return false;
    } else i2 = l2.max >= c2.max && l2.max >= u2.max && l2.max >= h2.max ? _WuQuant._red : u2.max >= c2.max && u2.max >= l2.max && u2.max >= h2.max ? _WuQuant._green : _WuQuant._blue;
    switch (t2.redMaximum = e4.redMaximum, t2.greenMaximum = e4.greenMaximum, t2.blueMaximum = e4.blueMaximum, t2.alphaMaximum = e4.alphaMaximum, i2) {
      case _WuQuant._red:
        t2.redMinimum = e4.redMaximum = l2.position, t2.greenMinimum = e4.greenMinimum, t2.blueMinimum = e4.blueMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant._green:
        t2.greenMinimum = e4.greenMaximum = u2.position, t2.redMinimum = e4.redMinimum, t2.blueMinimum = e4.blueMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant._blue:
        t2.blueMinimum = e4.blueMaximum = h2.position, t2.redMinimum = e4.redMinimum, t2.greenMinimum = e4.greenMinimum, t2.alphaMinimum = e4.alphaMinimum;
        break;
      case _WuQuant._alpha:
        t2.alphaMinimum = e4.alphaMaximum = c2.position, t2.blueMinimum = e4.blueMinimum, t2.redMinimum = e4.redMinimum, t2.greenMinimum = e4.greenMinimum;
    }
    return e4.volume = (e4.redMaximum - e4.redMinimum) * (e4.greenMaximum - e4.greenMinimum) * (e4.blueMaximum - e4.blueMinimum) * (e4.alphaMaximum - e4.alphaMinimum), t2.volume = (t2.redMaximum - t2.redMinimum) * (t2.greenMaximum - t2.greenMinimum) * (t2.blueMaximum - t2.blueMinimum) * (t2.alphaMaximum - t2.alphaMinimum), true;
  }
  _initialize(e4) {
    this._colors = e4, this._cubes = [];
    for (let t2 = 0; t2 < e4; t2++) this._cubes[t2] = new WuColorCube();
    this._cubes[0].redMinimum = 0, this._cubes[0].greenMinimum = 0, this._cubes[0].blueMinimum = 0, this._cubes[0].alphaMinimum = 0, this._cubes[0].redMaximum = this._maxSideIndex, this._cubes[0].greenMaximum = this._maxSideIndex, this._cubes[0].blueMaximum = this._maxSideIndex, this._cubes[0].alphaMaximum = this._alphaMaxSideIndex, this._weights = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsRed = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsGreen = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsBlue = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._momentsAlpha = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._moments = createArray4D(this._alphaSideSize, this._sideSize, this._sideSize, this._sideSize), this._table = [];
    for (let e5 = 0; e5 < 256; ++e5) this._table[e5] = e5 * e5;
    this._pixels = [];
  }
  _setQuality(e4 = 5) {
    this._significantBitsPerChannel = e4, this._maxSideIndex = 1 << this._significantBitsPerChannel, this._alphaMaxSideIndex = this._maxSideIndex, this._sideSize = this._maxSideIndex + 1, this._alphaSideSize = this._alphaMaxSideIndex + 1;
  }
}, WuQuant = _WuQuant;
__publicField(WuQuant, "_alpha", 3), __publicField(WuQuant, "_red", 2), __publicField(WuQuant, "_green", 1), __publicField(WuQuant, "_blue", 0);
var image_exports = {};
__export(image_exports, { AbstractImageQuantizer: () => AbstractImageQuantizer, ErrorDiffusionArray: () => ErrorDiffusionArray, ErrorDiffusionArrayKernel: () => ErrorDiffusionArrayKernel, ErrorDiffusionRiemersma: () => ErrorDiffusionRiemersma, NearestColor: () => NearestColor });
var AbstractImageQuantizer = class {
  quantizeSync(e4, t2) {
    for (const i2 of this.quantize(e4, t2)) if (i2.pointContainer) return i2.pointContainer;
    throw new Error("unreachable");
  }
}, NearestColor = class extends AbstractImageQuantizer {
  constructor(e4) {
    super(), __publicField(this, "_distance"), this._distance = e4;
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = e4.getWidth(), n2 = e4.getHeight(), a2 = new ProgressTracker(n2, 99);
    for (let e5 = 0; e5 < n2; e5++) {
      a2.shouldNotify(e5) && (yield { progress: a2.progress });
      for (let n3 = 0, a3 = e5 * r2; n3 < r2; n3++, a3++) {
        const e6 = i2[a3];
        e6.from(t2.getNearestColor(this._distance, e6));
      }
    }
    yield { pointContainer: e4, progress: 100 };
  }
}, ErrorDiffusionArrayKernel = ((e4) => (e4[e4.FloydSteinberg = 0] = "FloydSteinberg", e4[e4.FalseFloydSteinberg = 1] = "FalseFloydSteinberg", e4[e4.Stucki = 2] = "Stucki", e4[e4.Atkinson = 3] = "Atkinson", e4[e4.Jarvis = 4] = "Jarvis", e4[e4.Burkes = 5] = "Burkes", e4[e4.Sierra = 6] = "Sierra", e4[e4.TwoSierra = 7] = "TwoSierra", e4[e4.SierraLite = 8] = "SierraLite", e4))(ErrorDiffusionArrayKernel || {}), ErrorDiffusionArray = class extends AbstractImageQuantizer {
  constructor(e4, t2, i2 = true, r2 = 0, n2 = false) {
    super(), __publicField(this, "_minColorDistance"), __publicField(this, "_serpentine"), __publicField(this, "_kernel"), __publicField(this, "_calculateErrorLikeGIMP"), __publicField(this, "_distance"), this._setKernel(t2), this._distance = e4, this._minColorDistance = r2, this._serpentine = i2, this._calculateErrorLikeGIMP = n2;
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = new Point(), n2 = e4.getWidth(), a2 = e4.getHeight(), o2 = [];
    let s2 = 1, l2 = 1;
    for (const e5 of this._kernel) {
      const t3 = e5[2] + 1;
      l2 < t3 && (l2 = t3);
    }
    for (let e5 = 0; e5 < l2; e5++) this._fillErrorLine(o2[e5] = [], n2);
    const u2 = new ProgressTracker(a2, 99);
    for (let e5 = 0; e5 < a2; e5++) {
      u2.shouldNotify(e5) && (yield { progress: u2.progress }), this._serpentine && (s2 *= -1);
      const l3 = e5 * n2, h2 = 1 === s2 ? 0 : n2 - 1, c2 = 1 === s2 ? n2 : -1;
      this._fillErrorLine(o2[0], n2), o2.push(o2.shift());
      const f2 = o2[0];
      for (let u3 = h2, d = l3 + h2; u3 !== c2; u3 += s2, d += s2) {
        const l4 = i2[d], h3 = f2[u3];
        r2.from(l4);
        const c3 = Point.createByRGBA(inRange0to255Rounded(l4.r + h3[0]), inRange0to255Rounded(l4.g + h3[1]), inRange0to255Rounded(l4.b + h3[2]), inRange0to255Rounded(l4.a + h3[3])), p2 = t2.getNearestColor(this._distance, c3);
        if (l4.from(p2), this._minColorDistance) {
          if (this._distance.calculateNormalized(r2, p2) < this._minColorDistance) continue;
        }
        let m, _2, g, b2;
        this._calculateErrorLikeGIMP ? (m = c3.r - p2.r, _2 = c3.g - p2.g, g = c3.b - p2.b, b2 = c3.a - p2.a) : (m = r2.r - p2.r, _2 = r2.g - p2.g, g = r2.b - p2.b, b2 = r2.a - p2.a);
        const y2 = 1 === s2 ? 0 : this._kernel.length - 1, w = 1 === s2 ? this._kernel.length : -1;
        for (let t3 = y2; t3 !== w; t3 += s2) {
          const i3 = this._kernel[t3][1] * s2, r3 = this._kernel[t3][2];
          if (i3 + u3 >= 0 && i3 + u3 < n2 && r3 + e5 >= 0 && r3 + e5 < a2) {
            const e6 = this._kernel[t3][0], n3 = o2[r3][i3 + u3];
            n3[0] += m * e6, n3[1] += _2 * e6, n3[2] += g * e6, n3[3] += b2 * e6;
          }
        }
      }
    }
    yield { pointContainer: e4, progress: 100 };
  }
  _fillErrorLine(e4, t2) {
    e4.length > t2 && (e4.length = t2);
    const i2 = e4.length;
    for (let t3 = 0; t3 < i2; t3++) {
      const i3 = e4[t3];
      i3[0] = i3[1] = i3[2] = i3[3] = 0;
    }
    for (let r2 = i2; r2 < t2; r2++) e4[r2] = [0, 0, 0, 0];
  }
  _setKernel(e4) {
    switch (e4) {
      case 0:
        this._kernel = [[7 / 16, 1, 0], [3 / 16, -1, 1], [5 / 16, 0, 1], [1 / 16, 1, 1]];
        break;
      case 1:
        this._kernel = [[3 / 8, 1, 0], [3 / 8, 0, 1], [2 / 8, 1, 1]];
        break;
      case 2:
        this._kernel = [[8 / 42, 1, 0], [4 / 42, 2, 0], [2 / 42, -2, 1], [4 / 42, -1, 1], [8 / 42, 0, 1], [4 / 42, 1, 1], [2 / 42, 2, 1], [1 / 42, -2, 2], [2 / 42, -1, 2], [4 / 42, 0, 2], [2 / 42, 1, 2], [1 / 42, 2, 2]];
        break;
      case 3:
        this._kernel = [[1 / 8, 1, 0], [1 / 8, 2, 0], [1 / 8, -1, 1], [1 / 8, 0, 1], [1 / 8, 1, 1], [1 / 8, 0, 2]];
        break;
      case 4:
        this._kernel = [[7 / 48, 1, 0], [5 / 48, 2, 0], [3 / 48, -2, 1], [5 / 48, -1, 1], [7 / 48, 0, 1], [5 / 48, 1, 1], [3 / 48, 2, 1], [1 / 48, -2, 2], [3 / 48, -1, 2], [5 / 48, 0, 2], [3 / 48, 1, 2], [1 / 48, 2, 2]];
        break;
      case 5:
        this._kernel = [[0.25, 1, 0], [4 / 32, 2, 0], [2 / 32, -2, 1], [4 / 32, -1, 1], [0.25, 0, 1], [4 / 32, 1, 1], [2 / 32, 2, 1]];
        break;
      case 6:
        this._kernel = [[5 / 32, 1, 0], [3 / 32, 2, 0], [2 / 32, -2, 1], [4 / 32, -1, 1], [5 / 32, 0, 1], [4 / 32, 1, 1], [2 / 32, 2, 1], [2 / 32, -1, 2], [3 / 32, 0, 2], [2 / 32, 1, 2]];
        break;
      case 7:
        this._kernel = [[0.25, 1, 0], [3 / 16, 2, 0], [1 / 16, -2, 1], [2 / 16, -1, 1], [3 / 16, 0, 1], [2 / 16, 1, 1], [1 / 16, 2, 1]];
        break;
      case 8:
        this._kernel = [[0.5, 1, 0], [1 / 4, -1, 1], [1 / 4, 0, 1]];
        break;
      default:
        throw new Error(`ErrorDiffusionArray: unknown kernel = ${e4}`);
    }
  }
};
function* hilbertCurve(e4, t2, i2) {
  const r2 = Math.max(e4, t2), n2 = { width: e4, height: t2, level: Math.floor(Math.log(r2) / Math.log(2) + 1), callback: i2, tracker: new ProgressTracker(e4 * t2, 99), index: 0, x: 0, y: 0 };
  yield* walkHilbert(n2, 1), visit(n2, 0);
}
function* walkHilbert(e4, t2) {
  if (!(e4.level < 1)) {
    switch (e4.tracker.shouldNotify(e4.index) && (yield { progress: e4.tracker.progress }), e4.level--, t2) {
      case 2:
        yield* walkHilbert(e4, 1), visit(e4, 3), yield* walkHilbert(e4, 2), visit(e4, 4), yield* walkHilbert(e4, 2), visit(e4, 2), yield* walkHilbert(e4, 4);
        break;
      case 3:
        yield* walkHilbert(e4, 4), visit(e4, 2), yield* walkHilbert(e4, 3), visit(e4, 1), yield* walkHilbert(e4, 3), visit(e4, 3), yield* walkHilbert(e4, 1);
        break;
      case 1:
        yield* walkHilbert(e4, 2), visit(e4, 4), yield* walkHilbert(e4, 1), visit(e4, 3), yield* walkHilbert(e4, 1), visit(e4, 1), yield* walkHilbert(e4, 3);
        break;
      case 4:
        yield* walkHilbert(e4, 3), visit(e4, 1), yield* walkHilbert(e4, 4), visit(e4, 2), yield* walkHilbert(e4, 4), visit(e4, 4), yield* walkHilbert(e4, 2);
    }
    e4.level++;
  }
}
function visit(e4, t2) {
  switch (e4.x >= 0 && e4.x < e4.width && e4.y >= 0 && e4.y < e4.height && (e4.callback(e4.x, e4.y), e4.index++), t2) {
    case 2:
      e4.x--;
      break;
    case 3:
      e4.x++;
      break;
    case 1:
      e4.y--;
      break;
    case 4:
      e4.y++;
  }
}
var ErrorDiffusionRiemersma = class extends AbstractImageQuantizer {
  constructor(e4, t2 = 16, i2 = 1) {
    super(), __publicField(this, "_distance"), __publicField(this, "_weights"), __publicField(this, "_errorQueueSize"), this._distance = e4, this._errorQueueSize = t2, this._weights = ErrorDiffusionRiemersma._createWeights(i2, t2);
  }
  *quantize(e4, t2) {
    const i2 = e4.getPointArray(), r2 = e4.getWidth(), n2 = e4.getHeight(), a2 = [];
    let o2 = 0;
    for (let e5 = 0; e5 < this._errorQueueSize; e5++) a2[e5] = { r: 0, g: 0, b: 0, a: 0 };
    yield* hilbertCurve(r2, n2, (e5, n3) => {
      const s2 = i2[e5 + n3 * r2];
      let { r: l2, g: u2, b: h2, a: c2 } = s2;
      for (let e6 = 0; e6 < this._errorQueueSize; e6++) {
        const t3 = this._weights[e6], i3 = a2[(e6 + o2) % this._errorQueueSize];
        l2 += i3.r * t3, u2 += i3.g * t3, h2 += i3.b * t3, c2 += i3.a * t3;
      }
      const f2 = Point.createByRGBA(inRange0to255Rounded(l2), inRange0to255Rounded(u2), inRange0to255Rounded(h2), inRange0to255Rounded(c2)), d = t2.getNearestColor(this._distance, f2);
      o2 = (o2 + 1) % this._errorQueueSize;
      const p2 = (o2 + this._errorQueueSize - 1) % this._errorQueueSize;
      a2[p2].r = s2.r - d.r, a2[p2].g = s2.g - d.g, a2[p2].b = s2.b - d.b, a2[p2].a = s2.a - d.a, s2.from(d);
    }), yield { pointContainer: e4, progress: 100 };
  }
  static _createWeights(e4, t2) {
    const i2 = [], r2 = Math.exp(Math.log(t2) / (t2 - 1));
    for (let n2 = 0, a2 = 1; n2 < t2; n2++) i2[n2] = (a2 + 0.5 | 0) / t2 * e4, a2 *= r2;
    return i2;
  }
}, quality_exports = {};
__export(quality_exports, { ssim: () => ssim });
var K1 = 0.01, K2 = 0.03;
function ssim(e4, t2) {
  if (e4.getHeight() !== t2.getHeight() || e4.getWidth() !== t2.getWidth()) throw new Error("Images have different sizes!");
  const i2 = (255 * K1) ** 2, r2 = (255 * K2) ** 2;
  let n2 = 0, a2 = 0;
  return iterate(e4, t2, (e5, t3, o2, s2) => {
    let l2 = 0, u2 = 0, h2 = 0;
    for (let i3 = 0; i3 < e5.length; i3++) u2 += (e5[i3] - o2) ** 2, h2 += (t3[i3] - s2) ** 2, l2 += (e5[i3] - o2) * (t3[i3] - s2);
    const c2 = e5.length - 1;
    u2 /= c2, h2 /= c2, l2 /= c2;
    a2 += (2 * o2 * s2 + i2) * (2 * l2 + r2) / ((o2 ** 2 + s2 ** 2 + i2) * (u2 + h2 + r2)), n2++;
  }), a2 / n2;
}
function iterate(e4, t2, i2) {
  const r2 = e4.getWidth(), n2 = e4.getHeight();
  for (let a2 = 0; a2 < n2; a2 += 8) for (let o2 = 0; o2 < r2; o2 += 8) {
    const s2 = Math.min(8, r2 - o2), l2 = Math.min(8, n2 - a2), u2 = calculateLumaValuesForWindow(e4, o2, a2, s2, l2), h2 = calculateLumaValuesForWindow(t2, o2, a2, s2, l2);
    i2(u2, h2, calculateAverageLuma(u2), calculateAverageLuma(h2));
  }
}
function calculateLumaValuesForWindow(e4, t2, i2, r2, n2) {
  const a2 = e4.getPointArray(), o2 = [];
  let s2 = 0;
  for (let l2 = i2; l2 < i2 + n2; l2++) {
    const i3 = l2 * e4.getWidth();
    for (let e5 = t2; e5 < t2 + r2; e5++) {
      const t3 = a2[i3 + e5];
      o2[s2] = 0.2126 * t3.r + 0.7152 * t3.g + 0.0722 * t3.b, s2++;
    }
  }
  return o2;
}
function calculateAverageLuma(e4) {
  let t2 = 0;
  for (const i2 of e4) t2 += i2;
  return t2 / e4.length;
}
function buildPaletteSync(e4, { colorDistanceFormula: t2, paletteQuantization: i2, colors: r2 } = {}) {
  const n2 = paletteQuantizationToPaletteQuantizer(colorDistanceFormulaToColorDistance(t2), i2, r2);
  return e4.forEach((e5) => n2.sample(e5)), n2.quantizeSync();
}
function applyPaletteSync(e4, t2, { colorDistanceFormula: i2, imageQuantization: r2 } = {}) {
  return imageQuantizationToImageQuantizer(colorDistanceFormulaToColorDistance(i2), r2).quantizeSync(e4, t2);
}
function colorDistanceFormulaToColorDistance(e4 = "euclidean-bt709") {
  switch (e4) {
    case "cie94-graphic-arts":
      return new CIE94GraphicArts();
    case "cie94-textiles":
      return new CIE94Textiles();
    case "ciede2000":
      return new CIEDE2000();
    case "color-metric":
      return new CMetric();
    case "euclidean":
      return new Euclidean();
    case "euclidean-bt709":
      return new EuclideanBT709();
    case "euclidean-bt709-noalpha":
      return new EuclideanBT709NoAlpha();
    case "manhattan":
      return new Manhattan();
    case "manhattan-bt709":
      return new ManhattanBT709();
    case "manhattan-nommyde":
      return new ManhattanNommyde();
    case "pngquant":
      return new PNGQuant();
    default:
      throw new Error(`Unknown colorDistanceFormula ${e4}`);
  }
}
function imageQuantizationToImageQuantizer(e4, t2 = "floyd-steinberg") {
  switch (t2) {
    case "nearest":
      return new NearestColor(e4);
    case "riemersma":
      return new ErrorDiffusionRiemersma(e4);
    case "floyd-steinberg":
      return new ErrorDiffusionArray(e4, 0);
    case "false-floyd-steinberg":
      return new ErrorDiffusionArray(e4, 1);
    case "stucki":
      return new ErrorDiffusionArray(e4, 2);
    case "atkinson":
      return new ErrorDiffusionArray(e4, 3);
    case "jarvis":
      return new ErrorDiffusionArray(e4, 4);
    case "burkes":
      return new ErrorDiffusionArray(e4, 5);
    case "sierra":
      return new ErrorDiffusionArray(e4, 6);
    case "two-sierra":
      return new ErrorDiffusionArray(e4, 7);
    case "sierra-lite":
      return new ErrorDiffusionArray(e4, 8);
    default:
      throw new Error(`Unknown imageQuantization ${t2}`);
  }
}
function paletteQuantizationToPaletteQuantizer(e4, t2 = "wuquant", i2 = 256) {
  switch (t2) {
    case "neuquant":
      return new NeuQuant(e4, i2);
    case "rgbquant":
      return new RGBQuant(e4, i2);
    case "wuquant":
      return new WuQuant(e4, i2);
    case "neuquant-float":
      return new NeuQuantFloat(e4, i2);
    default:
      throw new Error(`Unknown paletteQuantization ${t2}`);
  }
}
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * cie94.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * ciede2000.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * cmetric.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * common.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * constants.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * ditherErrorDiffusionArray.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * euclidean.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * helper.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * hueStatistics.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * iq.ts - Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * lab2rgb.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * lab2xyz.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * manhattanNeuQuant.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * nearestColor.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * palette.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * pngQuant.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * point.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * pointContainer.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * rgb2hsl.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * rgb2lab.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * rgb2xyz.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * ssim.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * wuQuant.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * xyz2lab.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * xyz2rgb.ts - part of Image Quantization Library
 */
/**
 * @preserve
 * MIT License
 *
 * Copyright 2015-2018 Igor Bezkrovnyi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * riemersma.ts - part of Image Quantization Library
 */
/**
 * @preserve TypeScript port:
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * colorHistogram.ts - part of Image Quantization Library
 */
/**
 * @preserve TypeScript port:
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * neuquant.ts - part of Image Quantization Library
 */
/**
 * @preserve TypeScript port:
 * Copyright 2015-2018 Igor Bezkrovnyi
 * All rights reserved. (MIT Licensed)
 *
 * rgbquant.ts - part of Image Quantization Library
 */
"function" == typeof setImmediate ? setImmediate : "undefined" != typeof process && (null == process || process.nextTick);
const QuantizeOptionsSchema = z.object({ colors: z.number().optional(), colorDistanceFormula: z.union([z.literal("cie94-textiles"), z.literal("cie94-graphic-arts"), z.literal("ciede2000"), z.literal("color-metric"), z.literal("euclidean"), z.literal("euclidean-bt709-noalpha"), z.literal("euclidean-bt709"), z.literal("manhattan"), z.literal("manhattan-bt709"), z.literal("manhattan-nommyde"), z.literal("pngquant")]).optional(), paletteQuantization: z.union([z.literal("neuquant"), z.literal("neuquant-float"), z.literal("rgbquant"), z.literal("wuquant")]).optional(), imageQuantization: z.union([z.literal("nearest"), z.literal("riemersma"), z.literal("floyd-steinberg"), z.literal("false-floyd-steinberg"), z.literal("stucki"), z.literal("atkinson"), z.literal("jarvis"), z.literal("burkes"), z.literal("sierra"), z.literal("two-sierra"), z.literal("sierra-lite")]).optional() }), methods = { quantize(e4, t2) {
  const { colors: i2, colorDistanceFormula: r2, paletteQuantization: n2, imageQuantization: a2 } = QuantizeOptionsSchema.parse(t2), o2 = utils_exports.PointContainer.fromUint8Array(e4.bitmap.data, e4.bitmap.width, e4.bitmap.height), s2 = applyPaletteSync(o2, buildPaletteSync([o2], { colors: i2, colorDistanceFormula: r2, paletteQuantization: n2 }), { colorDistanceFormula: r2, imageQuantization: a2 });
  return e4.bitmap.data = Buffer$1.from(s2.toUint8Array()), e4;
} };
var parseBmfontAscii = function(e4) {
  if (!e4) throw new Error("no data provided");
  var t2 = { pages: [], chars: [], kernings: [] }, i2 = (e4 = e4.toString().trim()).split(/\r\n?|\n/g);
  if (0 === i2.length) throw new Error("no data in BMFont file");
  for (var r2 = 0; r2 < i2.length; r2++) {
    var n2 = splitLine(i2[r2], r2);
    if (n2) if ("page" === n2.key) {
      if ("number" != typeof n2.data.id) throw new Error("malformed file at line " + r2 + " -- needs page id=N");
      if ("string" != typeof n2.data.file) throw new Error("malformed file at line " + r2 + ' -- needs page file="path"');
      t2.pages[n2.data.id] = n2.data.file;
    } else "chars" === n2.key || "kernings" === n2.key || ("char" === n2.key ? t2.chars.push(n2.data) : "kerning" === n2.key ? t2.kernings.push(n2.data) : t2[n2.key] = n2.data);
  }
  return t2;
};
function splitLine(e4, t2) {
  if (!(e4 = e4.replace(/\t+/g, " ").trim())) return null;
  var i2 = e4.indexOf(" ");
  if (-1 === i2) throw new Error("no named row at line " + t2);
  var r2 = e4.substring(0, i2);
  e4 = (e4 = (e4 = (e4 = e4.substring(i2 + 1)).replace(/letter=[\'\"]\S+[\'\"]/gi, "")).split("=")).map(function(e5) {
    return e5.trim().match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g);
  });
  for (var n2 = [], a2 = 0; a2 < e4.length; a2++) {
    var o2 = e4[a2];
    0 === a2 ? n2.push({ key: o2[0], data: "" }) : a2 === e4.length - 1 ? n2[n2.length - 1].data = parseData(o2[0]) : (n2[n2.length - 1].data = parseData(o2[0]), n2.push({ key: o2[1], data: "" }));
  }
  var s2 = { key: r2, data: {} };
  return n2.forEach(function(e5) {
    s2.data[e5.key] = e5.data;
  }), s2;
}
function parseData(e4) {
  return e4 && 0 !== e4.length ? 0 === e4.indexOf('"') || 0 === e4.indexOf("'") ? e4.substring(1, e4.length - 1) : -1 !== e4.indexOf(",") ? parseIntList$1(e4) : parseInt(e4, 10) : "";
}
function parseIntList$1(e4) {
  return e4.split(",").map(function(e5) {
    return parseInt(e5, 10);
  });
}
getDefaultExportFromCjs(parseBmfontAscii);
var GLYPH_DESIGNER_ERROR = "chasrset", parseAttribs = function(e4) {
  for (var t2 in e4 = Object.assign({}, e4), GLYPH_DESIGNER_ERROR in e4 && (e4.charset = e4[GLYPH_DESIGNER_ERROR], delete e4[GLYPH_DESIGNER_ERROR]), e4) "face" !== t2 && "charset" !== t2 && (e4[t2] = "padding" === t2 || "spacing" === t2 ? parseIntList(e4[t2]) : parseInt(e4[t2], 10));
  return e4;
};
function parseIntList(e4) {
  return e4.split(",").map(function(e5) {
    return parseInt(e5, 10);
  });
}
var xmlParseFromString = void 0 !== self.DOMParser ? function(e4) {
  return new self.DOMParser().parseFromString(e4, "application/xml");
} : void 0 !== self.ActiveXObject && new self.ActiveXObject("Microsoft.XMLDOM") ? function(e4) {
  var t2 = new self.ActiveXObject("Microsoft.XMLDOM");
  return t2.async = "false", t2.loadXML(e4), t2;
} : function(e4) {
  var t2 = document.createElement("div");
  return t2.innerHTML = e4, t2;
}, parseAttributes = parseAttribs, parseFromString = xmlParseFromString, NAME_MAP = { scaleh: "scaleH", scalew: "scaleW", stretchh: "stretchH", lineheight: "lineHeight", alphachnl: "alphaChnl", redchnl: "redChnl", greenchnl: "greenChnl", bluechnl: "blueChnl" }, browser = function(e4) {
  e4 = e4.toString();
  var t2 = parseFromString(e4), i2 = { pages: [], chars: [], kernings: [] };
  ["info", "common"].forEach(function(e5) {
    var r3 = t2.getElementsByTagName(e5)[0];
    r3 && (i2[e5] = parseAttributes(getAttribs(r3)));
  });
  var r2 = t2.getElementsByTagName("pages")[0];
  if (!r2) throw new Error("malformed file -- no <pages> element");
  for (var n2 = r2.getElementsByTagName("page"), a2 = 0; a2 < n2.length; a2++) {
    var o2 = n2[a2], s2 = parseInt(o2.getAttribute("id"), 10), l2 = o2.getAttribute("file");
    if (isNaN(s2)) throw new Error('malformed file -- page "id" attribute is NaN');
    if (!l2) throw new Error('malformed file -- needs page "file" attribute');
    i2.pages[parseInt(s2, 10)] = l2;
  }
  return ["chars", "kernings"].forEach(function(e5) {
    var r3 = t2.getElementsByTagName(e5)[0];
    if (r3) for (var n3 = e5.substring(0, e5.length - 1), a3 = r3.getElementsByTagName(n3), o3 = 0; o3 < a3.length; o3++) {
      var s3 = a3[o3];
      i2[e5].push(parseAttributes(getAttribs(s3)));
    }
  }), i2;
};
function getAttribs(e4) {
  return getAttribList(e4).reduce(function(e5, t2) {
    return e5[mapName(t2.nodeName)] = t2.nodeValue, e5;
  }, {});
}
function getAttribList(e4) {
  for (var t2 = [], i2 = 0; i2 < e4.attributes.length; i2++) t2.push(e4.attributes[i2]);
  return t2;
}
function mapName(e4) {
  return NAME_MAP[e4.toLowerCase()] || e4;
}
getDefaultExportFromCjs(browser);
var HEADER$1 = [66, 77, 70], parseBmfontBinary = function(e4) {
  if (e4.length < 6) throw new Error("invalid buffer length for BMFont");
  var t2 = HEADER$1.every(function(t3, i3) {
    return e4.readUInt8(i3) === t3;
  });
  if (!t2) throw new Error("BMFont missing BMF byte header");
  var i2 = 3;
  if (e4.readUInt8(i2++) > 3) throw new Error("Only supports BMFont Binary v3 (BMFont App v1.10)");
  for (var r2 = { kernings: [], chars: [] }, n2 = 0; n2 < 5; n2++) i2 += readBlock(r2, e4, i2);
  return r2;
};
function readBlock(e4, t2, i2) {
  if (i2 > t2.length - 1) return 0;
  var r2 = t2.readUInt8(i2++), n2 = t2.readInt32LE(i2);
  switch (i2 += 4, r2) {
    case 1:
      e4.info = readInfo(t2, i2);
      break;
    case 2:
      e4.common = readCommon(t2, i2);
      break;
    case 3:
      e4.pages = readPages(t2, i2, n2);
      break;
    case 4:
      e4.chars = readChars(t2, i2, n2);
      break;
    case 5:
      e4.kernings = readKernings(t2, i2, n2);
  }
  return 5 + n2;
}
function readInfo(e4, t2) {
  var i2 = {};
  i2.size = e4.readInt16LE(t2);
  var r2 = e4.readUInt8(t2 + 2);
  return i2.smooth = r2 >> 7 & 1, i2.unicode = r2 >> 6 & 1, i2.italic = r2 >> 5 & 1, i2.bold = r2 >> 4 & 1, r2 >> 3 & 1 && (i2.fixedHeight = 1), i2.charset = e4.readUInt8(t2 + 3) || "", i2.stretchH = e4.readUInt16LE(t2 + 4), i2.aa = e4.readUInt8(t2 + 6), i2.padding = [e4.readInt8(t2 + 7), e4.readInt8(t2 + 8), e4.readInt8(t2 + 9), e4.readInt8(t2 + 10)], i2.spacing = [e4.readInt8(t2 + 11), e4.readInt8(t2 + 12)], i2.outline = e4.readUInt8(t2 + 13), i2.face = readStringNT(e4, t2 + 14), i2;
}
function readCommon(e4, t2) {
  var i2 = {};
  return i2.lineHeight = e4.readUInt16LE(t2), i2.base = e4.readUInt16LE(t2 + 2), i2.scaleW = e4.readUInt16LE(t2 + 4), i2.scaleH = e4.readUInt16LE(t2 + 6), i2.pages = e4.readUInt16LE(t2 + 8), e4.readUInt8(t2 + 10), i2.packed = 0, i2.alphaChnl = e4.readUInt8(t2 + 11), i2.redChnl = e4.readUInt8(t2 + 12), i2.greenChnl = e4.readUInt8(t2 + 13), i2.blueChnl = e4.readUInt8(t2 + 14), i2;
}
function readPages(e4, t2, i2) {
  for (var r2 = [], n2 = readNameNT(e4, t2), a2 = n2.length + 1, o2 = i2 / a2, s2 = 0; s2 < o2; s2++) r2[s2] = e4.slice(t2, t2 + n2.length).toString("utf8"), t2 += a2;
  return r2;
}
function readChars(e4, t2, i2) {
  for (var r2 = [], n2 = i2 / 20, a2 = 0; a2 < n2; a2++) {
    var o2 = {}, s2 = 20 * a2;
    o2.id = e4.readUInt32LE(t2 + 0 + s2), o2.x = e4.readUInt16LE(t2 + 4 + s2), o2.y = e4.readUInt16LE(t2 + 6 + s2), o2.width = e4.readUInt16LE(t2 + 8 + s2), o2.height = e4.readUInt16LE(t2 + 10 + s2), o2.xoffset = e4.readInt16LE(t2 + 12 + s2), o2.yoffset = e4.readInt16LE(t2 + 14 + s2), o2.xadvance = e4.readInt16LE(t2 + 16 + s2), o2.page = e4.readUInt8(t2 + 18 + s2), o2.chnl = e4.readUInt8(t2 + 19 + s2), r2[a2] = o2;
  }
  return r2;
}
function readKernings(e4, t2, i2) {
  for (var r2 = [], n2 = i2 / 10, a2 = 0; a2 < n2; a2++) {
    var o2 = {}, s2 = 10 * a2;
    o2.first = e4.readUInt32LE(t2 + 0 + s2), o2.second = e4.readUInt32LE(t2 + 4 + s2), o2.amount = e4.readInt16LE(t2 + 8 + s2), r2[a2] = o2;
  }
  return r2;
}
function readNameNT(e4, t2) {
  for (var i2 = t2; i2 < e4.length && 0 !== e4[i2]; i2++) ;
  return e4.slice(t2, i2);
}
function readStringNT(e4, t2) {
  return readNameNT(e4, t2).toString("utf8");
}
getDefaultExportFromCjs(parseBmfontBinary);
function e(e4) {
  return e4 && e4.__esModule && Object.prototype.hasOwnProperty.call(e4, "default") ? e4.default : e4;
}
const t$1 = (e4) => {
  if (!e4) return null;
  const i2 = {};
  switch (e4.type) {
    case "ELEMENT": {
      let n2 = {};
      const a2 = E(e4.value.attributes), o2 = t$1(e4.value.children);
      if (a2 && (n2 = Object.assign(n2, a2)), o2) {
        const t2 = r(e4.value.children);
        n2 = Object.assign(n2, t2);
      }
      i2[e4.value.type] = n2;
      break;
    }
    case "ATTRIBUTE": {
      const t2 = e4.value;
      i2[t2.name] = t2.value;
      break;
    }
    case "CONTENT":
      return { content: e4.value };
  }
  return i2;
}, r = (e4) => e4 && Array.isArray(e4) && 0 !== e4.length ? n(e4) ? { content: e4[0].value } : { children: e4.map(t$1) } : null, n = (e4) => e4 && Array.isArray(e4) && 1 === e4.length && "CONTENT" === e4[0].type, E = (e4) => e4 && Array.isArray(e4) ? e4.map(t$1).reduce((e5, t2) => Object.assign(e5, t2), {}) : null;
var s = { convert: (e4) => t$1(e4.value.children[0]) }, a = { Token: (e4, t2) => ({ type: e4, value: t2 }), TOKEN_TYPE: { OPEN_BRACKET: "OPEN_BRACKET", ELEMENT_TYPE: "ELEMENT_TYPE", CLOSE_ELEMENT: "CLOSE_ELEMENT", ATTRIB_NAME: "ATTRIB_NAME", ATTRIB_VALUE: "ATTRIB_VALUE", ASSIGN: "ASSIGN", CLOSE_BRACKET: "CLOSE_BRACKET", CONTENT: "CONTENT", EOF: "EOF" } };
const { Token: T, TOKEN_TYPE: u } = a, c = T("EOF"), l = (e4) => " " === e4 || "\n" === e4 || "\r" === e4 || "	" === e4, o = (e4) => e4.replace(/'/g, '"');
var N = { createLexer: function(e4) {
  let t2 = null, i2 = ((e5) => {
    let t3 = 0;
    for (; t3 < e5.length && l(e5[t3]); ) t3++;
    return ((e6, t4) => {
      if (e6.startsWith("<?xml", t4)) {
        const i3 = e6.length;
        for (; t4 < i3; ) if ("?" !== e6[t4]) t4++;
        else {
          if (">" === e6[t4 + 1]) return t4 + 2;
          t4++;
        }
      }
      return t4;
    })(e5, t3);
  })(e4), r2 = [];
  const n2 = () => e4[i2], a2 = () => t2 !== c && i2 < e4.length, s2 = (e5) => '"' === e5 || "'" === e5, h2 = () => {
    for (; a2() && l(e4[i2]); ) i2++;
  }, f2 = (t3) => {
    if (a2()) {
      if ("<" === e4[i2]) {
        let t4 = "<";
        return i2++, a2() && "/" === e4[i2] ? (i2++, t4 = "</") : a2() && "!" === e4[i2] && "-" === e4[i2 + 1] && "-" === e4[i2 + 2] && (i2++, i2++, i2++, t4 = "<!--"), t4;
      }
      if ("/" === n2()) {
        let e5 = "/";
        return i2++, a2() && ">" === n2() && (i2++, e5 = "/>"), e5;
      }
      if ("=" === e4[i2] || ">" === e4[i2]) {
        const t4 = e4[i2];
        return i2++, t4;
      }
    }
    return d(!!t3);
  }, d = (t3) => {
    const r3 = t3 ? /[^>=<]/u : /[a-zA-Z0-9_:-]/;
    let n3 = i2;
    for (; a2() && e4[i2].match(r3); ) i2++;
    return o(e4.substring(n3, i2));
  }, p2 = () => {
    const l2 = i2;
    h2();
    const m = i2 - l2;
    if (a2()) if (t2 && t2.type === u.OPEN_BRACKET) {
      h2();
      const e5 = f2(false);
      t2 = T(u.ELEMENT_TYPE, e5), r2.push(e5);
    } else if (t2 && t2.type === u.ASSIGN) {
      a2() && s2(n2()) && i2++;
      let r3 = i2;
      for (; a2() && !s2(n2()); ) i2++;
      const l3 = o(e4.substring(r3, i2));
      i2++, t2 = T(u.ATTRIB_VALUE, l3);
    } else {
      h2();
      let o2 = f2(true);
      switch (o2) {
        case "=":
          t2 = t2.type === u.ATTRIB_NAME ? T(u.ASSIGN) : T(u.CONTENT, o2);
          break;
        case "</": {
          const n3 = i2;
          for (; ">" !== e4[i2]; ) i2++;
          t2 = T(u.CLOSE_ELEMENT, e4.substring(n3, i2)), i2++, r2.pop();
          break;
        }
        case "/>": {
          const e5 = r2.pop();
          t2 = T(u.CLOSE_ELEMENT, e5);
          break;
        }
        case "<!--": {
          const t3 = ["!", "-", "-"];
          for (; a2() && (">" !== t3[2] || "-" !== t3[1] || "-" !== t3[0]); ) t3.shift(), t3.push(e4[i2]), i2++;
          return p2();
        }
        case ">":
          t2 = T(u.CLOSE_BRACKET);
          break;
        case "<":
          t2 = T(u.OPEN_BRACKET);
          break;
        default:
          if (o2 && o2.length > 0) {
            if (t2.type === u.CLOSE_BRACKET) {
              let e5 = "";
              "<" !== n2() && (e5 = d(true)), t2 = T(u.CONTENT, o2 + e5);
            } else if (t2.type !== u.ATTRIB_NAME && t2.type !== u.CONTENT) t2.type === u.CLOSE_ELEMENT ? (o2 = " ".repeat(m) + o2, t2 = T(u.CONTENT, o2)) : t2 = T(u.ATTRIB_NAME, o2);
            else {
              const e5 = " ".repeat(m) + o2;
              t2 = T(u.CONTENT, e5);
            }
            break;
          }
          {
            const t3 = 'Unknown Syntax : "' + e4[i2] + '"';
            throw new Error(t3);
          }
      }
    }
    else t2 = c;
    return t2;
  };
  return { peek: n2, next: p2, hasNext: a2 };
} };
const { createLexer: i } = N, { Token: p, TOKEN_TYPE: O } = a, [A, f, C, h] = ["ROOT", "ELEMENT", "ATTRIBUTE", "CONTENT"], _ = (e4, t2) => ({ type: e4, value: t2 }), L = (e4) => _(h, e4), y = (e4, t2, i2) => _(f, { type: e4, attributes: t2, children: i2 }), v = (e4, t2) => _(C, { name: e4, value: t2 }), S = (e4, t2) => {
  const i2 = [];
  for (; e4.hasNext(); ) {
    const r2 = e4.next();
    switch (r2.type) {
      case O.OPEN_BRACKET: {
        const t3 = e4.next(), [r3, n2] = R(e4);
        let a2 = [];
        n2.type !== O.CLOSE_ELEMENT && (a2 = S(e4, t3)), a2 && a2.length > 0 && a2[0].type === O.CONTENT && (a2 = b(a2)), i2.push(y(t3.value, r3, a2));
        break;
      }
      case O.CLOSE_ELEMENT:
        if (r2.value === t2.value) return i2;
        break;
      case O.CONTENT:
        i2.push(L(r2.value));
        break;
      case O.EOF:
        return i2;
      default:
        throw new Error(`Unknown Lexem type: ${r2.type} "${r2.value}, scoping element: ${t2.value}"`);
    }
  }
  return i2;
}, R = (e4) => {
  const t2 = [];
  let i2 = e4.peek();
  if (!e4.hasNext() || i2 && i2.type === O.CLOSE_BRACKET || i2 && i2.type === O.CLOSE_ELEMENT) return [t2, i2];
  for (i2 = e4.next(); e4.hasNext() && i2 && i2.type !== O.CLOSE_BRACKET && i2.type !== O.CLOSE_ELEMENT; ) {
    const r2 = i2;
    e4.next();
    const n2 = e4.next(), a2 = v(r2.value, n2.value);
    t2.push(a2), i2 = e4.next();
  }
  return [t2, i2];
};
function b(e4) {
  let t2 = [], i2 = "";
  return e4.forEach((e5) => {
    e5.type === O.CONTENT ? i2 += e5.value : (i2.length && (t2.push(L(i2)), i2 = ""), t2.push(e5));
  }), i2.length && t2.push(L(i2)), t2;
}
var B = { transpile: function(e4, t2) {
  const r2 = ((e5) => _(A, { children: S(e5, p(A, "ROOT")) }))(i(e4));
  return t2 ? t2.convert(r2) : r2;
} };
const M = s, { transpile: x } = B;
var k = e({ convertXML: function(e4, t2) {
  return x(e4, t2 || M);
}, createAST: function(e4) {
  return x(e4);
} }), simpleXmlToJson_min = k, xmlPackage = getDefaultExportFromCjs(simpleXmlToJson_min);
const { convertXML } = xmlPackage;
createJimp({ formats: [png] });
Buffer$1.from([66, 77, 70, 3]);
var pixelmatch_1 = pixelmatch;
const defaultOptions$1 = { threshold: 0.1, includeAA: false, alpha: 0.1, aaColor: [255, 255, 0], diffColor: [255, 0, 0], diffColorAlt: null, diffMask: false };
function pixelmatch(e4, t2, i2, r2, n2, a2) {
  if (!isPixelData(e4) || !isPixelData(t2) || i2 && !isPixelData(i2)) throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");
  if (e4.length !== t2.length || i2 && i2.length !== e4.length) throw new Error("Image sizes do not match.");
  if (e4.length !== r2 * n2 * 4) throw new Error("Image data size does not match width/height.");
  a2 = Object.assign({}, defaultOptions$1, a2);
  const o2 = r2 * n2, s2 = new Uint32Array(e4.buffer, e4.byteOffset, o2), l2 = new Uint32Array(t2.buffer, t2.byteOffset, o2);
  let u2 = true;
  for (let e5 = 0; e5 < o2; e5++) if (s2[e5] !== l2[e5]) {
    u2 = false;
    break;
  }
  if (u2) {
    if (i2 && !a2.diffMask) for (let t3 = 0; t3 < o2; t3++) drawGrayPixel(e4, 4 * t3, a2.alpha, i2);
    return 0;
  }
  const h2 = 35215 * a2.threshold * a2.threshold;
  let c2 = 0;
  for (let o3 = 0; o3 < n2; o3++) for (let s3 = 0; s3 < r2; s3++) {
    const l3 = 4 * (o3 * r2 + s3), u3 = colorDelta(e4, t2, l3, l3);
    Math.abs(u3) > h2 ? a2.includeAA || !antialiased(e4, s3, o3, r2, n2, t2) && !antialiased(t2, s3, o3, r2, n2, e4) ? (i2 && drawPixel(i2, l3, ...u3 < 0 && a2.diffColorAlt || a2.diffColor), c2++) : i2 && !a2.diffMask && drawPixel(i2, l3, ...a2.aaColor) : i2 && (a2.diffMask || drawGrayPixel(e4, l3, a2.alpha, i2));
  }
  return c2;
}
function isPixelData(e4) {
  return ArrayBuffer.isView(e4) && 1 === e4.constructor.BYTES_PER_ELEMENT;
}
function antialiased(e4, t2, i2, r2, n2, a2) {
  const o2 = Math.max(t2 - 1, 0), s2 = Math.max(i2 - 1, 0), l2 = Math.min(t2 + 1, r2 - 1), u2 = Math.min(i2 + 1, n2 - 1), h2 = 4 * (i2 * r2 + t2);
  let c2, f2, d, p2, m = t2 === o2 || t2 === l2 || i2 === s2 || i2 === u2 ? 1 : 0, _2 = 0, g = 0;
  for (let n3 = o2; n3 <= l2; n3++) for (let a3 = s2; a3 <= u2; a3++) {
    if (n3 === t2 && a3 === i2) continue;
    const o3 = colorDelta(e4, e4, h2, 4 * (a3 * r2 + n3), true);
    if (0 === o3) {
      if (m++, m > 2) return false;
    } else o3 < _2 ? (_2 = o3, c2 = n3, f2 = a3) : o3 > g && (g = o3, d = n3, p2 = a3);
  }
  return 0 !== _2 && 0 !== g && (hasManySiblings(e4, c2, f2, r2, n2) && hasManySiblings(a2, c2, f2, r2, n2) || hasManySiblings(e4, d, p2, r2, n2) && hasManySiblings(a2, d, p2, r2, n2));
}
function hasManySiblings(e4, t2, i2, r2, n2) {
  const a2 = Math.max(t2 - 1, 0), o2 = Math.max(i2 - 1, 0), s2 = Math.min(t2 + 1, r2 - 1), l2 = Math.min(i2 + 1, n2 - 1), u2 = 4 * (i2 * r2 + t2);
  let h2 = t2 === a2 || t2 === s2 || i2 === o2 || i2 === l2 ? 1 : 0;
  for (let n3 = a2; n3 <= s2; n3++) for (let a3 = o2; a3 <= l2; a3++) {
    if (n3 === t2 && a3 === i2) continue;
    const o3 = 4 * (a3 * r2 + n3);
    if (e4[u2] === e4[o3] && e4[u2 + 1] === e4[o3 + 1] && e4[u2 + 2] === e4[o3 + 2] && e4[u2 + 3] === e4[o3 + 3] && h2++, h2 > 2) return true;
  }
  return false;
}
function colorDelta(e4, t2, i2, r2, n2) {
  let a2 = e4[i2 + 0], o2 = e4[i2 + 1], s2 = e4[i2 + 2], l2 = e4[i2 + 3], u2 = t2[r2 + 0], h2 = t2[r2 + 1], c2 = t2[r2 + 2], f2 = t2[r2 + 3];
  if (l2 === f2 && a2 === u2 && o2 === h2 && s2 === c2) return 0;
  l2 < 255 && (l2 /= 255, a2 = blend(a2, l2), o2 = blend(o2, l2), s2 = blend(s2, l2)), f2 < 255 && (f2 /= 255, u2 = blend(u2, f2), h2 = blend(h2, f2), c2 = blend(c2, f2));
  const d = rgb2y(a2, o2, s2), p2 = rgb2y(u2, h2, c2), m = d - p2;
  if (n2) return m;
  const _2 = rgb2i(a2, o2, s2) - rgb2i(u2, h2, c2), g = rgb2q(a2, o2, s2) - rgb2q(u2, h2, c2), b2 = 0.5053 * m * m + 0.299 * _2 * _2 + 0.1957 * g * g;
  return d > p2 ? -b2 : b2;
}
function rgb2y(e4, t2, i2) {
  return 0.29889531 * e4 + 0.58662247 * t2 + 0.11448223 * i2;
}
function rgb2i(e4, t2, i2) {
  return 0.59597799 * e4 - 0.2741761 * t2 - 0.32180189 * i2;
}
function rgb2q(e4, t2, i2) {
  return 0.21147017 * e4 - 0.52261711 * t2 + 0.31114694 * i2;
}
function blend(e4, t2) {
  return 255 + (e4 - 255) * t2;
}
function drawPixel(e4, t2, i2, r2, n2) {
  e4[t2 + 0] = i2, e4[t2 + 1] = r2, e4[t2 + 2] = n2, e4[t2 + 3] = 255;
}
function drawGrayPixel(e4, t2, i2, r2) {
  const n2 = blend(rgb2y(e4[t2 + 0], e4[t2 + 1], e4[t2 + 2]), i2 * e4[t2 + 3] / 255);
  drawPixel(r2, t2, n2, n2, n2);
}
getDefaultExportFromCjs(pixelmatch_1);
const defaultPlugins = [methods$h, methods$g, methods$f, methods$e, methods$c, methods$a, methods$b, methods$9, methods$8, methods$7, methods$6, methods$5, methods$4, methods$3, methods$d, methods$2, methods$1, methods], defaultFormats = [bmp, msBmp, gif, jpeg$2, png, tiff], JimpMime = { bmp: bmp().mime, gif: gif().mime, jpeg: jpeg$2().mime, png: png().mime, tiff: tiff().mime }, Jimp = createJimp({ formats: defaultFormats, plugins: defaultPlugins });
const IMAGE_EXTENSIONS = [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"];
const VIDEO_EXTENSIONS = [".mp4", ".avi", ".mov", ".mkv", ".webm", ".flv", ".wmv"];
const EXTENSION_TO_MIME = {
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
  ".gif": "image/gif",
  ".bmp": "image/bmp",
  ".webp": "image/webp",
  ".tif": "image/tiff",
  ".tiff": "image/tiff",
  ".svg": "image/svg+xml",
  ".mp4": "video/mp4",
  ".avi": "video/x-msvideo",
  ".mov": "video/quicktime",
  ".mkv": "video/x-matroska",
  ".webm": "video/webm",
  ".flv": "video/x-flv",
  ".wmv": "video/x-ms-wmv"
};
const MIME_TO_EXTENSION = Object.entries(EXTENSION_TO_MIME).reduce(
  (acc, [ext, mime2]) => {
    if (!acc[mime2]) {
      acc[mime2] = ext;
    }
    return acc;
  },
  {}
);
function encodeSvgData(svg) {
  if (typeof btoa === "function") {
    return btoa(svg);
  }
  return bufferExports.Buffer.from(svg, "utf8").toString("base64");
}
function buildGenericFileThumbnail(extension) {
  return "data:image/svg+xml;base64," + encodeSvgData(`
      <svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
        <rect width="320" height="320" fill="#e0e0e0"/>
        <rect x="80" y="80" width="160" height="160" fill="white" stroke="#ccc" stroke-width="2"/>
        <text x="160" y="160" text-anchor="middle" font-family="Arial" font-size="16" fill="#666">File</text>
        <text x="160" y="180" text-anchor="middle" font-family="Arial" font-size="12" fill="#999">${extension}</text>
      </svg>
    `);
}
function buildVideoThumbnail() {
  return "data:image/svg+xml;base64," + encodeSvgData(`
      <svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
        <rect width="320" height="320" fill="#000" opacity="0.8"/>
        <circle cx="160" cy="160" r="50" fill="white" opacity="0.9"/>
        <polygon points="140,130 140,190 190,160" fill="black"/>
        <text x="160" y="220" text-anchor="middle" font-family="Arial" font-size="14" fill="white">Video</text>
      </svg>
    `);
}
function normaliseExtension(value) {
  if (!value) return void 0;
  const trimmed = value.trim();
  if (!trimmed) return void 0;
  return trimmed.startsWith(".") ? trimmed.toLowerCase() : `.${trimmed.toLowerCase()}`;
}
function mimeFromExtension(extension) {
  const normalised = normaliseExtension(extension);
  if (!normalised) {
    return "application/octet-stream";
  }
  return EXTENSION_TO_MIME[normalised] ?? "application/octet-stream";
}
function isImageExtension(extension) {
  const normalised = normaliseExtension(extension);
  if (!normalised) return false;
  return IMAGE_EXTENSIONS.includes(normalised);
}
function extensionFromMime(mime2) {
  if (!mime2) return void 0;
  return MIME_TO_EXTENSION[mime2.toLowerCase()] ?? void 0;
}
const DEFAULT_FILE_PREFIX = "downloaded_file";
function sanitizeFileName(input) {
  if (!input) {
    return DEFAULT_FILE_PREFIX;
  }
  const trimmed = input.trim();
  if (!trimmed) {
    return DEFAULT_FILE_PREFIX;
  }
  const withoutExtension = trimmed.includes(".") ? trimmed.slice(0, trimmed.lastIndexOf(".")) : trimmed;
  const sanitized = withoutExtension.replace(/[/\\?%*:|"<>]/g, "_").replace(/\s+/g, "_").replace(/_+/g, "_").replace(/^_+/, "").replace(/_+$/, "");
  return sanitized || DEFAULT_FILE_PREFIX;
}
function registerCreateFromExternalAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction(
    "fileResource.createFromExternal",
    async (params) => {
      try {
        const { url, fileName } = params;
        const localFileSystem = uxp.storage.localFileSystem;
        const tempFolder = await localFileSystem.getTemporaryFolder();
        let buffer2;
        let extension = ".png";
        let mimeType = "application/octet-stream";
        let isImageMime = false;
        if (url.startsWith("data:")) {
          const match = url.match(/^data:([^;]+)(;base64)?,(.*)$/);
          if (!match) {
            throw new Error("Invalid data URL");
          }
          const mime2 = match[1].toLowerCase();
          const isBase64 = !!match[2];
          const dataPart = match[3];
          const inferredExt = extensionFromMime(mime2) ?? ".png";
          extension = inferredExt;
          isImageMime = mime2.startsWith("image/");
          mimeType = mime2;
          buffer2 = isBase64 ? bufferExports.Buffer.from(dataPart, "base64") : bufferExports.Buffer.from(decodeURIComponent(dataPart), "utf8");
        } else {
          const urlObj = new URL(url);
          const pathname = urlObj.pathname;
          const lastDotIndex = pathname.lastIndexOf(".");
          extension = lastDotIndex > -1 ? pathname.substring(lastDotIndex).toLowerCase() : ".png";
          const filename = urlObj.searchParams.get("filename");
          if (filename) {
            const filenameDotIndex = filename.lastIndexOf(".");
            if (filenameDotIndex > -1) {
              extension = filename.substring(filenameDotIndex).toLowerCase();
            }
          }
          const response = await fetch(url);
          if (!response.ok) {
            throw new Error(`Failed to download file: ${response.status} ${response.statusText}`);
          }
          const arrayBuffer = await response.arrayBuffer();
          buffer2 = bufferExports.Buffer.from(arrayBuffer);
          isImageMime = isImageExtension(extension);
          if (isImageMime) {
            mimeType = mimeFromExtension(extension);
          } else {
            mimeType = response.headers.get("content-type") || "application/octet-stream";
          }
        }
        const timestamp = Date.now();
        const randomSuffix = Math.random().toString(36).substring(2, 8);
        const sanitizedBase = sanitizeFileName(fileName);
        const finalFilename = `${sanitizedBase}_${timestamp}_${randomSuffix}${extension}`;
        const tempFile = await tempFolder.createFile(finalFilename, { overwrite: true });
        await tempFile.write(new Uint8Array(buffer2), { format: uxp.storage.formats.binary });
        let thumbnailBase64;
        let imgWidth;
        let imgHeight;
        if (isImageExtension(extension) || isImageMime) {
          try {
            const image = await Jimp.read(buffer2);
            imgWidth = image.width;
            imgHeight = image.height;
            image.scaleToFit({ w: 320, h: 320 });
            const thumbnailBuffer = await image.getBuffer(JimpMime.png);
            thumbnailBase64 = "data:image/png;base64," + thumbnailBuffer.toString("base64");
          } catch (error) {
            thumbnailBase64 = buildGenericFileThumbnail(extension);
          }
        } else if (VIDEO_EXTENSIONS.includes(extension)) {
          thumbnailBase64 = buildVideoThumbnail();
        } else {
          thumbnailBase64 = buildGenericFileThumbnail(extension);
        }
        const resourceId = createResource({
          type: "file",
          data: {
            buffer: new Uint8Array(buffer2),
            mime: mimeType,
            path: tempFile.nativePath
          },
          originalMeta: {
            url,
            fileName: finalFilename,
            width: imgWidth,
            height: imgHeight,
            extension
          }
        });
        updateResource(resourceId, {
          thumbnailCache: {
            base64: thumbnailBase64,
            width: imgWidth,
            height: imgHeight,
            mime: "image/png",
            generatedAt: Date.now()
          }
        });
        return {
          resource: resourceId,
          width: imgWidth,
          height: imgHeight,
          mimeType
        };
      } catch (error) {
        return { error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error) };
      }
    }
  );
}
function registerDeleteDownloadedImageAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("fileResource.delete", async (params) => {
    try {
      const { resources } = params;
      const localFileSystem = uxp.storage.localFileSystem;
      const tempFolder = await localFileSystem.getTemporaryFolder();
      for (const resourceId of resources) {
        if (typeof resourceId !== "string") continue;
        const entry = isResourceId(resourceId) ? resolveResource(resourceId) : void 0;
        if (entry == null ? void 0 : entry.data.path) {
          try {
            const nativePath = String(entry.data.path);
            if (nativePath.includes(tempFolder.nativePath)) {
              const relativePath = nativePath.replace(tempFolder.nativePath, "").replace(/^[\\/\\]/, "");
              const file = await tempFolder.getEntry(relativePath);
              await (file == null ? void 0 : file.delete());
            }
          } catch {
          }
        }
        if (isResourceId(resourceId)) {
          deleteResource(resourceId);
        }
      }
      return {};
    } catch (error) {
      return {
        error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error)
      };
    }
  });
}
function registerThumbnailAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("fileResource.thumbnail", async (params) => {
    try {
      const { resource, maxSize = 192 } = params;
      if (typeof resource !== "string" || !resource.length) {
        throw new Error("fileResource.thumbnail: resource is required");
      }
      if (!isResourceId(resource)) {
        throw new Error("fileResource.thumbnail: invalid resource id");
      }
      const entry = resolveResource(resource);
      if (!entry) {
        throw new Error("fileResource.thumbnail: resource not found");
      }
      const cached = getResourceThumbnail(resource);
      if ((cached == null ? void 0 : cached.buffer) || (cached == null ? void 0 : cached.base64)) {
        const base642 = cached.base64 ?? "data:" + (cached.mime ?? "image/png") + ";base64," + bufferExports.Buffer.from(cached.buffer ?? new Uint8Array()).toString("base64");
        if (!cached.base64 && cached.buffer) {
          setResourceThumbnail(resource, {
            buffer: cached.buffer,
            width: cached.width,
            height: cached.height,
            originalWidth: cached.originalWidth,
            originalHeight: cached.originalHeight,
            mime: cached.mime
          });
        }
        return {
          thumbnail: base642,
          width: cached.originalWidth ?? cached.width,
          height: cached.originalHeight ?? cached.height
        };
      }
      const { buffer: buffer2 } = await resolveResourceBuffer(resource);
      const image = await Jimp.read(bufferExports.Buffer.from(buffer2));
      const origW = image.width;
      const origH = image.height;
      image.scaleToFit({ w: maxSize, h: maxSize });
      const thumbnailBuffer = await image.getBuffer(JimpMime.png);
      setResourceThumbnail(resource, {
        buffer: new Uint8Array(thumbnailBuffer),
        width: image.width,
        height: image.height,
        originalWidth: origW,
        originalHeight: origH,
        mime: "image/png"
      });
      const base64 = "data:image/png;base64," + bufferExports.Buffer.from(thumbnailBuffer).toString("base64");
      return {
        thumbnail: base64,
        width: origW,
        height: origH
      };
    } catch (error) {
      return { error: (error == null ? void 0 : error.message) || String(error) };
    }
  });
}
function registerSaveAsAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("fileResource.saveAs", async (params) => {
    var _a3;
    try {
      const { resources = [] } = params;
      const localFileSystem = uxp.storage.localFileSystem;
      const tempFolder = await localFileSystem.getTemporaryFolder();
      let saveFolder;
      try {
        saveFolder = await localFileSystem.getFolder();
      } catch (error) {
        const message = ((error == null ? void 0 : error.message) || "").toLowerCase();
        if (message.includes("cancel")) {
          return { error: "cancelled" };
        }
        throw error;
      }
      for (const resourceId of resources) {
        if (typeof resourceId !== "string") continue;
        try {
          const ensuredPath = isResourceId(resourceId) ? await ensureResourceTempFile(resourceId).catch(() => void 0) : void 0;
          if (!ensuredPath) {
            continue;
          }
          const nativePath = String(ensuredPath);
          if (nativePath.includes(tempFolder.nativePath)) {
            const relativePath = nativePath.replace(tempFolder.nativePath, "").replace(/^[\\/\\]/, "");
            const tempFile = await tempFolder.getEntry(relativePath);
            if (!tempFile) {
              continue;
            }
            const fileName = tempFile.name;
            const arrayBuffer2 = await tempFile.read({ format: uxp.storage.formats.binary });
            const saveFile2 = await saveFolder.createFile(fileName, { overwrite: true });
            await saveFile2.write(arrayBuffer2, { format: uxp.storage.formats.binary });
            continue;
          }
          const entryUrl = nativePath.startsWith("file://") ? nativePath : `file://${nativePath}`;
          const fileEntry = await localFileSystem.getEntryWithUrl(entryUrl);
          if (!fileEntry) {
            continue;
          }
          const resourceEntry = isResourceId(resourceId) ? resolveResource(resourceId) : void 0;
          const fallbackName = typeof ((_a3 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _a3.fileName) === "string" ? String(resourceEntry.originalMeta.fileName) : fileEntry.name || `resource-${Date.now()}`;
          const arrayBuffer = await fileEntry.read({ format: uxp.storage.formats.binary });
          const saveFile = await saveFolder.createFile(fallbackName, { overwrite: true });
          await saveFile.write(arrayBuffer, { format: uxp.storage.formats.binary });
        } catch {
        }
      }
      return {};
    } catch (error) {
      return {
        error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error)
      };
    }
  });
}
function toUint8Array$1(buffer2) {
  return buffer2 instanceof Uint8Array ? buffer2 : new Uint8Array(buffer2);
}
function isVideoExtension(extension) {
  const normalised = normaliseExtension(extension);
  if (!normalised) return false;
  return VIDEO_EXTENSIONS.includes(normalised);
}
function normalizeName(input) {
  if (!input) return void 0;
  const trimmed = input.trim();
  if (!trimmed) return void 0;
  const lower = trimmed.toLowerCase();
  if (lower === "undefined" || lower === "null") return void 0;
  return trimmed;
}
function normalizeExtensionValue(value) {
  if (typeof value !== "string") return void 0;
  const normalized = normaliseExtension(value);
  if (!normalized) return void 0;
  if (normalized === ".undefined" || normalized === ".null") return void 0;
  return normalized;
}
function extensionFromName$1(name) {
  const normalized = normalizeName(name);
  if (!normalized) return void 0;
  const dot = normalized.lastIndexOf(".");
  if (dot === -1) return void 0;
  return normalizeExtensionValue(normalized.slice(dot));
}
function normalizeNativePath(value) {
  if (typeof value !== "string") return void 0;
  const trimmed = value.trim();
  if (!trimmed) return void 0;
  const lower = trimmed.toLowerCase();
  if (lower === "undefined" || lower === "null") {
    return void 0;
  }
  return trimmed;
}
function sanitizeAcceptRecord(value) {
  if (!value || typeof value !== "object") return void 0;
  const result = {};
  for (const [mime2, extensions] of Object.entries(value)) {
    if (typeof mime2 !== "string" || !Array.isArray(extensions)) continue;
    const sanitized = extensions.map(normalizeExtensionValue).filter((ext) => Boolean(ext));
    if (!sanitized.length) continue;
    const trimmedMime = mime2.trim();
    if (!trimmedMime) continue;
    result[trimmedMime] = sanitized;
  }
  return Object.keys(result).length ? result : void 0;
}
async function materializeViaSystemDialog(params) {
  const pickerOptions = {
    allowMultiple: (params == null ? void 0 : params.multiple) ?? false
  };
  const sanitizeTypes = (types) => {
    const extensionsSet = /* @__PURE__ */ new Set();
    const acceptMap = {};
    if (!Array.isArray(types)) {
      return { extensions: extensionsSet, accept: acceptMap };
    }
    const pickerTypes2 = types.map((type2) => {
      if (!type2 || typeof type2 !== "object") return null;
      const description2 = typeof type2.description === "string" && type2.description.trim().length ? type2.description.trim() : void 0;
      const extensions = Array.isArray(type2.extensions) ? type2.extensions.map(normalizeExtensionValue).filter((ext) => Boolean(ext)) : [];
      const accept = sanitizeAcceptRecord(type2.accept);
      if (!extensions.length && !accept) {
        return null;
      }
      extensions.forEach((ext) => extensionsSet.add(ext));
      if (accept) {
        for (const [mime2, extensionList] of Object.entries(accept)) {
          if (!acceptMap[mime2]) {
            acceptMap[mime2] = [...extensionList];
          } else {
            for (const ext of extensionList) {
              if (!acceptMap[mime2].includes(ext)) {
                acceptMap[mime2].push(ext);
              }
            }
          }
        }
      }
      return {
        description: description2,
        extensions,
        ...accept ? { accept } : {}
      };
    }).filter(
      (entry) => Boolean(entry)
    );
    return {
      extensions: extensionsSet,
      accept: acceptMap,
      pickerTypes: pickerTypes2.length ? pickerTypes2 : void 0
    };
  };
  const { extensions: allowedExtensions, pickerTypes } = sanitizeTypes(params == null ? void 0 : params.types);
  const allowedExtensionsArray = Array.from(allowedExtensions);
  const entries = await uxp.storage.localFileSystem.getFileForOpening(pickerOptions);
  if (!entries) {
    throw new Error("cancelled");
  }
  const files = Array.isArray(entries) ? entries : [entries];
  if (!files.length) {
    throw new Error("cancelled");
  }
  return Promise.all(
    files.map(async (file) => {
      const name = normalizeName(file.name) ?? "local-file";
      const extension = extensionFromName$1(name);
      if (allowedExtensionsArray.length && (!extension || !allowedExtensions.has(extension))) {
        throw new Error(`Unsupported file type: ${extension ?? "unknown"}`);
      }
      const mime2 = mimeFromExtension(extension);
      const arrayBuffer = await file.read({ format: uxp.storage.formats.binary });
      return {
        buffer: toUint8Array$1(arrayBuffer),
        mime: mime2,
        name,
        meta: {
          nativePath: normalizeNativePath(file.nativePath)
        }
      };
    })
  );
}
function registerCreateFromLocalAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction(
    "fileResource.createFromLocal",
    async (params = {}) => {
      var _a3, _b2, _c2;
      try {
        const payloads = await materializeViaSystemDialog(params);
        const results = [];
        for (const payload of payloads) {
          try {
            const buffer2 = toUint8Array$1(payload.buffer);
            let extension = extensionFromName$1(payload.name);
            if (!extension && payload.mime) {
              extension = extensionFromMime(payload.mime);
            }
            const mime2 = payload.mime ?? mimeFromExtension(extension);
            let thumbnailBase64 = payload.thumbnail;
            let imgWidth = payload.width;
            let imgHeight = payload.height;
            if (!thumbnailBase64) {
              if (isImageExtension(extension)) {
                try {
                  const image = await Jimp.read(bufferExports.Buffer.from(buffer2));
                  imgWidth = imgWidth ?? image.width;
                  imgHeight = imgHeight ?? image.height;
                  image.scaleToFit({ w: 320, h: 320 });
                  const thumbnailBuffer = await image.getBuffer(JimpMime.png);
                  thumbnailBase64 = "data:image/png;base64," + thumbnailBuffer.toString("base64");
                } catch {
                  thumbnailBase64 = buildGenericFileThumbnail(extension ?? "");
                }
              } else if (isVideoExtension(extension)) {
                thumbnailBase64 = buildVideoThumbnail();
              } else {
                thumbnailBase64 = buildGenericFileThumbnail(extension ?? "");
              }
            }
            const resourceId = createResource({
              type: "file",
              data: {
                buffer: buffer2,
                mime: mime2,
                path: (_a3 = payload.meta) == null ? void 0 : _a3.nativePath
              },
              originalMeta: {
                fileName: payload.name,
                width: imgWidth,
                height: imgHeight,
                ...payload.meta
              }
            });
            if (thumbnailBase64) {
              updateResource(resourceId, {
                thumbnailCache: {
                  base64: thumbnailBase64,
                  width: imgWidth,
                  height: imgHeight,
                  mime: "image/png",
                  generatedAt: Date.now()
                }
              });
            }
            results.push({
              resource: resourceId,
              thumbnail: thumbnailBase64,
              width: imgWidth,
              height: imgHeight,
              mime: mime2,
              nativePath: normalizeNativePath((_b2 = payload.meta) == null ? void 0 : _b2.nativePath)
            });
          } catch (fileError) {
            results.push({
              resource: null,
              error: (fileError == null ? void 0 : fileError.message) || String(fileError),
              nativePath: normalizeNativePath((_c2 = payload.meta) == null ? void 0 : _c2.nativePath)
            });
          }
        }
        const successful = results.filter((entry) => entry.resource && !entry.error);
        if (!successful.length) {
          return results[0] ?? { resource: null, error: "no-successful-resource" };
        }
        const [primary, ...rest] = successful;
        if (!rest.length) {
          return primary;
        }
        return {
          ...primary,
          batch: successful
        };
      } catch (error) {
        const message = ((error == null ? void 0 : error.message) || String(error)).toLowerCase();
        if (message.includes("cancel")) {
          return { error: "cancelled" };
        }
        return { error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error) };
      }
    }
  );
}
function toUint8Array(value) {
  if (value instanceof Uint8Array) {
    return value;
  }
  if (ArrayBuffer.isView(value)) {
    return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
  }
  return new Uint8Array(value);
}
function normaliseBuffer(source) {
  if (typeof source === "string") {
    const trimmed = source.trim();
    if (trimmed.startsWith("data:")) {
      const match = trimmed.match(/^data:([^;,]*)(;base64)?,(.*)$/s);
      if (!match) {
        throw new Error("invalid-data-url");
      }
      const [, mime2 = "", base64Flag, data2] = match;
      const payload = base64Flag ? bufferExports.Buffer.from(data2, "base64") : bufferExports.Buffer.from(decodeURIComponent(data2), "utf8");
      return {
        buffer: new Uint8Array(payload),
        mimeFromDataUrl: mime2 || void 0
      };
    }
    try {
      const bin = bufferExports.Buffer.from(trimmed, "base64");
      if (!bin.length && trimmed.length) {
        const utf8 = bufferExports.Buffer.from(trimmed, "utf8");
        return { buffer: new Uint8Array(utf8) };
      }
      return { buffer: new Uint8Array(bin) };
    } catch {
      const fallback = bufferExports.Buffer.from(trimmed, "utf8");
      return { buffer: new Uint8Array(fallback) };
    }
  }
  if (source instanceof Uint8Array || ArrayBuffer.isView(source) || source instanceof ArrayBuffer) {
    return { buffer: toUint8Array(source) };
  }
  throw new Error("unsupported-buffer");
}
function extensionFromName(name) {
  if (!name) {
    return void 0;
  }
  const trimmed = name.trim();
  if (!trimmed) {
    return void 0;
  }
  const dot = trimmed.lastIndexOf(".");
  if (dot === -1) {
    return void 0;
  }
  return normaliseExtension(trimmed.slice(dot)) ?? void 0;
}
function registerCreateFromBufferAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("fileResource.createFromBuffer", async (params = {}) => {
    try {
      const files = Array.isArray(params.files) ? params.files : [];
      if (!files.length) {
        throw new Error("no-buffer-payload");
      }
      const results = [];
      for (const descriptor of files) {
        try {
          const { buffer: rawBuffer, mimeFromDataUrl } = normaliseBuffer(descriptor.buffer);
          const buffer2 = toUint8Array(rawBuffer);
          const rawName = typeof descriptor.name === "string" ? descriptor.name.trim() : "";
          const name = rawName.length ? rawName : void 0;
          let extension = extensionFromName(name);
          let mime2 = descriptor.mime ?? mimeFromDataUrl ?? (extension ? mimeFromExtension(extension) : void 0) ?? null;
          if (!extension && mime2) {
            extension = extensionFromMime(mime2);
          }
          const payloadMime = mime2 ?? "application/octet-stream";
          if (!extension && payloadMime && payloadMime !== "application/octet-stream") {
            extension = extensionFromMime(payloadMime) ?? extension;
          }
          let thumbnail = descriptor.thumbnail ?? void 0;
          let width = descriptor.width ?? void 0;
          let height = descriptor.height ?? void 0;
          if (!thumbnail) {
            if (extension && isImageExtension(extension)) {
              try {
                const image = await Jimp.read(bufferExports.Buffer.from(buffer2));
                width = width ?? image.width;
                height = height ?? image.height;
                image.scaleToFit({ w: 320, h: 320 });
                const thumbBuffer = await image.getBuffer(JimpMime.png);
                thumbnail = "data:image/png;base64," + thumbBuffer.toString("base64");
              } catch {
                thumbnail = buildGenericFileThumbnail(extension);
              }
            } else if (extension && VIDEO_EXTENSIONS.includes(extension)) {
              thumbnail = buildVideoThumbnail();
            } else {
              thumbnail = buildGenericFileThumbnail(extension ?? "");
            }
          }
          if (!width || !height) {
            if (extension && isImageExtension(extension)) {
              try {
                const image = await Jimp.read(bufferExports.Buffer.from(buffer2));
                width = width ?? image.width;
                height = height ?? image.height;
              } catch {
              }
            }
          }
          const originalMeta = descriptor.meta && typeof descriptor.meta === "object" ? descriptor.meta : void 0;
          const resourceId = createResource({
            type: "file",
            data: {
              buffer: buffer2,
              mime: payloadMime
            },
            originalMeta: {
              fileName: name,
              width,
              height,
              ...originalMeta ?? {}
            }
          });
          if (thumbnail) {
            updateResource(resourceId, {
              thumbnailCache: {
                base64: thumbnail,
                width,
                height,
                mime: "image/png",
                generatedAt: Date.now()
              }
            });
          }
          results.push({
            resource: resourceId,
            width: width ?? null,
            height: height ?? null,
            mime: payloadMime
          });
        } catch (fileError) {
          results.push({
            resource: null,
            error: (fileError == null ? void 0 : fileError.message) || String(fileError)
          });
        }
      }
      const successful = results.filter((entry) => entry.resource && !entry.error);
      if (!successful.length) {
        return results[0] ?? { resource: null, error: "no-successful-resource" };
      }
      const [primary, ...rest] = successful;
      if (!rest.length) {
        return primary;
      }
      return {
        ...primary,
        batch: successful
      };
    } catch (error) {
      return { error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error) };
    }
  });
}
const normalizeRect = (rect) => ({
  x: Math.round(rect.x),
  y: Math.round(rect.y),
  width: Math.max(1, Math.round(rect.width)),
  height: Math.max(1, Math.round(rect.height))
});
const ensurePositiveRect = (rect) => {
  if (rect.width <= 0 || rect.height <= 0) return null;
  return rect;
};
const createSnapshot = (image, rect) => {
  const fallback = {
    x: 0,
    y: 0,
    width: image.bitmap.width,
    height: image.bitmap.height
  };
  return {
    image,
    rect: normalizeRect(fallback)
  };
};
const createMaskSnapshotRect = (rect, fallback) => rect ? normalizeRect(rect) : normalizeRect(fallback);
const applyMaskToSnapshot = async (snapshot, params = {}) => {
  const maskSnapshot = params.maskSnapshot ?? null;
  if (!maskSnapshot) {
    const totalPixels2 = Math.max(1, Math.round(snapshot.rect.width)) * Math.max(1, Math.round(snapshot.rect.height));
    return {
      snapshot,
      stats: {
        totalPixels: totalPixels2,
        maskedPixels: 0,
        unmaskedPixels: totalPixels2,
        maskAlphaZeroPixels: 0,
        maskAlphaNonZeroPixels: 0,
        invertMaskApplied: false
      }
    };
  }
  const baseRect = normalizeRect(snapshot.rect);
  const baseImage = snapshot.image.clone();
  const width = Math.max(1, baseImage.bitmap.width);
  const height = Math.max(1, baseImage.bitmap.height);
  const data2 = baseImage.bitmap.data;
  let maskImage = maskSnapshot ? maskSnapshot.image.clone() : null;
  let maskSnapshotRect = maskSnapshot ? normalizeRect(maskSnapshot.maskRegion ?? maskSnapshot.rect) : null;
  if (maskImage && (maskImage.bitmap.width !== width || maskImage.bitmap.height !== height || !maskSnapshotRect)) {
    maskImage = maskImage.clone().resize({
      w: width,
      h: height
    });
    maskSnapshotRect = { ...baseRect };
  }
  const maskData = maskImage ? maskImage.bitmap.data : null;
  const maskWidth = (maskImage == null ? void 0 : maskImage.bitmap.width) ?? 0;
  const maskHeight = (maskImage == null ? void 0 : maskImage.bitmap.height) ?? 0;
  const snapshotMaskRect = maskSnapshotRect ? createMaskSnapshotRect(maskSnapshotRect, baseRect) : null;
  const invertMask = Boolean(params.invertMask);
  let maskedPixels = 0;
  let maskAlphaZeroPixels = 0;
  let maskAlphaNonZeroPixels = 0;
  let alphaRemovalTotal = 0;
  let alphaRemovalMax = 0;
  let stronglyMaskedPixels = 0;
  for (let y2 = 0; y2 < height; y2 += 1) {
    for (let x2 = 0; x2 < width; x2 += 1) {
      const idx = (y2 * width + x2) * 4;
      const globalX = baseRect.x + x2;
      const globalY = baseRect.y + y2;
      let maskValue = 0;
      if (maskData && snapshotMaskRect) {
        const relativeX = globalX - snapshotMaskRect.x;
        const relativeY = globalY - snapshotMaskRect.y;
        if (relativeX >= 0 && relativeY >= 0 && relativeX < snapshotMaskRect.width && relativeY < snapshotMaskRect.height) {
          const sampleX = Math.min(
            maskWidth - 1,
            Math.max(0, Math.floor(relativeX / Math.max(1, snapshotMaskRect.width) * maskWidth))
          );
          const sampleY = Math.min(
            maskHeight - 1,
            Math.max(0, Math.floor(relativeY / Math.max(1, snapshotMaskRect.height) * maskHeight))
          );
          const maskIdx = (sampleY * maskWidth + sampleX) * 4;
          const alpha = maskData[maskIdx + 3];
          if (alpha <= 0) {
            maskAlphaZeroPixels += 1;
          } else {
            maskAlphaNonZeroPixels += 1;
          }
          let normalizedAlpha = Math.min(1, Math.max(0, alpha / 255));
          normalizedAlpha = 1 - normalizedAlpha;
          const effectiveAlpha = (maskSnapshot == null ? void 0 : maskSnapshot.reverse) ? 1 - normalizedAlpha : normalizedAlpha;
          const normalizedMask = Math.min(1, Math.max(0, effectiveAlpha));
          maskValue = Math.max(maskValue, normalizedMask);
        }
      }
      let removal = Math.min(1, maskValue);
      if (invertMask) {
        removal = Math.max(0, 1 - removal);
      }
      if (removal <= 0) continue;
      maskedPixels += 1;
      const previousAlpha = data2[idx + 3];
      const nextAlpha = Math.max(0, Math.round(previousAlpha * (1 - removal)));
      const alphaReduction = Math.max(0, previousAlpha - nextAlpha);
      alphaRemovalTotal += alphaReduction;
      alphaRemovalMax = Math.max(alphaRemovalMax, alphaReduction);
      if (alphaReduction >= 128) {
        stronglyMaskedPixels += 1;
      }
      data2[idx + 3] = nextAlpha;
    }
  }
  const totalPixels = width * height;
  maskedPixels = Math.max(0, Math.min(totalPixels, maskedPixels));
  const unmaskedPixels = Math.max(0, Math.min(totalPixels, totalPixels - maskedPixels));
  const alphaRemovalAverage = totalPixels > 0 ? alphaRemovalTotal / totalPixels : 0;
  const alphaRemovalAverageNormalized = Math.max(0, Math.min(1, alphaRemovalAverage / 255));
  return {
    snapshot: {
      image: baseImage,
      rect: baseRect
    },
    stats: {
      totalPixels,
      maskedPixels,
      unmaskedPixels,
      maskAlphaZeroPixels,
      maskAlphaNonZeroPixels,
      invertMaskApplied: invertMask,
      alphaRemovalTotal,
      alphaRemovalAverage,
      alphaRemovalAverageNormalized,
      alphaRemovalMax,
      stronglyMaskedPixels
    }
  };
};
const _SpeicialIDManager = class _SpeicialIDManager {
  static is_SPECIAL_DOCUMENT_CURRENT(str) {
    return this.SPECIAL_DOCUMENT_CURRENT === str;
  }
  static get_SPECIAL_DOCUMENT_CURRENT() {
    return this.SPECIAL_DOCUMENT_CURRENT;
  }
  static is_SPECIAL_LAYER_FIT(str) {
    return this.SPECIAL_LAYER_KEEP_SIZE === str;
  }
  static get_SPECIAL_LAYER_FIT() {
    return this.SPECIAL_LAYER_KEEP_SIZE;
  }
  static is_SPECIAL_LAYER_USE_CANVAS(str) {
    return this.SPECIAL_LAYER_USE_CANVAS === str;
  }
  static get_SPECIAL_LAYER_USE_CANVAS() {
    return this.SPECIAL_LAYER_USE_CANVAS;
  }
  static is_SPECIAL_LAYER_NEW_LAYER(str) {
    return this.SPECIAL_LAYER_NEW_LAYER === str;
  }
  static get_SPECIAL_LAYER_NEW_LAYER() {
    return this.SPECIAL_LAYER_NEW_LAYER;
  }
  static is_SPECIAL_LAYER_SELECTED_LAYER(str) {
    return this.SPECIAL_LAYER_SELECTED_LAYER === str;
  }
  static get_SPECIAL_LAYER_SELECTED_LAYER() {
    return this.SPECIAL_LAYER_SELECTED_LAYER;
  }
  static is_SPECIAL_LAYER_PREVIEW_DOCUMENT(str) {
    return this.SPECIAL_LAYER_PREVIEW_DOCUMENT === str;
  }
  static get_SPECIAL_LAYER_PREVIEW_DOCUMENT() {
    return this.SPECIAL_LAYER_PREVIEW_DOCUMENT;
  }
  static getSpecialDocumentCurrent() {
    return _SpeicialIDManager.SPECIAL_DOCUMENT_CURRENT;
  }
  static getSpecialLayerForGet() {
    return [
      _SpeicialIDManager.SPECIAL_LAYER_USE_CANVAS,
      _SpeicialIDManager.SPECIAL_LAYER_SELECTED_LAYER
    ];
  }
  static getSpecialLayerForSend() {
    return [
      _SpeicialIDManager.SPECIAL_LAYER_NEW_LAYER,
      _SpeicialIDManager.SPECIAL_LAYER_SELECTED_LAYER
    ];
  }
  static getSpecialDocumentForPreview() {
    return _SpeicialIDManager.SPECIAL_LAYER_PREVIEW_DOCUMENT;
  }
  static fix(str) {
    if (this.is_SPECIAL_DOCUMENT_CURRENT(str)) {
      return this.SPECIAL_DOCUMENT_CURRENT;
    }
    if (this.is_SPECIAL_LAYER_NEW_LAYER(str)) {
      return this.SPECIAL_LAYER_NEW_LAYER;
    }
    if (this.is_SPECIAL_LAYER_PREVIEW_DOCUMENT(str)) {
      return this.SPECIAL_LAYER_PREVIEW_DOCUMENT;
    }
    if (this.is_SPECIAL_LAYER_USE_CANVAS(str)) {
      return this.SPECIAL_LAYER_USE_CANVAS;
    }
    if (this.is_SPECIAL_LAYER_SELECTED_LAYER(str)) {
      return this.SPECIAL_LAYER_SELECTED_LAYER;
    }
    return str;
  }
};
_SpeicialIDManager.SPECIAL_DOCUMENT_CURRENT = "### Active Document ###";
_SpeicialIDManager.SPECIAL_LAYER_KEEP_SIZE = "### Keep Size or Fit Canvas ###";
_SpeicialIDManager.SPECIAL_LAYER_USE_CANVAS = "### The Canvas ###";
_SpeicialIDManager.SPECIAL_LAYER_NEW_LAYER = "### New Layer ###";
_SpeicialIDManager.SPECIAL_LAYER_SELECTED_LAYER = "### Selected Layer ###";
_SpeicialIDManager.SPECIAL_LAYER_PREVIEW_DOCUMENT = "_SDPPP_PSD_";
let SpeicialIDManager = _SpeicialIDManager;
const BOUNDARY_HOST$1 = "boundary";
const CONTENT_HOST$1 = "content";
const MASK_HOST$1 = "mask";
function ensureFiniteNumber$1(value, label) {
  if (!Number.isFinite(value)) {
    throw new Error(`${label} must be a finite number`);
  }
}
function parseNumberQuery$1(url, key2) {
  const raw = url.searchParams.get(key2);
  if (raw == null || raw === "") {
    return void 0;
  }
  const num = Number(raw);
  ensureFiniteNumber$1(num, key2);
  return num;
}
function composeLayerIdentify$1(layerId, layerName) {
  const id = layerId == null ? void 0 : layerId.trim();
  const name = layerName == null ? void 0 : layerName.trim();
  if (name && id) {
    return `${name} (id:${id})`;
  }
  if (name) {
    return name;
  }
  if (id) {
    return `${id} (id:${id})`;
  }
  return void 0;
}
function parseBoundaryResource$1(resource) {
  if (typeof resource !== "string" || resource.trim() === "") {
    throw new Error("boundary must be a non-empty string");
  }
  let url;
  try {
    url = new URL(resource);
  } catch {
    throw new Error(`Invalid boundary uri: ${resource}`);
  }
  if (url.protocol !== "uxp:") {
    throw new Error("boundary uri must use uxp:// scheme");
  }
  if (url.hostname !== BOUNDARY_HOST$1) {
    throw new Error(`boundary uri host must be "${BOUNDARY_HOST$1}"`);
  }
  const segments = url.pathname.split("/").filter(Boolean);
  if (segments.length < 2) {
    throw new Error("boundary uri is missing required segments");
  }
  const docIdRaw = segments[0];
  const docId = Number(docIdRaw);
  ensureFiniteNumber$1(docId, "docId");
  if (!Number.isInteger(docId) || docId < 0) {
    throw new Error("docId must be a non-negative integer");
  }
  const boundaryType = segments[1];
  if (boundaryType === "rect") {
    const rectKeys = [
      "leftDistance",
      "topDistance",
      "rightDistance",
      "bottomDistance",
      "width",
      "height"
    ];
    const rect = {};
    for (const key2 of rectKeys) {
      const value = parseNumberQuery$1(url, key2);
      if (value === void 0) {
        throw new Error(`boundary rect missing query parameter "${key2}"`);
      }
      rect[key2] = value;
    }
    return {
      docId,
      boundary: rect,
      imageSize: parseNumberQuery$1(url, "imageSize"),
      imageQuality: parseNumberQuery$1(url, "imageQuality")
    };
  }
  if (boundaryType !== "canvas" && boundaryType !== "curlayer" && boundaryType !== "selection") {
    throw new Error(`Unsupported boundary type "${boundaryType}"`);
  }
  return {
    docId,
    boundary: boundaryType,
    imageSize: parseNumberQuery$1(url, "imageSize"),
    imageQuality: parseNumberQuery$1(url, "imageQuality")
  };
}
function parseContentResource$1(resource) {
  if (typeof resource !== "string" || resource.trim() === "") {
    throw new Error("content must be a non-empty string");
  }
  let url;
  try {
    url = new URL(resource);
  } catch {
    throw new Error(`Invalid content uri: ${resource}`);
  }
  if (url.protocol !== "uxp:") {
    throw new Error("content uri must use uxp:// scheme");
  }
  if (url.hostname !== CONTENT_HOST$1) {
    throw new Error(`content uri host must be "${CONTENT_HOST$1}"`);
  }
  const segments = url.pathname.split("/").filter(Boolean);
  if (segments.length < 2) {
    throw new Error("content uri is missing required segments");
  }
  const docIdRaw = segments[0];
  const docId = Number(docIdRaw);
  ensureFiniteNumber$1(docId, "docId");
  if (!Number.isInteger(docId) || docId < 0) {
    throw new Error("docId must be a non-negative integer");
  }
  const contentType = segments[1];
  const layerIdParam = url.searchParams.get("layerid");
  const layerNameParam = url.searchParams.get("layername");
  switch (contentType) {
    case "canvas":
      return { docId, content: "canvas" };
    case "curlayer":
      return {
        docId,
        content: "curlayer",
        layerIdentify: composeLayerIdentify$1(layerIdParam ?? void 0, layerNameParam ?? void 0)
      };
    case "selection":
      return { docId, content: "selection" };
    case "layer": {
      const layerId = layerIdParam;
      if (!layerId) {
        throw new Error("content uri with /layer requires layerid query parameter");
      }
      return {
        docId,
        content: "curlayer",
        layerIdentify: composeLayerIdentify$1(layerId, layerNameParam ?? void 0)
      };
    }
    default:
      throw new Error(`Unsupported content type "${contentType}"`);
  }
}
function parseMaskContentResource(resource) {
  var _a3;
  if (typeof resource !== "string" || resource.trim() === "") {
    throw new Error("mask content must be a non-empty string");
  }
  let url;
  try {
    url = new URL(resource);
  } catch {
    throw new Error(`Invalid mask content uri: ${resource}`);
  }
  if (url.protocol !== "uxp:") {
    throw new Error("mask content uri must use uxp:// scheme");
  }
  if (url.hostname !== MASK_HOST$1) {
    throw new Error(`mask content uri host must be "${MASK_HOST$1}"`);
  }
  const segments = url.pathname.split("/").filter(Boolean);
  if (segments.length < 2) {
    throw new Error("mask content uri is missing required segments");
  }
  const docIdRaw = segments[0];
  const docId = Number(docIdRaw);
  ensureFiniteNumber$1(docId, "docId");
  if (!Number.isInteger(docId) || docId < 0) {
    throw new Error("docId must be a non-negative integer");
  }
  const contentType = segments[1];
  const layerIdParam = url.searchParams.get("layerid");
  const reverseParam = url.searchParams.get("reverse");
  const reverse = reverseParam === "1" || ((_a3 = reverseParam == null ? void 0 : reverseParam.toLowerCase) == null ? void 0 : _a3.call(reverseParam)) === "true";
  switch (contentType) {
    case "canvas":
      return { docId, content: "canvas", reverse };
    case "curlayer":
      return {
        docId,
        content: "curlayer",
        reverse,
        layerIdentify: layerIdParam ?? void 0
      };
    case "selection":
      return { docId, content: "selection", reverse };
    case "layer": {
      const layerId = layerIdParam;
      if (!layerId) {
        throw new Error("mask content uri with /layer requires layerid query parameter");
      }
      return {
        docId,
        content: "curlayer",
        layerIdentify: layerId,
        reverse
      };
    }
    default:
      throw new Error(`Unsupported mask content type "${contentType}"`);
  }
}
function buildGetImageParamsFromResources(boundaryResource, contentResource) {
  const boundary = parseBoundaryResource$1(boundaryResource);
  const content = parseContentResource$1(contentResource);
  if (boundary.docId !== content.docId) {
    throw new Error("boundary and content must target the same document");
  }
  return {
    boundary: boundary.boundary,
    content: content.content,
    imageSize: boundary.imageSize ?? 0,
    imageQuality: boundary.imageQuality ?? 1,
    layer_identify: content.layerIdentify ?? null
  };
}
function buildGetMaskParamsFromResources(boundaryResource, maskContentResource) {
  const boundary = parseBoundaryResource$1(boundaryResource);
  const content = parseMaskContentResource(maskContentResource);
  if (boundary.docId !== content.docId) {
    throw new Error("boundary and mask content must target the same document");
  }
  return {
    boundary: boundary.boundary,
    content: content.content,
    imageSize: boundary.imageSize ?? 0,
    reverse: content.reverse ?? false,
    layer_identify: content.layerIdentify ?? null
  };
}
function unTrimImageData(fromImageDataArray, toImageDataArray, fromImageBounds, toImageBounds, components) {
  const fromLeft = fromImageBounds.left;
  const fromTop = fromImageBounds.top;
  const fromRight = fromImageBounds.right;
  const fromBottom = fromImageBounds.bottom;
  const fromWidth = fromRight - fromLeft;
  const fromHeight = fromBottom - fromTop;
  const toLeft = toImageBounds.left;
  const toTop = toImageBounds.top;
  const toRight = toImageBounds.right;
  const toBottom = toImageBounds.bottom;
  const toWidth = toRight - toLeft;
  const toHeight = toBottom - toTop;
  const toLength = toWidth * toHeight * components;
  if (toImageDataArray.length !== toLength) {
    throw new Error(`toImageDataArray.length(${toImageDataArray.length}) !== toLength(${toLength})`);
  }
  const fromLength = fromWidth * fromHeight * components;
  if (fromImageDataArray.length !== fromLength) {
    throw new Error(`fromImageDataArray.length(${fromImageDataArray.length}) !== fromLength(${fromLength})`);
  }
  for (let i2 = 0; i2 < toLength; i2 += components) {
    const currentLeft = i2 / components % toWidth + toLeft;
    const currentTop = Math.floor(i2 / components / toWidth) + toTop;
    if (currentLeft >= fromLeft && currentLeft < fromRight && currentTop >= fromTop && currentTop < fromBottom) {
      const fromIndex = ((currentTop - fromTop) * fromWidth + (currentLeft - fromLeft)) * components;
      for (let j = 0; j < components; j++) {
        toImageDataArray[i2 + j] = fromImageDataArray[fromIndex + j];
      }
    }
  }
  return toImageDataArray;
}
function getIntersectBounds(fromImageBounds, toImageBounds) {
  const intersectLeft = Math.max(fromImageBounds.left, toImageBounds.left);
  const intersectTop = Math.max(fromImageBounds.top, toImageBounds.top);
  const intersectRight = Math.min(fromImageBounds.right, toImageBounds.right);
  const intersectBottom = Math.min(fromImageBounds.bottom, toImageBounds.bottom);
  const intersectWidth = intersectRight - intersectLeft;
  const intersectHeight = intersectBottom - intersectTop;
  return {
    left: intersectLeft,
    top: intersectTop,
    right: intersectRight,
    bottom: intersectBottom,
    width: intersectWidth,
    height: intersectHeight
  };
}
function applyLayerDataWithTransparent(pixelData, maskData) {
  for (let i2 = 0, length = pixelData.length / 4; i2 < length; i2++) {
    const maskPixel = maskData ? maskData[i2] / 255 : 1;
    pixelData[4 * i2 + 3] = maskPixel * pixelData[4 * i2 + 3];
    if (!pixelData[4 * i2 + 3]) {
      pixelData[4 * i2] = pixelData[4 * i2 + 1] = pixelData[4 * i2 + 2] = 0;
    }
  }
  return pixelData;
}
function fixAlphaChannel(pixelDataWithSize) {
  if (pixelDataWithSize.dataFromAPI.length !== pixelDataWithSize.width * pixelDataWithSize.height * 3) {
    throw new Error(
      `unsupported channel counts: ${pixelDataWithSize.dataFromAPI.length / (pixelDataWithSize.width * pixelDataWithSize.height)}`
    );
  }
  const uint8Data = new Uint8Array(pixelDataWithSize.width * pixelDataWithSize.height * 4);
  for (let i2 = 0; i2 < pixelDataWithSize.width * pixelDataWithSize.height; i2++) {
    uint8Data[i2 * 4] = pixelDataWithSize.dataFromAPI[i2 * 3];
    uint8Data[i2 * 4 + 1] = pixelDataWithSize.dataFromAPI[i2 * 3 + 1];
    uint8Data[i2 * 4 + 2] = pixelDataWithSize.dataFromAPI[i2 * 3 + 2];
    uint8Data[i2 * 4 + 3] = 255;
  }
  return {
    dataFromAPI: uint8Data,
    width: pixelDataWithSize.width,
    height: pixelDataWithSize.height
  };
}
function alignPixelBit(pixelAndSize) {
  if (pixelAndSize.dataFromAPI instanceof Uint8Array) {
    return pixelAndSize;
  }
  const { dataFromAPI, width, height } = pixelAndSize;
  const uint8Data = new Uint8Array(dataFromAPI.length);
  for (let i2 = 0; i2 < dataFromAPI.length; i2++) {
    if (dataFromAPI instanceof Uint16Array) {
      if (dataFromAPI[i2] === 32768) {
        uint8Data[i2] = 255;
      } else {
        uint8Data[i2] = Math.floor(dataFromAPI[i2] / 128);
      }
    } else {
      throw new Error("32-bit color not supported");
    }
  }
  return {
    dataFromAPI: uint8Data,
    width,
    height
  };
}
function padAndTrimToDesireBounds(pixelDataAndSize, fromBounds, toBounds, components = 4) {
  if (pixelDataAndSize.width === toBounds.width && pixelDataAndSize.height === toBounds.height && pixelDataAndSize.dataFromAPI.length === toBounds.width * toBounds.height * components) {
    return pixelDataAndSize.dataFromAPI;
  }
  const resPixelData = new Uint8Array(toBounds.width * toBounds.height * components);
  resPixelData.fill(0);
  unTrimImageData(pixelDataAndSize.dataFromAPI, resPixelData, fromBounds, toBounds, components);
  return resPixelData;
}
function scaleBounds(bounds, scaleRatio) {
  const newLeft = Math.floor(bounds.left * scaleRatio);
  const newTop = Math.floor(bounds.top * scaleRatio);
  const newWidth = Math.ceil((bounds.width || bounds.right - bounds.left) * scaleRatio);
  const newHeight = Math.ceil((bounds.height || bounds.bottom - bounds.top) * scaleRatio);
  return {
    left: newLeft,
    top: newTop,
    right: newLeft + newWidth,
    bottom: newTop + newHeight,
    width: newWidth,
    height: newHeight
  };
}
function getScaleRatio(bounds, maxWidthHeight) {
  const boundWidth = bounds.width || bounds.right - bounds.left;
  const boundHeight = bounds.height || bounds.bottom - bounds.top;
  if (maxWidthHeight && (boundWidth > maxWidthHeight || boundHeight > maxWidthHeight)) {
    return maxWidthHeight / Math.max(boundWidth, boundHeight);
  }
  return 1;
}
function getDesireBounds(docWidth, docHeight, boundary) {
  if (!boundary) {
    return {
      left: 0,
      top: 0,
      right: docWidth,
      bottom: docHeight,
      width: docWidth,
      height: docHeight
    };
  }
  const width = boundary.width ?? docWidth - boundary.leftDistance - boundary.rightDistance;
  const height = boundary.height ?? docHeight - boundary.topDistance - boundary.bottomDistance;
  return {
    left: boundary.leftDistance,
    top: boundary.topDistance,
    right: docWidth - boundary.rightDistance,
    bottom: docHeight - boundary.bottomDistance,
    width,
    height
  };
}
function convertSDPPPBoundsToBoundaryRect(bounds, docWidth, docHeight) {
  return {
    leftDistance: bounds.left,
    topDistance: bounds.top,
    rightDistance: docWidth - bounds.right,
    bottomDistance: docHeight - bounds.bottom,
    width: bounds.width,
    height: bounds.height
  };
}
class ModalStateRestorer {
  constructor() {
    this.restore = () => {
    };
    this.promise = new Promise((resolve2) => {
      this.restore = resolve2;
    });
  }
  add(fn) {
    this.promise.then(fn);
  }
}
photoshop.core.setExecutionMode({ enableErrorStacktraces: true });
let modalStatePromise = Promise.resolve();
async function runNextModalState(fn, options2) {
  const dontRecoverSelection = options2.dontRecoverSelection || false;
  const suspendHistory = options2.suspendHistory === void 0 ? true : !!options2.suspendHistory;
  const restorer = new ModalStateRestorer();
  let anyLayerSelectedChanged = false;
  const activeLayers = [];
  let formerActiveLayersVisible = [];
  const commandName = options2.commandName;
  if (!dontRecoverSelection) {
    photoshop.app.activeDocument.activeLayers.forEach((layer) => activeLayers.push(layer));
    if (options2.document && photoshop.app.activeDocument.id !== options2.document.id) {
      options2.document.activeLayers.forEach((layer) => activeLayers.push(layer));
    }
    formerActiveLayersVisible = activeLayers.map((layer) => layer.visible);
    restorer.add(() => {
      activeLayers.forEach((formerActiveLayer) => {
        if (!formerActiveLayer.selected) {
          formerActiveLayer.selected = true;
          anyLayerSelectedChanged = true;
        }
      });
      if (options2.document === photoshop.app.activeDocument) {
        activeLayers.forEach((formerActiveLayer, index2) => {
          formerActiveLayer.visible = formerActiveLayersVisible[index2];
        });
      }
    });
  }
  let suspensionID = null;
  modalStatePromise = modalStatePromise.catch((e4) => e4).then(() => {
    return new Promise((resolve2) => {
      checkModal();
      function checkModal() {
        if (!photoshop.core.isModal()) resolve2();
        else requestAnimationFrame(checkModal);
      }
    });
  }).then(() => {
    return photoshop.core.executeAsModal(async (executionContext, ...args) => {
      suspensionID = suspendHistory && options2.document ? await executionContext.hostControl.suspendHistory({
        documentID: options2.document.id,
        name: commandName
      }) : null;
      restorer.add(async () => {
        await new Promise(requestAnimationFrame);
        if (!anyLayerSelectedChanged) {
          if (suspendHistory && suspensionID) {
            executionContext.hostControl.resumeHistory(suspensionID);
          }
        }
      });
      try {
        const ret = await fn(restorer, executionContext, ...args);
        restorer.restore(true);
        return ret;
      } catch (e4) {
        restorer.restore(false);
        throw e4;
      }
    }, { commandName: Math.random().toString() });
  });
  let error = null;
  try {
    await modalStatePromise;
  } catch (e4) {
    error = e4;
  }
  if (anyLayerSelectedChanged) {
    modalStatePromise = photoshop.core.executeAsModal(async (executionContext) => {
      activeLayers.forEach((layer, index2) => {
        layer.visible = formerActiveLayersVisible[index2];
      });
      if (suspendHistory && suspensionID) {
        executionContext.hostControl.resumeHistory(suspensionID);
      }
    }, {
      commandName,
      interactive: true
    });
    await modalStatePromise;
  }
  if (error) throw error;
  return null;
}
const zhCN = {
  // 已有的翻译资源（从 locales/zh-CN.ts）
  "preview.show": "显示预览框 ({{count}}张图片)",
  "gateway.select_ai_service": "请选择AI服务",
  "provider.select.title": "选择 AI 服务提供商",
  "provider.comfyui.description": "自定义AI工作流引擎",
  "provider.replicate.description": "海量模型，稳定服务",
  "provider.runninghub.description": "模型物美价廉，海量社区应用",
  "provider.google.description": "OpenAI/Google 格式API",
  "task.waiting_upload": "正在等待图片上传...",
  "task.creating_task": "正在创建任务...",
  "task.running_duration": "运行了 {{duration}} 秒，{{message}}",
  "task.cancelled": "任务已取消",
  "task.cancel_failed": "任务取消失败: {{error}}",
  "task.default_name": "AI 生成任务",
  "comfy.connect": "连接",
  "comfy.load_failed": "云端尚未完全启动请等待2分钟后连接，HTTP状态码：{{code}}",
  "comfy.loading": "云端加载中...",
  "comfy.channel_connecting": "通道连接中...",
  "comfy.server_reconnecting": "云端服务器已关机请启动后连接",
  "comfy.version_unknown": "获取不到云端版本，服务可能暂未启动，运行可能有问题",
  "comfy.version_mismatch": "云端版本({{comfyVersion}})与插件({{pluginVersion}})不匹配，运行可能有问题",
  "comfy.cloud_recommend": "云端推荐：",
  "comfy.your_workflows": "你的工作流",
  "comfy.refresh_workflows": "刷新工作流列表",
  "comfy.queue_progress": "(队列:{{queueSize}}) {{progress}}% {{executingNodeTitle}}...",
  "comfy.save": "保存",
  "comfy.refresh": "刷新",
  "comfy.stop_cancel_all": "停止并取消全部",
  "comfy.stop_auto_run": "停止自动运行",
  "comfy.start_auto_run": "画布变动后自动运行",
  "comfy.auto_run_status": "画布变更后自动运行工作流",
  "comfy.run": "运行",
  "comfy.back": "返回",
  "comfy.uploading": "正在上传...",
  "comfy.task.name": "ComfyUI - {{workflowName}}",
  "comfy.error.task_cancelled": "任务已取消",
  "comfy.task.processing_progress": "处理进度 {{processed}}/{{total}}",
  "comfy.help_tooltip": "使用教程",
  "comfy.no_workflow_selected": "未选择工作流",
  "boundary.title": "输入设置",
  "boundary.tooltip": "AI使用的区域与最大尺寸控制",
  "boundary.current_canvas": "整个画布",
  "boundary.current_layer": "当前图层",
  "boundary.current_selection": "当前选区",
  "boundary.set_as_canvas": "设为画布",
  "boundary.set_as_layer": "设为当前图层",
  "boundary.set_as_selection": "设为当前选区",
  "http.404": "云端可能未运行或和插件版本不匹配 (404)",
  "http.401": "未授权 (401)",
  "http.403": "禁止访问 (403)",
  "http.408": "请求超时 (408)",
  "http.500": "服务器错误 (500)",
  "http.501": "未实现 (501)",
  "http.502": "网关错误 (502)",
  "http.503": "服务不可用 (503)",
  "http.504": "网关超时 (504)",
  "http.unknown": "未知错误（{{code}}）",
  "runninghub.get_apikey": "点此获取RunningHub APIKey",
  "runninghub.apikey_placeholder": "请输入您的RunningHub API Key",
  "runninghub.app_id": "应用ID:",
  "runninghub.webapp_id_placeholder": "此处粘贴 WebApp ID",
  "runninghub.open_app": "按回车打开应用： {{appName}}",
  "runninghub.execute": "执行",
  "runninghub.running": "运行中...",
  "runninghub.rh_coins": "RH币:",
  "runninghub.current_tasks": "当前任务数:",
  "runninghub.help_tooltip": "使用教程",
  "runninghub.stop_all": "停止全部",
  "runninghub.status.waiting": "排队等待",
  "runninghub.status.running": "正在运行",
  "runninghub.status.failed": "执行失败",
  "runninghub.status.success": "执行成功",
  "image.auto_refetch": "自动从PS重新获取",
  "local_resource.selection.images": "图片",
  "runninghub.error.get_result_failed": "获取结果失败: {{error}}",
  "runninghub.error.task_failed": "任务执行失败: {{error}}",
  "runninghub.error.task_incomplete": "任务未完成，当前状态: {{status}}",
  "runninghub.error.account_status_http": "getAccountStatus API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.account_status_reason_unknown": "获取账户信息失败",
  "runninghub.error.account_status_failed": "getAccountStatus API 调用失败 - {{reason}}",
  "runninghub.error.form_data_http": "getNodes API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.form_data_reason_unknown": "获取表单数据失败",
  "runninghub.error.form_data_failed": "getNodes API 调用失败 - {{reason}}",
  "runninghub.error.node_info_missing": "运行失败 - 未获取到 nodeInfoList，请先执行 getNodes()。",
  "runninghub.error.run_http": "run API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.run_reason_default": "任务执行失败",
  "runninghub.error.run_failed": "run API 调用失败 - {{reason}}",
  "runninghub.error.status_http": "status API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.status_reason_unknown": "获取任务状态失败",
  "runninghub.error.status_failed": "status API 调用失败 - {{reason}}",
  "runninghub.error.outputs_http": "outputs API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.outputs_failed": "outputs API 调用失败 - {{reason}}",
  "runninghub.task.title": "RunningHub - {{webappId}}",
  "runninghub.error.upload_http": "uploadImage API 调用失败 - HTTP 错误，状态: {{status}}",
  "runninghub.error.upload_reason_unknown": "文件上传失败",
  "runninghub.error.upload_failed": "uploadImage API 调用失败 - {{reason}}",
  "customapi.error.no_image_returned": "未返回图片",
  "customapi.error.openai_api": "OpenAI API 错误",
  "customapi.error.input_required": "需要提供图像和提示词",
  "customapi.error.generation_failed": "生成失败",
  "customapi.task.name.google": "Google Gemini - 图片生成",
  "customapi.task.name.openai": "OpenAI - 图片编辑",
  "customapi.error.unsupported_image_input": "不支持的图像输入类型",
  "replicate.get_apikey": "如何获取APIKey",
  "replicate.apikey_placeholder": "请输入您的Replicate API Key",
  "replicate.execute": "执行",
  "replicate.model_placeholder": "粘贴你的模型名称",
  "replicate.help_tooltip": "使用教程",
  "replicate.loading": "加载中...",
  "replicate.running": "运行中...",
  "replicate.stop": "停止",
  "liblib.get_apikey": "如何获取APIKey和API Secret",
  "liblib.execute": "执行",
  "common.close": "关闭",
  "common.save": "保存",
  "common.save_and_run": "保存并立即执行",
  "common.loading": "加载中...",
  "common.error": "错误",
  "common.error.unknown": "未知错误",
  "common.error.task_creation_aborted": "任务创建已中止",
  "common.error.status_check_aborted": "状态检查已中止",
  "common.error.result_fetch_aborted": "结果获取已中止",
  "common.error.upload_aborted": "上传已中止",
  "common.success": "成功",
  "common.failed": "失败",
  "common.generating": "生成中...",
  "common.cancel": "取消",
  "common.confirm": "确认",
  "common.options": "选项",
  "common.options_separator": "=== 选项 ===",
  "upload_pass.error.unsupported_type": "不支持的上传类型：{{type}}",
  "upload_pass.error.uploader_missing": "未配置上传器",
  // 已有的翻译资源（从 locales/zh.json）
  "webviewInForeground": "插件可能正在拦截 PS 快捷键... ",
  "webviewInForeground2": "点我恢复",
  // PS-UXP 新增的翻译资源
  "auth.login_success": "登录成功",
  "auth.username_label": "用户名: {{username}}",
  "auth.email_label": "邮箱: {{email}}",
  "auth.logout": "退出登录",
  "auth.login_required": "请登陆后使用插件",
  "image.send.select_position": "请选择要发送图像的位置",
  "image.send.sending": "正在发送图像...",
  "image.layer.new": "新图层",
  "image.layer.current": "当前图层",
  "image.layer.fit_to_current": "适配至当前图层",
  "image.layer.fit_to_selection": "适配至选区",
  "image.layer.fit_to_canvas": "适配至画布",
  "image.shortcut_auth_required": "快捷键选图功能仅登陆后可用",
  "image.shortcut_focus_required": "快捷键选图功能仅在插件窗口聚焦时可用",
  "image.get.select_image": "请选择要获取的图像",
  "image.get.entire_canvas": "整个画布",
  "image.get.canvas": "画布",
  "image.get.current_layer": "当前图层",
  "image.get.current_layer_bounds": "仅当前图层范围",
  "image.get.selection_bounds": "仅选区范围",
  "image.get.canvas_bounds": "画布范围",
  "image.crop_by_selection": "按选区裁剪",
  "image.limit_size": "限制图片尺寸",
  "image.crop.none": "不裁剪",
  "image.crop.inpaint": "反向裁剪(Inpaint)",
  "image.crop.outpaint": "正向裁剪(Outpaint)",
  "image.send_all": "发送所有",
  "image.save_all": "保存所有",
  "image.save_current": "保存当前图片",
  "image.delete_current": "删除当前",
  "image.more_actions": "更多操作",
  "image.jump_to_last": "跳转到最后一个",
  "image.clear_all": "清空预览",
  "image.send_to_ps": "发送到PS",
  "image.download": "下载",
  "image.copy": "复制",
  "image.sending": "正在发送...",
  "image.sending_all": "正在发送所有图片...",
  "mask.get.select_mask": "请选择要获取的遮罩",
  "mask.selection": "选区",
  "mask.current_layer_bounds": "当前图层范围",
  "mask.all": "全部",
  "mask.selection_exclude": "选区除外",
  "mask.current_layer_exclude": "当前图层除外",
  "mask.empty": "空",
  "widgetable.photoshop.deprecated_node": "SDPPP 2.0 不再需要此节点",
  "work_boundary.error.empty_selection_mask": "选区遮罩为空",
  "work_boundary.error.primary_resource_missing": "缺少主图资源",
  "work_boundary.error.mask_resource_missing": "缺少遮罩资源",
  "work_boundary.error.mask_apply_empty": "遮罩应用后未得到资源",
  // 文档和图层操作相关翻译
  "document {{0}} not found": "找不到文档: {{0}}",
  "create document for preview": "创建预览文档",
  "resize document for preview": "调整预览文档尺寸",
  "create document for sent images": "给发送的图片创建文档",
  "show sent images": "显示发送的图片",
  "create layer failed": "创建图层失败",
  "layer not found {{0}}": "找不到图层: {{0}}",
  "layer not found: {{0}}": "找不到图层: {{0}}",
  "layer {{0}} is not a group": "图层 {{0}} 不是一个组",
  "no linked layer for {{0}}": "没有链接图层: {{0}}",
  "no first related layer in {{0}}": "组 {{0}} 中没有第一个相关图层",
  "merge group failed": "合并组失败",
  "get content of layer {{0}}": "获取图层 {{0}} 的内容",
  "get layer info": "获取图层信息",
  "get_layer_info: layer_identify required": "get_layer_info: 需要 layer_identify",
  "get pixel of {{0}} failed": "获取像素失败: {{0}}",
  "get selection failed": "获取选区失败",
  "invalid name: {{0}}": "非法的名称: {{0}}",
  "desire bounds is null": "目标边界为空",
  "intersect or scaledDesire is null": "交集或缩放目标为空",
  'only layer kind "TEXT" is supported, invalid layer: {{0}}': "不支持非文本图层: {{0}}",
  "select layer": "sdppp 选中图层",
  "run Photoshop Action": "sdppp 运行 Photoshop Action",
  "Action {{0}} not found": "Action {{0}} 未找到",
  "Action set {{0}} not found": "ActionSet {{0}} 未找到",
  "set text to layer": "设置图层的文本",
  // ComfyUI 管理相关翻译
  "ComfyManager not found, cannot reboot": "Comfy Manager未安装，无法重启",
  "Failed to reboot ComfyUI": "重启ComfyUI失败",
  // 图片上传组件相关翻译
  "image.upload.from_canvas": "画布",
  "image.upload.from_curlayer": "当前图层",
  "image.upload.from_selection": "选区",
  "image.upload.from_harddisk": "本地文件",
  "image.upload.clear": "清空",
  "image.upload.uploading": "上传中，如果图片长边超过4000像素，可能会卡顿...",
  "image.upload.syncing": "素材同步中",
  "image.upload.no_images": "暂无图片",
  "image.upload.error": "上传失败，请重试",
  // PS获取按钮提示
  "image.upload.tooltip.more_options_hint": "+Shift 调整更多选项；Ctrl 单次获取。",
  "image.upload.tooltip.alt.crop": "+Alt 按选区裁剪",
  "image.upload.tooltip.alt.reverse": "+Alt 反转遮罩",
  "image.upload.tooltip.image.canvas": "从 画布 获取图像",
  "image.upload.tooltip.image.curlayer": "从 当前图层 获取图像",
  "image.upload.tooltip.mask.curlayer": "从 当前图层 获取遮罩",
  "image.upload.tooltip.mask.selection": "从 选区 获取遮罩",
  "image.upload.tooltip.mask.canvas": "从 画布 获取遮罩",
  "image.upload.tooltip.cut_action": "上传图片",
  "image.upload.tooltip.scan_action": "上传部分图片（慎用）",
  "image.upload.tooltip.autosync.on": "自动同步: 开启",
  "image.upload.tooltip.autosync.off": "自动同步: 关闭",
  "image.upload.tooltip.sync_action": "同步当前内容",
  "image.upload.autosync.fetching": "自动获取中…",
  "image.upload.autosync.status.enabled": "自动同步中…",
  "image.upload.autosync.status.disabled": "自动同步未打开",
  "image.upload.tooltip.current.canvas": "当前选项：画布",
  "image.upload.tooltip.current.layer": "当前选项：图层",
  "image.upload.tooltip.current.layer_named": "当前选项：图层 {{layerName}}",
  "image.upload.tooltip.current.file": "当前选项：文件",
  "image.upload.retry": "重试",
  "image.pack.local.button": "本地图片包",
  "image.pack.local.empty": "暂无图片",
  "image.auto_send_enabled": "自动填入画布开启",
  "image.auto_send_disabled": "自动填入画布关闭",
  "image.upload.primary.auto": "自动取图中…",
  "image.upload.primary.manual": "获取图片",
  "image.upload.primary.hint": "该节点默认继承当前图层与遮罩",
  "image.upload.primary.cut": "标准",
  "image.upload.primary.scan": "部分",
  "image.upload.primary.hint.line1": "本节点默认继承:",
  "image.upload.primary.hint.line2": "主图",
  "workflow.output.destination.title": "输出至：",
  "workflow.output.destination.canvas": "全图",
  "image.upload.primary.advanced": "高级选图",
  "image.upload.primary.advanced.modify": "修改",
  "image.upload.primary.advanced.reset": "重置",
  "image.upload.primary.advanced.local_file": "从本地获取",
  "image.upload.primary.advanced.content.canvas": "画布",
  "image.upload.primary.advanced.content.curlayer": "当前图层",
  "image.upload.primary.advanced.content.selection": "选区",
  "image.upload.primary.advanced.boundary.canvas": "画布边界",
  "image.upload.primary.advanced.boundary.curlayer": "当前图层边界",
  "image.upload.primary.advanced.boundary.selection": "选区边界",
  "image.upload.primary.advanced.boundary.primary": "主图边界",
  "image.upload.mode.file.label": "文件",
  "image.upload.mode.layer.label": "图层",
  "image.upload.mode.canvas.label": "画布",
  "image.upload.source.file.tooltip": "从本地上传",
  "image.upload.source.layer.tooltip": "使用当前图层",
  "image.upload.source.canvas.tooltip": "使用整个画布",
  "image.upload.dropHint": "拖拽图片到此处松开完成上传",
  "image.upload.tooltip.clear_action": "清空选择",
  "image.upload.status.layer.short_named": "图层 {{layerName}}",
  "image.upload.status.layer.short": "图层",
  "image.upload.status.file.short": "本地文件",
  "image.upload.status.canvas.short": "画布",
  "image.upload.status.file.active": "正在使用本地文件",
  "image.upload.status.file.resetHint": "点击移除本地文件",
  "image.upload.status.mask.resetHint": "点击恢复默认遮罩",
  "image.upload.status.mask.modified": "已设置遮罩",
  "image.upload.status.boundary.resetHint": "点击恢复默认边界",
  "image.upload.status.boundary.modified": "已设置范围",
  "image.upload.mask.button": "选区遮罩",
  "image.upload.mask.selection": "选区遮罩",
  "image.upload.mask.layer": "图层遮罩",
  "image.upload.remove_slot": "移除槽位",
  "image.upload.add_slot": "新增槽位",
  "video.local.button": "本地视频",
  "video.local.empty": "暂无视频",
  "video.local.remove": "清除视频",
  // 来源渲染组件相关翻译
  "source.source": "来源",
  "source.content": "内容",
  "source.boundary": "范围",
  "source.mask": "遮罩",
  "source.disk": "本地",
  "source.remote": "云端",
  "source.unknown": "未知",
  "source.ps_image": "PS图片",
  "source.ps_mask": "PS遮罩",
  "source.canvas": "整个画布",
  "source.current_layer": "当前图层",
  "source.selection": "选区",
  "source.quality_percent": "质量{{percent}}%",
  "source.crop.positive": "正向裁剪",
  "source.crop.negative": "反向裁剪",
  "source.reverse": "反转",
  "send_images.create_document": "创建文档",
  "send_images.create_document_failed": "创建文档失败",
  // Photoshop 操作翻译
  "photoshop.no_active_document": "没有活动文档",
  "photoshop.rectangle_coordinates_required": "创建操作需要矩形坐标",
  "photoshop.create_guide_frame": "创建参考线框架",
  "photoshop.clear_guide_frame": "清除参考线框架",
  "photoshop.invalid_action": "无效操作: {{action}}",
  "photoshop.file_not_found": "文件未找到: {{path}}",
  "photoshop.failed_to_open_file_as_document": "无法将文件作为文档打开: {{path}}",
  "photoshop.invalid_boundary": "无效边界: 左边必须小于右边，上边必须小于下边",
  "photoshop.failed_to_open_image_file": "无法打开图像文件: {{error}}",
  "photoshop.open_images_from_file": "从文件打开图像",
  "photoshop.failed_to_create_document_from_file": "无法从文件创建文档",
  // Google 提供商翻译
  "google.field.image_input": "输入图像",
  "google.field.prompt": "提示词",
  "google.field.batch_count": "批次数量",
  "google.field.images_per_batch": "每批图像数",
  "google.status.success": "成功",
  "google.status.failed": "失败",
  "google.status.generating": "生成中",
  "google.apikey_placeholder": "请输入您的 Google API Key",
  "google.baseurl_placeholder": "基础 URL",
  "google.get_apikey": "获取 API Key",
  "google.help_tooltip": "Google Gemini 图像生成器",
  "google.model_name": "Gemini 2.5 Flash 图像",
  "google.model_label": "模型",
  "google.model_placeholder": "选择模型",
  "google.stop": "停止",
  "google.loading": "加载中...",
  "google.generating": "生成中...",
  "google.generate": "生成",
  // 图像预览自动切换
  "image.auto_toggle": "自动",
  // 导入模式相关
  "image.import_as_smartobject": "作为智能对象导入",
  "image.import_as_newdoc": "作为新文档导入",
  "image.import_to_selection": "发送到当前选区",
  "image.boundary": "边界",
  "image.import_tip": "按住 Shift 键以新文档方式导入",
  // === 自动补充缺失的键 ===
  "auth.guest_login_success": "访客登录成功",
  "boundary.canvas": "画布",
  "boundary.select_boundary": "选择边界",
  "boundary.selection": "选区",
  "boundary.max_size": "尺寸限制 (px)",
  "boundary.max_size_error": "请输入大于 0 的像素值",
  "boundary.max_size_hint": "留空表示不限",
  "boundary.max_size_placeholder": "留空表示不限",
  "boundary.no_limit": "不限",
  "boundary.image_quality": "图像质量 (%)",
  "boundary.image_quality_required": "请输入质量百分比",
  "boundary.image_quality_range": "范围 1-100",
  "boundary.preview_main_image": "输出区域",
  "boundary.preview_select": "设为选区",
  "boundary.preview_alt": "边界预览",
  "boundary.preview_placeholder": "点击使用当前选区",
  "boundary.settings": "调整输入设置",
  "convert widget {0} failed:": "控件 {0} 转换失败：",
  "document {0} not found": "未找到文档 {0}",
  "image.document.new": "新建文档",
  "image.layer.smart_object": "智能对象图层",
  "layer not found {0}": "未找到图层 {0}",
  "photoshop.invalid_boundary_type": "无效的边界类型: {{type}}",
  "photoshop.no_active_layer": "当前没有活动图层",
  // 图像来源对话框
  "dialog.image_source.title": "选择图像来源",
  "dialog.image_source.primary_canvas": "以主图边界获取画布",
  "dialog.image_source.primary_curlayer": "以主图边界获取当前图层",
  "dialog.image_source.canvas_canvas": "以画布边界获取画布",
  "dialog.image_source.canvas_curlayer": "以画布边界获取当前图层",
  "dialog.image_source.curlayer_canvas": "以当前图层边界获取画布",
  "dialog.image_source.curlayer_curlayer": "以当前图层边界获取当前图层",
  "dialog.image_source.local_file": "从本地获取",
  "dialog.simple_source.title": "选择素材来源",
  "dialog.simple_source.canvas": "画布",
  "dialog.simple_source.current_layer": "当前图层",
  "dialog.simple_source.local_file": "选择文件",
  "dialog.simple_source.no_active_layer": "当前没有可用图层",
  "dialog.simple_source.pick_error": "选择文件失败，请重试"
};
const enUS = {
  // Existing translations (from locales/en-US.ts)
  "preview.show": "Show Preview ({{count}} images)",
  "gateway.select_ai_service": "Please select AI service",
  "provider.select.title": "Select AI Service Provider",
  "provider.comfyui.description": "Your powerful node-based workflow engine",
  "provider.replicate.description": "Cloud-based model service platform",
  "provider.runninghub.description": "Model with affordable price, abundant community applications",
  "provider.google.description": "OpenAI/Google format API",
  "task.waiting_upload": "Waiting for image upload...",
  "task.creating_task": "Creating task...",
  "task.running_duration": "Running for {{duration}} secs, {{message}}",
  "task.cancelled": "Task cancelled",
  "task.cancel_failed": "Task cancel failed: {{error}}",
  "task.default_name": "AI Generation Task",
  "comfy.connect": "Connect",
  "comfy.load_failed": "ComfyUI failed to load, HTTP status code: {{code}}",
  "comfy.loading": "ComfyUI loading...",
  "comfy.channel_connecting": "Channel connecting...",
  "comfy.server_reconnecting": "ComfyUI server reconnecting",
  "comfy.version_unknown": "Cannot get ComfyUI version, server may not be started, may cause issues",
  "comfy.version_mismatch": "Comfy SDPPP version ({{comfyVersion}}) does not match plugin ({{pluginVersion}}), may cause issues",
  "comfy.cloud_recommend": "Cloud:",
  "comfy.your_workflows": "Your Workflows",
  "comfy.refresh_workflows": "Refresh workflow list",
  "comfy.queue_progress": "(Queue:{{queueSize}}) {{progress}}% {{executingNodeTitle}}...",
  "comfy.save": "Save",
  "comfy.refresh": "Refresh",
  "comfy.stop_cancel_all": "Stop and cancel all",
  "comfy.stop_auto_run": "Stop auto run",
  "comfy.start_auto_run": "Auto run after canvas change",
  "comfy.auto_run_status": "Auto-run workflow after changes...",
  "comfy.run": "Run",
  "comfy.back": "Back",
  "comfy.uploading": "Uploading...",
  "comfy.task.name": "ComfyUI - {{workflowName}}",
  "comfy.error.task_cancelled": "Task cancelled",
  "comfy.task.processing_progress": "Processing {{processed}}/{{total}}",
  "comfy.help_tooltip": "Tutorial",
  "comfy.no_workflow_selected": "No workflow selected",
  "boundary.title": "Input Setting",
  "boundary.tooltip": "Area AI reads from; controls max image size",
  "boundary.current_canvas": "Entire Canvas",
  "boundary.current_layer": "Current Layer",
  "boundary.current_selection": "Current Selection",
  "boundary.set_as_canvas": "Set as Canvas",
  "boundary.set_as_layer": "Set as Current Layer",
  "boundary.set_as_selection": "Set as Current Selection",
  "http.404": "SDPPP may not be installed or version mismatch (404)",
  "http.401": "Unauthorized (401)",
  "http.403": "Forbidden (403)",
  "http.408": "Request timeout (408)",
  "http.500": "Server error (500)",
  "http.501": "Not implemented (501)",
  "http.502": "Gateway error (502)",
  "http.503": "Service unavailable (503)",
  "http.504": "Gateway timeout (504)",
  "http.unknown": "Unknown error ({{code}})",
  "runninghub.get_apikey": "Click to get RunningHub APIKey",
  "runninghub.apikey_placeholder": "Enter your RunningHub API Key",
  "runninghub.app_id": "App ID:",
  "runninghub.webapp_id_placeholder": "Paste WebApp ID here",
  "runninghub.open_app": "Press Enter to open app: {{appName}}",
  "runninghub.execute": "Execute",
  "runninghub.running": "Running...",
  "runninghub.rh_coins": "RH Coins:",
  "runninghub.current_tasks": "Current Tasks:",
  "runninghub.help_tooltip": "Tutorial",
  "runninghub.stop_all": "Stop all",
  "runninghub.status.waiting": "Waiting in queue",
  "runninghub.status.running": "Running",
  "runninghub.status.failed": "Failed",
  "runninghub.status.success": "Success",
  "image.auto_refetch": "Auto repick from PS",
  "local_resource.selection.images": "Images",
  "runninghub.error.get_result_failed": "Failed to get result: {{error}}",
  "runninghub.error.task_failed": "Task execution failed: {{error}}",
  "runninghub.error.task_incomplete": "Task incomplete, current status: {{status}}",
  "runninghub.error.account_status_http": "getAccountStatus API failed - HTTP error! status: {{status}}",
  "runninghub.error.account_status_reason_unknown": "Failed to fetch account status",
  "runninghub.error.account_status_failed": "getAccountStatus API failed - {{reason}}",
  "runninghub.error.form_data_http": "getNodes API failed - HTTP error! status: {{status}}",
  "runninghub.error.form_data_reason_unknown": "Failed to fetch form data",
  "runninghub.error.form_data_failed": "getNodes API failed - {{reason}}",
  "runninghub.error.node_info_missing": "run API failed - nodeInfoList unavailable. Please call getNodes() first.",
  "runninghub.error.run_http": "run API failed - HTTP error! status: {{status}}",
  "runninghub.error.run_reason_default": "Task execution failed",
  "runninghub.error.run_failed": "run API failed - {{reason}}",
  "runninghub.error.status_http": "status API failed - HTTP error! status: {{status}}",
  "runninghub.error.status_reason_unknown": "Failed to get task status",
  "runninghub.error.status_failed": "status API failed - {{reason}}",
  "runninghub.error.outputs_http": "outputs API failed - HTTP error! status: {{status}}",
  "runninghub.error.outputs_failed": "outputs API failed - {{reason}}",
  "runninghub.task.title": "RunningHub - {{webappId}}",
  "runninghub.error.upload_http": "uploadImage API failed - HTTP error! status: {{status}}",
  "runninghub.error.upload_reason_unknown": "File upload failed",
  "runninghub.error.upload_failed": "uploadImage API failed - {{reason}}",
  "customapi.error.no_image_returned": "No image returned",
  "customapi.error.openai_api": "OpenAI API error",
  "customapi.error.input_required": "Image input and prompt are required",
  "customapi.error.generation_failed": "Generation failed",
  "customapi.task.name.google": "Google Gemini - Image Generation",
  "customapi.task.name.openai": "OpenAI - Image Edit",
  "customapi.error.unsupported_image_input": "Unsupported image input type",
  "replicate.get_apikey": "How to get APIKey",
  "replicate.apikey_placeholder": "Enter your Replicate API Key",
  "replicate.execute": "Execute",
  "replicate.model_placeholder": "Paste your model name",
  "replicate.help_tooltip": "Tutorial",
  "replicate.loading": "Loading...",
  "replicate.running": "Running...",
  "replicate.stop": "Stop",
  "liblib.get_apikey": "How to get APIKey and API Secret",
  "liblib.execute": "Execute",
  "common.close": "Close",
  "common.save": "Save",
  "common.save_and_run": "Save and run immediately",
  "common.loading": "Loading...",
  "common.error": "Error",
  "common.error.unknown": "Unknown error",
  "common.error.task_creation_aborted": "Task creation aborted",
  "common.error.status_check_aborted": "Status check aborted",
  "common.error.result_fetch_aborted": "Result fetch aborted",
  "common.error.upload_aborted": "Upload aborted",
  "common.success": "Success",
  "common.failed": "Failed",
  "common.generating": "Generating...",
  "common.cancel": "Cancel",
  "common.confirm": "Confirm",
  "common.options": "Options",
  "common.options_separator": "=== Options ===",
  "upload_pass.error.unsupported_type": "Unsupported upload type: {{type}}",
  "upload_pass.error.uploader_missing": "Uploader not set",
  // Existing translations (from locales/en.json)
  "webviewInForeground": "PS shortcuts may be blocked by plugin...",
  "webviewInForeground2": "click to restore",
  // PS-UXP new translations
  "auth.login_success": "Login Successful",
  "auth.username_label": "Username: {{username}}",
  "auth.email_label": "Email: {{email}}",
  "auth.logout": "Logout",
  "auth.login_required": "Please login to use the plugin",
  "image.send.select_position": "Please select the position to send image",
  "image.send.sending": "Sending image...",
  "image.layer.new": "New Layer",
  "image.layer.current": "Current Layer",
  "image.layer.fit_to_current": "Fit to current layer",
  "image.layer.fit_to_selection": "Fit to selection",
  "image.layer.fit_to_canvas": "Fit to canvas",
  "image.shortcut_auth_required": "Shortcut selection feature requires login",
  "image.shortcut_focus_required": "Plugin window focused required to use keyboard shortcut",
  "image.get.select_image": "Please select the image to get",
  "image.get.entire_canvas": "Entire Canvas",
  "image.get.canvas": "Canvas",
  "image.get.current_layer": "Current Layer",
  "image.get.current_layer_bounds": "Current layer bounds only",
  "image.get.selection_bounds": "Selection bounds only",
  "image.get.canvas_bounds": "Canvas bounds",
  "image.crop_by_selection": "Crop by selection",
  "image.limit_size": "Limit image size",
  "image.crop.none": "No crop",
  "image.crop.inpaint": "Inpaint (reverse crop)",
  "image.crop.outpaint": "Outpaint (positive crop)",
  "image.send_all": "Send all",
  "image.save_all": "Save all",
  "image.save_current": "Save current",
  "image.delete_current": "Delete current",
  "image.more_actions": "More actions",
  "image.jump_to_last": "Jump to last",
  "image.clear_all": "Clear all",
  "image.send_to_ps": "Send to PS",
  "image.download": "Download",
  "image.copy": "Copy",
  "image.sending": "Sending...",
  "image.sending_all": "Sending all images...",
  "mask.get.select_mask": "Please select the mask to get",
  "mask.selection": "Selection",
  "mask.current_layer_bounds": "Current layer bounds",
  "mask.all": "All",
  "mask.selection_exclude": "Exclude selection",
  "mask.current_layer_exclude": "Exclude current layer",
  "mask.empty": "Empty",
  "widgetable.photoshop.deprecated_node": "SDPPP 2.0 no longer needs this node",
  "work_boundary.error.empty_selection_mask": "Empty selection mask",
  "work_boundary.error.primary_resource_missing": "Primary image resource is missing",
  "work_boundary.error.mask_resource_missing": "Mask resource is missing",
  "work_boundary.error.mask_apply_empty": "Mask apply returned empty resource",
  // Document and layer operation related translations
  "document {{0}} not found": "Document {{0}} not found",
  "create document for preview": "Create document for preview",
  "resize document for preview": "Resize document for preview",
  "create document for sent images": "Create document for sent images",
  "show sent images": "Show sent images",
  "create layer failed": "Create layer failed",
  "layer not found {{0}}": "Layer not found {{0}}",
  "layer not found: {{0}}": "Layer not found: {{0}}",
  "layer {{0}} is not a group": "Layer {{0}} is not a group",
  "no linked layer for {{0}}": "No linked layer for {{0}}",
  "no first related layer in {{0}}": "No first related layer in {{0}}",
  "merge group failed": "Merge group failed",
  "get content of layer {{0}}": "Get content of layer {{0}}",
  "get layer info": "Get layer info",
  "get_layer_info: layer_identify required": "get_layer_info requires layer_identify",
  "get pixel of {{0}} failed": "Get pixel of {{0}} failed",
  "get selection failed": "Get selection failed",
  "invalid name: {{0}}": "Invalid name: {{0}}",
  "desire bounds is null": "Desire bounds is null",
  "intersect or scaledDesire is null": "Intersect or scaledDesire is null",
  'only layer kind "TEXT" is supported, invalid layer: {{0}}': 'Only layer kind "TEXT" is supported, invalid layer: {{0}}',
  "select layer": "Select layer",
  "run Photoshop Action": "Run Photoshop Action",
  "Action {{0}} not found": "Action {{0}} was not found",
  "Action set {{0}} not found": "Action set {{0}} was not found",
  "set text to layer": "Set text to layer",
  // ComfyUI management related translations
  "ComfyManager not found, cannot reboot": "Cannot reboot because ComfyManager is missing",
  "Failed to reboot ComfyUI": "Unable to reboot ComfyUI",
  // Image upload component related translations
  "image.upload.from_canvas": "Canvas",
  "image.upload.from_curlayer": "Current Layer",
  "image.upload.from_selection": "Selection",
  "image.upload.from_harddisk": "Disk",
  "image.upload.clear": "Clear",
  "image.upload.uploading": "Uploading, if the image too large, may be lag...",
  "image.upload.syncing": "Syncing assets",
  "image.upload.no_images": "No images",
  "image.upload.error": "Upload failed, please try again",
  // Tooltips for Photoshop fetch buttons
  "image.upload.tooltip.alt.crop": "+Alt crop by selection",
  "image.upload.tooltip.alt.reverse": "+Alt reversed mask",
  "image.upload.tooltip.image.canvas": "Get image from Canvas",
  "image.upload.tooltip.image.curlayer": "Get image from Current Layer",
  "image.upload.tooltip.mask.canvas": "Get mask from Canvas",
  "image.upload.tooltip.mask.curlayer": "Get mask from Current Layer",
  "image.upload.tooltip.mask.selection": "Get mask from Selection",
  "image.upload.tooltip.cut_action": "Upload Image +\nSelection Mask",
  "image.upload.tooltip.scan_action": "Get image &\nLimit image boundary",
  "image.upload.tooltip.autosync.on": "Auto Sync: on",
  "image.upload.tooltip.autosync.off": "Auto Sync: off",
  "image.upload.tooltip.sync_action": "Sync current content",
  "image.upload.tooltip.more_options_hint": "Hold Shift for more options; Ctrl for single fetch",
  "image.upload.tooltip.current.canvas": "Current selection: Canvas",
  "image.upload.tooltip.current.layer": "Current selection: Layer",
  "image.upload.tooltip.current.layer_named": "Current selection: Layer {{layerName}}",
  "image.upload.tooltip.current.file": "Current option: File",
  "image.upload.autosync.fetching": "Auto fetching…",
  "image.upload.autosync.status.enabled": "Auto sync in progress…",
  "image.upload.autosync.status.disabled": "Auto sync is off",
  "image.upload.retry": "Retry",
  "image.pack.local.button": "Local image pack",
  "image.pack.local.empty": "No images yet",
  "image.auto_send_enabled": "Auto send enabled",
  "image.auto_send_disabled": "Auto send disabled",
  "image.upload.primary.auto": "Auto fetching…",
  "image.upload.primary.manual": "Get Image",
  "image.upload.primary.cut": "Crop",
  "image.upload.primary.scan": "Scan",
  "image.upload.primary.hint": "This node defaults to current layer + mask",
  "image.upload.primary.hint.line1": "Defaults using",
  "image.upload.primary.hint.line2": "Main Image",
  "workflow.output.destination.title": "Output to:",
  "workflow.output.destination.canvas": "Full Canvas",
  "image.upload.primary.advanced": "Advanced selection",
  "image.upload.primary.advanced.modify": "Modify",
  "image.upload.primary.advanced.reset": "Reset",
  "image.upload.primary.advanced.local_file": "Local file",
  "image.upload.primary.advanced.content.canvas": "Canvas",
  "image.upload.primary.advanced.content.curlayer": "Current layer",
  "image.upload.primary.advanced.content.selection": "Selection",
  "image.upload.primary.advanced.boundary.canvas": "Canvas boundary",
  "image.upload.primary.advanced.boundary.curlayer": "Current layer boundary",
  "image.upload.primary.advanced.boundary.selection": "Selection boundary",
  "image.upload.primary.advanced.boundary.primary": "Primary boundary",
  "image.upload.mode.file.label": "File",
  "image.upload.mode.layer.label": "Layer",
  "image.upload.mode.canvas.label": "Canvas",
  "image.upload.source.file.tooltip": "Upload from disk",
  "image.upload.source.layer.tooltip": "Use current layer",
  "image.upload.source.canvas.tooltip": "Use entire canvas",
  "image.upload.dropHint": "Drag images here and release to upload",
  "image.upload.tooltip.clear_action": "Clear selection",
  "image.upload.status.layer.short_named": "Layer {{layerName}}",
  "image.upload.status.layer.short": "Layer",
  "image.upload.status.file.short": "Local file",
  "image.upload.status.canvas.short": "Canvas",
  "image.upload.status.file.active": "Using local file",
  "image.upload.status.file.resetHint": "Click to remove local file",
  "image.upload.status.mask.resetHint": "Click to restore default mask",
  "image.upload.status.mask.modified": "Masked",
  "image.upload.status.boundary.resetHint": "Click to restore default boundary",
  "image.upload.status.boundary.modified": "Rescoped",
  "image.upload.mask.button": "Selection mask",
  "image.upload.mask.selection": "Selection mask",
  "image.upload.mask.layer": "Layer mask",
  "image.upload.remove_slot": "Remove slot",
  "image.upload.add_slot": "Add slot",
  "video.local.button": "Local video",
  "video.local.empty": "No videos yet",
  "video.local.remove": "Remove video",
  // Source render component related translations
  "source.source": "Source",
  "source.content": "Content",
  "source.boundary": "Bounds",
  "source.mask": "Mask",
  "source.disk": "Disk",
  "source.remote": "Remote",
  "source.unknown": "Unknown",
  "source.ps_image": "PS",
  "source.ps_mask": "PS",
  "source.canvas": "Canvas",
  "source.current_layer": "CurLayer",
  "source.selection": "Selection",
  "source.quality_percent": "Quality {{percent}}%",
  "source.crop.positive": "Positive Crop",
  "source.crop.negative": "Negative Crop",
  "source.reverse": "Reverse",
  "send_images.create_document": "Create document",
  "send_images.create_document_failed": "Create document failed",
  // Photoshop operations translations
  "photoshop.no_active_document": "No active document",
  "photoshop.rectangle_coordinates_required": "Rectangle coordinates required for create action",
  "photoshop.create_guide_frame": "Create guide frame",
  "photoshop.clear_guide_frame": "Clear guide frame",
  "photoshop.invalid_action": "Invalid action: {{action}}",
  "photoshop.file_not_found": "File not found: {{path}}",
  "photoshop.failed_to_open_file_as_document": "Failed to open file as document: {{path}}",
  "photoshop.invalid_boundary": "Invalid boundary: left must be less than right, top must be less than bottom",
  "photoshop.failed_to_open_image_file": "Failed to open image file: {{error}}",
  "photoshop.open_images_from_file": "Open images from file",
  "photoshop.failed_to_create_document_from_file": "Failed to create document from file",
  // Google provider translations
  "google.field.image_input": "Input Image",
  "google.field.prompt": "Prompt",
  "google.field.batch_count": "Batch Count",
  "google.field.images_per_batch": "Images Per Batch",
  "google.status.success": "Success",
  "google.status.failed": "Failed",
  "google.status.generating": "Generating",
  "google.apikey_placeholder": "Enter Google API Key",
  "google.get_apikey": "Get API Key",
  "google.baseurl_placeholder": "Base URL",
  "google.help_tooltip": "Google Gemini Image Generator",
  "google.model_name": "Gemini 2.5 Flash Image",
  "google.model_label": "Model",
  "google.model_placeholder": "Select a model",
  "google.stop": "Stop",
  "google.loading": "Loading...",
  "google.generating": "Generating...",
  "google.generate": "Generate",
  // Image preview auto toggle
  "image.auto_toggle": "AUTO",
  // Import mode related
  "image.import_as_smartobject": "Import as Smart Object",
  "image.import_as_newdoc": "Import as New Document",
  "image.import_to_selection": "Send to Selection",
  "image.boundary": "Boundary",
  "image.import_tip": "Hold Shift key to import as new document",
  // === Auto-added missing keys ===
  "auth.guest_login_success": "Guest login successful",
  "boundary.canvas": "Canvas",
  "boundary.select_boundary": "Select boundary",
  "boundary.selection": "Selection",
  "boundary.max_size": "Max size (px)",
  "boundary.max_size_error": "Enter a pixel value greater than 0",
  "boundary.max_size_hint": "Leave empty for no limit",
  "boundary.max_size_placeholder": "Leave empty for no limit",
  "boundary.no_limit": "No limit",
  "boundary.image_quality": "Image quality (%)",
  "boundary.image_quality_required": "Enter a quality percentage",
  "boundary.image_quality_range": "Range 1-100",
  "boundary.preview_main_image": "Output to",
  "boundary.preview_select": "Get selection",
  "boundary.preview_alt": "Boundary preview",
  "boundary.preview_placeholder": "Click to use current selection",
  "boundary.settings": "Adjust input settings",
  "convert widget {0} failed:": "Failed to convert widget {0}:",
  "document {0} not found": "Document {0} not found",
  "image.document.new": "New Document",
  "image.layer.smart_object": "Smart Object Layer",
  "layer not found {0}": "Layer {0} not found",
  "photoshop.invalid_boundary_type": "Invalid boundary type: {{type}}",
  "photoshop.no_active_layer": "No active layer",
  // Image source dialog
  "dialog.image_source.title": "Select Image Source",
  "dialog.image_source.primary_canvas": "Fetch canvas with primary boundary",
  "dialog.image_source.primary_curlayer": "Fetch current layer with primary boundary",
  "dialog.image_source.canvas_canvas": "Fetch canvas with canvas boundary",
  "dialog.image_source.canvas_curlayer": "Fetch current layer with canvas boundary",
  "dialog.image_source.curlayer_canvas": "Fetch canvas with current-layer boundary",
  "dialog.image_source.curlayer_curlayer": "Fetch current layer with current-layer boundary",
  "dialog.image_source.local_file": "Import from disk",
  "dialog.simple_source.title": "Select Source",
  "dialog.simple_source.canvas": "Canvas",
  "dialog.simple_source.current_layer": "Current Layer",
  "dialog.simple_source.local_file": "Choose File",
  "dialog.simple_source.no_active_layer": "No active layer available",
  "dialog.simple_source.pick_error": "Failed to pick file. Please try again."
};
const isString = (obj) => typeof obj === "string";
const defer = () => {
  let res;
  let rej;
  const promise = new Promise((resolve2, reject2) => {
    res = resolve2;
    rej = reject2;
  });
  promise.resolve = res;
  promise.reject = rej;
  return promise;
};
const makeString = (object) => {
  if (object == null) return "";
  return "" + object;
};
const copy = (a2, s2, t2) => {
  a2.forEach((m) => {
    if (s2[m]) t2[m] = s2[m];
  });
};
const lastOfPathSeparatorRegExp = /###/g;
const cleanKey = (key2) => key2 && key2.indexOf("###") > -1 ? key2.replace(lastOfPathSeparatorRegExp, ".") : key2;
const canNotTraverseDeeper = (object) => !object || isString(object);
const getLastOfPath = (object, path, Empty) => {
  const stack = !isString(path) ? path : path.split(".");
  let stackIndex = 0;
  while (stackIndex < stack.length - 1) {
    if (canNotTraverseDeeper(object)) return {};
    const key2 = cleanKey(stack[stackIndex]);
    if (!object[key2] && Empty) object[key2] = new Empty();
    if (Object.prototype.hasOwnProperty.call(object, key2)) {
      object = object[key2];
    } else {
      object = {};
    }
    ++stackIndex;
  }
  if (canNotTraverseDeeper(object)) return {};
  return {
    obj: object,
    k: cleanKey(stack[stackIndex])
  };
};
const setPath = (object, path, newValue) => {
  const {
    obj,
    k: k2
  } = getLastOfPath(object, path, Object);
  if (obj !== void 0 || path.length === 1) {
    obj[k2] = newValue;
    return;
  }
  let e4 = path[path.length - 1];
  let p2 = path.slice(0, path.length - 1);
  let last = getLastOfPath(object, p2, Object);
  while (last.obj === void 0 && p2.length) {
    e4 = `${p2[p2.length - 1]}.${e4}`;
    p2 = p2.slice(0, p2.length - 1);
    last = getLastOfPath(object, p2, Object);
    if ((last == null ? void 0 : last.obj) && typeof last.obj[`${last.k}.${e4}`] !== "undefined") {
      last.obj = void 0;
    }
  }
  last.obj[`${last.k}.${e4}`] = newValue;
};
const pushPath = (object, path, newValue, concat) => {
  const {
    obj,
    k: k2
  } = getLastOfPath(object, path, Object);
  obj[k2] = obj[k2] || [];
  obj[k2].push(newValue);
};
const getPath = (object, path) => {
  const {
    obj,
    k: k2
  } = getLastOfPath(object, path);
  if (!obj) return void 0;
  if (!Object.prototype.hasOwnProperty.call(obj, k2)) return void 0;
  return obj[k2];
};
const getPathWithDefaults = (data2, defaultData, key2) => {
  const value = getPath(data2, key2);
  if (value !== void 0) {
    return value;
  }
  return getPath(defaultData, key2);
};
const deepExtend = (target, source, overwrite) => {
  for (const prop in source) {
    if (prop !== "__proto__" && prop !== "constructor") {
      if (prop in target) {
        if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
          if (overwrite) target[prop] = source[prop];
        } else {
          deepExtend(target[prop], source[prop], overwrite);
        }
      } else {
        target[prop] = source[prop];
      }
    }
  }
  return target;
};
const regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
var _entityMap = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;",
  "/": "&#x2F;"
};
const escape$1 = (data2) => {
  if (isString(data2)) {
    return data2.replace(/[&<>"'\/]/g, (s2) => _entityMap[s2]);
  }
  return data2;
};
class RegExpCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.regExpMap = /* @__PURE__ */ new Map();
    this.regExpQueue = [];
  }
  getRegExp(pattern2) {
    const regExpFromCache = this.regExpMap.get(pattern2);
    if (regExpFromCache !== void 0) {
      return regExpFromCache;
    }
    const regExpNew = new RegExp(pattern2);
    if (this.regExpQueue.length === this.capacity) {
      this.regExpMap.delete(this.regExpQueue.shift());
    }
    this.regExpMap.set(pattern2, regExpNew);
    this.regExpQueue.push(pattern2);
    return regExpNew;
  }
}
const chars = [" ", ",", "?", "!", ";"];
const looksLikeObjectPathRegExpCache = new RegExpCache(20);
const looksLikeObjectPath = (key2, nsSeparator, keySeparator) => {
  nsSeparator = nsSeparator || "";
  keySeparator = keySeparator || "";
  const possibleChars = chars.filter((c2) => nsSeparator.indexOf(c2) < 0 && keySeparator.indexOf(c2) < 0);
  if (possibleChars.length === 0) return true;
  const r2 = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c2) => c2 === "?" ? "\\?" : c2).join("|")})`);
  let matched = !r2.test(key2);
  if (!matched) {
    const ki = key2.indexOf(keySeparator);
    if (ki > 0 && !r2.test(key2.substring(0, ki))) {
      matched = true;
    }
  }
  return matched;
};
const deepFind = (obj, path, keySeparator = ".") => {
  if (!obj) return void 0;
  if (obj[path]) {
    if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
    return obj[path];
  }
  const tokens = path.split(keySeparator);
  let current = obj;
  for (let i2 = 0; i2 < tokens.length; ) {
    if (!current || typeof current !== "object") {
      return void 0;
    }
    let next;
    let nextPath = "";
    for (let j = i2; j < tokens.length; ++j) {
      if (j !== i2) {
        nextPath += keySeparator;
      }
      nextPath += tokens[j];
      next = current[nextPath];
      if (next !== void 0) {
        if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
          continue;
        }
        i2 += j - i2 + 1;
        break;
      }
    }
    current = next;
  }
  return current;
};
const getCleanedCode = (code) => code == null ? void 0 : code.replace("_", "-");
const consoleLogger = {
  type: "logger",
  log(args) {
    this.output("log", args);
  },
  warn(args) {
    this.output("warn", args);
  },
  error(args) {
    this.output("error", args);
  },
  output(type2, args) {
    var _a3, _b2;
    (_b2 = (_a3 = console == null ? void 0 : console[type2]) == null ? void 0 : _a3.apply) == null ? void 0 : _b2.call(_a3, console, args);
  }
};
class Logger {
  constructor(concreteLogger, options2 = {}) {
    this.init(concreteLogger, options2);
  }
  init(concreteLogger, options2 = {}) {
    this.prefix = options2.prefix || "i18next:";
    this.logger = concreteLogger || consoleLogger;
    this.options = options2;
    this.debug = options2.debug;
  }
  log(...args) {
    return this.forward(args, "log", "", true);
  }
  warn(...args) {
    return this.forward(args, "warn", "", true);
  }
  error(...args) {
    return this.forward(args, "error", "");
  }
  deprecate(...args) {
    return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
  }
  forward(args, lvl, prefix, debugOnly) {
    if (debugOnly && !this.debug) return null;
    if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
    return this.logger[lvl](args);
  }
  create(moduleName) {
    return new Logger(this.logger, {
      ...{
        prefix: `${this.prefix}:${moduleName}:`
      },
      ...this.options
    });
  }
  clone(options2) {
    options2 = options2 || this.options;
    options2.prefix = options2.prefix || this.prefix;
    return new Logger(this.logger, options2);
  }
}
var baseLogger = new Logger();
class EventEmitter {
  constructor() {
    this.observers = {};
  }
  on(events2, listener) {
    events2.split(" ").forEach((event) => {
      if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
      const numListeners = this.observers[event].get(listener) || 0;
      this.observers[event].set(listener, numListeners + 1);
    });
    return this;
  }
  off(event, listener) {
    if (!this.observers[event]) return;
    if (!listener) {
      delete this.observers[event];
      return;
    }
    this.observers[event].delete(listener);
  }
  emit(event, ...args) {
    if (this.observers[event]) {
      const cloned = Array.from(this.observers[event].entries());
      cloned.forEach(([observer, numTimesAdded]) => {
        for (let i2 = 0; i2 < numTimesAdded; i2++) {
          observer(...args);
        }
      });
    }
    if (this.observers["*"]) {
      const cloned = Array.from(this.observers["*"].entries());
      cloned.forEach(([observer, numTimesAdded]) => {
        for (let i2 = 0; i2 < numTimesAdded; i2++) {
          observer.apply(observer, [event, ...args]);
        }
      });
    }
  }
}
class ResourceStore extends EventEmitter {
  constructor(data2, options2 = {
    ns: ["translation"],
    defaultNS: "translation"
  }) {
    super();
    this.data = data2 || {};
    this.options = options2;
    if (this.options.keySeparator === void 0) {
      this.options.keySeparator = ".";
    }
    if (this.options.ignoreJSONStructure === void 0) {
      this.options.ignoreJSONStructure = true;
    }
  }
  addNamespaces(ns) {
    if (this.options.ns.indexOf(ns) < 0) {
      this.options.ns.push(ns);
    }
  }
  removeNamespaces(ns) {
    const index2 = this.options.ns.indexOf(ns);
    if (index2 > -1) {
      this.options.ns.splice(index2, 1);
    }
  }
  getResource(lng, ns, key2, options2 = {}) {
    var _a3, _b2;
    const keySeparator = options2.keySeparator !== void 0 ? options2.keySeparator : this.options.keySeparator;
    const ignoreJSONStructure = options2.ignoreJSONStructure !== void 0 ? options2.ignoreJSONStructure : this.options.ignoreJSONStructure;
    let path;
    if (lng.indexOf(".") > -1) {
      path = lng.split(".");
    } else {
      path = [lng, ns];
      if (key2) {
        if (Array.isArray(key2)) {
          path.push(...key2);
        } else if (isString(key2) && keySeparator) {
          path.push(...key2.split(keySeparator));
        } else {
          path.push(key2);
        }
      }
    }
    const result = getPath(this.data, path);
    if (!result && !ns && !key2 && lng.indexOf(".") > -1) {
      lng = path[0];
      ns = path[1];
      key2 = path.slice(2).join(".");
    }
    if (result || !ignoreJSONStructure || !isString(key2)) return result;
    return deepFind((_b2 = (_a3 = this.data) == null ? void 0 : _a3[lng]) == null ? void 0 : _b2[ns], key2, keySeparator);
  }
  addResource(lng, ns, key2, value, options2 = {
    silent: false
  }) {
    const keySeparator = options2.keySeparator !== void 0 ? options2.keySeparator : this.options.keySeparator;
    let path = [lng, ns];
    if (key2) path = path.concat(keySeparator ? key2.split(keySeparator) : key2);
    if (lng.indexOf(".") > -1) {
      path = lng.split(".");
      value = ns;
      ns = path[1];
    }
    this.addNamespaces(ns);
    setPath(this.data, path, value);
    if (!options2.silent) this.emit("added", lng, ns, key2, value);
  }
  addResources(lng, ns, resources, options2 = {
    silent: false
  }) {
    for (const m in resources) {
      if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
        silent: true
      });
    }
    if (!options2.silent) this.emit("added", lng, ns, resources);
  }
  addResourceBundle(lng, ns, resources, deep, overwrite, options2 = {
    silent: false,
    skipCopy: false
  }) {
    let path = [lng, ns];
    if (lng.indexOf(".") > -1) {
      path = lng.split(".");
      deep = resources;
      resources = ns;
      ns = path[1];
    }
    this.addNamespaces(ns);
    let pack = getPath(this.data, path) || {};
    if (!options2.skipCopy) resources = JSON.parse(JSON.stringify(resources));
    if (deep) {
      deepExtend(pack, resources, overwrite);
    } else {
      pack = {
        ...pack,
        ...resources
      };
    }
    setPath(this.data, path, pack);
    if (!options2.silent) this.emit("added", lng, ns, resources);
  }
  removeResourceBundle(lng, ns) {
    if (this.hasResourceBundle(lng, ns)) {
      delete this.data[lng][ns];
    }
    this.removeNamespaces(ns);
    this.emit("removed", lng, ns);
  }
  hasResourceBundle(lng, ns) {
    return this.getResource(lng, ns) !== void 0;
  }
  getResourceBundle(lng, ns) {
    if (!ns) ns = this.options.defaultNS;
    return this.getResource(lng, ns);
  }
  getDataByLanguage(lng) {
    return this.data[lng];
  }
  hasLanguageSomeTranslations(lng) {
    const data2 = this.getDataByLanguage(lng);
    const n2 = data2 && Object.keys(data2) || [];
    return !!n2.find((v2) => data2[v2] && Object.keys(data2[v2]).length > 0);
  }
  toJSON() {
    return this.data;
  }
}
var postProcessor = {
  processors: {},
  addPostProcessor(module2) {
    this.processors[module2.name] = module2;
  },
  handle(processors, value, key2, options2, translator) {
    processors.forEach((processor) => {
      var _a3;
      value = ((_a3 = this.processors[processor]) == null ? void 0 : _a3.process(value, key2, options2, translator)) ?? value;
    });
    return value;
  }
};
const checkedLoadedFor = {};
const shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
class Translator extends EventEmitter {
  constructor(services, options2 = {}) {
    super();
    copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
    this.options = options2;
    if (this.options.keySeparator === void 0) {
      this.options.keySeparator = ".";
    }
    this.logger = baseLogger.create("translator");
  }
  changeLanguage(lng) {
    if (lng) this.language = lng;
  }
  exists(key2, o2 = {
    interpolation: {}
  }) {
    const opt = {
      ...o2
    };
    if (key2 == null) return false;
    const resolved = this.resolve(key2, opt);
    return (resolved == null ? void 0 : resolved.res) !== void 0;
  }
  extractFromKey(key2, opt) {
    let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
    if (nsSeparator === void 0) nsSeparator = ":";
    const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
    let namespaces = opt.ns || this.options.defaultNS || [];
    const wouldCheckForNsInKey = nsSeparator && key2.indexOf(nsSeparator) > -1;
    const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key2, nsSeparator, keySeparator);
    if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
      const m = key2.match(this.interpolator.nestingRegexp);
      if (m && m.length > 0) {
        return {
          key: key2,
          namespaces: isString(namespaces) ? [namespaces] : namespaces
        };
      }
      const parts = key2.split(nsSeparator);
      if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
      key2 = parts.join(keySeparator);
    }
    return {
      key: key2,
      namespaces: isString(namespaces) ? [namespaces] : namespaces
    };
  }
  translate(keys, o2, lastKey) {
    let opt = typeof o2 === "object" ? {
      ...o2
    } : o2;
    if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
      opt = this.options.overloadTranslationOptionHandler(arguments);
    }
    if (typeof options === "object") opt = {
      ...opt
    };
    if (!opt) opt = {};
    if (keys == null) return "";
    if (!Array.isArray(keys)) keys = [String(keys)];
    const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
    const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
    const {
      key: key2,
      namespaces
    } = this.extractFromKey(keys[keys.length - 1], opt);
    const namespace = namespaces[namespaces.length - 1];
    let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
    if (nsSeparator === void 0) nsSeparator = ":";
    const lng = opt.lng || this.language;
    const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
    if ((lng == null ? void 0 : lng.toLowerCase()) === "cimode") {
      if (appendNamespaceToCIMode) {
        if (returnDetails) {
          return {
            res: `${namespace}${nsSeparator}${key2}`,
            usedKey: key2,
            exactUsedKey: key2,
            usedLng: lng,
            usedNS: namespace,
            usedParams: this.getUsedParamsDetails(opt)
          };
        }
        return `${namespace}${nsSeparator}${key2}`;
      }
      if (returnDetails) {
        return {
          res: key2,
          usedKey: key2,
          exactUsedKey: key2,
          usedLng: lng,
          usedNS: namespace,
          usedParams: this.getUsedParamsDetails(opt)
        };
      }
      return key2;
    }
    const resolved = this.resolve(keys, opt);
    let res = resolved == null ? void 0 : resolved.res;
    const resUsedKey = (resolved == null ? void 0 : resolved.usedKey) || key2;
    const resExactUsedKey = (resolved == null ? void 0 : resolved.exactUsedKey) || key2;
    const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
    const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
    const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
    const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
    const hasDefaultValue = Translator.hasDefaultValue(opt);
    const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
    const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
      ordinal: false
    }) : "";
    const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
    const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
    let resForObjHndl = res;
    if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
      resForObjHndl = defaultValue;
    }
    const handleAsObject = shouldHandleAsObject(resForObjHndl);
    const resType = Object.prototype.toString.apply(resForObjHndl);
    if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
      if (!opt.returnObjects && !this.options.returnObjects) {
        if (!this.options.returnedObjectHandler) {
          this.logger.warn("accessing an object - but returnObjects options is not enabled!");
        }
        const r2 = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
          ...opt,
          ns: namespaces
        }) : `key '${key2} (${this.language})' returned an object instead of string.`;
        if (returnDetails) {
          resolved.res = r2;
          resolved.usedParams = this.getUsedParamsDetails(opt);
          return resolved;
        }
        return r2;
      }
      if (keySeparator) {
        const resTypeIsArray = Array.isArray(resForObjHndl);
        const copy2 = resTypeIsArray ? [] : {};
        const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
        for (const m in resForObjHndl) {
          if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
            const deepKey = `${newKeyToUse}${keySeparator}${m}`;
            if (hasDefaultValue && !res) {
              copy2[m] = this.translate(deepKey, {
                ...opt,
                defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
                ...{
                  joinArrays: false,
                  ns: namespaces
                }
              });
            } else {
              copy2[m] = this.translate(deepKey, {
                ...opt,
                ...{
                  joinArrays: false,
                  ns: namespaces
                }
              });
            }
            if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
          }
        }
        res = copy2;
      }
    } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
      res = res.join(joinArrays);
      if (res) res = this.extendTranslation(res, keys, opt, lastKey);
    } else {
      let usedDefault = false;
      let usedKey = false;
      if (!this.isValidLookup(res) && hasDefaultValue) {
        usedDefault = true;
        res = defaultValue;
      }
      if (!this.isValidLookup(res)) {
        usedKey = true;
        res = key2;
      }
      const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
      const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
      const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
      if (usedKey || usedDefault || updateMissing) {
        this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key2, updateMissing ? defaultValue : res);
        if (keySeparator) {
          const fk = this.resolve(key2, {
            ...opt,
            keySeparator: false
          });
          if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
        }
        let lngs = [];
        const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
        if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
          for (let i2 = 0; i2 < fallbackLngs.length; i2++) {
            lngs.push(fallbackLngs[i2]);
          }
        } else if (this.options.saveMissingTo === "all") {
          lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
        } else {
          lngs.push(opt.lng || this.language);
        }
        const send = (l2, k2, specificDefaultValue) => {
          var _a3;
          const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
          if (this.options.missingKeyHandler) {
            this.options.missingKeyHandler(l2, namespace, k2, defaultForMissing, updateMissing, opt);
          } else if ((_a3 = this.backendConnector) == null ? void 0 : _a3.saveMissing) {
            this.backendConnector.saveMissing(l2, namespace, k2, defaultForMissing, updateMissing, opt);
          }
          this.emit("missingKey", l2, namespace, k2, res);
        };
        if (this.options.saveMissing) {
          if (this.options.saveMissingPlurals && needsPluralHandling) {
            lngs.forEach((language) => {
              const suffixes = this.pluralResolver.getSuffixes(language, opt);
              if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
                suffixes.push(`${this.options.pluralSeparator}zero`);
              }
              suffixes.forEach((suffix) => {
                send([language], key2 + suffix, opt[`defaultValue${suffix}`] || defaultValue);
              });
            });
          } else {
            send(lngs, key2, defaultValue);
          }
        }
      }
      res = this.extendTranslation(res, keys, opt, resolved, lastKey);
      if (usedKey && res === key2 && this.options.appendNamespaceToMissingKey) {
        res = `${namespace}${nsSeparator}${key2}`;
      }
      if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
        res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key2}` : key2, usedDefault ? res : void 0, opt);
      }
    }
    if (returnDetails) {
      resolved.res = res;
      resolved.usedParams = this.getUsedParamsDetails(opt);
      return resolved;
    }
    return res;
  }
  extendTranslation(res, key2, opt, resolved, lastKey) {
    var _a3, _b2;
    if ((_a3 = this.i18nFormat) == null ? void 0 : _a3.parse) {
      res = this.i18nFormat.parse(res, {
        ...this.options.interpolation.defaultVariables,
        ...opt
      }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
        resolved
      });
    } else if (!opt.skipInterpolation) {
      if (opt.interpolation) this.interpolator.init({
        ...opt,
        ...{
          interpolation: {
            ...this.options.interpolation,
            ...opt.interpolation
          }
        }
      });
      const skipOnVariables = isString(res) && (((_b2 = opt == null ? void 0 : opt.interpolation) == null ? void 0 : _b2.skipOnVariables) !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
      let nestBef;
      if (skipOnVariables) {
        const nb = res.match(this.interpolator.nestingRegexp);
        nestBef = nb && nb.length;
      }
      let data2 = opt.replace && !isString(opt.replace) ? opt.replace : opt;
      if (this.options.interpolation.defaultVariables) data2 = {
        ...this.options.interpolation.defaultVariables,
        ...data2
      };
      res = this.interpolator.interpolate(res, data2, opt.lng || this.language || resolved.usedLng, opt);
      if (skipOnVariables) {
        const na = res.match(this.interpolator.nestingRegexp);
        const nestAft = na && na.length;
        if (nestBef < nestAft) opt.nest = false;
      }
      if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
      if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
        if ((lastKey == null ? void 0 : lastKey[0]) === args[0] && !opt.context) {
          this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key2[0]}`);
          return null;
        }
        return this.translate(...args, key2);
      }, opt);
      if (opt.interpolation) this.interpolator.reset();
    }
    const postProcess = opt.postProcess || this.options.postProcess;
    const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
    if (res != null && (postProcessorNames == null ? void 0 : postProcessorNames.length) && opt.applyPostProcessor !== false) {
      res = postProcessor.handle(postProcessorNames, res, key2, this.options && this.options.postProcessPassResolved ? {
        i18nResolved: {
          ...resolved,
          usedParams: this.getUsedParamsDetails(opt)
        },
        ...opt
      } : opt, this);
    }
    return res;
  }
  resolve(keys, opt = {}) {
    let found;
    let usedKey;
    let exactUsedKey;
    let usedLng;
    let usedNS;
    if (isString(keys)) keys = [keys];
    keys.forEach((k2) => {
      if (this.isValidLookup(found)) return;
      const extracted = this.extractFromKey(k2, opt);
      const key2 = extracted.key;
      usedKey = key2;
      let namespaces = extracted.namespaces;
      if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
      const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
      const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
      const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
      const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
      namespaces.forEach((ns) => {
        var _a3, _b2;
        if (this.isValidLookup(found)) return;
        usedNS = ns;
        if (!checkedLoadedFor[`${codes[0]}-${ns}`] && ((_a3 = this.utils) == null ? void 0 : _a3.hasLoadedNamespace) && !((_b2 = this.utils) == null ? void 0 : _b2.hasLoadedNamespace(usedNS))) {
          checkedLoadedFor[`${codes[0]}-${ns}`] = true;
          this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
        }
        codes.forEach((code) => {
          var _a4;
          if (this.isValidLookup(found)) return;
          usedLng = code;
          const finalKeys = [key2];
          if ((_a4 = this.i18nFormat) == null ? void 0 : _a4.addLookupKeys) {
            this.i18nFormat.addLookupKeys(finalKeys, key2, code, ns, opt);
          } else {
            let pluralSuffix;
            if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
            const zeroSuffix = `${this.options.pluralSeparator}zero`;
            const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
            if (needsPluralHandling) {
              finalKeys.push(key2 + pluralSuffix);
              if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
                finalKeys.push(key2 + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
              }
              if (needsZeroSuffixLookup) {
                finalKeys.push(key2 + zeroSuffix);
              }
            }
            if (needsContextHandling) {
              const contextKey = `${key2}${this.options.contextSeparator}${opt.context}`;
              finalKeys.push(contextKey);
              if (needsPluralHandling) {
                finalKeys.push(contextKey + pluralSuffix);
                if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
                  finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
                }
                if (needsZeroSuffixLookup) {
                  finalKeys.push(contextKey + zeroSuffix);
                }
              }
            }
          }
          let possibleKey;
          while (possibleKey = finalKeys.pop()) {
            if (!this.isValidLookup(found)) {
              exactUsedKey = possibleKey;
              found = this.getResource(code, ns, possibleKey, opt);
            }
          }
        });
      });
    });
    return {
      res: found,
      usedKey,
      exactUsedKey,
      usedLng,
      usedNS
    };
  }
  isValidLookup(res) {
    return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
  }
  getResource(code, ns, key2, options2 = {}) {
    var _a3;
    if ((_a3 = this.i18nFormat) == null ? void 0 : _a3.getResource) return this.i18nFormat.getResource(code, ns, key2, options2);
    return this.resourceStore.getResource(code, ns, key2, options2);
  }
  getUsedParamsDetails(options2 = {}) {
    const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
    const useOptionsReplaceForData = options2.replace && !isString(options2.replace);
    let data2 = useOptionsReplaceForData ? options2.replace : options2;
    if (useOptionsReplaceForData && typeof options2.count !== "undefined") {
      data2.count = options2.count;
    }
    if (this.options.interpolation.defaultVariables) {
      data2 = {
        ...this.options.interpolation.defaultVariables,
        ...data2
      };
    }
    if (!useOptionsReplaceForData) {
      data2 = {
        ...data2
      };
      for (const key2 of optionsKeys) {
        delete data2[key2];
      }
    }
    return data2;
  }
  static hasDefaultValue(options2) {
    const prefix = "defaultValue";
    for (const option in options2) {
      if (Object.prototype.hasOwnProperty.call(options2, option) && prefix === option.substring(0, prefix.length) && void 0 !== options2[option]) {
        return true;
      }
    }
    return false;
  }
}
class LanguageUtil {
  constructor(options2) {
    this.options = options2;
    this.supportedLngs = this.options.supportedLngs || false;
    this.logger = baseLogger.create("languageUtils");
  }
  getScriptPartFromCode(code) {
    code = getCleanedCode(code);
    if (!code || code.indexOf("-") < 0) return null;
    const p2 = code.split("-");
    if (p2.length === 2) return null;
    p2.pop();
    if (p2[p2.length - 1].toLowerCase() === "x") return null;
    return this.formatLanguageCode(p2.join("-"));
  }
  getLanguagePartFromCode(code) {
    code = getCleanedCode(code);
    if (!code || code.indexOf("-") < 0) return code;
    const p2 = code.split("-");
    return this.formatLanguageCode(p2[0]);
  }
  formatLanguageCode(code) {
    if (isString(code) && code.indexOf("-") > -1) {
      let formattedCode;
      try {
        formattedCode = Intl.getCanonicalLocales(code)[0];
      } catch (e4) {
      }
      if (formattedCode && this.options.lowerCaseLng) {
        formattedCode = formattedCode.toLowerCase();
      }
      if (formattedCode) return formattedCode;
      if (this.options.lowerCaseLng) {
        return code.toLowerCase();
      }
      return code;
    }
    return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
  }
  isSupportedCode(code) {
    if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
      code = this.getLanguagePartFromCode(code);
    }
    return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
  }
  getBestMatchFromCodes(codes) {
    if (!codes) return null;
    let found;
    codes.forEach((code) => {
      if (found) return;
      const cleanedLng = this.formatLanguageCode(code);
      if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
    });
    if (!found && this.options.supportedLngs) {
      codes.forEach((code) => {
        if (found) return;
        const lngScOnly = this.getScriptPartFromCode(code);
        if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
        const lngOnly = this.getLanguagePartFromCode(code);
        if (this.isSupportedCode(lngOnly)) return found = lngOnly;
        found = this.options.supportedLngs.find((supportedLng) => {
          if (supportedLng === lngOnly) return supportedLng;
          if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
          if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
          if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
        });
      });
    }
    if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
    return found;
  }
  getFallbackCodes(fallbacks, code) {
    if (!fallbacks) return [];
    if (typeof fallbacks === "function") fallbacks = fallbacks(code);
    if (isString(fallbacks)) fallbacks = [fallbacks];
    if (Array.isArray(fallbacks)) return fallbacks;
    if (!code) return fallbacks.default || [];
    let found = fallbacks[code];
    if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
    if (!found) found = fallbacks[this.formatLanguageCode(code)];
    if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
    if (!found) found = fallbacks.default;
    return found || [];
  }
  toResolveHierarchy(code, fallbackCode) {
    const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
    const codes = [];
    const addCode = (c2) => {
      if (!c2) return;
      if (this.isSupportedCode(c2)) {
        codes.push(c2);
      } else {
        this.logger.warn(`rejecting language code not found in supportedLngs: ${c2}`);
      }
    };
    if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
      if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
      if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
      if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
    } else if (isString(code)) {
      addCode(this.formatLanguageCode(code));
    }
    fallbackCodes.forEach((fc) => {
      if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
    });
    return codes;
  }
}
const suffixesOrder = {
  zero: 0,
  one: 1,
  two: 2,
  few: 3,
  many: 4,
  other: 5
};
const dummyRule = {
  select: (count) => count === 1 ? "one" : "other",
  resolvedOptions: () => ({
    pluralCategories: ["one", "other"]
  })
};
class PluralResolver {
  constructor(languageUtils, options2 = {}) {
    this.languageUtils = languageUtils;
    this.options = options2;
    this.logger = baseLogger.create("pluralResolver");
    this.pluralRulesCache = {};
  }
  addRule(lng, obj) {
    this.rules[lng] = obj;
  }
  clearCache() {
    this.pluralRulesCache = {};
  }
  getRule(code, options2 = {}) {
    const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
    const type2 = options2.ordinal ? "ordinal" : "cardinal";
    const cacheKey = JSON.stringify({
      cleanedCode,
      type: type2
    });
    if (cacheKey in this.pluralRulesCache) {
      return this.pluralRulesCache[cacheKey];
    }
    let rule;
    try {
      rule = new Intl.PluralRules(cleanedCode, {
        type: type2
      });
    } catch (err) {
      if (!Intl) {
        this.logger.error("No Intl support, please use an Intl polyfill!");
        return dummyRule;
      }
      if (!code.match(/-|_/)) return dummyRule;
      const lngPart = this.languageUtils.getLanguagePartFromCode(code);
      rule = this.getRule(lngPart, options2);
    }
    this.pluralRulesCache[cacheKey] = rule;
    return rule;
  }
  needsPlural(code, options2 = {}) {
    let rule = this.getRule(code, options2);
    if (!rule) rule = this.getRule("dev", options2);
    return (rule == null ? void 0 : rule.resolvedOptions().pluralCategories.length) > 1;
  }
  getPluralFormsOfKey(code, key2, options2 = {}) {
    return this.getSuffixes(code, options2).map((suffix) => `${key2}${suffix}`);
  }
  getSuffixes(code, options2 = {}) {
    let rule = this.getRule(code, options2);
    if (!rule) rule = this.getRule("dev", options2);
    if (!rule) return [];
    return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options2.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
  }
  getSuffix(code, count, options2 = {}) {
    const rule = this.getRule(code, options2);
    if (rule) {
      return `${this.options.prepend}${options2.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
    }
    this.logger.warn(`no plural rule found for: ${code}`);
    return this.getSuffix("dev", count, options2);
  }
}
const deepFindWithDefaults = (data2, defaultData, key2, keySeparator = ".", ignoreJSONStructure = true) => {
  let path = getPathWithDefaults(data2, defaultData, key2);
  if (!path && ignoreJSONStructure && isString(key2)) {
    path = deepFind(data2, key2, keySeparator);
    if (path === void 0) path = deepFind(defaultData, key2, keySeparator);
  }
  return path;
};
const regexSafe = (val) => val.replace(/\$/g, "$$$$");
class Interpolator {
  constructor(options2 = {}) {
    var _a3;
    this.logger = baseLogger.create("interpolator");
    this.options = options2;
    this.format = ((_a3 = options2 == null ? void 0 : options2.interpolation) == null ? void 0 : _a3.format) || ((value) => value);
    this.init(options2);
  }
  init(options2 = {}) {
    if (!options2.interpolation) options2.interpolation = {
      escapeValue: true
    };
    const {
      escape: escape$1$1,
      escapeValue,
      useRawValueToEscape,
      prefix,
      prefixEscaped,
      suffix,
      suffixEscaped,
      formatSeparator,
      unescapeSuffix,
      unescapePrefix,
      nestingPrefix,
      nestingPrefixEscaped,
      nestingSuffix,
      nestingSuffixEscaped,
      nestingOptionsSeparator,
      maxReplaces,
      alwaysFormat
    } = options2.interpolation;
    this.escape = escape$1$1 !== void 0 ? escape$1$1 : escape$1;
    this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
    this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
    this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
    this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
    this.formatSeparator = formatSeparator || ",";
    this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
    this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
    this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
    this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
    this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
    this.maxReplaces = maxReplaces || 1e3;
    this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
    this.resetRegExp();
  }
  reset() {
    if (this.options) this.init(this.options);
  }
  resetRegExp() {
    const getOrResetRegExp = (existingRegExp, pattern2) => {
      if ((existingRegExp == null ? void 0 : existingRegExp.source) === pattern2) {
        existingRegExp.lastIndex = 0;
        return existingRegExp;
      }
      return new RegExp(pattern2, "g");
    };
    this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
    this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
    this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}(.+?)${this.nestingSuffix}`);
  }
  interpolate(str, data2, lng, options2) {
    var _a3;
    let match;
    let value;
    let replaces;
    const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
    const handleFormat = (key2) => {
      if (key2.indexOf(this.formatSeparator) < 0) {
        const path = deepFindWithDefaults(data2, defaultData, key2, this.options.keySeparator, this.options.ignoreJSONStructure);
        return this.alwaysFormat ? this.format(path, void 0, lng, {
          ...options2,
          ...data2,
          interpolationkey: key2
        }) : path;
      }
      const p2 = key2.split(this.formatSeparator);
      const k2 = p2.shift().trim();
      const f2 = p2.join(this.formatSeparator).trim();
      return this.format(deepFindWithDefaults(data2, defaultData, k2, this.options.keySeparator, this.options.ignoreJSONStructure), f2, lng, {
        ...options2,
        ...data2,
        interpolationkey: k2
      });
    };
    this.resetRegExp();
    const missingInterpolationHandler = (options2 == null ? void 0 : options2.missingInterpolationHandler) || this.options.missingInterpolationHandler;
    const skipOnVariables = ((_a3 = options2 == null ? void 0 : options2.interpolation) == null ? void 0 : _a3.skipOnVariables) !== void 0 ? options2.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
    const todos = [{
      regex: this.regexpUnescape,
      safeValue: (val) => regexSafe(val)
    }, {
      regex: this.regexp,
      safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
    }];
    todos.forEach((todo) => {
      replaces = 0;
      while (match = todo.regex.exec(str)) {
        const matchedVar = match[1].trim();
        value = handleFormat(matchedVar);
        if (value === void 0) {
          if (typeof missingInterpolationHandler === "function") {
            const temp = missingInterpolationHandler(str, match, options2);
            value = isString(temp) ? temp : "";
          } else if (options2 && Object.prototype.hasOwnProperty.call(options2, matchedVar)) {
            value = "";
          } else if (skipOnVariables) {
            value = match[0];
            continue;
          } else {
            this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
            value = "";
          }
        } else if (!isString(value) && !this.useRawValueToEscape) {
          value = makeString(value);
        }
        const safeValue = todo.safeValue(value);
        str = str.replace(match[0], safeValue);
        if (skipOnVariables) {
          todo.regex.lastIndex += value.length;
          todo.regex.lastIndex -= match[0].length;
        } else {
          todo.regex.lastIndex = 0;
        }
        replaces++;
        if (replaces >= this.maxReplaces) {
          break;
        }
      }
    });
    return str;
  }
  nest(str, fc, options2 = {}) {
    let match;
    let value;
    let clonedOptions;
    const handleHasOptions = (key2, inheritedOptions) => {
      const sep = this.nestingOptionsSeparator;
      if (key2.indexOf(sep) < 0) return key2;
      const c2 = key2.split(new RegExp(`${sep}[ ]*{`));
      let optionsString = `{${c2[1]}`;
      key2 = c2[0];
      optionsString = this.interpolate(optionsString, clonedOptions);
      const matchedSingleQuotes = optionsString.match(/'/g);
      const matchedDoubleQuotes = optionsString.match(/"/g);
      if (((matchedSingleQuotes == null ? void 0 : matchedSingleQuotes.length) ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
        optionsString = optionsString.replace(/'/g, '"');
      }
      try {
        clonedOptions = JSON.parse(optionsString);
        if (inheritedOptions) clonedOptions = {
          ...inheritedOptions,
          ...clonedOptions
        };
      } catch (e4) {
        this.logger.warn(`failed parsing options string in nesting for key ${key2}`, e4);
        return `${key2}${sep}${optionsString}`;
      }
      if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
      return key2;
    };
    while (match = this.nestingRegexp.exec(str)) {
      let formatters = [];
      clonedOptions = {
        ...options2
      };
      clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
      clonedOptions.applyPostProcessor = false;
      delete clonedOptions.defaultValue;
      let doReduce = false;
      if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
        const r2 = match[1].split(this.formatSeparator).map((elem) => elem.trim());
        match[1] = r2.shift();
        formatters = r2;
        doReduce = true;
      }
      value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
      if (value && match[0] === str && !isString(value)) return value;
      if (!isString(value)) value = makeString(value);
      if (!value) {
        this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
        value = "";
      }
      if (doReduce) {
        value = formatters.reduce((v2, f2) => this.format(v2, f2, options2.lng, {
          ...options2,
          interpolationkey: match[1].trim()
        }), value.trim());
      }
      str = str.replace(match[0], value);
      this.regexp.lastIndex = 0;
    }
    return str;
  }
}
const parseFormatStr = (formatStr) => {
  let formatName = formatStr.toLowerCase().trim();
  const formatOptions = {};
  if (formatStr.indexOf("(") > -1) {
    const p2 = formatStr.split("(");
    formatName = p2[0].toLowerCase().trim();
    const optStr = p2[1].substring(0, p2[1].length - 1);
    if (formatName === "currency" && optStr.indexOf(":") < 0) {
      if (!formatOptions.currency) formatOptions.currency = optStr.trim();
    } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
      if (!formatOptions.range) formatOptions.range = optStr.trim();
    } else {
      const opts = optStr.split(";");
      opts.forEach((opt) => {
        if (opt) {
          const [key2, ...rest] = opt.split(":");
          const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
          const trimmedKey = key2.trim();
          if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
          if (val === "false") formatOptions[trimmedKey] = false;
          if (val === "true") formatOptions[trimmedKey] = true;
          if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
        }
      });
    }
  }
  return {
    formatName,
    formatOptions
  };
};
const createCachedFormatter = (fn) => {
  const cache2 = {};
  return (v2, l2, o2) => {
    let optForCache = o2;
    if (o2 && o2.interpolationkey && o2.formatParams && o2.formatParams[o2.interpolationkey] && o2[o2.interpolationkey]) {
      optForCache = {
        ...optForCache,
        [o2.interpolationkey]: void 0
      };
    }
    const key2 = l2 + JSON.stringify(optForCache);
    let frm = cache2[key2];
    if (!frm) {
      frm = fn(getCleanedCode(l2), o2);
      cache2[key2] = frm;
    }
    return frm(v2);
  };
};
const createNonCachedFormatter = (fn) => (v2, l2, o2) => fn(getCleanedCode(l2), o2)(v2);
class Formatter {
  constructor(options2 = {}) {
    this.logger = baseLogger.create("formatter");
    this.options = options2;
    this.init(options2);
  }
  init(services, options2 = {
    interpolation: {}
  }) {
    this.formatSeparator = options2.interpolation.formatSeparator || ",";
    const cf = options2.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
    this.formats = {
      number: cf((lng, opt) => {
        const formatter = new Intl.NumberFormat(lng, {
          ...opt
        });
        return (val) => formatter.format(val);
      }),
      currency: cf((lng, opt) => {
        const formatter = new Intl.NumberFormat(lng, {
          ...opt,
          style: "currency"
        });
        return (val) => formatter.format(val);
      }),
      datetime: cf((lng, opt) => {
        const formatter = new Intl.DateTimeFormat(lng, {
          ...opt
        });
        return (val) => formatter.format(val);
      }),
      relativetime: cf((lng, opt) => {
        const formatter = new Intl.RelativeTimeFormat(lng, {
          ...opt
        });
        return (val) => formatter.format(val, opt.range || "day");
      }),
      list: cf((lng, opt) => {
        const formatter = new Intl.ListFormat(lng, {
          ...opt
        });
        return (val) => formatter.format(val);
      })
    };
  }
  add(name, fc) {
    this.formats[name.toLowerCase().trim()] = fc;
  }
  addCached(name, fc) {
    this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
  }
  format(value, format2, lng, options2 = {}) {
    const formats = format2.split(this.formatSeparator);
    if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f2) => f2.indexOf(")") > -1)) {
      const lastIndex = formats.findIndex((f2) => f2.indexOf(")") > -1);
      formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
    }
    const result = formats.reduce((mem, f2) => {
      var _a3;
      const {
        formatName,
        formatOptions
      } = parseFormatStr(f2);
      if (this.formats[formatName]) {
        let formatted = mem;
        try {
          const valOptions = ((_a3 = options2 == null ? void 0 : options2.formatParams) == null ? void 0 : _a3[options2.interpolationkey]) || {};
          const l2 = valOptions.locale || valOptions.lng || options2.locale || options2.lng || lng;
          formatted = this.formats[formatName](mem, l2, {
            ...formatOptions,
            ...options2,
            ...valOptions
          });
        } catch (error) {
          this.logger.warn(error);
        }
        return formatted;
      } else {
        this.logger.warn(`there was no format function for ${formatName}`);
      }
      return mem;
    }, value);
    return result;
  }
}
const removePending = (q, name) => {
  if (q.pending[name] !== void 0) {
    delete q.pending[name];
    q.pendingCount--;
  }
};
class Connector extends EventEmitter {
  constructor(backend, store, services, options2 = {}) {
    var _a3, _b2;
    super();
    this.backend = backend;
    this.store = store;
    this.services = services;
    this.languageUtils = services.languageUtils;
    this.options = options2;
    this.logger = baseLogger.create("backendConnector");
    this.waitingReads = [];
    this.maxParallelReads = options2.maxParallelReads || 10;
    this.readingCalls = 0;
    this.maxRetries = options2.maxRetries >= 0 ? options2.maxRetries : 5;
    this.retryTimeout = options2.retryTimeout >= 1 ? options2.retryTimeout : 350;
    this.state = {};
    this.queue = [];
    (_b2 = (_a3 = this.backend) == null ? void 0 : _a3.init) == null ? void 0 : _b2.call(_a3, services, options2.backend, options2);
  }
  queueLoad(languages, namespaces, options2, callback) {
    const toLoad = {};
    const pending = {};
    const toLoadLanguages = {};
    const toLoadNamespaces = {};
    languages.forEach((lng) => {
      let hasAllNamespaces = true;
      namespaces.forEach((ns) => {
        const name = `${lng}|${ns}`;
        if (!options2.reload && this.store.hasResourceBundle(lng, ns)) {
          this.state[name] = 2;
        } else if (this.state[name] < 0) ;
        else if (this.state[name] === 1) {
          if (pending[name] === void 0) pending[name] = true;
        } else {
          this.state[name] = 1;
          hasAllNamespaces = false;
          if (pending[name] === void 0) pending[name] = true;
          if (toLoad[name] === void 0) toLoad[name] = true;
          if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
        }
      });
      if (!hasAllNamespaces) toLoadLanguages[lng] = true;
    });
    if (Object.keys(toLoad).length || Object.keys(pending).length) {
      this.queue.push({
        pending,
        pendingCount: Object.keys(pending).length,
        loaded: {},
        errors: [],
        callback
      });
    }
    return {
      toLoad: Object.keys(toLoad),
      pending: Object.keys(pending),
      toLoadLanguages: Object.keys(toLoadLanguages),
      toLoadNamespaces: Object.keys(toLoadNamespaces)
    };
  }
  loaded(name, err, data2) {
    const s2 = name.split("|");
    const lng = s2[0];
    const ns = s2[1];
    if (err) this.emit("failedLoading", lng, ns, err);
    if (!err && data2) {
      this.store.addResourceBundle(lng, ns, data2, void 0, void 0, {
        skipCopy: true
      });
    }
    this.state[name] = err ? -1 : 2;
    if (err && data2) this.state[name] = 0;
    const loaded = {};
    this.queue.forEach((q) => {
      pushPath(q.loaded, [lng], ns);
      removePending(q, name);
      if (err) q.errors.push(err);
      if (q.pendingCount === 0 && !q.done) {
        Object.keys(q.loaded).forEach((l2) => {
          if (!loaded[l2]) loaded[l2] = {};
          const loadedKeys = q.loaded[l2];
          if (loadedKeys.length) {
            loadedKeys.forEach((n2) => {
              if (loaded[l2][n2] === void 0) loaded[l2][n2] = true;
            });
          }
        });
        q.done = true;
        if (q.errors.length) {
          q.callback(q.errors);
        } else {
          q.callback();
        }
      }
    });
    this.emit("loaded", loaded);
    this.queue = this.queue.filter((q) => !q.done);
  }
  read(lng, ns, fcName, tried = 0, wait2 = this.retryTimeout, callback) {
    if (!lng.length) return callback(null, {});
    if (this.readingCalls >= this.maxParallelReads) {
      this.waitingReads.push({
        lng,
        ns,
        fcName,
        tried,
        wait: wait2,
        callback
      });
      return;
    }
    this.readingCalls++;
    const resolver = (err, data2) => {
      this.readingCalls--;
      if (this.waitingReads.length > 0) {
        const next = this.waitingReads.shift();
        this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
      }
      if (err && data2 && tried < this.maxRetries) {
        setTimeout(() => {
          this.read.call(this, lng, ns, fcName, tried + 1, wait2 * 2, callback);
        }, wait2);
        return;
      }
      callback(err, data2);
    };
    const fc = this.backend[fcName].bind(this.backend);
    if (fc.length === 2) {
      try {
        const r2 = fc(lng, ns);
        if (r2 && typeof r2.then === "function") {
          r2.then((data2) => resolver(null, data2)).catch(resolver);
        } else {
          resolver(null, r2);
        }
      } catch (err) {
        resolver(err);
      }
      return;
    }
    return fc(lng, ns, resolver);
  }
  prepareLoading(languages, namespaces, options2 = {}, callback) {
    if (!this.backend) {
      this.logger.warn("No backend was added via i18next.use. Will not load resources.");
      return callback && callback();
    }
    if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
    if (isString(namespaces)) namespaces = [namespaces];
    const toLoad = this.queueLoad(languages, namespaces, options2, callback);
    if (!toLoad.toLoad.length) {
      if (!toLoad.pending.length) callback();
      return null;
    }
    toLoad.toLoad.forEach((name) => {
      this.loadOne(name);
    });
  }
  load(languages, namespaces, callback) {
    this.prepareLoading(languages, namespaces, {}, callback);
  }
  reload(languages, namespaces, callback) {
    this.prepareLoading(languages, namespaces, {
      reload: true
    }, callback);
  }
  loadOne(name, prefix = "") {
    const s2 = name.split("|");
    const lng = s2[0];
    const ns = s2[1];
    this.read(lng, ns, "read", void 0, void 0, (err, data2) => {
      if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
      if (!err && data2) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data2);
      this.loaded(name, err, data2);
    });
  }
  saveMissing(languages, namespace, key2, fallbackValue, isUpdate, options2 = {}, clb = () => {
  }) {
    var _a3, _b2, _c2, _d2, _e2;
    if (((_b2 = (_a3 = this.services) == null ? void 0 : _a3.utils) == null ? void 0 : _b2.hasLoadedNamespace) && !((_d2 = (_c2 = this.services) == null ? void 0 : _c2.utils) == null ? void 0 : _d2.hasLoadedNamespace(namespace))) {
      this.logger.warn(`did not save key "${key2}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
      return;
    }
    if (key2 === void 0 || key2 === null || key2 === "") return;
    if ((_e2 = this.backend) == null ? void 0 : _e2.create) {
      const opts = {
        ...options2,
        isUpdate
      };
      const fc = this.backend.create.bind(this.backend);
      if (fc.length < 6) {
        try {
          let r2;
          if (fc.length === 5) {
            r2 = fc(languages, namespace, key2, fallbackValue, opts);
          } else {
            r2 = fc(languages, namespace, key2, fallbackValue);
          }
          if (r2 && typeof r2.then === "function") {
            r2.then((data2) => clb(null, data2)).catch(clb);
          } else {
            clb(null, r2);
          }
        } catch (err) {
          clb(err);
        }
      } else {
        fc(languages, namespace, key2, fallbackValue, clb, opts);
      }
    }
    if (!languages || !languages[0]) return;
    this.store.addResource(languages[0], namespace, key2, fallbackValue);
  }
}
const get = () => ({
  debug: false,
  initAsync: true,
  ns: ["translation"],
  defaultNS: ["translation"],
  fallbackLng: ["dev"],
  fallbackNS: false,
  supportedLngs: false,
  nonExplicitSupportedLngs: false,
  load: "all",
  preload: false,
  simplifyPluralSuffix: true,
  keySeparator: ".",
  nsSeparator: ":",
  pluralSeparator: "_",
  contextSeparator: "_",
  partialBundledLanguages: false,
  saveMissing: false,
  updateMissing: false,
  saveMissingTo: "fallback",
  saveMissingPlurals: true,
  missingKeyHandler: false,
  missingInterpolationHandler: false,
  postProcess: false,
  postProcessPassResolved: false,
  returnNull: false,
  returnEmptyString: true,
  returnObjects: false,
  joinArrays: false,
  returnedObjectHandler: false,
  parseMissingKeyHandler: false,
  appendNamespaceToMissingKey: false,
  appendNamespaceToCIMode: false,
  overloadTranslationOptionHandler: (args) => {
    let ret = {};
    if (typeof args[1] === "object") ret = args[1];
    if (isString(args[1])) ret.defaultValue = args[1];
    if (isString(args[2])) ret.tDescription = args[2];
    if (typeof args[2] === "object" || typeof args[3] === "object") {
      const options2 = args[3] || args[2];
      Object.keys(options2).forEach((key2) => {
        ret[key2] = options2[key2];
      });
    }
    return ret;
  },
  interpolation: {
    escapeValue: true,
    format: (value) => value,
    prefix: "{{",
    suffix: "}}",
    formatSeparator: ",",
    unescapePrefix: "-",
    nestingPrefix: "$t(",
    nestingSuffix: ")",
    nestingOptionsSeparator: ",",
    maxReplaces: 1e3,
    skipOnVariables: true
  },
  cacheInBuiltFormats: true
});
const transformOptions = (options2) => {
  var _a3, _b2;
  if (isString(options2.ns)) options2.ns = [options2.ns];
  if (isString(options2.fallbackLng)) options2.fallbackLng = [options2.fallbackLng];
  if (isString(options2.fallbackNS)) options2.fallbackNS = [options2.fallbackNS];
  if (((_b2 = (_a3 = options2.supportedLngs) == null ? void 0 : _a3.indexOf) == null ? void 0 : _b2.call(_a3, "cimode")) < 0) {
    options2.supportedLngs = options2.supportedLngs.concat(["cimode"]);
  }
  if (typeof options2.initImmediate === "boolean") options2.initAsync = options2.initImmediate;
  return options2;
};
const noop$1 = () => {
};
const bindMemberFunctions = (inst) => {
  const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
  mems.forEach((mem) => {
    if (typeof inst[mem] === "function") {
      inst[mem] = inst[mem].bind(inst);
    }
  });
};
class I18n extends EventEmitter {
  constructor(options2 = {}, callback) {
    super();
    this.options = transformOptions(options2);
    this.services = {};
    this.logger = baseLogger;
    this.modules = {
      external: []
    };
    bindMemberFunctions(this);
    if (callback && !this.isInitialized && !options2.isClone) {
      if (!this.options.initAsync) {
        this.init(options2, callback);
        return this;
      }
      setTimeout(() => {
        this.init(options2, callback);
      }, 0);
    }
  }
  init(options2 = {}, callback) {
    this.isInitializing = true;
    if (typeof options2 === "function") {
      callback = options2;
      options2 = {};
    }
    if (options2.defaultNS == null && options2.ns) {
      if (isString(options2.ns)) {
        options2.defaultNS = options2.ns;
      } else if (options2.ns.indexOf("translation") < 0) {
        options2.defaultNS = options2.ns[0];
      }
    }
    const defOpts = get();
    this.options = {
      ...defOpts,
      ...this.options,
      ...transformOptions(options2)
    };
    this.options.interpolation = {
      ...defOpts.interpolation,
      ...this.options.interpolation
    };
    if (options2.keySeparator !== void 0) {
      this.options.userDefinedKeySeparator = options2.keySeparator;
    }
    if (options2.nsSeparator !== void 0) {
      this.options.userDefinedNsSeparator = options2.nsSeparator;
    }
    const createClassOnDemand = (ClassOrObject) => {
      if (!ClassOrObject) return null;
      if (typeof ClassOrObject === "function") return new ClassOrObject();
      return ClassOrObject;
    };
    if (!this.options.isClone) {
      if (this.modules.logger) {
        baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
      } else {
        baseLogger.init(null, this.options);
      }
      let formatter;
      if (this.modules.formatter) {
        formatter = this.modules.formatter;
      } else {
        formatter = Formatter;
      }
      const lu = new LanguageUtil(this.options);
      this.store = new ResourceStore(this.options.resources, this.options);
      const s2 = this.services;
      s2.logger = baseLogger;
      s2.resourceStore = this.store;
      s2.languageUtils = lu;
      s2.pluralResolver = new PluralResolver(lu, {
        prepend: this.options.pluralSeparator,
        simplifyPluralSuffix: this.options.simplifyPluralSuffix
      });
      if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
        s2.formatter = createClassOnDemand(formatter);
        s2.formatter.init(s2, this.options);
        this.options.interpolation.format = s2.formatter.format.bind(s2.formatter);
      }
      s2.interpolator = new Interpolator(this.options);
      s2.utils = {
        hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
      };
      s2.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s2.resourceStore, s2, this.options);
      s2.backendConnector.on("*", (event, ...args) => {
        this.emit(event, ...args);
      });
      if (this.modules.languageDetector) {
        s2.languageDetector = createClassOnDemand(this.modules.languageDetector);
        if (s2.languageDetector.init) s2.languageDetector.init(s2, this.options.detection, this.options);
      }
      if (this.modules.i18nFormat) {
        s2.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
        if (s2.i18nFormat.init) s2.i18nFormat.init(this);
      }
      this.translator = new Translator(this.services, this.options);
      this.translator.on("*", (event, ...args) => {
        this.emit(event, ...args);
      });
      this.modules.external.forEach((m) => {
        if (m.init) m.init(this);
      });
    }
    this.format = this.options.interpolation.format;
    if (!callback) callback = noop$1;
    if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
      const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
      if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
    }
    if (!this.services.languageDetector && !this.options.lng) {
      this.logger.warn("init: no languageDetector is used and no lng is defined");
    }
    const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
    storeApi.forEach((fcName) => {
      this[fcName] = (...args) => this.store[fcName](...args);
    });
    const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
    storeApiChained.forEach((fcName) => {
      this[fcName] = (...args) => {
        this.store[fcName](...args);
        return this;
      };
    });
    const deferred = defer();
    const load2 = () => {
      const finish = (err, t2) => {
        this.isInitializing = false;
        if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
        this.isInitialized = true;
        if (!this.options.isClone) this.logger.log("initialized", this.options);
        this.emit("initialized", this.options);
        deferred.resolve(t2);
        callback(err, t2);
      };
      if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
      this.changeLanguage(this.options.lng, finish);
    };
    if (this.options.resources || !this.options.initAsync) {
      load2();
    } else {
      setTimeout(load2, 0);
    }
    return deferred;
  }
  loadResources(language, callback = noop$1) {
    var _a3, _b2;
    let usedCallback = callback;
    const usedLng = isString(language) ? language : this.language;
    if (typeof language === "function") usedCallback = language;
    if (!this.options.resources || this.options.partialBundledLanguages) {
      if ((usedLng == null ? void 0 : usedLng.toLowerCase()) === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
      const toLoad = [];
      const append = (lng) => {
        if (!lng) return;
        if (lng === "cimode") return;
        const lngs = this.services.languageUtils.toResolveHierarchy(lng);
        lngs.forEach((l2) => {
          if (l2 === "cimode") return;
          if (toLoad.indexOf(l2) < 0) toLoad.push(l2);
        });
      };
      if (!usedLng) {
        const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
        fallbacks.forEach((l2) => append(l2));
      } else {
        append(usedLng);
      }
      (_b2 = (_a3 = this.options.preload) == null ? void 0 : _a3.forEach) == null ? void 0 : _b2.call(_a3, (l2) => append(l2));
      this.services.backendConnector.load(toLoad, this.options.ns, (e4) => {
        if (!e4 && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
        usedCallback(e4);
      });
    } else {
      usedCallback(null);
    }
  }
  reloadResources(lngs, ns, callback) {
    const deferred = defer();
    if (typeof lngs === "function") {
      callback = lngs;
      lngs = void 0;
    }
    if (typeof ns === "function") {
      callback = ns;
      ns = void 0;
    }
    if (!lngs) lngs = this.languages;
    if (!ns) ns = this.options.ns;
    if (!callback) callback = noop$1;
    this.services.backendConnector.reload(lngs, ns, (err) => {
      deferred.resolve();
      callback(err);
    });
    return deferred;
  }
  use(module2) {
    if (!module2) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
    if (!module2.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
    if (module2.type === "backend") {
      this.modules.backend = module2;
    }
    if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
      this.modules.logger = module2;
    }
    if (module2.type === "languageDetector") {
      this.modules.languageDetector = module2;
    }
    if (module2.type === "i18nFormat") {
      this.modules.i18nFormat = module2;
    }
    if (module2.type === "postProcessor") {
      postProcessor.addPostProcessor(module2);
    }
    if (module2.type === "formatter") {
      this.modules.formatter = module2;
    }
    if (module2.type === "3rdParty") {
      this.modules.external.push(module2);
    }
    return this;
  }
  setResolvedLanguage(l2) {
    if (!l2 || !this.languages) return;
    if (["cimode", "dev"].indexOf(l2) > -1) return;
    for (let li = 0; li < this.languages.length; li++) {
      const lngInLngs = this.languages[li];
      if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
      if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
        this.resolvedLanguage = lngInLngs;
        break;
      }
    }
    if (!this.resolvedLanguage && this.languages.indexOf(l2) < 0 && this.store.hasLanguageSomeTranslations(l2)) {
      this.resolvedLanguage = l2;
      this.languages.unshift(l2);
    }
  }
  changeLanguage(lng, callback) {
    this.isLanguageChangingTo = lng;
    const deferred = defer();
    this.emit("languageChanging", lng);
    const setLngProps = (l2) => {
      this.language = l2;
      this.languages = this.services.languageUtils.toResolveHierarchy(l2);
      this.resolvedLanguage = void 0;
      this.setResolvedLanguage(l2);
    };
    const done = (err, l2) => {
      if (l2) {
        if (this.isLanguageChangingTo === lng) {
          setLngProps(l2);
          this.translator.changeLanguage(l2);
          this.isLanguageChangingTo = void 0;
          this.emit("languageChanged", l2);
          this.logger.log("languageChanged", l2);
        }
      } else {
        this.isLanguageChangingTo = void 0;
      }
      deferred.resolve((...args) => this.t(...args));
      if (callback) callback(err, (...args) => this.t(...args));
    };
    const setLng = (lngs) => {
      var _a3, _b2;
      if (!lng && !lngs && this.services.languageDetector) lngs = [];
      const fl = isString(lngs) ? lngs : lngs && lngs[0];
      const l2 = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
      if (l2) {
        if (!this.language) {
          setLngProps(l2);
        }
        if (!this.translator.language) this.translator.changeLanguage(l2);
        (_b2 = (_a3 = this.services.languageDetector) == null ? void 0 : _a3.cacheUserLanguage) == null ? void 0 : _b2.call(_a3, l2);
      }
      this.loadResources(l2, (err) => {
        done(err, l2);
      });
    };
    if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
      setLng(this.services.languageDetector.detect());
    } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
      if (this.services.languageDetector.detect.length === 0) {
        this.services.languageDetector.detect().then(setLng);
      } else {
        this.services.languageDetector.detect(setLng);
      }
    } else {
      setLng(lng);
    }
    return deferred;
  }
  getFixedT(lng, ns, keyPrefix) {
    const fixedT = (key2, opts, ...rest) => {
      let o2;
      if (typeof opts !== "object") {
        o2 = this.options.overloadTranslationOptionHandler([key2, opts].concat(rest));
      } else {
        o2 = {
          ...opts
        };
      }
      o2.lng = o2.lng || fixedT.lng;
      o2.lngs = o2.lngs || fixedT.lngs;
      o2.ns = o2.ns || fixedT.ns;
      if (o2.keyPrefix !== "") o2.keyPrefix = o2.keyPrefix || keyPrefix || fixedT.keyPrefix;
      const keySeparator = this.options.keySeparator || ".";
      let resultKey;
      if (o2.keyPrefix && Array.isArray(key2)) {
        resultKey = key2.map((k2) => `${o2.keyPrefix}${keySeparator}${k2}`);
      } else {
        resultKey = o2.keyPrefix ? `${o2.keyPrefix}${keySeparator}${key2}` : key2;
      }
      return this.t(resultKey, o2);
    };
    if (isString(lng)) {
      fixedT.lng = lng;
    } else {
      fixedT.lngs = lng;
    }
    fixedT.ns = ns;
    fixedT.keyPrefix = keyPrefix;
    return fixedT;
  }
  t(...args) {
    var _a3;
    return (_a3 = this.translator) == null ? void 0 : _a3.translate(...args);
  }
  exists(...args) {
    var _a3;
    return (_a3 = this.translator) == null ? void 0 : _a3.exists(...args);
  }
  setDefaultNamespace(ns) {
    this.options.defaultNS = ns;
  }
  hasLoadedNamespace(ns, options2 = {}) {
    if (!this.isInitialized) {
      this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
      return false;
    }
    if (!this.languages || !this.languages.length) {
      this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
      return false;
    }
    const lng = options2.lng || this.resolvedLanguage || this.languages[0];
    const fallbackLng = this.options ? this.options.fallbackLng : false;
    const lastLng = this.languages[this.languages.length - 1];
    if (lng.toLowerCase() === "cimode") return true;
    const loadNotPending = (l2, n2) => {
      const loadState = this.services.backendConnector.state[`${l2}|${n2}`];
      return loadState === -1 || loadState === 0 || loadState === 2;
    };
    if (options2.precheck) {
      const preResult = options2.precheck(this, loadNotPending);
      if (preResult !== void 0) return preResult;
    }
    if (this.hasResourceBundle(lng, ns)) return true;
    if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
    if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
    return false;
  }
  loadNamespaces(ns, callback) {
    const deferred = defer();
    if (!this.options.ns) {
      if (callback) callback();
      return Promise.resolve();
    }
    if (isString(ns)) ns = [ns];
    ns.forEach((n2) => {
      if (this.options.ns.indexOf(n2) < 0) this.options.ns.push(n2);
    });
    this.loadResources((err) => {
      deferred.resolve();
      if (callback) callback(err);
    });
    return deferred;
  }
  loadLanguages(lngs, callback) {
    const deferred = defer();
    if (isString(lngs)) lngs = [lngs];
    const preloaded = this.options.preload || [];
    const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
    if (!newLngs.length) {
      if (callback) callback();
      return Promise.resolve();
    }
    this.options.preload = preloaded.concat(newLngs);
    this.loadResources((err) => {
      deferred.resolve();
      if (callback) callback(err);
    });
    return deferred;
  }
  dir(lng) {
    var _a3, _b2;
    if (!lng) lng = this.resolvedLanguage || (((_a3 = this.languages) == null ? void 0 : _a3.length) > 0 ? this.languages[0] : this.language);
    if (!lng) return "rtl";
    const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
    const languageUtils = ((_b2 = this.services) == null ? void 0 : _b2.languageUtils) || new LanguageUtil(get());
    return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
  }
  static createInstance(options2 = {}, callback) {
    return new I18n(options2, callback);
  }
  cloneInstance(options2 = {}, callback = noop$1) {
    const forkResourceStore = options2.forkResourceStore;
    if (forkResourceStore) delete options2.forkResourceStore;
    const mergedOptions = {
      ...this.options,
      ...options2,
      ...{
        isClone: true
      }
    };
    const clone2 = new I18n(mergedOptions);
    if (options2.debug !== void 0 || options2.prefix !== void 0) {
      clone2.logger = clone2.logger.clone(options2);
    }
    const membersToCopy = ["store", "services", "language"];
    membersToCopy.forEach((m) => {
      clone2[m] = this[m];
    });
    clone2.services = {
      ...this.services
    };
    clone2.services.utils = {
      hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2)
    };
    if (forkResourceStore) {
      const clonedData = Object.keys(this.store.data).reduce((prev, l2) => {
        prev[l2] = {
          ...this.store.data[l2]
        };
        prev[l2] = Object.keys(prev[l2]).reduce((acc, n2) => {
          acc[n2] = {
            ...prev[l2][n2]
          };
          return acc;
        }, prev[l2]);
        return prev;
      }, {});
      clone2.store = new ResourceStore(clonedData, mergedOptions);
      clone2.services.resourceStore = clone2.store;
    }
    clone2.translator = new Translator(clone2.services, mergedOptions);
    clone2.translator.on("*", (event, ...args) => {
      clone2.emit(event, ...args);
    });
    clone2.init(mergedOptions, callback);
    clone2.translator.options = mergedOptions;
    clone2.translator.backendConnector.services.utils = {
      hasLoadedNamespace: clone2.hasLoadedNamespace.bind(clone2)
    };
    return clone2;
  }
  toJSON() {
    return {
      options: this.options,
      store: this.store,
      language: this.language,
      languages: this.languages,
      resolvedLanguage: this.resolvedLanguage
    };
  }
}
const instance = I18n.createInstance();
instance.createInstance = I18n.createInstance;
instance.createInstance;
instance.dir;
instance.init;
instance.loadResources;
instance.reloadResources;
instance.use;
instance.changeLanguage;
instance.getFixedT;
instance.t;
instance.exists;
instance.setDefaultNamespace;
instance.hasLoadedNamespace;
instance.loadNamespaces;
instance.loadLanguages;
function detectLanguage() {
  if (typeof navigator !== "undefined" && navigator.language) {
    return navigator.language === "zh-CN" ? "zh-CN" : "en-US";
  }
  try {
    const require_ = typeof require !== "undefined" ? require : void 0;
    if (require_) {
      const uxp2 = require_("uxp");
      return uxp2.host.uiLocale.startsWith("zh") ? "zh-CN" : "en-US";
    }
  } catch {
  }
  return "en-US";
}
let currentLanguage = detectLanguage();
const translationOverrides = {
  "zh-CN": {},
  "en-US": {}
};
function getMergedTranslations(language) {
  const baseTranslations = language === "zh-CN" ? zhCN : enUS;
  const overrides = translationOverrides[language];
  return { ...baseTranslations, ...overrides };
}
let onTranslationChange = null;
function setTranslationChangeCallback(callback) {
  onTranslationChange = callback;
}
function changeLanguage(language) {
  currentLanguage = language;
  if (onTranslationChange) {
    onTranslationChange(language);
  }
}
function getCurrentLanguage() {
  return currentLanguage;
}
function t(key2, options2 = {}) {
  const translations = getMergedTranslations(currentLanguage);
  let value = translations[key2];
  if (!value) return key2;
  if (typeof value === "string") {
    return value.replace(
      /\{\{(\w+)\}\}/g,
      (match, paramName) => options2[paramName] !== void 0 ? String(options2[paramName]) : match
    );
  }
  return value;
}
const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
const htmlEntities = {
  "&amp;": "&",
  "&#38;": "&",
  "&lt;": "<",
  "&#60;": "<",
  "&gt;": ">",
  "&#62;": ">",
  "&apos;": "'",
  "&#39;": "'",
  "&quot;": '"',
  "&#34;": '"',
  "&nbsp;": " ",
  "&#160;": " ",
  "&copy;": "©",
  "&#169;": "©",
  "&reg;": "®",
  "&#174;": "®",
  "&hellip;": "…",
  "&#8230;": "…",
  "&#x2F;": "/",
  "&#47;": "/"
};
const unescapeHtmlEntity = (m) => htmlEntities[m];
const unescape$1 = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
let defaultOptions = {
  bindI18n: "languageChanged",
  bindI18nStore: "",
  transEmptyNodeValue: "",
  transSupportBasicHtmlNodes: true,
  transWrapTextNodes: "",
  transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
  useSuspense: true,
  unescape: unescape$1
};
const setDefaults = (options2 = {}) => {
  defaultOptions = {
    ...defaultOptions,
    ...options2
  };
};
const initReactI18next = {
  type: "3rdParty",
  init(instance2) {
    setDefaults(instance2.options.react);
  }
};
if (!instance.isInitialized) {
  instance.use(initReactI18next).init({
    resources: {
      "zh-CN": {
        translation: getMergedTranslations("zh-CN")
      },
      "en-US": {
        translation: getMergedTranslations("en-US")
      }
    },
    lng: getCurrentLanguage(),
    fallbackLng: "en-US",
    interpolation: {
      escapeValue: false
    }
  });
  setTranslationChangeCallback((language) => {
    instance.addResourceBundle(language, "translation", getMergedTranslations(language), true, true);
    instance.changeLanguage(language);
  });
}
const sdpppSDK = globalThis.sdpppSDK;
function getDocumentOrLayerID(name) {
  if (typeof name !== "string") throw new Error("not a invalid identifer: " + name);
  const split = name.split("(id:");
  const layerID = split.pop();
  if (!layerID) throw new Error(t(`invalid name: {0}`, name));
  return parseInt(layerID.trim().slice(0, -1));
}
function getDocumentID(name) {
  if (SpeicialIDManager.is_SPECIAL_DOCUMENT_CURRENT(name)) {
    return -1;
  }
  return getDocumentOrLayerID(name);
}
function getLayerID(document2, name) {
  if (SpeicialIDManager.is_SPECIAL_LAYER_USE_CANVAS(name)) return 0;
  if (SpeicialIDManager.is_SPECIAL_LAYER_SELECTED_LAYER(name))
    return document2.activeLayers.length > 0 ? document2.activeLayers[0].id : 0;
  if (SpeicialIDManager.is_SPECIAL_LAYER_NEW_LAYER(name)) return -2;
  return getDocumentOrLayerID(name);
}
function getDocumentFromIdentify(documentIdentify) {
  return (SpeicialIDManager.is_SPECIAL_DOCUMENT_CURRENT(documentIdentify) ? photoshop.app.activeDocument : photoshop.app.documents.find((document2) => document2.id === getDocumentID(documentIdentify))) || null;
}
function makeLayerIdentify$1(id, name, level = 0) {
  return `${"-".repeat(level)}${name} (id:${id})`;
}
function getSelectedLayerIdentify() {
  var _a3, _b2;
  const layer = (_b2 = (_a3 = photoshop.app.activeDocument) == null ? void 0 : _a3.activeLayers) == null ? void 0 : _b2[0];
  if (!layer) return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
  return makeLayerIdentify$1(layer.id, layer.name);
}
function getAllSubLayer(layer, level = 0, parentPath = "") {
  if (!("layers" in layer) || !layer.layers) return [];
  return layer.layers.reduce((ret, subLayer) => {
    const path = level === 0 ? `/${subLayer.name}` : `${parentPath}/${subLayer.name}`;
    ret.push({
      layer: subLayer,
      path,
      level
    });
    return ret.concat(getAllSubLayer(subLayer, level + 1, path));
  }, []);
}
function findInAllSubLayer(rootLayer, layerid) {
  if (!("layers" in rootLayer) || !rootLayer.layers) return null;
  for (const layer of rootLayer.layers) {
    if (layer.id === layerid) return layer;
    const result = findInAllSubLayer(layer, layerid);
    if (result) return result;
  }
  return null;
}
async function getRasterizedLayer(document2, layerID) {
  if (layerID <= 0) return [null, false];
  const layer = findInAllSubLayer(document2, layerID);
  if (!layer) throw new Error(t("layer not found {{0}}", { "0": layerID }));
  if (layer.kind === photoshop.constants.LayerKind.GROUP) {
    const mergedLayer = await mergeGroupLayer(layer, document2);
    if (!mergedLayer) throw new Error(t("merge group failed"));
    return [mergedLayer, true];
  } else if (layer.kind === photoshop.constants.LayerKind.GRADIENTFILL) {
    const dupLayer = await layer.duplicate(document2);
    await (dupLayer == null ? void 0 : dupLayer.rasterize(photoshop.constants.RasterizeType.ENTIRELAYER));
    return [dupLayer, true];
  }
  return [layer, false];
}
async function mergeGroupLayer(layer, document2) {
  let visibleOriginal = true;
  if (!layer.visible) {
    layer.visible = true;
    visibleOriginal = false;
  }
  const dupLayer = await layer.duplicate(document2);
  const mergedLayer = await (dupLayer == null ? void 0 : dupLayer.merge());
  if (!visibleOriginal) layer.visible = false;
  return mergedLayer || null;
}
function getLayerInfoFromLayer(document2, layer) {
  const docWidth = Number(document2.width) || 0;
  const docHeight = Number(document2.height) || 0;
  const layerBounds = layer.bounds ?? null;
  const boundary = layerBounds ? BoundaryRectUtils.fromPhotoshopBounds(
    {
      left: Number(layerBounds.left ?? 0),
      top: Number(layerBounds.top ?? 0),
      right: Number(layerBounds.right ?? docWidth),
      bottom: Number(layerBounds.bottom ?? docHeight)
    },
    docWidth,
    docHeight
  ) : BoundaryRectUtils.fromPositionAndSize(0, 0, docWidth, docHeight, docWidth, docHeight);
  return {
    name: layer.name,
    opacity: layer.opacity / 100,
    boundary,
    isGroup: layer.kind === photoshop.constants.LayerKind.GROUP
  };
}
async function getDocumentInfo(params) {
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  const docWidth = Number(document2.width) || 0;
  const docHeight = Number(document2.height) || 0;
  const documentBoundary = BoundaryRectUtils.fromPositionAndSize(
    0,
    0,
    docWidth,
    docHeight,
    docWidth,
    docHeight
  );
  const selection = document2.selection;
  const selectionBounds = selection == null ? void 0 : selection.bounds;
  const selectionBoundary = selectionBounds ? BoundaryRectUtils.fromPhotoshopBounds(
    {
      left: Number(selectionBounds.left ?? 0),
      top: Number(selectionBounds.top ?? 0),
      right: Number(selectionBounds.right ?? docWidth),
      bottom: Number(selectionBounds.bottom ?? docHeight)
    },
    docWidth,
    docHeight
  ) : null;
  return {
    document_boundary: documentBoundary,
    selection_boundary: selectionBoundary || documentBoundary
  };
}
const perfLogger$1 = sdpppLogger.extend("perf");
const PERF_ALLOWED_REGEX$1 = /^fileResource\.(createBy|createFrom)[^.]+\.action$/;
const shouldLogPerf$1 = (label) => PERF_ALLOWED_REGEX$1.test(label);
function createPerfTracker$1(label) {
  if (!shouldLogPerf$1(label)) {
    return () => void 0;
  }
  const startedAt = Date.now();
  const logger = perfLogger$1.extend(label);
  return (stage, extra) => {
    const elapsed = Date.now() - startedAt;
    if (extra) {
      logger(`${stage} +${elapsed}ms`, extra);
    } else {
      logger(`${stage} +${elapsed}ms`);
    }
  };
}
async function getPixelsData({
  document: document2,
  layer,
  bounds,
  targetSize
}) {
  const log2 = createPerfTracker$1("getPixelsData");
  log2("start", {
    layerId: layer == null ? void 0 : layer.id,
    targetWidth: targetSize.width,
    targetHeight: targetSize.height
  });
  const options2 = {
    documentID: document2.id,
    applyAlpha: false,
    hasAlpha: true,
    sourceBounds: bounds,
    targetSize,
    colorSpace: "RGB"
  };
  if (document2.mode !== photoshop.constants.DocumentMode.RGB) {
    Object.assign(options2, { colorProfile: "sRGB IEC61966-2.1" });
  }
  if (layer) options2.layerID = layer.id;
  const pixels = await photoshop.imaging.getPixels(options2);
  const imageData = pixels.imageData;
  log2("imaging.getPixels.resolved", {
    width: imageData == null ? void 0 : imageData.width,
    height: imageData == null ? void 0 : imageData.height
  });
  const dataFromAPI = await imageData.getData({});
  Promise.resolve().then(() => {
    imageData.dispose();
  });
  log2("completed", {
    width: imageData.width,
    height: imageData.height
  });
  return {
    dataFromAPI,
    width: imageData.width,
    height: imageData.height
  };
}
async function getMaskData({
  document: document2,
  layer,
  bounds,
  targetSize
}) {
  var _a3, _b2;
  const log2 = createPerfTracker$1("getMaskData");
  log2("start", {
    layerId: layer == null ? void 0 : layer.id,
    targetWidth: targetSize.width,
    targetHeight: targetSize.height
  });
  if (!layer) return null;
  const options2 = {
    documentID: document2.id,
    sourceBounds: bounds,
    targetSize,
    layerID: layer.id
  };
  let mask = null;
  try {
    mask = await photoshop.imaging.getLayerMask(options2);
    log2("getLayerMask.resolved", {
      width: (_a3 = mask == null ? void 0 : mask.imageData) == null ? void 0 : _a3.width,
      height: (_b2 = mask == null ? void 0 : mask.imageData) == null ? void 0 : _b2.height
    });
  } catch {
    return null;
  }
  const imageData = mask.imageData;
  if (!imageData) return null;
  const dataFromAPI = await imageData.getData({});
  Promise.resolve().then(() => {
    imageData.dispose();
  });
  log2("completed", {
    width: imageData.width,
    height: imageData.height
  });
  return {
    dataFromAPI,
    width: imageData.width,
    height: imageData.height
  };
}
async function getJimpImageSimple(params) {
  const log2 = createPerfTracker$1("getJimpImageSimple");
  log2("start", {
    document: params.document_identify,
    layerIdentify: params.layer_identify,
    maxWH: params.max_wh
  });
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  const layerIdentify = params.layer_identify;
  const layerID = getLayerID(document2, layerIdentify);
  const maxWidthHeight = params.max_wh;
  const isCanvas = SpeicialIDManager.is_SPECIAL_LAYER_USE_CANVAS(layerIdentify);
  const layer = !isCanvas && layerID > 0 ? findInAllSubLayer(document2, layerID) : null;
  const bounds = {
    origin: (layer == null ? void 0 : layer.bounds) ?? {
      left: 0,
      top: 0,
      right: document2.width,
      bottom: document2.height,
      width: document2.width,
      height: document2.height
    },
    intersect: null,
    scaledIntersect: null,
    desire: params.boundary ? getDesireBounds(
      document2.width,
      document2.height,
      convertSDPPPBoundsToBoundaryRect(params.boundary, document2.width, document2.height)
    ) : getDesireBounds(document2.width, document2.height),
    scaledDesire: null
  };
  if (!bounds.desire) throw new Error(t("desire bounds is null"));
  const scaleRatio = getScaleRatio(bounds.desire, maxWidthHeight);
  bounds.scaledDesire = scaleBounds(bounds.desire, scaleRatio);
  bounds.intersect = getIntersectBounds(bounds.origin, bounds.desire);
  if (!bounds.intersect || !bounds.scaledDesire) throw new Error(t("intersect or scaledDesire is null"));
  bounds.scaledIntersect = scaleBounds(bounds.intersect, scaleRatio);
  let pixelDataFromAPIInit;
  let maskDataFromAPIInit;
  await runNextModalState(async () => {
    log2("modalStart");
    [pixelDataFromAPIInit, maskDataFromAPIInit] = await Promise.all([
      getPixelsData({
        document: document2,
        layer,
        bounds: bounds.intersect,
        targetSize: { width: bounds.scaledIntersect.width, height: bounds.scaledIntersect.height }
      }),
      getMaskData({
        document: document2,
        layer,
        bounds: bounds.intersect,
        targetSize: { width: bounds.scaledIntersect.width, height: bounds.scaledIntersect.height }
      })
    ]);
  }, { commandName: "SDPPP getImage (read-only)", document: document2, suspendHistory: false, dontRecoverSelection: true });
  log2("modalEnd");
  if (!pixelDataFromAPIInit) throw new Error(t("get pixel of {{0}} failed", { "0": layerIdentify }));
  let pixelDataFromAPI = alignPixelBit(pixelDataFromAPIInit);
  let layerWithoutTransparent = false;
  if (layer) {
    layerWithoutTransparent = layer.transparentPixelsLocked;
  } else if (isCanvas) {
    layerWithoutTransparent = document2.layers.every((l2) => l2.transparentPixelsLocked);
  }
  if (layerWithoutTransparent) {
    pixelDataFromAPI = fixAlphaChannel(pixelDataFromAPI);
  }
  let pixelData = padAndTrimToDesireBounds(pixelDataFromAPI, bounds.scaledIntersect, bounds.scaledDesire);
  let maskData = null;
  if (maskDataFromAPIInit) {
    const alignedMask = alignPixelBit(maskDataFromAPIInit);
    maskData = padAndTrimToDesireBounds(alignedMask, bounds.scaledIntersect, bounds.scaledDesire, 1);
  }
  pixelData = applyLayerDataWithTransparent(pixelData, maskData);
  const result = new Jimp({
    data: Buffer.from(pixelData),
    width: bounds.scaledDesire.width,
    height: bounds.scaledDesire.height
  });
  log2("completed", {
    width: result.bitmap.width,
    height: result.bitmap.height
  });
  return result;
}
async function getJimpImageWithHistory(params) {
  var _a3, _b2;
  const log2 = createPerfTracker$1("getJimpImageWithHistory");
  log2("start", {
    document: params.document_identify,
    layerIdentify: params.layer_identify,
    maxWH: params.max_wh
  });
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  const layerIdentify = params.layer_identify;
  const layerID = getLayerID(document2, layerIdentify);
  const maxWidthHeight = params.max_wh;
  const bounds = {
    origin: {
      left: 0,
      top: 0,
      right: document2.width,
      bottom: document2.height,
      width: document2.width,
      height: document2.height
    },
    intersect: null,
    scaledIntersect: null,
    desire: params.boundary ? getDesireBounds(
      document2.width,
      document2.height,
      convertSDPPPBoundsToBoundaryRect(params.boundary, document2.width, document2.height)
    ) : getDesireBounds(document2.width, document2.height),
    scaledDesire: null
  };
  if (!bounds.desire) throw new Error(t("desire bounds is null"));
  const scaleRatio = getScaleRatio(bounds.desire, maxWidthHeight);
  bounds.scaledDesire = scaleBounds(bounds.desire, scaleRatio);
  let mergedLayer = null;
  let pixelDataFromAPI;
  let maskDataFromAPI;
  let layerWithoutTransparent = false;
  await runNextModalState(async (restorer) => {
    log2("modalStart");
    const [layer, isGroup] = await getRasterizedLayer(document2, layerID);
    if (isGroup) mergedLayer = layer;
    if (mergedLayer != null) {
      restorer.add(() => {
        mergedLayer.delete();
      });
    }
    bounds.origin = (layer == null ? void 0 : layer.bounds) ?? bounds.origin;
    bounds.intersect = getIntersectBounds(bounds.origin, bounds.desire);
    bounds.scaledIntersect = scaleBounds(bounds.intersect, scaleRatio);
    if (!bounds.intersect || !bounds.scaledDesire) throw new Error(t("intersect or scaledDesire is null"));
    [pixelDataFromAPI, maskDataFromAPI] = await Promise.all([
      getPixelsData({
        document: document2,
        layer,
        bounds: bounds.intersect,
        targetSize: { width: bounds.scaledIntersect.width, height: bounds.scaledIntersect.height }
      }),
      getMaskData({
        document: document2,
        layer,
        bounds: bounds.intersect,
        targetSize: { width: bounds.scaledIntersect.width, height: bounds.scaledIntersect.height }
      })
    ]);
    layerWithoutTransparent = false;
    if (layer) {
      layerWithoutTransparent = layer.transparentPixelsLocked;
    } else if (SpeicialIDManager.is_SPECIAL_LAYER_USE_CANVAS(layerIdentify)) {
      layerWithoutTransparent = document2.layers.every((l2) => l2.transparentPixelsLocked);
    }
  }, {
    commandName: t("get content of layer {{0}}", { "0": layerIdentify }),
    document: document2
  });
  log2("modalEnd", {
    width: (_a3 = bounds.scaledDesire) == null ? void 0 : _a3.width,
    height: (_b2 = bounds.scaledDesire) == null ? void 0 : _b2.height
  });
  if (!pixelDataFromAPI || !bounds.scaledIntersect || !bounds.origin) {
    throw new Error(t("get pixel of {{0}} failed", { "0": layerIdentify }));
  }
  pixelDataFromAPI = alignPixelBit(pixelDataFromAPI);
  if (layerWithoutTransparent) {
    pixelDataFromAPI = fixAlphaChannel(pixelDataFromAPI);
  }
  let pixelData = padAndTrimToDesireBounds(pixelDataFromAPI, bounds.scaledIntersect, bounds.scaledDesire);
  let maskData = null;
  if (maskDataFromAPI) {
    maskDataFromAPI = alignPixelBit(maskDataFromAPI);
    maskData = padAndTrimToDesireBounds(maskDataFromAPI, bounds.scaledIntersect, bounds.scaledDesire, 1);
  }
  pixelData = applyLayerDataWithTransparent(pixelData, maskData);
  const result = new Jimp({
    data: Buffer.from(pixelData),
    width: bounds.scaledDesire.width,
    height: bounds.scaledDesire.height
  });
  log2("completed", {
    width: result.bitmap.width,
    height: result.bitmap.height
  });
  return result;
}
async function getJimpImage(params) {
  const log2 = createPerfTracker$1("getJimpImage");
  log2("start", {
    document: params.document_identify,
    layerIdentify: params.layer_identify,
    boundaryProvided: Boolean(params.boundary)
  });
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  const layerIdentify = params.layer_identify;
  const layerID = getLayerID(document2, layerIdentify);
  const isCanvas = SpeicialIDManager.is_SPECIAL_LAYER_USE_CANVAS(layerIdentify);
  let useSimple = true;
  if (!isCanvas && layerID > 0) {
    const layer = findInAllSubLayer(document2, layerID);
    if (layer) {
      if (layer.kind === photoshop.constants.LayerKind.GROUP || layer.kind === photoshop.constants.LayerKind.GRADIENTFILL) {
        useSimple = false;
      }
    }
  }
  if (useSimple) {
    log2("simplePath");
    const result2 = await getJimpImageSimple(params);
    log2("completed", {
      width: result2.bitmap.width,
      height: result2.bitmap.height
    });
    return result2;
  }
  log2("historyPath");
  const result = await getJimpImageWithHistory(params);
  log2("completed", {
    width: result.bitmap.width,
    height: result.bitmap.height
  });
  return result;
}
async function getImage(params) {
  const log2 = createPerfTracker$1("getImage");
  log2("start", {
    document: params.document_identify,
    layerIdentify: params.layer_identify
  });
  const jimpImage = await getJimpImage(params);
  log2("jimpReady", {
    width: jimpImage.bitmap.width,
    height: jimpImage.bitmap.height
  });
  const width = jimpImage.bitmap.width;
  const height = jimpImage.bitmap.height;
  const blackImage = new Jimp({ width, height });
  for (let i2 = 0; i2 < width * height; i2++) {
    blackImage.bitmap.data[i2 * 4 + 3] = jimpImage.bitmap.data[i2 * 4 + 3];
  }
  const result = {
    jpegData: new Uint8Array(await jimpImage.getBuffer(JimpMime.jpeg, { quality: params.quality })),
    alphaData: new Uint8Array(await blackImage.getBuffer(JimpMime.png))
  };
  log2("completed", { width, height });
  return result;
}
getImage.getJimpImage = getJimpImage;
async function getLayerInfo(params) {
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  if (!params.layer_identify) throw new Error(t("get_layer_info: layer_identify required"));
  let returnData = {
    name: "",
    opacity: 0,
    boundary: BoundaryRectUtils.fromPositionAndSize(
      0,
      0,
      Number(document2.width) || 0,
      Number(document2.height) || 0,
      Number(document2.width) || 0,
      Number(document2.height) || 0
    ),
    isGroup: false,
    identify: ""
  };
  await runNextModalState(async (restorer) => {
    let layer = null;
    let layerIdentify = params.layer_identify;
    let isGroup = false;
    if (params.layer_identify) {
      layerIdentify = params.layer_identify;
      const layerID = getLayerID(document2, layerIdentify);
      if (SpeicialIDManager.is_SPECIAL_LAYER_USE_CANVAS(layerIdentify)) {
        returnData = {
          name: "",
          opacity: 1,
          boundary: BoundaryRectUtils.fromPositionAndSize(
            0,
            0,
            Number(document2.width) || 0,
            Number(document2.height) || 0,
            Number(document2.width) || 0,
            Number(document2.height) || 0
          ),
          isGroup: true,
          identify: layerIdentify
        };
        return returnData;
      }
      [layer, isGroup] = await getRasterizedLayer(document2, layerID);
      restorer.add(() => {
        if (layer && isGroup) {
          layer.delete();
        }
      });
    }
    if (!layer) throw new Error(t("layer not found: {{0}}", { "0": params.layer_identify }));
    returnData = Object.assign(
      {
        isGroup,
        identify: layerIdentify || ""
      },
      getLayerInfoFromLayer(document2, layer)
    );
  }, {
    commandName: t("get layer info"),
    document: document2
  });
  return returnData;
}
async function getSelectionData({
  document: document2,
  bounds,
  targetSize
}) {
  const options2 = {
    documentID: document2.id,
    sourceBounds: bounds,
    targetSize
  };
  const selection = await photoshop.imaging.getSelection(options2);
  const imageData = selection.imageData;
  const dataFromAPI = await imageData.getData({});
  Promise.resolve().then(() => {
    imageData.dispose();
  });
  return {
    dataFromAPI,
    width: imageData.width,
    height: imageData.height
  };
}
async function getSelection(params) {
  var _a3;
  const documentIdentify = params.document_identify;
  const document2 = getDocumentFromIdentify(documentIdentify);
  if (!document2) throw new Error(t("document {{0}} not found", { "0": documentIdentify }));
  const bounds = {
    origin: {
      left: 0,
      top: 0,
      right: document2.width,
      bottom: document2.height,
      width: document2.width,
      height: document2.height
    },
    intersect: null,
    scaledIntersect: null,
    desire: params.boundary ? getDesireBounds(
      document2.width,
      document2.height,
      convertSDPPPBoundsToBoundaryRect(params.boundary, document2.width, document2.height)
    ) : getDesireBounds(document2.width, document2.height),
    scaledDesire: null
  };
  if (!bounds.desire) throw new Error(t("desire bounds is null"));
  const scaleRatio = getScaleRatio(bounds.desire, params.max_wh);
  bounds.scaledDesire = scaleBounds(bounds.desire, scaleRatio);
  if (!((_a3 = document2.selection) == null ? void 0 : _a3.bounds)) {
    const arr = new Uint8Array(bounds.desire.width * bounds.desire.height);
    arr.fill(255);
    return {
      blob: arr,
      width: bounds.desire.width,
      height: bounds.desire.height
    };
  }
  let selectionData = null;
  let selectionDataFromAPI = null;
  await runNextModalState(async () => {
    var _a4;
    bounds.origin = ((_a4 = document2.selection) == null ? void 0 : _a4.bounds) || {
      left: 0,
      top: 0,
      right: document2.width,
      bottom: document2.height
    };
    bounds.intersect = getIntersectBounds(bounds.origin, bounds.desire);
    bounds.scaledIntersect = scaleBounds(bounds.intersect, scaleRatio);
    selectionDataFromAPI = await getSelectionData({
      document: document2,
      bounds: bounds.intersect,
      targetSize: {
        width: bounds.scaledIntersect.width,
        height: bounds.scaledIntersect.height
      }
    });
  }, { document: document2, commandName: "SDPPP getSelection", suspendHistory: false, dontRecoverSelection: true });
  if (!selectionDataFromAPI || !bounds.scaledIntersect || !bounds.origin) {
    throw new Error(t("get selection failed"));
  }
  selectionDataFromAPI = alignPixelBit(selectionDataFromAPI);
  selectionData = padAndTrimToDesireBounds(selectionDataFromAPI, bounds.scaledIntersect, bounds.scaledDesire, 1);
  return {
    blob: selectionData,
    width: bounds.scaledDesire.width,
    height: bounds.scaledDesire.height
  };
}
async function getBoundaryImpl(params) {
  var _a3, _b2;
  if (!photoshop.app.activeDocument) {
    throw new Error(t("photoshop.no_active_document"));
  }
  const document2 = photoshop.app.activeDocument;
  let boundaryRect;
  switch (params.type) {
    case "curlayer": {
      const activeLayer = (_a3 = document2.activeLayers) == null ? void 0 : _a3[0];
      if (!activeLayer) {
        throw new Error(t("photoshop.no_active_layer"));
      }
      const layerBounds = activeLayer.bounds;
      if (!layerBounds) {
        boundaryRect = BoundaryRectUtils.fromPositionAndSize(
          0,
          0,
          document2.width,
          document2.height,
          document2.width,
          document2.height
        );
      } else {
        boundaryRect = BoundaryRectUtils.fromPhotoshopBounds(layerBounds, document2.width, document2.height);
      }
      break;
    }
    case "selection": {
      const selectionBounds = (_b2 = document2.selection) == null ? void 0 : _b2.bounds;
      if (!selectionBounds) {
        boundaryRect = BoundaryRectUtils.fromPositionAndSize(
          0,
          0,
          document2.width,
          document2.height,
          document2.width,
          document2.height
        );
      } else {
        boundaryRect = BoundaryRectUtils.fromPhotoshopBounds(selectionBounds, document2.width, document2.height);
      }
      break;
    }
    default:
      throw new Error(t("photoshop.invalid_boundary_type", { type: params.type }));
  }
  const thumbnail = await generateBoundaryThumbnail(document2, boundaryRect);
  return {
    boundary: boundaryRect,
    thumbnail
  };
}
async function generateBoundaryThumbnail(document2, boundaryRect) {
  try {
    const documentInfo = await getDocumentInfo({
      document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT()
    });
    const docWidth = Number(document2.width) || 0;
    const docHeight = Number(document2.height) || 0;
    const documentBoundary = BoundaryRectUtils.toSDPPPBounds(
      documentInfo.document_boundary,
      docWidth,
      docHeight
    );
    const canvasImage = await getImage.getJimpImage({
      document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
      layer_identify: SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS(),
      boundary: documentBoundary,
      max_wh: 192,
      quality: 8
    });
    const thumbWidth = canvasImage.width;
    const thumbHeight = canvasImage.height;
    const docWidthPx = Number(document2.width) || 0;
    const docHeightPx = Number(document2.height) || 0;
    const scaleX = thumbWidth / docWidthPx;
    const scaleY = thumbHeight / docHeightPx;
    const boundaryLeft = Math.round(boundaryRect.leftDistance * scaleX);
    const boundaryTop = Math.round(boundaryRect.topDistance * scaleY);
    const boundaryRight = Math.round((docWidth - boundaryRect.rightDistance) * scaleX);
    const boundaryBottom = Math.round((docHeight - boundaryRect.bottomDistance) * scaleY);
    canvasImage.scan(0, 0, thumbWidth, thumbHeight, function(x2, y2, idx) {
      const isOutsideBoundary = x2 < boundaryLeft || x2 >= boundaryRight || y2 < boundaryTop || y2 >= boundaryBottom;
      if (isOutsideBoundary) {
        canvasImage.bitmap.data[idx + 3] = Math.round(canvasImage.bitmap.data[idx + 3] * 0.3);
      }
    });
    const thumbnailBuffer = await canvasImage.getBuffer(JimpMime.png);
    return "data:image/png;base64," + thumbnailBuffer.toString("base64");
  } catch (error) {
    console.error("Error generating boundary thumbnail:", error);
    return "";
  }
}
async function getCurrentLayerIdentify() {
  var _a3;
  if (!photoshop.app.activeDocument) {
    throw new Error(t("photoshop.no_active_document"));
  }
  const activeLayer = ((_a3 = photoshop.app.activeDocument.activeLayers) == null ? void 0 : _a3[0]) ?? null;
  if (!activeLayer) {
    return { layer_identify: null };
  }
  const identify = getSelectedLayerIdentify();
  return { layer_identify: identify };
}
const UXP_PROTOCOL = "uxp:";
const BOUNDARY_HOST = "boundary";
const CONTENT_HOST = "content";
const MASK_HOST = "mask";
const BOUNDARY_SCHEME$1 = `uxp://${BOUNDARY_HOST}`;
const CONTENT_SCHEME$1 = `uxp://${CONTENT_HOST}`;
const MASK_SCHEME = `uxp://${MASK_HOST}`;
const RECT_QUERY_KEYS = [
  "leftDistance",
  "topDistance",
  "rightDistance",
  "bottomDistance",
  "width",
  "height"
];
function normalizeDocId$1(docId) {
  const numeric = Number(docId);
  if (!Number.isFinite(numeric)) return 0;
  const normalized = Math.floor(numeric);
  return normalized < 0 ? 0 : normalized;
}
function appendQuery$1(base2, params) {
  const searchParams = new URLSearchParams();
  for (const [key2, value] of Object.entries(params)) {
    if (value === void 0 || value === null || value === "") continue;
    searchParams.set(key2, String(value));
  }
  const query = searchParams.toString();
  return query ? `${base2}?${query}` : base2;
}
function ensureFiniteNumber(value, label) {
  if (!Number.isFinite(value)) {
    throw new Error(`${label} must be a finite number`);
  }
}
function parseNumberQuery(url, key2) {
  const raw = url.searchParams.get(key2);
  if (raw == null || raw === "") return void 0;
  const num = Number(raw);
  ensureFiniteNumber(num, key2);
  return num;
}
function serializeBoundaryRect(rect) {
  const serialized = {};
  for (const key2 of RECT_QUERY_KEYS) {
    serialized[key2] = Number(rect[key2]);
  }
  return serialized;
}
function deserializeBoundaryRect(url) {
  const rect = {};
  for (const key2 of RECT_QUERY_KEYS) {
    const value = parseNumberQuery(url, key2);
    if (value === void 0) {
      throw new Error(`boundary rect missing query parameter "${key2}"`);
    }
    rect[key2] = value;
  }
  return rect;
}
function extractLayerParams(layerIdentify) {
  if (!layerIdentify) return {};
  const trimmed = String(layerIdentify).trim();
  if (!trimmed) return {};
  const match = /(.*)\(id:([^\)]+)\)\s*$/.exec(trimmed);
  let layerId;
  let layerName;
  if (match) {
    layerName = match[1].trim().replace(/^-+/, "").trim() || void 0;
    layerId = match[2].trim();
  } else if (trimmed.startsWith("(id:") && trimmed.endsWith(")")) {
    const inner = trimmed.slice(4, -1).trim();
    layerId = inner || void 0;
  } else if (/^\d+$/.test(trimmed)) {
    layerId = trimmed;
  } else {
    layerName = trimmed.replace(/^-+/, "").trim() || void 0;
  }
  return { layerId, layerName };
}
function composeLayerIdentify(layerId, layerName) {
  const id = layerId == null ? void 0 : layerId.trim();
  const name = layerName == null ? void 0 : layerName.trim();
  if (name && id) {
    return `${name} (id:${id})`;
  }
  if (name) {
    return name;
  }
  if (id) {
    return `${id} (id:${id})`;
  }
  return void 0;
}
function ensureUxpUrl(uri2, expectedHost) {
  let parsed;
  try {
    parsed = new URL(uri2);
  } catch {
    throw new Error(`Invalid ${expectedHost} uri: ${uri2}`);
  }
  if (parsed.protocol !== UXP_PROTOCOL) {
    throw new Error(`${expectedHost} uri must use uxp:// scheme`);
  }
  if (parsed.hostname !== expectedHost) {
    throw new Error(`${expectedHost} uri host must be "${expectedHost}"`);
  }
  const [docSegment, ...rest] = parsed.pathname.split("/").filter(Boolean);
  if (!docSegment) {
    throw new Error(`${expectedHost} uri is missing required segments`);
  }
  const docId = Number(docSegment);
  ensureFiniteNumber(docId, "docId");
  if (!Number.isInteger(docId) || docId < 0) {
    throw new Error("docId must be a non-negative integer");
  }
  return { parsed, docId, segments: rest };
}
function parseBoundaryResource(resource) {
  const { parsed, docId, segments } = ensureUxpUrl(resource, BOUNDARY_HOST);
  const boundaryType = segments[0];
  if (!boundaryType || boundaryType === "canvas" || boundaryType === "curlayer" || boundaryType === "selection") {
    return {
      docId,
      boundary: boundaryType ?? "canvas",
      imageSize: parseNumberQuery(parsed, "imageSize"),
      imageQuality: parseNumberQuery(parsed, "imageQuality")
    };
  }
  if (boundaryType !== "rect") {
    throw new Error(`Unsupported boundary type "${boundaryType}"`);
  }
  return {
    docId,
    boundary: deserializeBoundaryRect(parsed),
    imageSize: parseNumberQuery(parsed, "imageSize"),
    imageQuality: parseNumberQuery(parsed, "imageQuality")
  };
}
function parseContentResource(resource) {
  const { parsed, docId, segments } = ensureUxpUrl(resource, CONTENT_HOST);
  const contentType = segments[0];
  if (!contentType) {
    throw new Error("content uri is missing required segments");
  }
  if (contentType === "canvas" || contentType === "selection") {
    return {
      docId,
      content: contentType
    };
  }
  if (contentType === "curlayer") {
    const layerId = parsed.searchParams.get("layerid");
    const layerName = parsed.searchParams.get("layername");
    return {
      docId,
      content: "curlayer",
      layerIdentify: composeLayerIdentify(layerId, layerName)
    };
  }
  if (contentType === "layer") {
    const layerId = parsed.searchParams.get("layerid");
    if (!layerId) {
      throw new Error("content uri with /layer requires layerid query parameter");
    }
    return {
      docId,
      content: "curlayer",
      layerIdentify: composeLayerIdentify(layerId, parsed.searchParams.get("layername"))
    };
  }
  throw new Error(`Unsupported content type "${contentType}"`);
}
function parseMaskResource(resource) {
  const { parsed, docId, segments } = ensureUxpUrl(resource, MASK_HOST);
  const contentType = segments[0];
  if (!contentType) {
    throw new Error("mask content uri is missing required segments");
  }
  const reverseParam = parsed.searchParams.get("reverse");
  const reverse = reverseParam === "1" || (reverseParam == null ? void 0 : reverseParam.toLowerCase()) === "true";
  if (contentType === "canvas" || contentType === "selection") {
    return { docId, content: contentType, reverse };
  }
  if (contentType === "curlayer") {
    const layerId = parsed.searchParams.get("layerid");
    const layerName = parsed.searchParams.get("layername");
    return {
      docId,
      content: "curlayer",
      reverse,
      layerIdentify: composeLayerIdentify(layerId, layerName)
    };
  }
  if (contentType === "layer") {
    const layerId = parsed.searchParams.get("layerid");
    if (!layerId) {
      throw new Error("mask content uri with /layer requires layerid query parameter");
    }
    return {
      docId,
      content: "curlayer",
      layerIdentify: composeLayerIdentify(layerId, parsed.searchParams.get("layername")),
      reverse
    };
  }
  throw new Error(`Unsupported mask content type "${contentType}"`);
}
function buildBoundaryUri$1(docId, boundary, options2) {
  const docSegment = normalizeDocId$1(docId);
  if (!boundary || boundary === "canvas" || boundary === "curlayer" || boundary === "selection") {
    return appendQuery$1(`${BOUNDARY_SCHEME$1}/${docSegment}/${boundary ?? "canvas"}`, {
      imageSize: options2 == null ? void 0 : options2.imageSize,
      imageQuality: options2 == null ? void 0 : options2.imageQuality
    });
  }
  return appendQuery$1(`${BOUNDARY_SCHEME$1}/${docSegment}/rect`, {
    ...serializeBoundaryRect(boundary),
    imageSize: options2 == null ? void 0 : options2.imageSize,
    imageQuality: options2 == null ? void 0 : options2.imageQuality
  });
}
function buildContentUri$1(docId, content, layerIdentify) {
  const docSegment = normalizeDocId$1(docId);
  if (content === "curlayer") {
    if (layerIdentify && layerIdentify !== "") {
      const { layerId, layerName } = extractLayerParams(layerIdentify);
      return appendQuery$1(`${CONTENT_SCHEME$1}/${docSegment}/layer`, {
        layerid: layerId ?? layerIdentify.trim(),
        layername: layerName ?? void 0
      });
    }
    return `${CONTENT_SCHEME$1}/${docSegment}/curlayer`;
  }
  return `${CONTENT_SCHEME$1}/${docSegment}/${content}`;
}
function buildMaskContentUri(docId, content, layerIdentify, reverse) {
  const docSegment = normalizeDocId$1(docId);
  if (content === "curlayer") {
    const { layerId, layerName } = extractLayerParams(layerIdentify ?? void 0);
    return appendQuery$1(`${MASK_SCHEME}/${docSegment}/layer`, {
      layerid: layerId ?? (layerIdentify == null ? void 0 : layerIdentify.trim()) ?? void 0,
      layername: layerName ?? void 0,
      reverse: reverse ? 1 : void 0
    });
  }
  return appendQuery$1(`${MASK_SCHEME}/${docSegment}/${content}`, {
    reverse: reverse ? 1 : void 0
  });
}
function extractDocIdFromUris(uris) {
  for (const uri2 of uris) {
    if (!uri2) continue;
    try {
      const parsed = new URL(uri2);
      if (parsed.protocol !== UXP_PROTOCOL) continue;
      const docSegment = parsed.pathname.split("/").filter(Boolean)[0];
      if (!docSegment) continue;
      const numeric = Number(docSegment);
      if (!Number.isFinite(numeric)) continue;
      const normalized = Math.floor(numeric);
      if (normalized >= 0) {
        return normalized;
      }
    } catch {
      continue;
    }
  }
  return null;
}
const PNG_MIME$2 = "image/png";
const DATA_URL_REGEX$2 = /^data:([^;,]+)?(;base64)?,(.*)$/i;
const perfLogger = sdpppLogger.extend("perf");
const PERF_ALLOWED_REGEX = /^fileResource\.(createBy|createFrom|combineBy)[^.]+\.action$/;
const shouldLogPerf = (label) => PERF_ALLOWED_REGEX.test(label);
const projectBoundaryRectFromResource = (boundaryUri, options2) => {
  try {
    const parsed = parseBoundaryResource(boundaryUri);
    if (typeof parsed.boundary === "string") {
      return null;
    }
    const rect = parsed.boundary;
    const docWidth = Math.round(rect.leftDistance + rect.width + rect.rightDistance);
    const docHeight = Math.round(rect.topDistance + rect.height + rect.bottomDistance);
    if (!(docWidth > 0 && docHeight > 0)) {
      console.warn("[createFromCBM] boundary projection invalid", {
        boundaryUri,
        docWidth,
        docHeight
      });
      return null;
    }
    const maxSide = Math.max(docWidth, docHeight);
    const override = options2 == null ? void 0 : options2.imageSizeOverride;
    const targetSize = override !== void 0 ? override : parsed.imageSize;
    const maxTarget = targetSize && targetSize > 0 ? targetSize : maxSide;
    const scale = maxSide > 0 ? Math.min(1, maxTarget / maxSide) : 1;
    const scaledDocWidth = Math.max(1, Math.round(docWidth * scale));
    const scaledDocHeight = Math.max(1, Math.round(docHeight * scale));
    const cropRect = ensurePositiveRect({
      x: Math.round(rect.leftDistance * scale),
      y: Math.round(rect.topDistance * scale),
      width: Math.max(1, Math.round(rect.width * scale)),
      height: Math.max(1, Math.round(rect.height * scale))
    });
    if (!(scaledDocWidth > 0 && scaledDocHeight > 0)) {
      console.warn("[createFromCBM] boundary projection scaled invalid", {
        boundaryUri,
        scaledDocWidth,
        scaledDocHeight
      });
      return null;
    }
    return {
      docWidth: scaledDocWidth,
      docHeight: scaledDocHeight,
      cropRect
    };
  } catch (error) {
    console.warn("[createFromCBM] boundary projection failed", {
      boundaryUri,
      message: error instanceof Error ? error.message : String(error)
    });
    return null;
  }
};
function createPerfTracker(label) {
  if (!shouldLogPerf(label)) {
    return () => void 0;
  }
  const startedAt = Date.now();
  const logger = perfLogger.extend(label);
  return (stage, extra) => {
    const elapsed = Date.now() - startedAt;
    if (extra) {
      logger(`${stage} +${elapsed}ms`, extra);
    } else {
      logger(`${stage} +${elapsed}ms`);
    }
  };
}
function normalizeUri$1(value) {
  if (typeof value !== "string") return void 0;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function isCanvasMaskUri(value) {
  const normalized = normalizeUri$1(value);
  if (!normalized || !normalized.startsWith("uxp://mask/")) {
    return false;
  }
  try {
    const parsed = parseMaskResource(normalized);
    return parsed.content === "canvas";
  } catch {
    return false;
  }
}
function normalizeFileResourceUri$1(uri2) {
  try {
    const parsed = new URL(uri2);
    const reverseParam = parsed.searchParams.get("reverse");
    const reverse = reverseParam === "1" || (reverseParam == null ? void 0 : reverseParam.trim().toLowerCase()) === "true" ? true : reverseParam === "0" ? false : void 0;
    parsed.search = "";
    parsed.hash = "";
    return {
      resourceId: `${parsed.protocol}//${parsed.host}${parsed.pathname}`,
      reverse
    };
  } catch {
    return { resourceId: uri2 };
  }
}
function decodeDataUrl$1(dataUrl) {
  const match = DATA_URL_REGEX$2.exec(dataUrl);
  if (!match) {
    throw new Error("Invalid data URL");
  }
  const mime2 = match[1] ?? void 0;
  const isBase64 = !!match[2];
  const payload = match[3] ?? "";
  if (isBase64) {
    return { buffer: bufferExports.Buffer.from(payload, "base64"), mime: mime2 };
  }
  return { buffer: bufferExports.Buffer.from(decodeURIComponent(payload), "utf8"), mime: mime2 };
}
const boundaryRectToSDPPP$1 = (rect) => BoundaryRectUtils.toSDPPPBoundsAuto(rect);
async function isPhotoshopSelectionEmpty$1() {
  try {
    const doc = photoshop.app.activeDocument;
    if (!doc) return true;
    const selection = doc.selection;
    if (!selection) return true;
    const bounds = selection.bounds;
    if (!bounds) {
      return true;
    }
    return false;
  } catch (error) {
    return true;
  }
}
async function resolveEffectiveBoundaryUri(params) {
  const boundaryCandidate = normalizeUri$1(params.boundaryUri);
  if (boundaryCandidate) {
    return boundaryCandidate;
  }
  const contentUri = normalizeUri$1(params.contentUri);
  if (contentUri && !contentUri.startsWith("uxp://file/")) {
    const parsed = parseContentResource(contentUri);
    return buildBoundaryUri$1(parsed.docId, "canvas");
  }
  const maskUri = normalizeUri$1(params.maskUri);
  if (maskUri && maskUri.startsWith("uxp://mask/")) {
    const parsed = parseMaskResource(maskUri);
    return buildBoundaryUri$1(parsed.docId, "canvas");
  }
  const docId = extractDocIdFromUris([boundaryCandidate, contentUri, maskUri]);
  if (docId != null) {
    return buildBoundaryUri$1(docId, "canvas");
  }
  throw new Error("Unable to resolve boundary for CBM materialization");
}
function getEffectiveImageSize(mesh, requested) {
  var _a3, _b2, _c2, _d2, _e2, _f2;
  const activeNodeState = (_d2 = (_c2 = (_b2 = (_a3 = mesh == null ? void 0 : mesh.getNode) == null ? void 0 : _a3.call(mesh, "uxp")) == null ? void 0 : _b2.store) == null ? void 0 : _c2.getState) == null ? void 0 : _d2.call(_c2);
  const activeDocumentID = activeNodeState == null ? void 0 : activeNodeState.activeDocumentID;
  const meshState = ((_f2 = (_e2 = mesh == null ? void 0 : mesh.store) == null ? void 0 : _e2.getState) == null ? void 0 : _f2.call(_e2)) ?? {};
  const workBoundaryMaxSizes = (meshState == null ? void 0 : meshState.workBoundaryMaxSizes) ?? {};
  const defaultSize = sdpppX["settings.imaging.defaultImagesSizeLimit"];
  if (requested && requested > 0) {
    return requested;
  }
  if (activeDocumentID != null && workBoundaryMaxSizes[activeDocumentID]) {
    return workBoundaryMaxSizes[activeDocumentID];
  }
  return defaultSize;
}
async function resolveBoundaryParam$1(boundary, layerIdentify) {
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  if (typeof boundary === "string") {
    switch (boundary) {
      case "canvas": {
        const docInfo = await getDocumentInfo({ document_identify: documentIdentify });
        return boundaryRectToSDPPP$1(docInfo.document_boundary);
      }
      case "curlayer": {
        const layerInfo = await getLayerInfo({
          document_identify: documentIdentify,
          layer_identify: layerIdentify ?? SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER()
        });
        return boundaryRectToSDPPP$1(layerInfo.boundary);
      }
      case "selection": {
        const docInfo = await getDocumentInfo({ document_identify: documentIdentify });
        const selectionRect = docInfo.selection_boundary ?? docInfo.document_boundary;
        return boundaryRectToSDPPP$1(selectionRect);
      }
      default:
        throw new Error(`Unsupported boundary specification: ${boundary}`);
    }
  }
  const doc = photoshop.app.activeDocument;
  if (!doc) {
    throw new Error("No active document to compute boundary rect.");
  }
  const docWidth = Number(doc.width);
  const docHeight = Number(doc.height);
  return BoundaryRectUtils.toSDPPPBounds(boundary, docWidth, docHeight);
}
function resolveLayerIdentifyForContent$1(content, layerIdentify) {
  if (layerIdentify && layerIdentify.length > 0) {
    return layerIdentify;
  }
  switch (content) {
    case "canvas":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    case "curlayer":
      return SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    case "selection":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    default:
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
  }
}
function resolveLayerIdentifyForMask$1(content, layerIdentify) {
  if (layerIdentify && layerIdentify.length > 0) {
    return layerIdentify;
  }
  switch (content) {
    case "canvas":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    case "curlayer":
      return SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    case "selection":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    default:
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
  }
}
async function loadMaskSnapshotForMaterializer(mesh, boundaryUri, maskUri, options2) {
  const log2 = createPerfTracker("loadMaskSnapshotForMaterializer");
  log2("start", { boundaryUri, hasMaskUri: Boolean(maskUri) });
  const normalizedMaskUri = normalizeUri$1(maskUri);
  if (!normalizedMaskUri) {
    log2("noMaskUri");
    console.warn("[createFromCBM] mask ignored: missing maskUri", { boundaryUri });
    return null;
  }
  if (normalizedMaskUri.startsWith("uxp://mask/")) {
    const parsedMask = parseMaskResource(normalizedMaskUri);
    const selectionEmpty = parsedMask.content === "selection" ? await isPhotoshopSelectionEmpty$1() : false;
    log2("maskUriDetected", {
      content: parsedMask.content,
      reverse: parsedMask.reverse
    });
    const fetchLog = createPerfTracker("loadMaskSnapshotForMaterializer.getJimpImage");
    const layerSnapshot = await loadMaskSnapshotJimp$1(mesh, boundaryUri, normalizedMaskUri, options2);
    fetchLog("completed", {
      width: layerSnapshot.jimp.bitmap.width,
      height: layerSnapshot.jimp.bitmap.height
    });
    const width = layerSnapshot.jimp.bitmap.width;
    const height = layerSnapshot.jimp.bitmap.height;
    if (selectionEmpty) {
      const fallback = await createSolidMask$1(width, height);
      const parsedBoundary = parseBoundaryResource(boundaryUri);
      const boundaryType = typeof parsedBoundary.boundary === "string" ? parsedBoundary.boundary : "rect";
      log2("selectionEmptyFallback", {
        width,
        height,
        boundaryType,
        docId: parsedBoundary.docId,
        maskContent: parsedMask.content
      });
      console.warn("[createFromCBM] mask fallback due to empty selection", {
        boundaryUri,
        maskUri: normalizedMaskUri,
        maskContent: parsedMask.content
      });
      return {
        jimp: fallback
      };
    }
    log2("maskSnapshotReady", { width, height });
    return { jimp: layerSnapshot.jimp };
  }
  if (normalizedMaskUri.startsWith("uxp://file/")) {
    const fetchLog = createPerfTracker("loadMaskSnapshotForMaterializer.resolveSharedBuffer");
    const normalized = normalizeFileResourceUri$1(normalizedMaskUri);
    const cached = getJimpForResource(normalized.resourceId);
    if (cached) {
      log2("maskJimpCacheHit", {
        width: cached.image.bitmap.width,
        height: cached.image.bitmap.height
      });
      return {
        jimp: cached.image,
        reverse: normalized.reverse
      };
    }
    const { buffer: buffer2 } = await resolveResourceBuffer(normalized.resourceId);
    const jimpImage = await Jimp.read(bufferExports.Buffer.from(buffer2));
    fetchLog("completed", {
      width: jimpImage.bitmap.width,
      height: jimpImage.bitmap.height
    });
    const sample = Array.from(
      { length: Math.min(10, jimpImage.bitmap.width * jimpImage.bitmap.height) },
      (_unused, index2) => {
        const idx = index2 * 4;
        return {
          r: jimpImage.bitmap.data[idx + 0],
          g: jimpImage.bitmap.data[idx + 1],
          b: jimpImage.bitmap.data[idx + 2],
          a: jimpImage.bitmap.data[idx + 3]
        };
      }
    );
    log2("maskFileSample", {
      width: jimpImage.bitmap.width,
      height: jimpImage.bitmap.height,
      sample
    });
    if (jimpImage.bitmap.width <= 32 || jimpImage.bitmap.height <= 32) {
      console.warn("[createFromCBM] mask very small relative to boundary", {
        maskUri: normalizedMaskUri,
        width: jimpImage.bitmap.width,
        height: jimpImage.bitmap.height
      });
    }
    if (normalized.reverse !== void 0) {
      log2("maskFileReverseDetected", { reverse: normalized.reverse });
    }
    return {
      jimp: jimpImage,
      reverse: normalized.reverse
    };
  }
  if (DATA_URL_REGEX$2.test(normalizedMaskUri)) {
    const fetchLog = createPerfTracker("loadMaskSnapshotForMaterializer.decodeDataUrl");
    const decoded = decodeDataUrl$1(normalizedMaskUri);
    const jimpImage = await Jimp.read(decoded.buffer);
    fetchLog("completed", {
      width: jimpImage.bitmap.width,
      height: jimpImage.bitmap.height
    });
    return {
      jimp: jimpImage
    };
  }
  log2("unsupportedMaskUri", { maskUri: normalizedMaskUri });
  return null;
}
async function createSolidMask$1(width, height) {
  const safeWidth = Math.max(1, width);
  const safeHeight = Math.max(1, height);
  return new Jimp({
    width: safeWidth,
    height: safeHeight,
    color: 0
  });
}
async function loadContentSnapshotJimp(mesh, boundaryUri, contentUri, options2) {
  const log2 = createPerfTracker("loadContentSnapshotJimp");
  log2("start", { boundaryUri, contentUri });
  const normalizedContentUri = normalizeUri$1(contentUri);
  if (!normalizedContentUri) {
    throw new Error("contentUri is required for CBM materialization");
  }
  if (normalizedContentUri.startsWith("uxp://file/")) {
    const normalizedFile = normalizeFileResourceUri$1(normalizedContentUri);
    const cached = getJimpForResource(normalizedFile.resourceId);
    if (cached) {
      log2("jimpCacheHit", {
        width: cached.image.bitmap.width,
        height: cached.image.bitmap.height
      });
      if (options2 == null ? void 0 : options2.maxSizeOverride) {
        resizeImageToMaxSize(cached.image, options2.maxSizeOverride);
      }
      return {
        jimp: cached.image
      };
    }
    if (options2 == null ? void 0 : options2.preferThumbnail) {
      const cachedThumbnail = getResourceThumbnail(normalizedFile.resourceId);
      if (cachedThumbnail == null ? void 0 : cachedThumbnail.buffer) {
        log2("thumbnailHit", {
          width: cachedThumbnail.width,
          height: cachedThumbnail.height
        });
        const jimpImage3 = await Jimp.read(bufferExports.Buffer.from(cachedThumbnail.buffer));
        return {
          jimp: jimpImage3
        };
      }
    }
    const fetchLog = createPerfTracker("loadContentSnapshotJimp.resolveSharedBuffer");
    const { buffer: buffer2 } = await resolveResourceBuffer(normalizedFile.resourceId);
    const jimpImage2 = await Jimp.read(bufferExports.Buffer.from(buffer2));
    if (options2 == null ? void 0 : options2.maxSizeOverride) {
      resizeImageToMaxSize(jimpImage2, options2.maxSizeOverride);
    }
    fetchLog("completed", {
      width: jimpImage2.bitmap.width,
      height: jimpImage2.bitmap.height
    });
    return {
      jimp: jimpImage2
    };
  }
  if (DATA_URL_REGEX$2.test(normalizedContentUri)) {
    const fetchLog = createPerfTracker("loadContentSnapshotJimp.decodeDataUrl");
    const decoded = decodeDataUrl$1(normalizedContentUri);
    const jimpImage2 = await Jimp.read(decoded.buffer);
    if (options2 == null ? void 0 : options2.maxSizeOverride) {
      resizeImageToMaxSize(jimpImage2, options2.maxSizeOverride);
    }
    fetchLog("completed", {
      width: jimpImage2.bitmap.width,
      height: jimpImage2.bitmap.height
    });
    return {
      jimp: jimpImage2
    };
  }
  const built = (options2 == null ? void 0 : options2.prebuiltParams) ?? buildGetImageParamsFromResources(boundaryUri, normalizedContentUri);
  const boundarySpecForFetch = (options2 == null ? void 0 : options2.boundaryOverride) ?? built.boundary;
  const effectiveImageSize = (options2 == null ? void 0 : options2.maxSizeOverride) ?? getEffectiveImageSize(mesh, built.imageSize);
  const boundaryType = boundarySpecForFetch ? typeof boundarySpecForFetch === "string" ? boundarySpecForFetch : "rect" : "none";
  log2("paramsResolved", {
    imageSize: effectiveImageSize,
    boundaryType,
    skipBoundaryParam: Boolean(options2 == null ? void 0 : options2.skipBoundaryParam),
    preferThumbnail: Boolean(options2 == null ? void 0 : options2.preferThumbnail),
    content: built.content
  });
  const shouldSkipBoundary = Boolean(options2 == null ? void 0 : options2.skipBoundaryParam);
  const boundaryParam = !shouldSkipBoundary && boundarySpecForFetch ? await resolveBoundaryParam$1(boundarySpecForFetch, built.layer_identify ?? null) : void 0;
  const layerIdentify = resolveLayerIdentifyForContent$1(built.content, built.layer_identify ?? null);
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  const jimpImage = await getImage.getJimpImage({
    document_identify: documentIdentify,
    layer_identify: layerIdentify,
    boundary: boundaryParam,
    max_wh: effectiveImageSize,
    quality: built.imageQuality
  });
  log2("jimpFetched", {
    width: jimpImage.bitmap.width,
    height: jimpImage.bitmap.height
  });
  if (built.content === "selection") {
    try {
      let selectionBoundaryParam = boundaryParam;
      if (!selectionBoundaryParam && boundarySpecForFetch) {
        selectionBoundaryParam = await resolveBoundaryParam$1(boundarySpecForFetch, built.layer_identify ?? null);
      }
      const selection = await getSelection({
        document_identify: documentIdentify,
        boundary: selectionBoundaryParam,
        max_wh: effectiveImageSize
      });
      const { blob, width, height } = selection;
      if (blob && blob.length === width * height) {
        let nonZero = 0;
        for (let i2 = 0; i2 < blob.length; i2 += 1) {
          if (blob[i2] !== 0) {
            nonZero += 1;
          }
        }
        log2("selectionBlobStats", {
          boundaryType,
          width,
          height,
          nonZero,
          total: blob.length,
          ratio: blob.length > 0 ? nonZero / blob.length : 0
        });
        for (let i2 = 0; i2 < width * height; i2++) {
          const idx = i2 * 4;
          const alpha = blob[i2];
          if (idx + 3 < jimpImage.bitmap.data.length) {
            jimpImage.bitmap.data[idx + 3] = alpha;
          }
        }
      }
      if ((!blob || blob.length !== width * height) && typeof console !== "undefined" && console.warn) {
        console.warn("[createFromCBM] selection blob size mismatch", {
          phase: "content",
          boundaryType,
          width,
          height,
          blobLength: (blob == null ? void 0 : blob.length) ?? null,
          expected: width * height
        });
      }
      log2("selectionAlphaApplied");
    } catch {
    }
  }
  log2("completed");
  return {
    jimp: jimpImage
  };
}
async function loadMaskSnapshotJimp$1(mesh, boundaryUri, maskUri, options2) {
  const log2 = createPerfTracker("loadMaskSnapshotJimp");
  log2("start", { boundaryUri, maskUri });
  const built = buildGetMaskParamsFromResources(boundaryUri, maskUri);
  const boundaryForFetch = built.boundary;
  const effectiveImageSize = getEffectiveImageSize(mesh, built.imageSize);
  const boundaryType = typeof boundaryForFetch === "string" ? boundaryForFetch : "rect";
  log2("paramsResolved", {
    imageSize: effectiveImageSize,
    content: built.content,
    reverse: built.reverse,
    boundaryType,
    preferThumbnail: Boolean(options2 == null ? void 0 : options2.preferThumbnail)
  });
  const boundaryParam = boundaryForFetch ? await resolveBoundaryParam$1(boundaryForFetch, built.layer_identify ?? null) : void 0;
  const layerIdentify = resolveLayerIdentifyForMask$1(built.content, built.layer_identify ?? null);
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  const jimpImage = await getImage.getJimpImage({
    document_identify: documentIdentify,
    layer_identify: layerIdentify,
    boundary: boundaryParam,
    max_wh: effectiveImageSize
  });
  log2("jimpFetched", {
    width: jimpImage.bitmap.width,
    height: jimpImage.bitmap.height
  });
  if (built.content === "selection") {
    try {
      const selection = await getSelection({
        document_identify: documentIdentify,
        boundary: boundaryParam,
        max_wh: effectiveImageSize
      });
      const { blob, width, height } = selection;
      if (blob && blob.length === width * height) {
        let nonZero = 0;
        for (let i2 = 0; i2 < blob.length; i2 += 1) {
          if (blob[i2] !== 0) {
            nonZero += 1;
          }
        }
        log2("selectionBlobStats", {
          boundaryType,
          width,
          height,
          nonZero,
          total: blob.length,
          ratio: blob.length > 0 ? nonZero / blob.length : 0
        });
        for (let i2 = 0; i2 < width * height; i2++) {
          const idx = i2 * 4;
          const alpha = blob[i2];
          if (idx + 3 < jimpImage.bitmap.data.length) {
            jimpImage.bitmap.data[idx + 3] = alpha;
          }
        }
      }
      if ((!blob || blob.length !== width * height) && typeof console !== "undefined" && console.warn) {
        console.warn("[createFromCBM] selection blob size mismatch", {
          phase: "mask",
          boundaryType,
          width,
          height,
          blobLength: (blob == null ? void 0 : blob.length) ?? null,
          expected: width * height
        });
      }
      log2("selectionAlphaApplied");
    } catch {
    }
    jimpImage.scan(0, 0, jimpImage.bitmap.width, jimpImage.bitmap.height, (_x, _y, idx) => {
      const alpha = jimpImage.bitmap.data[idx + 3];
      const grayValue = built.reverse ? 255 - alpha : alpha;
      jimpImage.bitmap.data[idx + 0] = grayValue;
      jimpImage.bitmap.data[idx + 1] = grayValue;
      jimpImage.bitmap.data[idx + 2] = grayValue;
      jimpImage.bitmap.data[idx + 3] = 255 - grayValue;
    });
    log2("completed");
    return {
      jimp: jimpImage
    };
  }
}
function resizeImageToMaxSize(image, maxSize) {
  if (!(maxSize && maxSize > 0)) {
    return;
  }
  const maxSide = Math.max(image.bitmap.width, image.bitmap.height);
  if (maxSide <= maxSize) {
    return;
  }
  const scale = maxSize / maxSide;
  const targetWidth = Math.max(1, Math.round(image.bitmap.width * scale));
  const targetHeight = Math.max(1, Math.round(image.bitmap.height * scale));
  image.resize({
    w: targetWidth,
    h: targetHeight
  });
}
const normalizeContentParams = (params) => ({
  contentUri: (params == null ? void 0 : params.contentUri) ?? "",
  options: params == null ? void 0 : params.options
});
const normalizeMaskParams = (params) => ({
  maskUri: (params == null ? void 0 : params.maskUri) ?? "",
  options: params == null ? void 0 : params.options
});
const normalizeCombineParams = (params) => ({
  contentUri: (params == null ? void 0 : params.contentUri) ?? "",
  boundaryUri: (params == null ? void 0 : params.boundaryUri) ?? "",
  maskUri: (params == null ? void 0 : params.maskUri) ?? void 0,
  thumbnail: (params == null ? void 0 : params.thumbnail) ?? false,
  options: params == null ? void 0 : params.options
});
const actionErrorResult = (error) => ({
  error: (error == null ? void 0 : error.message) || String(error)
});
const boundaryRectToSDPPP = (rect) => BoundaryRectUtils.toSDPPPBoundsAuto(rect);
function normalizeUri(value) {
  if (typeof value !== "string") {
    return void 0;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function decodeDataUrl(dataUrl) {
  const DATA_URL_REGEX2 = /^data:([^;,]+)?(;base64)?,(.*)$/i;
  const match = DATA_URL_REGEX2.exec(dataUrl);
  if (!match) {
    throw new Error("Invalid data URL");
  }
  const mime2 = match[1] ?? void 0;
  const isBase64 = !!match[2];
  const payload = match[3] ?? "";
  if (isBase64) {
    return { buffer: bufferExports.Buffer.from(payload, "base64"), mime: mime2 };
  }
  return { buffer: bufferExports.Buffer.from(decodeURIComponent(payload), "utf8"), mime: mime2 };
}
async function resolveBoundaryParam(boundary, layerIdentify) {
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  if (typeof boundary === "string") {
    switch (boundary) {
      case "canvas": {
        const docInfo = await getDocumentInfo({ document_identify: documentIdentify });
        return boundaryRectToSDPPP(docInfo.document_boundary);
      }
      case "curlayer": {
        const layerInfo = await getLayerInfo({
          document_identify: documentIdentify,
          layer_identify: layerIdentify ?? SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER()
        });
        return boundaryRectToSDPPP(layerInfo.boundary);
      }
      case "selection": {
        const docInfo = await getDocumentInfo({ document_identify: documentIdentify });
        const selectionRect = docInfo.selection_boundary ?? docInfo.document_boundary;
        return boundaryRectToSDPPP(selectionRect);
      }
      default:
        throw new Error(`Unsupported boundary specification: ${boundary}`);
    }
  }
  const doc = photoshop.app.activeDocument;
  if (!doc) {
    throw new Error("No active document to compute boundary rect.");
  }
  const docWidth = Number(doc.width);
  const docHeight = Number(doc.height);
  return BoundaryRectUtils.toSDPPPBounds(boundary, docWidth, docHeight);
}
function resolveLayerIdentifyForContent(content, layerIdentify) {
  if (layerIdentify && layerIdentify.length > 0) {
    return layerIdentify;
  }
  switch (content) {
    case "canvas":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    case "curlayer":
      return SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    case "selection":
    default:
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
  }
}
function resolveLayerIdentifyForMask(content, layerIdentify) {
  if (layerIdentify && layerIdentify.length > 0) {
    return layerIdentify;
  }
  switch (content) {
    case "canvas":
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    case "curlayer":
      return SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    case "selection":
    default:
      return SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
  }
}
async function persistMaterializedPayload(payload) {
  if (!(payload == null ? void 0 : payload.image)) {
    throw new Error("CBM materializer returned empty payload");
  }
  const image = payload.image;
  const width = image.bitmap.width;
  const height = image.bitmap.height;
  const mime2 = payload.mime ?? PNG_MIME$2;
  const encodeLog = createPerfTracker("fileResource.cbm.encode");
  encodeLog("start");
  const pngBuffer = await image.getBuffer(JimpMime.png);
  encodeLog("completed", { bytes: pngBuffer.length });
  const createLog = createPerfTracker("fileResource.cbm.createResource");
  createLog("start");
  const resourceId = createResource({
    type: "file",
    data: {
      buffer: new Uint8Array(pngBuffer),
      mime: mime2
    },
    originalMeta: {
      width,
      height,
      ...payload.meta ?? {}
    }
  });
  createLog("completed", { resourceId });
  return {
    resource: resourceId,
    width,
    height,
    mime: mime2
  };
}
function registerCreateByContentAction(context) {
  var _a3;
  const { mcpMesh: mcpMesh2 } = context;
  const mesh = mcpMesh2;
  const materialize = ((_a3 = context.materializers) == null ? void 0 : _a3.fromContent) ?? (async (params) => materializeContentOnly(mesh, params));
  mcpMesh2.implementAction("fileResource.createByContent", async (rawParams) => {
    const actionLog = createPerfTracker("fileResource.createByContent.action");
    try {
      actionLog("start");
      const params = normalizeContentParams(rawParams);
      const payload = await materialize(params);
      const response = await persistMaterializedPayload(payload);
      actionLog("completed", { width: response.width, height: response.height });
      if (response.resource && payload.image) {
        storeJimpForResource(response.resource, payload.image, payload.mime);
      }
      return response;
    } catch (error) {
      actionLog("failed", { message: error == null ? void 0 : error.message });
      return actionErrorResult(error);
    }
  });
}
const PNG_MIME$1 = "image/png";
const DATA_URL_REGEX$1 = /^data:([^;,]+)?(;base64)?,(.*)$/i;
async function materializeContentOnly(mesh, params) {
  const contentUri = normalizeUri(params.contentUri);
  if (!contentUri) {
    throw new Error("contentUri is required for fileResource.createByContent");
  }
  const boundaryUri = resolveCanvasBoundaryForContent(contentUri);
  const log2 = createPerfTracker("fileResource.createByContent.materialize");
  log2("boundaryResolved", { boundaryUri: boundaryUri ?? null });
  const contentSnapshot = await loadContentSnapshot(mesh, boundaryUri, contentUri, {
    maxSizeOverride: 0
  });
  log2("snapshotLoaded", {
    width: contentSnapshot.jimp.bitmap.width,
    height: contentSnapshot.jimp.bitmap.height
  });
  let snapshot = createSnapshot(contentSnapshot.jimp);
  const meta = {
    contentUri
  };
  log2("materialized", {
    width: snapshot.image.bitmap.width,
    height: snapshot.image.bitmap.height
  });
  return {
    type: "image",
    image: snapshot.image,
    mime: PNG_MIME$1,
    meta
  };
}
async function loadContentSnapshot(mesh, boundaryUri, contentUri, options2) {
  const log2 = createPerfTracker("fileResource.createByContent.loadContentSnapshot");
  log2("start", { boundaryUri, contentUri });
  const normalizedContentUri = normalizeUri(contentUri);
  if (!normalizedContentUri) {
    throw new Error("contentUri is required for snapshot loading");
  }
  if (normalizedContentUri.startsWith("uxp://file/")) {
    const cached = getJimpForResource(normalizedContentUri);
    if (cached) {
      return { jimp: cached.image };
    }
    const fetchLog = createPerfTracker("fileResource.createByContent.resolveSharedBuffer");
    const { buffer: buffer2 } = await resolveResourceBuffer(normalizedContentUri);
    const jimpImage2 = await Jimp.read(bufferExports.Buffer.from(buffer2));
    fetchLog("completed", {
      width: jimpImage2.bitmap.width,
      height: jimpImage2.bitmap.height
    });
    return { jimp: jimpImage2 };
  }
  if (DATA_URL_REGEX$1.test(normalizedContentUri)) {
    const decoded = decodeDataUrl(normalizedContentUri);
    const jimpImage2 = await Jimp.read(decoded.buffer);
    return { jimp: jimpImage2 };
  }
  if (!boundaryUri) {
    throw new Error("Unable to resolve boundary for content resource");
  }
  const built = buildGetImageParamsFromResources(boundaryUri, normalizedContentUri);
  const boundaryParam = await resolveBoundaryParam(built.boundary, built.layer_identify ?? null);
  const layerIdentify = resolveLayerIdentifyForContent(built.content, built.layer_identify ?? null);
  const effectiveImageSize = options2 == null ? void 0 : options2.maxSizeOverride;
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  const jimpImage = await getImage.getJimpImage({
    document_identify: documentIdentify,
    layer_identify: layerIdentify,
    boundary: boundaryParam,
    max_wh: effectiveImageSize,
    quality: built.imageQuality
  });
  if (built.content === "selection") {
    await applySelectionAlpha(jimpImage, boundaryParam, effectiveImageSize);
  }
  log2("completed", { width: jimpImage.bitmap.width, height: jimpImage.bitmap.height });
  return { jimp: jimpImage };
}
async function applySelectionAlpha(jimpImage, boundaryParam, effectiveImageSize) {
  try {
    const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
    const selection = await getSelection({
      document_identify: documentIdentify,
      boundary: boundaryParam,
      max_wh: effectiveImageSize
    });
    const { blob, width, height } = selection;
    if (!blob || blob.length !== width * height) {
      console.warn("[fileResource.createByContent] selection blob mismatch", {
        width,
        height,
        blobLength: (blob == null ? void 0 : blob.length) ?? null
      });
      return;
    }
    for (let i2 = 0; i2 < width * height; i2 += 1) {
      const idx = i2 * 4;
      const alpha = blob[i2];
      if (idx + 3 < jimpImage.bitmap.data.length) {
        jimpImage.bitmap.data[idx + 3] = alpha;
      }
    }
  } catch (error) {
    console.warn("[fileResource.createByContent] selection alpha failed", {
      message: error instanceof Error ? error.message : String(error)
    });
  }
}
function resolveCanvasBoundaryForContent(contentUri) {
  if (!contentUri) {
    return null;
  }
  try {
    const parsed = parseContentResource(contentUri);
    return buildBoundaryUri$1(parsed.docId, "canvas");
  } catch {
    return null;
  }
}
function registerCreateByMaskAction(context) {
  var _a3;
  const { mcpMesh: mcpMesh2 } = context;
  const mesh = mcpMesh2;
  const materialize = ((_a3 = context.materializers) == null ? void 0 : _a3.fromMask) ?? (async (params) => materializeMaskOnly(mesh, params));
  mcpMesh2.implementAction("fileResource.createByMask", async (rawParams) => {
    const actionLog = createPerfTracker("fileResource.createByMask.action");
    try {
      actionLog("start");
      const params = normalizeMaskParams(rawParams);
      const payload = await materialize(params);
      const response = await persistMaterializedPayload(payload);
      actionLog("completed", { width: response.width, height: response.height });
      if (response.resource && payload.image) {
        storeJimpForResource(response.resource, payload.image, payload.mime);
      }
      return response;
    } catch (error) {
      actionLog("failed", { message: error == null ? void 0 : error.message });
      return actionErrorResult(error);
    }
  });
}
const PNG_MIME = "image/png";
const DATA_URL_REGEX = /^data:([^;,]+)?(;base64)?,(.*)$/i;
async function materializeMaskOnly(mesh, params) {
  const maskUri = normalizeUri(params.maskUri);
  if (!maskUri) {
    throw new Error("maskUri is required for fileResource.createByMask");
  }
  const boundaryUri = resolveCanvasBoundaryForMask(maskUri);
  const log2 = createPerfTracker("fileResource.createByMask.materialize");
  log2("boundaryResolved", { boundaryUri: boundaryUri ?? null });
  const maskSnapshot = await loadMaskSnapshot(mesh, boundaryUri, maskUri, {
    maxSizeOverride: 0
  });
  if (!maskSnapshot) {
    throw new Error("Unable to resolve mask snapshot");
  }
  log2("maskReady", {
    width: maskSnapshot.jimp.bitmap.width,
    height: maskSnapshot.jimp.bitmap.height
  });
  return {
    type: "mask",
    image: maskSnapshot.jimp,
    mime: PNG_MIME,
    meta: {
      sourceMaskUri: maskUri,
      maskReverse: maskSnapshot.reverse
    }
  };
}
async function loadMaskSnapshot(mesh, boundaryUri, maskUri, options2) {
  const log2 = createPerfTracker("fileResource.createByMask.loadMaskSnapshot");
  log2("start", { boundaryUri, maskUri });
  const normalizedMaskUri = normalizeUri(maskUri);
  if (!normalizedMaskUri) {
    log2("noMaskUri");
    return null;
  }
  if (normalizedMaskUri.startsWith("uxp://mask/")) {
    const parsedMask = parseMaskResource(normalizedMaskUri);
    const selectionEmpty = parsedMask.content === "selection" ? await isPhotoshopSelectionEmpty() : false;
    const fetchLog = createPerfTracker("fileResource.createByMask.getMaskSnapshot");
    const layerSnapshot = await loadMaskSnapshotJimp(mesh, boundaryUri, normalizedMaskUri, options2);
    fetchLog("completed", {
      width: layerSnapshot.jimp.bitmap.width,
      height: layerSnapshot.jimp.bitmap.height
    });
    if (selectionEmpty) {
      const fallback = await createSolidMask(
        layerSnapshot.jimp.bitmap.width,
        layerSnapshot.jimp.bitmap.height
      );
      log2("selectionEmptyFallback", {
        width: fallback.bitmap.width,
        height: fallback.bitmap.height,
        maskContent: parsedMask.content
      });
      return { jimp: fallback };
    }
    log2("maskSnapshotReady", {
      width: layerSnapshot.jimp.bitmap.width,
      height: layerSnapshot.jimp.bitmap.height
    });
    return { jimp: layerSnapshot.jimp };
  }
  if (normalizedMaskUri.startsWith("uxp://file/")) {
    const normalized = normalizeFileResourceUri(normalizedMaskUri);
    const cached = getJimpForResource(normalized.resourceId);
    if (cached) {
      return {
        jimp: cached.image,
        reverse: normalized.reverse
      };
    }
    const { buffer: buffer2 } = await resolveResourceBuffer(normalized.resourceId);
    const jimpImage = await Jimp.read(bufferExports.Buffer.from(buffer2));
    if (normalized.reverse !== void 0) {
      log2("maskFileReverseDetected", { reverse: normalized.reverse });
    }
    return {
      jimp: jimpImage,
      reverse: normalized.reverse
    };
  }
  if (DATA_URL_REGEX.test(normalizedMaskUri)) {
    const decoded = decodeDataUrl(normalizedMaskUri);
    const jimpImage = await Jimp.read(decoded.buffer);
    return { jimp: jimpImage };
  }
  log2("unsupportedMaskUri", { maskUri: normalizedMaskUri });
  return null;
}
async function loadMaskSnapshotJimp(mesh, boundaryUri, maskUri, options2) {
  const log2 = createPerfTracker("fileResource.createByMask.loadMaskSnapshotJimp");
  const effectiveBoundaryUri = boundaryUri ?? resolveCanvasBoundaryForMask(maskUri);
  if (!effectiveBoundaryUri) {
    throw new Error("Unable to resolve boundary for mask resource");
  }
  const built = buildGetMaskParamsFromResources(effectiveBoundaryUri, maskUri);
  const boundaryParam = await resolveBoundaryParam(built.boundary, built.layer_identify ?? null);
  const layerIdentify = resolveLayerIdentifyForMask(built.content, built.layer_identify ?? null);
  const effectiveImageSize = options2 == null ? void 0 : options2.maxSizeOverride;
  const documentIdentify = SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT();
  const jimpImage = await getImage.getJimpImage({
    document_identify: documentIdentify,
    layer_identify: layerIdentify,
    boundary: boundaryParam,
    max_wh: effectiveImageSize
  });
  if (built.content === "selection") {
    try {
      const selection = await getSelection({
        document_identify: documentIdentify,
        boundary: boundaryParam,
        max_wh: effectiveImageSize
      });
      const { blob, width, height } = selection;
      if (blob && blob.length === width * height) {
        for (let i2 = 0; i2 < width * height; i2 += 1) {
          const idx = i2 * 4;
          const alpha = blob[i2];
          if (idx + 3 < jimpImage.bitmap.data.length) {
            jimpImage.bitmap.data[idx + 3] = alpha;
          }
        }
      }
    } catch (error) {
      console.warn("[fileResource.createByMask] selection alpha failed", {
        message: error instanceof Error ? error.message : String(error)
      });
    }
    jimpImage.scan(0, 0, jimpImage.bitmap.width, jimpImage.bitmap.height, (_x, _y, idx) => {
      const alpha = jimpImage.bitmap.data[idx + 3];
      const grayValue = built.reverse ? 255 - alpha : alpha;
      jimpImage.bitmap.data[idx + 0] = grayValue;
      jimpImage.bitmap.data[idx + 1] = grayValue;
      jimpImage.bitmap.data[idx + 2] = grayValue;
      jimpImage.bitmap.data[idx + 3] = 255 - grayValue;
    });
  }
  log2("completed", { width: jimpImage.bitmap.width, height: jimpImage.bitmap.height });
  return { jimp: jimpImage };
}
function resolveCanvasBoundaryForMask(maskUri) {
  if (!maskUri) {
    return null;
  }
  try {
    const parsed = parseMaskResource(maskUri);
    return buildBoundaryUri$1(parsed.docId, "canvas");
  } catch {
    return null;
  }
}
function normalizeFileResourceUri(uri2) {
  try {
    const parsed = new URL(uri2);
    const reverseParam = parsed.searchParams.get("reverse");
    const reverse = reverseParam === "1" || (reverseParam == null ? void 0 : reverseParam.trim().toLowerCase()) === "true" ? true : reverseParam === "0" ? false : void 0;
    parsed.search = "";
    parsed.hash = "";
    return {
      resourceId: `${parsed.protocol}//${parsed.host}${parsed.pathname}`,
      reverse
    };
  } catch {
    return { resourceId: uri2 };
  }
}
async function isPhotoshopSelectionEmpty() {
  try {
    const doc = photoshop.app.activeDocument;
    if (!doc) return true;
    const selection = doc.selection;
    if (!selection) return true;
    const bounds = selection.bounds;
    if (!bounds) {
      return true;
    }
    return false;
  } catch {
    return true;
  }
}
async function createSolidMask(width, height) {
  const safeWidth = Math.max(1, width);
  const safeHeight = Math.max(1, height);
  return new Jimp({ width: safeWidth, height: safeHeight, color: 0 });
}
function registerCombineByCbmAction(context) {
  var _a3;
  const { mcpMesh: mcpMesh2 } = context;
  const mesh = mcpMesh2;
  const materialize = ((_a3 = context.materializers) == null ? void 0 : _a3.combineCBM) ?? (async (params) => materializeCombineByCbm(mesh, params));
  mcpMesh2.implementAction("fileResource.combineByCBM", async (rawParams) => {
    const actionLog = createPerfTracker("fileResource.combineByCBM.action");
    try {
      actionLog("start");
      const params = normalizeCombineParams(rawParams);
      const payload = await materialize(params);
      const response = await persistMaterializedPayload(payload);
      actionLog("completed", {
        boundaryUri: params.boundaryUri ?? null,
        contentUri: params.contentUri ?? null,
        maskUri: params.maskUri ?? null,
        resource: response.resource ?? null
      });
      return response;
    } catch (error) {
      actionLog("failed", { message: error == null ? void 0 : error.message });
      return actionErrorResult(error);
    }
  });
}
async function materializeCombineByCbm(mesh, params) {
  var _a3;
  const perfLog = createPerfTracker("fileResource.combineByCBM.action");
  perfLog("materialize.start", {
    boundaryUri: params.boundaryUri ?? null,
    contentUri: params.contentUri ?? null,
    maskUri: params.maskUri ?? null
  });
  console.log("[combineByCBM][调试] 接收到参数", {
    boundaryUri: params.boundaryUri ?? null,
    contentUri: params.contentUri ?? null,
    maskUri: params.maskUri ?? null,
    thumbnail: params.thumbnail ?? false
  });
  const contentUri = normalizeUri$1(params.contentUri);
  const maskUri = normalizeUri$1(params.maskUri);
  if (params.maskUri && !maskUri) {
    console.warn("[combineByCBM] mask skipped: invalid maskUri after normalization", {
      boundaryUri: params.boundaryUri ?? null,
      rawMaskUri: params.maskUri
    });
  }
  if (!contentUri) {
    throw new Error("contentUri is required");
  }
  const boundaryUri = await resolveEffectiveBoundaryUri(params);
  const boundarySampling = createBoundarySamplingMetadata(boundaryUri);
  const boundaryDetails = boundarySampling.parsed;
  const maskIsCanvas = maskUri ? isCanvasMaskUri(maskUri) : false;
  const maskIsFileResource = Boolean(maskUri && maskUri.startsWith("uxp://file/"));
  const contentIsFileResource = Boolean(contentUri && contentUri.startsWith("uxp://file/"));
  const contentParams = contentIsFileResource ? {
    boundary: boundaryDetails.boundary,
    content: "canvas",
    imageSize: boundaryDetails.imageSize ?? 0,
    imageQuality: boundaryDetails.imageQuality ?? 1,
    layer_identify: null
  } : buildGetImageParamsFromResources(boundaryUri, contentUri);
  perfLog("materialize.content.load.start", { contentIsFileResource });
  const contentSnapshot = await loadContentSnapshotJimp(mesh, boundaryUri, contentUri, {
    prebuiltParams: contentParams
  });
  perfLog("materialize.content.load.completed", {
    width: contentSnapshot.jimp.bitmap.width,
    height: contentSnapshot.jimp.bitmap.height
  });
  let contentImage = contentSnapshot.jimp;
  if (contentIsFileResource) {
    perfLog("materialize.content.sample.start");
    contentImage = sampleFilehostImageForBoundary(contentImage, boundaryUri, boundarySampling, contentUri);
    perfLog("materialize.content.sample.completed", {
      width: contentImage.bitmap.width,
      height: contentImage.bitmap.height
    });
  }
  let snapshot = createSnapshot(contentImage);
  const meta = {
    boundaryUri,
    contentUri
  };
  console.log("[combineByCBM][调试] 内容图像已就绪", {
    width: contentImage.bitmap.width,
    height: contentImage.bitmap.height,
    contentIsFileResource
  });
  if (maskUri && !maskIsCanvas) {
    perfLog("materialize.mask.load.start", { maskIsFileResource });
    const maskSnapshot = await loadMaskSnapshotForMaterializer(mesh, boundaryUri, maskUri);
    if (!maskSnapshot) {
      throw new Error("Unable to resolve mask snapshot");
    }
    perfLog("materialize.mask.load.completed", {
      width: maskSnapshot.jimp.bitmap.width,
      height: maskSnapshot.jimp.bitmap.height
    });
    let maskImage = maskSnapshot.jimp;
    if (maskIsFileResource) {
      perfLog("materialize.mask.sample.start");
      maskImage = sampleFilehostImageForBoundary(maskImage, boundaryUri, boundarySampling, maskUri);
      perfLog("materialize.mask.sample.completed", {
        width: maskImage.bitmap.width,
        height: maskImage.bitmap.height
      });
    }
    console.log("[combineByCBM][调试] 遮罩图像已就绪", {
      width: maskImage.bitmap.width,
      height: maskImage.bitmap.height,
      maskIsFileResource,
      reverse: maskSnapshot.reverse ?? null
    });
    const normalizedMaskSnapshot = {
      ...createSnapshot(maskImage),
      maskRegion: null
    };
    const invertSettingEnabled = Number(sdpppX["settings.imaging.applyMaskInvert"]) === 1;
    const reverseFlag = maskSnapshot.reverse === true;
    const invertMask = Boolean(invertSettingEnabled) !== reverseFlag;
    const applicationResult = await applyMaskToSnapshot(snapshot, {
      maskSnapshot: normalizedMaskSnapshot,
      invertMask
    });
    snapshot = applicationResult.snapshot;
    const maskStats = applicationResult.stats ?? null;
    console.log("[combineByCBM][调试] 遮罩已应用", {
      invertMask,
      maskedPixels: (maskStats == null ? void 0 : maskStats.maskedPixels) ?? null,
      totalPixels: (maskStats == null ? void 0 : maskStats.totalPixels) ?? null,
      coverage: maskStats ? Number((maskStats.maskedPixels / Math.max(1, maskStats.totalPixels) * 100).toFixed(2)) : null,
      maskAlphaZeroPixels: (maskStats == null ? void 0 : maskStats.maskAlphaZeroPixels) ?? null,
      maskAlphaNonZeroPixels: (maskStats == null ? void 0 : maskStats.maskAlphaNonZeroPixels) ?? null,
      invertMaskApplied: (maskStats == null ? void 0 : maskStats.invertMaskApplied) ?? null,
      alphaRemovalAverage: (maskStats == null ? void 0 : maskStats.alphaRemovalAverage) ?? null,
      alphaRemovalAverageNormalized: (maskStats == null ? void 0 : maskStats.alphaRemovalAverageNormalized) ?? null,
      alphaRemovalMax: (maskStats == null ? void 0 : maskStats.alphaRemovalMax) ?? null,
      stronglyMaskedPixels: (maskStats == null ? void 0 : maskStats.stronglyMaskedPixels) ?? null
    });
    meta.maskApplied = maskUri;
    meta.maskStats = applicationResult.stats;
    perfLog("materialize.mask.apply.completed", {
      maskedPixels: ((_a3 = applicationResult.stats) == null ? void 0 : _a3.maskedPixels) ?? null
    });
    if (maskSnapshot.reverse !== void 0) {
      meta.maskReverse = maskSnapshot.reverse;
    }
  } else if (maskUri && maskIsCanvas) {
    console.warn("[combineByCBM] mask skipped: canvas maskUri detected", {
      boundaryUri,
      maskUri
    });
    perfLog("materialize.mask.skip.canvas");
  }
  perfLog("materialize.completed", {
    outputWidth: snapshot.image.bitmap.width,
    outputHeight: snapshot.image.bitmap.height
  });
  console.log("[combineByCBM][调试] 合成完成", {
    outputWidth: snapshot.image.bitmap.width,
    outputHeight: snapshot.image.bitmap.height,
    hasMaskApplied: Boolean(meta.maskApplied)
  });
  return {
    type: "image",
    image: snapshot.image,
    mime: PNG_MIME$2,
    meta
  };
}
const FILEHOST_BOUNDARY_CACHE_TTL_MS = 5e3;
const filehostBoundarySampleCache = /* @__PURE__ */ new Map();
function createBoundarySamplingMetadata(boundaryUri) {
  const parsed = parseBoundaryResource(boundaryUri);
  if (typeof parsed.boundary !== "string" && parsed.boundary) {
    const normalizedRect = normalizeBoundaryRect(parsed.boundary);
    const docWidth = Math.max(
      1,
      Math.round(normalizedRect.leftDistance + normalizedRect.width + normalizedRect.rightDistance)
    );
    const docHeight = Math.max(
      1,
      Math.round(normalizedRect.topDistance + normalizedRect.height + normalizedRect.bottomDistance)
    );
    const projected = projectBoundaryRectFromResource(boundaryUri) ?? {
      docWidth,
      docHeight,
      cropRect: ensurePositiveRect({
        x: Math.round(normalizedRect.leftDistance),
        y: Math.round(normalizedRect.topDistance),
        width: Math.max(1, Math.round(normalizedRect.width)),
        height: Math.max(1, Math.round(normalizedRect.height))
      })
    };
    return {
      parsed,
      rectSpec: {
        sourceRect: normalizedRect,
        docWidth,
        docHeight,
        targetDocWidth: projected.docWidth,
        targetDocHeight: projected.docHeight,
        targetCropRect: projected.cropRect
      }
    };
  }
  return { parsed };
}
function normalizeBoundaryRect(rect) {
  return {
    leftDistance: Math.max(0, Math.round(rect.leftDistance)),
    topDistance: Math.max(0, Math.round(rect.topDistance)),
    rightDistance: Math.max(0, Math.round(rect.rightDistance)),
    bottomDistance: Math.max(0, Math.round(rect.bottomDistance)),
    width: Math.max(1, Math.round(rect.width)),
    height: Math.max(1, Math.round(rect.height))
  };
}
function sampleFilehostImageForBoundary(image, boundaryUri, sampling, resourceUri) {
  const perfLog = createPerfTracker("fileResource.combineByCBM.action");
  perfLog("sample.start", {
    boundaryUri,
    resourceUri,
    hasRectSpec: Boolean(sampling.rectSpec)
  });
  pruneExpiredBoundarySamples();
  const cacheKey = createFilehostBoundaryCacheKey(resourceUri, boundaryUri, image);
  if (cacheKey) {
    const cached = takeCachedBoundarySample(cacheKey);
    if (cached) {
      perfLog("sample.cacheHit", { width: cached.bitmap.width, height: cached.bitmap.height });
      return cached;
    }
  }
  let result;
  if (sampling.rectSpec) {
    perfLog("sample.rect.start");
    const { sourceRect, targetCropRect, docWidth, docHeight } = sampling.rectSpec;
    if (image.bitmap.width !== docWidth || image.bitmap.height !== docHeight) {
      console.warn("[combineByCBM] filehost dimensions differ from boundary projection", {
        boundaryUri,
        resourceUri,
        expectedWidth: docWidth,
        expectedHeight: docHeight,
        actualWidth: image.bitmap.width,
        actualHeight: image.bitmap.height
      });
    }
    result = image.clone();
    const cropX = Math.max(0, Math.round(sourceRect.leftDistance));
    const cropY = Math.max(0, Math.round(sourceRect.topDistance));
    const cropWidth = Math.max(1, Math.round(sourceRect.width));
    const cropHeight = Math.max(1, Math.round(sourceRect.height));
    result.crop({
      x: cropX,
      y: cropY,
      w: cropWidth,
      h: cropHeight
    });
    const targetWidth = Math.max(1, Math.round(targetCropRect.width));
    const targetHeight = Math.max(1, Math.round(targetCropRect.height));
    if (result.bitmap.width !== targetWidth || result.bitmap.height !== targetHeight) {
      result.resize({ w: targetWidth, h: targetHeight });
    }
    perfLog("sample.rect.completed", {
      width: result.bitmap.width,
      height: result.bitmap.height
    });
  } else {
    perfLog("sample.scale.start");
    result = rescaleImageToBoundaryMaxSize(image, sampling.parsed.imageSize);
    perfLog("sample.scale.completed", {
      width: result.bitmap.width,
      height: result.bitmap.height
    });
  }
  if (cacheKey) {
    cacheBoundarySample(cacheKey, result);
  }
  perfLog("sample.completed", {
    width: result.bitmap.width,
    height: result.bitmap.height
  });
  return result;
}
function rescaleImageToBoundaryMaxSize(image, imageSize) {
  if (!(imageSize && imageSize > 0)) {
    return image.clone();
  }
  const maxSide = Math.max(image.bitmap.width, image.bitmap.height);
  if (maxSide <= imageSize) {
    return image.clone();
  }
  const scale = imageSize / maxSide;
  const targetWidth = Math.max(1, Math.round(image.bitmap.width * scale));
  const targetHeight = Math.max(1, Math.round(image.bitmap.height * scale));
  const resized = image.clone();
  resized.resize({ w: targetWidth, h: targetHeight });
  return resized;
}
function createFilehostBoundaryCacheKey(resourceUri, boundaryUri, image) {
  try {
    const parsed = new URL(resourceUri);
    parsed.search = "";
    parsed.hash = "";
    return `${parsed.protocol}//${parsed.host}${parsed.pathname}::${boundaryUri}::${image.bitmap.width}x${image.bitmap.height}`;
  } catch {
    return null;
  }
}
function takeCachedBoundarySample(key2) {
  const entry = filehostBoundarySampleCache.get(key2);
  if (!entry) {
    return null;
  }
  if (entry.expiresAt <= Date.now()) {
    filehostBoundarySampleCache.delete(key2);
    return null;
  }
  return entry.image.clone();
}
function cacheBoundarySample(key2, image) {
  filehostBoundarySampleCache.set(key2, {
    expiresAt: Date.now() + FILEHOST_BOUNDARY_CACHE_TTL_MS,
    image: image.clone()
  });
}
function pruneExpiredBoundarySamples() {
  const now = Date.now();
  for (const [key2, entry] of filehostBoundarySampleCache.entries()) {
    if (entry.expiresAt <= now) {
      filehostBoundarySampleCache.delete(key2);
    }
  }
}
function registerBoundaryNormalizeAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("boundary.normalize", async (params) => {
    try {
      if (!(params == null ? void 0 : params.boundary)) {
        throw new Error("boundary parameter is required");
      }
      const rectUri = await resolveBoundaryToRect(params.boundary);
      return { boundary: rectUri };
    } catch (error) {
      return { error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error) };
    }
  });
}
async function resolveBoundaryToRect(boundaryUri) {
  const parsed = parseBoundaryResource(boundaryUri);
  const { docId, boundary, imageSize, imageQuality } = parsed;
  if (typeof boundary === "object") {
    return buildBoundaryUri$1(docId, boundary, { imageSize, imageQuality });
  }
  if (!photoshop.app.activeDocument) {
    throw new Error("No active document to resolve boundary.");
  }
  let resolved = boundary;
  switch (boundary) {
    case "canvas": {
      const doc = photoshop.app.activeDocument;
      const width = Number(doc.width);
      const height = Number(doc.height);
      resolved = BoundaryRectUtils.fromPositionAndSize(0, 0, width, height, width, height);
      break;
    }
    case "curlayer": {
      const { boundary: computed } = await getBoundaryImpl({ type: "curlayer" });
      resolved = computed;
      break;
    }
    case "selection": {
      const { boundary: computed } = await getBoundaryImpl({ type: "selection" });
      resolved = computed;
      break;
    }
    default: {
      throw new Error(`Unsupported boundary type "${boundary}"`);
    }
  }
  return buildBoundaryUri$1(docId, resolved, { imageSize, imageQuality });
}
function registerLayerResolveAction(context) {
  const { mcpMesh: mcpMesh2 } = context;
  mcpMesh2.implementAction("layer.resolve", async (params) => {
    try {
      if (!(params == null ? void 0 : params.uri)) {
        throw new Error("uri parameter is required");
      }
      if (!(params == null ? void 0 : params.type)) {
        throw new Error("type parameter is required");
      }
      if (params.type === "content") {
        const resolved = await resolveContentToLayer(params.uri);
        return { uri: resolved };
      }
      if (params.type === "mask") {
        const resolved = await resolveMaskToLayer(params.uri);
        return { uri: resolved };
      }
      throw new Error(`Unsupported type: ${params.type}`);
    } catch (error) {
      return { error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error) };
    }
  });
}
async function resolveContentToLayer(contentUri) {
  const parsed = parseContentResource(contentUri);
  const { docId, content, layerIdentify } = parsed;
  if (content !== "curlayer") {
    return buildContentUri$1(docId, content, layerIdentify);
  }
  if (layerIdentify && layerIdentify.length > 0) {
    return buildContentUri$1(docId, content, layerIdentify);
  }
  const { layer_identify } = await getCurrentLayerIdentify();
  if (!layer_identify) {
    throw new Error("No active layer available to resolve content.");
  }
  return buildContentUri$1(docId, content, layer_identify);
}
async function resolveMaskToLayer(maskUri) {
  const parsed = parseMaskResource(maskUri);
  const { docId, content, reverse, layerIdentify } = parsed;
  if (content !== "curlayer") {
    return buildMaskContentUri(docId, content, void 0, reverse);
  }
  const existing = layerIdentify && layerIdentify.length > 0 ? layerIdentify : (await getCurrentLayerIdentify()).layer_identify;
  if (!existing) {
    throw new Error("No active layer available to resolve mask.");
  }
  return buildMaskContentUri(docId, content, existing, reverse);
}
const EPSILON = 1e-3;
let initialized = false;
const toPixels = (value) => {
  if (value == null) return null;
  if (typeof value === "number") {
    return Number.isFinite(value) ? value : null;
  }
  if (typeof value === "object") {
    try {
      if (typeof value.as === "function") {
        const px = value.as("px");
        if (Number.isFinite(px)) {
          return px;
        }
      }
    } catch {
    }
    if ("value" in value) {
      const raw = Number(value.value);
      if (Number.isFinite(raw)) {
        return raw;
      }
    }
  }
  const coerced = Number(value);
  return Number.isFinite(coerced) ? coerced : null;
};
const boundariesEqual = (a2, b2) => {
  if (!a2 && !b2) return true;
  if (!a2 || !b2) return false;
  return Math.abs(a2.leftDistance - b2.leftDistance) < EPSILON && Math.abs(a2.topDistance - b2.topDistance) < EPSILON && Math.abs(a2.rightDistance - b2.rightDistance) < EPSILON && Math.abs(a2.bottomDistance - b2.bottomDistance) < EPSILON && Math.abs(a2.width - b2.width) < EPSILON && Math.abs(a2.height - b2.height) < EPSILON;
};
const computeSelectionBoundary = () => {
  try {
    const doc = photoshop.app.activeDocument;
    if (!doc) {
      return null;
    }
    const docWidth = toPixels(doc.width);
    const docHeight = toPixels(doc.height);
    if (docWidth == null || docHeight == null || docWidth <= 0 || docHeight <= 0) {
      return null;
    }
    const selection = doc.selection;
    if (!selection) {
      return null;
    }
    let bounds;
    try {
      bounds = selection.bounds;
    } catch {
      return null;
    }
    if (!bounds) {
      return null;
    }
    const left = toPixels(bounds.left ?? bounds[0]);
    const top = toPixels(bounds.top ?? bounds[1]);
    const right = toPixels(bounds.right ?? bounds[2]);
    const bottom = toPixels(bounds.bottom ?? bounds[3]);
    if (left == null || top == null || right == null || bottom == null || right <= left || bottom <= top) {
      return null;
    }
    const rect = BoundaryRectUtils.fromPhotoshopBounds(
      { left, top, right, bottom },
      docWidth,
      docHeight
    );
    return BoundaryRectUtils.isValid(rect) ? rect : null;
  } catch {
    return null;
  }
};
function registerSelectionBoundaryMaintenance(context) {
  if (initialized) return;
  initialized = true;
  const mesh = context.mcpMesh;
  const store = mesh == null ? void 0 : mesh.store;
  if (!store || typeof store.getState !== "function" || typeof store.setState !== "function") {
    console.warn("[resourcing] selection boundary maintenance skipped: mesh store missing");
    return;
  }
  const updateSelectionBoundary = () => {
    var _a3;
    const nextBoundary = computeSelectionBoundary();
    const currentState = (_a3 = store.getState) == null ? void 0 : _a3.call(store);
    const prevBoundary = (currentState == null ? void 0 : currentState.selectionBoundary) ?? null;
    if (boundariesEqual(prevBoundary, nextBoundary)) {
      return;
    }
    store.setState({
      selectionBoundary: nextBoundary ?? null
    });
  };
  updateSelectionBoundary();
  if (typeof store.subscribe === "function") {
    store.subscribe((state, prev) => {
      if ((state == null ? void 0 : state.selectionStateID) !== (prev == null ? void 0 : prev.selectionStateID) || (state == null ? void 0 : state.activeDocumentID) !== (prev == null ? void 0 : prev.activeDocumentID)) {
        updateSelectionBoundary();
      }
    });
  }
}
function registerImagingActions(context) {
  registerCreateFromExternalAction(context);
  registerCreateFromLocalAction(context);
  registerCreateFromBufferAction(context);
  registerCreateByContentAction(context);
  registerCreateByMaskAction(context);
  registerCombineByCbmAction(context);
  registerDeleteDownloadedImageAction(context);
  registerThumbnailAction(context);
  registerSaveAsAction(context);
  registerBoundaryNormalizeAction(context);
  registerLayerResolveAction(context);
  registerSelectionBoundaryMaintenance(context);
}
registerImagingActions({ mcpMesh });
class TaskEventEmitter {
  constructor() {
    __publicField2(this, "taskListeners", []);
    __publicField2(this, "executionListeners", []);
  }
  // 订阅任务事件
  onTaskEvent(listener) {
    this.taskListeners.push(listener);
    return () => {
      const index2 = this.taskListeners.indexOf(listener);
      if (index2 > -1) {
        this.taskListeners.splice(index2, 1);
      }
    };
  }
  // 订阅任务执行事件
  onTaskExecution(listener) {
    this.executionListeners.push(listener);
    return () => {
      const index2 = this.executionListeners.indexOf(listener);
      if (index2 > -1) {
        this.executionListeners.splice(index2, 1);
      }
    };
  }
  // 发射任务事件
  async emitTaskEvent(event) {
    const fullEvent = {
      ...event,
      timestamp: Date.now()
    };
    const promises = this.taskListeners.map(
      (listener) => Promise.resolve(listener(fullEvent)).catch(
        (error) => console.error("Task event listener error:", error)
      )
    );
    await Promise.allSettled(promises);
  }
  // 发射任务执行事件
  async emitTaskExecution(event) {
    const fullEvent = {
      ...event,
      timestamp: Date.now()
    };
    const promises = this.executionListeners.map(
      (listener) => Promise.resolve(listener(fullEvent)).catch(
        (error) => console.error("Task execution event listener error:", error)
      )
    );
    await Promise.allSettled(promises);
  }
  // 便捷方法：发射任务执行事件
  async emitTaskExecutionEvent(taskId, action, metadata) {
    await this.emitTaskExecution({
      type: "task:execution",
      taskId,
      action,
      metadata
    });
  }
}
const taskEventEmitter = new TaskEventEmitter();
const emitTaskEvent = taskEventEmitter.emitTaskEvent.bind(taskEventEmitter);
const emitTaskExecutionEvent = taskEventEmitter.emitTaskExecutionEvent.bind(taskEventEmitter);
mcpMesh.implementAction("taskAdd", async (params) => {
  try {
    taskHelpers.addTask(params);
    mcpMesh.store.setState({ taskLastRun: Date.now() });
    await emitTaskEvent({
      type: "task:added",
      taskId: params.taskId,
      task: params
    });
    if (params.status === "running") {
      await emitTaskExecutionEvent(params.taskId, "start", params.metadata);
    }
    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
});
mcpMesh.implementAction("taskUpdate", async (params) => {
  try {
    const existingTask = taskHelpers.getTask(params.taskId);
    if (!existingTask) {
      return {
        success: false,
        error: `Task with ID ${params.taskId} not found`
      };
    }
    taskHelpers.updateTask(params.taskId, params);
    const updatedTask = taskHelpers.getTask(params.taskId);
    if (params.status === "running") {
      mcpMesh.store.setState({ taskLastRun: Date.now() });
    }
    await emitTaskEvent({
      type: "task:updated",
      taskId: params.taskId,
      task: updatedTask,
      previousTask: existingTask
    });
    if (params.status && params.status !== existingTask.status) {
      let action;
      let eventType = "task:updated";
      switch (params.status) {
        case "running":
          action = "start";
          eventType = "task:started";
          break;
        case "completed":
          action = "complete";
          eventType = "task:completed";
          break;
        case "failed":
          action = "fail";
          eventType = "task:failed";
          break;
        case "cancelled":
          action = "cancel";
          break;
        default:
          action = "start";
      }
      if (eventType !== "task:updated") {
        await emitTaskEvent({
          type: eventType,
          taskId: params.taskId,
          task: updatedTask,
          previousTask: existingTask
        });
      }
      await emitTaskExecutionEvent(params.taskId, action, updatedTask == null ? void 0 : updatedTask.metadata);
    }
    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
});
mcpMesh.implementAction("taskRemove", async (params) => {
  try {
    const existingTask = taskHelpers.getTask(params.taskId);
    const deleted = taskHelpers.removeTask(params.taskId);
    if (!deleted) {
      return {
        success: false,
        error: `Task with ID ${params.taskId} not found`
      };
    }
    await emitTaskEvent({
      type: "task:removed",
      taskId: params.taskId,
      previousTask: existingTask
    });
    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error.message
    };
  }
});
const BOUNDARY_SCHEME = "uxp://boundary";
const CONTENT_SCHEME = "uxp://content";
const normalizeDocId = (docId) => {
  const numeric = Number(docId);
  if (!Number.isFinite(numeric)) {
    return 0;
  }
  const normalized = Math.floor(numeric);
  return normalized < 0 ? 0 : normalized;
};
const getActiveDocumentId = () => {
  var _a3, _b2, _c2;
  try {
    const storeId = (_b2 = (_a3 = sdpppSDK == null ? void 0 : sdpppSDK.stores) == null ? void 0 : _a3.PhotoshopStore) == null ? void 0 : _b2.getState().activeDocumentID;
    if (typeof storeId === "number" && Number.isFinite(storeId)) {
      return normalizeDocId(storeId);
    }
  } catch {
  }
  const doc = (_c2 = photoshop.app) == null ? void 0 : _c2.activeDocument;
  if (doc && doc.id !== void 0) {
    const parsed = normalizeDocId(doc.id);
    if (parsed >= 0) {
      return parsed;
    }
  }
  return 0;
};
const appendQuery = (base2, params) => {
  const searchParams = new URLSearchParams();
  Object.entries(params).forEach(([key2, value]) => {
    if (value === void 0 || value === null || value === "") {
      return;
    }
    searchParams.set(key2, String(value));
  });
  const query = searchParams.toString();
  return query ? `${base2}?${query}` : base2;
};
const extractLayerMetadata = (identify) => {
  const trimmed = typeof identify === "string" ? identify.trim() : "";
  if (!trimmed) {
    return {};
  }
  const explicitMatch = /(.*)\(id:(\d+)\)\s*$/.exec(trimmed);
  if (explicitMatch) {
    const baseName = explicitMatch[1].trim().replace(/^-+/, "").trim();
    return {
      layerId: explicitMatch[2],
      layerName: baseName.length ? baseName : trimmed
    };
  }
  if (/^\d+$/.test(trimmed)) {
    return { layerId: trimmed, layerName: trimmed };
  }
  const inferredName = trimmed.replace(/^-+/, "").trim();
  return {
    layerName: inferredName.length ? inferredName : trimmed
  };
};
const buildBoundaryUri = (docId, boundary) => {
  const docSegment = normalizeDocId(docId);
  if (typeof boundary === "string") {
    const boundaryKey = boundary;
    return `${BOUNDARY_SCHEME}/${docSegment}/${boundaryKey}`;
  }
  const rect = boundary;
  return appendQuery(`${BOUNDARY_SCHEME}/${docSegment}/rect`, {
    leftDistance: rect.leftDistance,
    topDistance: rect.topDistance,
    rightDistance: rect.rightDistance,
    bottomDistance: rect.bottomDistance,
    width: rect.width,
    height: rect.height
  });
};
const buildContentUri = (docId, content, layerIdentify) => {
  const docSegment = normalizeDocId(docId);
  if (content === "curlayer") {
    if (layerIdentify && layerIdentify !== "") {
      const { layerId, layerName } = extractLayerMetadata(layerIdentify);
      const fallbackId = layerIdentify.trim();
      return appendQuery(`${CONTENT_SCHEME}/${docSegment}/layer`, {
        layerid: layerId ?? fallbackId,
        layername: layerName ?? void 0
      });
    }
    return `${CONTENT_SCHEME}/${docSegment}/curlayer`;
  }
  return `${CONTENT_SCHEME}/${docSegment}/${content}`;
};
({
  title: t("image.send.select_position"),
  optionRows: [
    [
      {
        id: "newlayer",
        text: t("image.layer.new"),
        keyboardShortcut: "Q",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "smartobject",
        text: t("image.layer.smart_object"),
        keyboardShortcut: "W",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "curlayer",
        text: t("image.layer.current"),
        keyboardShortcut: "E",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "curlayer" }
      },
      {
        id: "newdoc",
        text: t("image.document.new"),
        keyboardShortcut: "R",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      }
    ]
  ]
});
({
  title: t("image.get.canvas"),
  optionRows: [
    [
      {
        id: "canvas_crop_none",
        text: t("image.crop.none"),
        keyboardShortcut: "Q",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "canvas_crop_negative",
        text: t("image.crop.inpaint"),
        keyboardShortcut: "W",
        visibility: { requiresSelection: true },
        thumbnailConfig: { content: "canvas", boundary: "selection" }
      },
      {
        id: "canvas_crop_positive",
        text: t("image.crop.outpaint"),
        keyboardShortcut: "E",
        visibility: { requiresSelection: true },
        thumbnailConfig: { content: "canvas", boundary: "selection" }
      }
    ]
  ]
});
({
  title: t("image.get.current_layer"),
  optionRows: [
    [
      {
        id: "curlayer_crop_none",
        text: t("image.crop.none"),
        keyboardShortcut: "A",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "curlayer" }
      },
      {
        id: "curlayer_crop_negative",
        text: t("image.crop.inpaint"),
        keyboardShortcut: "S",
        visibility: { requiresActiveLayers: true, requiresSelection: true },
        thumbnailConfig: { content: "curlayer", boundary: "selection" }
      },
      {
        id: "curlayer_crop_positive",
        text: t("image.crop.outpaint"),
        keyboardShortcut: "D",
        visibility: { requiresActiveLayers: true, requiresSelection: true },
        thumbnailConfig: { content: "curlayer", boundary: "selection" }
      }
    ]
  ]
});
const boundaryDialogConfig = {
  dialogType: "boundary",
  title: t("boundary.select_boundary"),
  className: "w-[40rem] h-[30rem]",
  optionRows: [
    [
      {
        id: "canvas",
        text: t("boundary.canvas"),
        keyboardShortcut: "Q",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "curlayer",
        text: t("boundary.current_layer"),
        keyboardShortcut: "W",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "canvas" }
      },
      {
        id: "selection",
        text: t("boundary.selection"),
        keyboardShortcut: "E",
        visibility: { requiresSelection: true },
        // Use the selection boundary so the thumbnail reflects the actual selection area
        thumbnailConfig: { content: "selection", boundary: "canvas" }
      }
    ]
  ],
  keyboardMapping: {
    "KeyQ": "canvas",
    "KeyW": "curlayer",
    "KeyE": "selection",
    "KeyX": () => {
      const state = DialogManagerStore.getState();
      const defaultSize = sdpppX["settings.imaging.defaultImagesSizeLimit"];
      const current = (state.genericDialog.additionalData || {}).imageSize || 0;
      DialogManagerStore.setState({
        genericDialog: {
          ...state.genericDialog,
          additionalData: {
            ...state.genericDialog.additionalData || {},
            imageSize: current === 0 ? defaultSize : 0
          }
        }
      });
    }
  },
  storeConfig: {
    activeSelector: (state) => state.genericDialog.active,
    resolveSelector: (state) => state.resolveGenericDialog,
    rejectSelector: (state) => state.rejectGenericDialog,
    additionalSelectors: {
      imageSize: (state) => (state.genericDialog.additionalData || {}).imageSize
    }
  },
  // Include imageSize in result so WorkBoundary can persist per-doc max size
  onSelect: async (boundary, additionalData) => {
    const inputSize = (additionalData == null ? void 0 : additionalData.imageSize) || 0;
    const imageSize = inputSize > 0 ? inputSize : 999999;
    return { boundary, imageSize };
  },
  // Add control to adjust max_wh (image size)
  controls: [
    {
      type: "imageSize",
      title: t("image.limit_size"),
      keyboardShortcut: "X",
      config: {
        defaultSize: sdpppX["settings.imaging.defaultImagesSizeLimit"],
        onChange: (enabled, size) => {
          DialogManagerStore.setState((prev) => ({
            ...prev,
            genericDialog: {
              ...prev.genericDialog,
              additionalData: {
                ...prev.genericDialog.additionalData || {},
                imageSize: enabled ? size : 0
              }
            }
          }));
        }
      }
    }
  ]
};
const contentSourceDialogConfig = {
  dialogType: "content_source_simple",
  title: t("dialog.simple_source.title", { defaultValue: "选择内容来源" }),
  className: "w-[40rem] h-[30rem]",
  optionRows: [
    [
      {
        id: "canvas",
        text: t("dialog.simple_source.canvas", { defaultValue: "画布" }),
        keyboardShortcut: "Q",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "current_layer",
        text: t("dialog.simple_source.current_layer", { defaultValue: "当前图层" }),
        keyboardShortcut: "W",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "canvas" }
      }
    ],
    [
      {
        id: "local_file",
        text: t("dialog.simple_source.local_file", { defaultValue: "选择文件" }),
        keyboardShortcut: "E",
        variant: "wide"
      }
    ]
  ],
  keyboardMapping: {
    "KeyQ": "canvas",
    "KeyW": "current_layer",
    "KeyE": "local_file"
  },
  storeConfig: {
    activeSelector: (state) => state.genericDialog.active,
    resolveSelector: (state) => state.resolveGenericDialog,
    rejectSelector: (state) => state.rejectGenericDialog,
    additionalSelectors: {}
  },
  onSelect: async (selection) => {
    var _a3, _b2;
    const activeDocId = getActiveDocumentId();
    if (selection === "canvas") {
      return {
        resource: buildContentUri(activeDocId, "canvas")
      };
    }
    if (selection === "current_layer") {
      const layerIdentifyResult = await getCurrentLayerIdentify().catch(() => ({ layer_identify: null }));
      const layerIdentify = layerIdentifyResult == null ? void 0 : layerIdentifyResult.layer_identify;
      if (!layerIdentify) {
        throw new Error(t("dialog.simple_source.no_active_layer", { defaultValue: "当前没有可用图层" }));
      }
      return {
        resource: buildContentUri(activeDocId, "curlayer", layerIdentify),
        layerIdentify
      };
    }
    if (selection === "local_file") {
      const pickResult = await ((_b2 = (_a3 = mcpMesh.actions).pickLocalFile) == null ? void 0 : _b2.call(_a3, { kind: "file" }).catch(() => null));
      if (!pickResult || pickResult.cancelled) {
        return { cancelled: true };
      }
      let resourceId = pickResult.resource;
      if (!resourceId || typeof resourceId !== "string") {
        throw new Error(t("dialog.simple_source.pick_error", { defaultValue: "选择文件失败，请重试" }));
      }
      if (!resourceId.startsWith("uxp://file/")) {
        const entry = resolveResource(resourceId);
        if (entry) {
          const originalResourceId = resourceId;
          resourceId = createResource({
            type: "file",
            data: { ...entry.data ?? {} },
            originalMeta: {
              ...entry.originalMeta ?? {},
              fileName: pickResult.fileName,
              mimeType: pickResult.mimeType,
              size: pickResult.size,
              convertedFrom: resourceId
            }
          });
          deleteResource(originalResourceId);
        }
      }
      return {
        resource: resourceId,
        fileName: pickResult.fileName,
        mimeType: pickResult.mimeType,
        size: pickResult.size
      };
    }
    throw new Error(`Unknown simple content source selection: ${selection}`);
  }
};
const imageSourceDialogConfig = {
  dialogType: "image_source",
  title: t("dialog.image_source.title", { defaultValue: "选择图像来源" }),
  className: "w-[42rem] h-[38rem]",
  optionRows: [
    [
      {
        id: "primary_canvas",
        text: t("dialog.image_source.primary_canvas", { defaultValue: "以主图边界获取画布" }),
        keyboardShortcut: "Q",
        thumbnailConfig: { content: "canvas", boundary: "canvas" },
        usesPrimaryBoundary: true
      },
      {
        id: "canvas_canvas",
        text: t("dialog.image_source.canvas_canvas", { defaultValue: "以画布边界获取画布" }),
        keyboardShortcut: "W",
        thumbnailConfig: { content: "canvas", boundary: "canvas" }
      },
      {
        id: "curlayer_canvas",
        text: t("dialog.image_source.curlayer_canvas", { defaultValue: "以当前图层边界获取画布" }),
        keyboardShortcut: "E",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "canvas", boundary: "curlayer" }
      }
    ],
    [
      {
        id: "primary_curlayer",
        text: t("dialog.image_source.primary_curlayer", { defaultValue: "以主图边界获取当前图层" }),
        keyboardShortcut: "A",
        thumbnailConfig: { content: "curlayer", boundary: "canvas" },
        usesPrimaryBoundary: true
      },
      {
        id: "canvas_curlayer",
        text: t("dialog.image_source.canvas_curlayer", { defaultValue: "以画布边界获取当前图层" }),
        keyboardShortcut: "S",
        thumbnailConfig: { content: "curlayer", boundary: "canvas" }
      },
      {
        id: "curlayer_curlayer",
        text: t("dialog.image_source.curlayer_curlayer", { defaultValue: "以当前图层边界获取当前图层" }),
        keyboardShortcut: "D",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "curlayer" }
      }
    ],
    [
      {
        id: "local_file",
        text: t("dialog.image_source.local_file", { defaultValue: "从磁盘获取" }),
        keyboardShortcut: "F",
        variant: "wide"
      }
    ]
  ],
  keyboardMapping: {
    "KeyQ": "primary_canvas",
    "KeyW": "canvas_canvas",
    "KeyE": "curlayer_canvas",
    "KeyA": "primary_curlayer",
    "KeyS": "canvas_curlayer",
    "KeyD": "curlayer_curlayer",
    "KeyF": "local_file"
  },
  storeConfig: {
    activeSelector: (state) => state.genericDialog.active,
    resolveSelector: (state) => state.resolveGenericDialog,
    rejectSelector: (state) => state.rejectGenericDialog,
    additionalSelectors: {}
  },
  onSelect: async (selection, additionalData) => {
    const optionMap = {
      primary_canvas: { mode: "image", boundary: "primary", content: "canvas" },
      canvas_canvas: { mode: "image", boundary: "canvas", content: "canvas" },
      curlayer_canvas: { mode: "image", boundary: "curlayer", content: "canvas" },
      primary_curlayer: { mode: "image", boundary: "primary", content: "curlayer" },
      canvas_curlayer: { mode: "image", boundary: "canvas", content: "curlayer" },
      curlayer_curlayer: { mode: "image", boundary: "curlayer", content: "curlayer" },
      local_file: { mode: "file" }
    };
    const option = optionMap[selection];
    if (!option) {
      throw new Error(`Unknown image source selection: ${selection}`);
    }
    if (option.mode === "file") {
      return {
        mode: "file"
      };
    }
    const inboundBoundaryResource = additionalData == null ? void 0 : additionalData.boundaryResource;
    if (option.boundary === "primary") {
      if (!inboundBoundaryResource || typeof inboundBoundaryResource !== "string") {
        throw new Error("boundaryResource is required for image source dialog");
      }
    }
    const activeDocumentId = getActiveDocumentId();
    let boundaryResource;
    if (option.boundary === "primary") {
      boundaryResource = inboundBoundaryResource;
    } else {
      boundaryResource = buildBoundaryUri(activeDocumentId, option.boundary);
    }
    const contentResource = buildContentUri(activeDocumentId, option.content);
    try {
      console.log("[ImageSelectionDialog] return image resources", { contentResource, boundaryResource });
    } catch {
    }
    return {
      mode: "image",
      boundaryResource,
      contentResource
    };
  }
};
({
  title: t("mask.get.select_mask"),
  optionRows: [
    [
      {
        id: "curlayer",
        text: t("mask.current_layer_bounds"),
        keyboardShortcut: "Q",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "canvas" }
      },
      {
        id: "curlayer_reverse",
        text: t("mask.current_layer_exclude"),
        keyboardShortcut: "W",
        visibility: { requiresActiveLayers: true },
        thumbnailConfig: { content: "curlayer", boundary: "canvas", reverse: true }
      }
    ]
  ]
});
({
  title: t("mask.get.select_mask"),
  optionRows: [
    [
      {
        id: "selection",
        text: t("mask.selection"),
        keyboardShortcut: "A",
        visibility: { requiresSelection: true },
        thumbnailConfig: { content: "selection", boundary: "canvas" }
      },
      {
        id: "selection_reverse",
        text: t("mask.selection_exclude"),
        keyboardShortcut: "S",
        visibility: { requiresSelection: true },
        thumbnailConfig: { content: "selection", boundary: "canvas", reverse: true }
      }
    ]
  ]
});
async function getImageImpl(params) {
  var _a3;
  try {
    const { boundary, content, imageSize, imageQuality, cropBySelection, layer_identify } = params;
    const activeDocumentID = mcpMesh.getNode("uxp").store.getState().activeDocumentID;
    const webviewState = mcpMesh.store.getState();
    const workBoundaryMaxSizes = webviewState.workBoundaryMaxSizes || {};
    const defaultSize = sdpppX["settings.imaging.defaultImagesSizeLimit"];
    const effectiveImageSize = imageSize && imageSize > 0 ? imageSize : workBoundaryMaxSizes[activeDocumentID] || defaultSize;
    const isBoundaryRect = (obj) => {
      return obj && typeof obj === "object" && "leftDistance" in obj && "topDistance" in obj && "rightDistance" in obj && "bottomDistance" in obj && "width" in obj && "height" in obj;
    };
    if (!photoshop.app.activeDocument) {
      throw new Error(t("photoshop.no_active_document"));
    }
    if (params.SkipNonNormalLayer && content === "curlayer") {
      try {
        const doc = photoshop.app.activeDocument;
        const activeLayer = doc.activeLayers && doc.activeLayers.length > 0 ? doc.activeLayers[0] : null;
        const kind = activeLayer == null ? void 0 : activeLayer.kind;
        if (kind === photoshop.constants.LayerKind.GROUP || kind === photoshop.constants.LayerKind.GRADIENTFILL) {
          return {
            thumbnail: "",
            source: JSON.stringify(params)
          };
        }
      } catch {
      }
    }
    let boundaryParam;
    if (typeof boundary === "string") {
      if (boundary === "canvas") {
        const documentInfo = await getDocumentInfo({ document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT() });
        boundaryParam = documentInfo.document_boundary;
      } else if (boundary === "curlayer") {
        const layerInfo = await getLayerInfo({
          document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
          layer_identify: layer_identify || SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER()
        });
        boundaryParam = layerInfo.boundary;
      } else if (boundary === "selection") {
        const documentInfo = await getDocumentInfo({ document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT() });
        boundaryParam = documentInfo.selection_boundary;
      } else {
        throw new Error(`Invalid boundary value: ${boundary}`);
      }
    } else if (isBoundaryRect(boundary)) {
      const doc = photoshop.app.activeDocument;
      const docWidth = Number(doc.width);
      const docHeight = Number(doc.height);
      boundaryParam = BoundaryRectUtils.toSDPPPBounds(boundary, docWidth, docHeight);
      console.log("[getImageImpl] Using BoundaryRect:", boundaryParam);
    } else {
      throw new Error("Invalid boundary type");
    }
    const hasSelection = ((_a3 = photoshop.app.activeDocument.selection) == null ? void 0 : _a3.bounds) !== null;
    let finalCropBySelection = cropBySelection;
    if (!hasSelection && cropBySelection !== "no") {
      finalCropBySelection = "no";
    }
    let layerIdentify = content;
    if (layer_identify) {
      layerIdentify = layer_identify;
    } else if (content === "canvas") {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    } else if (content === "curlayer") {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    } else if (content === "selection") {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    }
    const jimpImage = await getImage.getJimpImage({
      document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
      layer_identify: layerIdentify,
      boundary: boundaryParam,
      max_wh: effectiveImageSize,
      quality: imageQuality
    });
    if (content === "selection" || finalCropBySelection !== "no") {
      try {
        const selection = await getSelection({
          document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
          boundary: boundaryParam,
          max_wh: effectiveImageSize
        });
        const { blob: buffer2, width, height } = selection;
        if (buffer2 && buffer2.length === width * height) {
          const negative = finalCropBySelection === "negative";
          for (let i2 = 0; i2 < width * height; i2++) {
            const idx = i2 * 4;
            const alpha = negative ? 255 - buffer2[i2] : buffer2[i2];
            if (idx + 3 < jimpImage.bitmap.data.length) {
              jimpImage.bitmap.data[idx + 3] = alpha;
            }
          }
        }
      } catch (e4) {
        console.warn("[getImageImpl] Selection masking failed; proceeding without mask", e4);
      }
    }
    const thumbnailImage = jimpImage.clone();
    thumbnailImage.scaleToFit({
      w: 192,
      h: 192
    });
    const thumbnailBuffer = await thumbnailImage.getBuffer(JimpMime.png);
    const thumbnail = "data:image/png;base64," + thumbnailBuffer.toString("base64");
    const imageBuffer = await jimpImage.getBuffer(JimpMime.png);
    const resourceId = createResource({
      type: "image",
      data: {
        buffer: new Uint8Array(imageBuffer),
        mime: "image/png"
      },
      originalMeta: {
        width: jimpImage.bitmap.width,
        height: jimpImage.bitmap.height,
        params: JSON.stringify(params)
      }
    });
    updateResource(resourceId, {
      thumbnailCache: {
        base64: thumbnail,
        width: thumbnailImage.bitmap.width,
        height: thumbnailImage.bitmap.height,
        mime: "image/png",
        generatedAt: Date.now()
      }
    });
    return {
      resource: resourceId,
      thumbnail,
      width: jimpImage.bitmap.width,
      height: jimpImage.bitmap.height,
      mimeType: "image/png",
      source: JSON.stringify(params)
    };
  } catch (error) {
    return {
      error: error.stack || error.message || error
    };
  }
}
async function importImageImpl(params) {
  var _a3, _b2, _c2, _d2, _e2, _f2;
  try {
    const { resource, type: type2, boundary } = params;
    const applyMask = params.applyMask === true;
    const shouldAttemptMask = applyMask && type2 === "smartobject";
    let originalSelectionDescriptor = null;
    let hasOriginalSelection = false;
    if (shouldAttemptMask && ((_a3 = photoshop.app.activeDocument) == null ? void 0 : _a3.selection)) {
      try {
        const selectionResult = await photoshop.action.batchPlay([
          {
            "_obj": "get",
            "_target": [
              { "_property": "selection", "_ref": "document", "_enum": "ordinal", "_value": "targetEnum" }
            ],
            "_options": { "dialogOptions": "dontDisplay" }
          }
        ], {
          synchronousExecution: true,
          modalBehavior: "fail"
        });
        const descriptor = (_b2 = selectionResult == null ? void 0 : selectionResult[0]) == null ? void 0 : _b2.selection;
        if (descriptor) {
          originalSelectionDescriptor = descriptor;
          hasOriginalSelection = true;
        }
      } catch (error) {
        const reason = error instanceof Error ? error.message : String(error);
        console.log("[importImageImpl] no selection snapshot captured", reason);
      }
    }
    const resourceEntry = resolveResource(resource);
    let nativePath;
    console.log("[importImageImpl] received params", {
      resource,
      type: type2,
      boundaryType: typeof boundary,
      hasBoundary: !!boundary,
      applyMask: shouldAttemptMask,
      sourceWidth: params.sourceWidth,
      sourceHeight: params.sourceHeight,
      resourceMeta: {
        width: (_c2 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _c2.width,
        height: (_d2 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _d2.height
      }
    });
    const extensionHint = typeof ((_e2 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _e2.extension) === "string" ? String(resourceEntry.originalMeta.extension) : void 0;
    nativePath = await ensureResourceTempFile(resource, { extensionHint }).catch(() => void 0);
    if (!nativePath) {
      throw new Error("Failed to materialize resource");
    }
    nativePath = String(nativePath);
    const isBoundaryRect = (obj) => {
      return obj && typeof obj === "object" && "leftDistance" in obj && "topDistance" in obj && "rightDistance" in obj && "bottomDistance" in obj && "width" in obj && "height" in obj;
    };
    let resolvedBoundary;
    if (boundary) {
      if (!photoshop.app.activeDocument) {
        throw new Error("No active document");
      }
      if (typeof boundary === "string") {
        if (boundary === "canvas") {
          const documentInfo = await getDocumentInfo({ document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT() });
          console.log("[importImageImpl] documentInfo.document_boundary", documentInfo.document_boundary);
          resolvedBoundary = documentInfo.document_boundary;
        } else if (boundary === "curlayer") {
          const layerInfo = await getLayerInfo({
            document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
            layer_identify: SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER()
          });
          console.log("[importImageImpl] layerInfo.boundary", layerInfo.boundary);
          resolvedBoundary = layerInfo.boundary;
        } else if (boundary === "selection") {
          const documentInfo = await getDocumentInfo({ document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT() });
          console.log("[importImageImpl] documentInfo.selection_boundary", documentInfo.selection_boundary);
          resolvedBoundary = documentInfo.selection_boundary;
        } else {
          throw new Error(`Invalid boundary value: ${boundary}`);
        }
      } else if (isBoundaryRect(boundary)) {
        resolvedBoundary = boundary;
      } else {
        throw new Error("Invalid boundary type");
      }
      if (resolvedBoundary) {
        const docWidth = Number(photoshop.app.activeDocument.width);
        const docHeight = Number(photoshop.app.activeDocument.height);
        resolvedBoundary = BoundaryRectUtils.clampToDocument(resolvedBoundary, docWidth, docHeight);
        console.log("[importImageImpl] resolved boundary", {
          docWidth,
          docHeight,
          boundary: resolvedBoundary
        });
      }
    }
    const localFileSystem = uxp.storage.localFileSystem;
    const tempFolder = await localFileSystem.getTemporaryFolder();
    let fileEntry;
    let token;
    if (nativePath.includes(tempFolder.nativePath)) {
      const relativePath = nativePath.replace(tempFolder.nativePath, "").replace(/^[\/\\]/, "");
      fileEntry = await tempFolder.getEntry(relativePath);
      if (!fileEntry) {
        throw new Error(`Temporary file not found: ${nativePath}`);
      }
      token = localFileSystem.createSessionToken(fileEntry);
    } else {
      fileEntry = await localFileSystem.getEntryWithUrl(nativePath.startsWith("file://") ? nativePath : `file://${nativePath}`);
      if (!fileEntry) {
        throw new Error(`File not found: ${nativePath}`);
      }
      token = localFileSystem.createSessionToken(fileEntry);
    }
    const metaFileName = typeof ((_f2 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _f2.fileName) === "string" ? String(resourceEntry.originalMeta.fileName) : nativePath.split(/[\/\\]/).pop() || "Imported Image";
    const fileName = metaFileName.replace(/\.[^/.]+$/, "");
    if (type2 === "newdoc") {
      await runNextModalState(async (restorer) => {
        await photoshop.action.batchPlay([
          {
            "_obj": "open",
            "null": { "_kind": "local", "_path": token },
            "smartObject": false,
            "template": false
          }
        ], {
          synchronousExecution: true
        });
      }, {
        commandName: `Import ${fileName} as new document`,
        document: null,
        dontRecoverSelection: true
      });
      return {
        success: true,
        message: `Image opened as new document: ${fileName}`
      };
    } else if (type2 === "smartobject") {
      if (!photoshop.app.activeDocument) {
        throw new Error("No active document");
      }
      const document2 = photoshop.app.activeDocument;
      await runNextModalState(async (restorer) => {
        var _a4, _b3;
        const docWidth = Number(document2.width);
        const docHeight = Number(document2.height);
        let placeEventParams = {
          "_obj": "placeEvent",
          "null": {
            "_kind": "local",
            "_path": token
          },
          "freeTransformCenterState": { "_enum": "quadCenterState", "_value": "QCSAverage" }
        };
        if (resolvedBoundary) {
          const left = Math.max(0, Math.min(resolvedBoundary.leftDistance, docWidth));
          const top = Math.max(0, Math.min(resolvedBoundary.topDistance, docHeight));
          const right = Math.max(left, Math.min(docWidth - resolvedBoundary.rightDistance, docWidth));
          const bottom = Math.max(top, Math.min(docHeight - resolvedBoundary.bottomDistance, docHeight));
          const width = right - left;
          const height = bottom - top;
          const srcW = Number(params.sourceWidth ?? ((_a4 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _a4.width) ?? NaN);
          const srcH = Number(params.sourceHeight ?? ((_b3 = resourceEntry == null ? void 0 : resourceEntry.originalMeta) == null ? void 0 : _b3.height) ?? NaN);
          let widthPercent;
          let heightPercent;
          if (srcW > 0 && srcH > 0) {
            const documentDPI = Number(document2.resolution) || 72;
            const IMAGE_DPI = 72;
            const dpiScale = documentDPI / IMAGE_DPI;
            let physicalW = srcW * dpiScale;
            let physicalH = srcH * dpiScale;
            let effW = physicalW;
            let effH = physicalH;
            const containScale = Math.min(docWidth / physicalW, docHeight / physicalH);
            if (containScale < 1) {
              effW = physicalW * containScale;
              effH = physicalH * containScale;
            }
            widthPercent = width / effW * 100;
            heightPercent = height / effH * 100;
            console.log("[importImageImpl] scaling info", {
              sourceSize: { width: srcW, height: srcH },
              documentSize: { width: docWidth, height: docHeight },
              boundarySize: { width, height },
              dpiInfo: { documentDPI, imageDPI: IMAGE_DPI, dpiScale },
              containScale,
              effectiveSourceSize: { width: effW, height: effH },
              scalingPercent: { width: widthPercent, height: heightPercent }
            });
            console.log(`[importImage] Scaling calculation:`, {
              sourceSize: { width: srcW, height: srcH },
              documentSize: { width: docWidth, height: docHeight },
              dpiInfo: { documentDPI, imageDPI: IMAGE_DPI, dpiScale },
              physicalSize: { width: physicalW, height: physicalH },
              containScale,
              effectiveSize: { width: effW, height: effH },
              targetBoundary: { width, height },
              scalingPercent: { width: widthPercent, height: heightPercent }
            });
            placeEventParams.width = { "_unit": "percentUnit", "_value": widthPercent };
            placeEventParams.height = { "_unit": "percentUnit", "_value": heightPercent };
          }
          await photoshop.action.batchPlay([
            {
              "_obj": "set",
              "_target": [
                { "_property": "selection", "_ref": "channel" }
              ],
              "to": {
                "_obj": "rectangle",
                "top": { "_unit": "pixelsUnit", "_value": top },
                "left": { "_unit": "pixelsUnit", "_value": left },
                "bottom": { "_unit": "pixelsUnit", "_value": bottom },
                "right": { "_unit": "pixelsUnit", "_value": right }
              }
            }
          ], { synchronousExecution: true });
        }
        await photoshop.action.batchPlay([placeEventParams], { synchronousExecution: true });
        if (shouldAttemptMask && hasOriginalSelection && originalSelectionDescriptor) {
          try {
            console.log("[importImageImpl] restoring selection for mask application");
            await photoshop.action.batchPlay([
              {
                "_obj": "set",
                "_target": [
                  { "_property": "selection", "_ref": "channel" }
                ],
                "to": originalSelectionDescriptor,
                "_options": { "dialogOptions": "dontDisplay" }
              }
            ], { synchronousExecution: true });
            await photoshop.action.batchPlay([
              {
                "_obj": "make",
                "at": { "_enum": "channel", "_ref": "channel", "_value": "mask" },
                "new": { "_class": "channel" },
                "using": { "_enum": "userMaskEnabled", "_value": "revealSelection" },
                "_options": { "dialogOptions": "dontDisplay" }
              }
            ], { synchronousExecution: true });
            console.log("[importImageImpl] mask created from selection");
          } catch (maskError) {
            const reason = maskError instanceof Error ? maskError.message : String(maskError);
            console.warn("[importImageImpl] mask application failed", reason);
          }
        } else if (shouldAttemptMask) {
          console.log("[importImageImpl] applyMask requested but no selection available; skipping mask creation");
        }
      }, {
        commandName: `Import ${fileName} as smart object`,
        document: document2,
        dontRecoverSelection: true
      });
      return {
        success: true,
        message: `Image imported as smart object: ${fileName}`
      };
    } else {
      throw new Error(`Import type '${type2}' is not yet implemented`);
    }
  } catch (error) {
    return {
      success: false,
      error: error.stack || error.message || error
    };
  }
}
async function getMaskImpl(params) {
  try {
    const { boundary, content, reverse, imageSize, layer_identify } = params;
    const activeDocumentID = mcpMesh.getNode("uxp").store.getState().activeDocumentID;
    const webviewState = mcpMesh.store.getState();
    const workBoundaryMaxSizes = webviewState.workBoundaryMaxSizes || {};
    const defaultSize = sdpppX["settings.imaging.defaultImagesSizeLimit"];
    const effectiveImageSize = imageSize && imageSize > 0 ? imageSize : workBoundaryMaxSizes[activeDocumentID] || defaultSize;
    const isBoundaryRect = (obj) => {
      return obj && typeof obj === "object" && "leftDistance" in obj && "topDistance" in obj && "rightDistance" in obj && "bottomDistance" in obj && "width" in obj && "height" in obj;
    };
    if (!photoshop.app.activeDocument) {
      throw new Error(t("photoshop.no_active_document"));
    }
    let boundaryParam;
    if (boundary == null || boundary === "canvas") {
      const documentInfo = await getDocumentInfo({
        document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT()
      });
      boundaryParam = documentInfo.document_boundary;
    } else if (typeof boundary === "string") {
      if (boundary === "curlayer") {
        const layerInfo = await getLayerInfo({
          document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
          layer_identify: layer_identify || SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER()
        });
        boundaryParam = layerInfo.boundary;
      } else if (boundary === "selection") {
        const documentInfo = await getDocumentInfo({
          document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT()
        });
        boundaryParam = documentInfo.selection_boundary;
      } else {
        throw new Error(`Invalid boundary value: ${boundary}`);
      }
    } else if (isBoundaryRect(boundary)) {
      const doc = photoshop.app.activeDocument;
      const docWidth = Number(doc.width);
      const docHeight = Number(doc.height);
      boundaryParam = BoundaryRectUtils.toSDPPPBounds(boundary, docWidth, docHeight);
    } else {
      throw new Error("Invalid boundary type");
    }
    let layerIdentify;
    if (layer_identify) {
      layerIdentify = layer_identify;
    } else if (content === "canvas") {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    } else if (content === "curlayer") {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_SELECTED_LAYER();
    } else {
      layerIdentify = SpeicialIDManager.get_SPECIAL_LAYER_USE_CANVAS();
    }
    const jimpImage = await getImage.getJimpImage({
      document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
      layer_identify: layerIdentify,
      boundary: boundaryParam,
      max_wh: effectiveImageSize
    });
    if (content === "selection") {
      try {
        const selection = await getSelection({
          document_identify: SpeicialIDManager.get_SPECIAL_DOCUMENT_CURRENT(),
          boundary: boundaryParam,
          max_wh: effectiveImageSize
        });
        const { blob: buffer2, width, height } = selection;
        if (buffer2 && buffer2.length === width * height) {
          for (let i2 = 0; i2 < width * height; i2++) {
            const idx = i2 * 4;
            const alpha = buffer2[i2];
            if (idx + 3 < jimpImage.bitmap.data.length) {
              jimpImage.bitmap.data[idx + 3] = alpha;
            }
          }
        }
      } catch (e4) {
        console.warn("[getMaskImpl] Selection masking failed; proceeding without mask", e4);
      }
    }
    jimpImage.scan(0, 0, jimpImage.bitmap.width, jimpImage.bitmap.height, (x2, y2, idx) => {
      const alpha = jimpImage.bitmap.data[idx + 3];
      const grayValue = reverse ? alpha : 255 - alpha;
      jimpImage.bitmap.data[idx + 0] = grayValue;
      jimpImage.bitmap.data[idx + 1] = grayValue;
      jimpImage.bitmap.data[idx + 2] = grayValue;
      jimpImage.bitmap.data[idx + 3] = grayValue;
    });
    const thumbnailImage = jimpImage.clone();
    thumbnailImage.scaleToFit({ w: 192, h: 192 });
    thumbnailImage.scan(0, 0, thumbnailImage.bitmap.width, thumbnailImage.bitmap.height, (x2, y2, idx) => {
      thumbnailImage.bitmap.data[idx + 3] = 255;
    });
    const thumbnailBuffer = await thumbnailImage.getBuffer(JimpMime.png);
    const thumbnail = "data:image/png;base64," + thumbnailBuffer.toString("base64");
    const imageBuffer = await jimpImage.getBuffer(JimpMime.png);
    const resourceId = createResource({
      type: "mask",
      data: {
        buffer: new Uint8Array(imageBuffer),
        mime: "image/png"
      },
      originalMeta: {
        width: jimpImage.bitmap.width,
        height: jimpImage.bitmap.height,
        params: JSON.stringify(params)
      }
    });
    updateResource(resourceId, {
      thumbnailCache: {
        base64: thumbnail,
        width: thumbnailImage.bitmap.width,
        height: thumbnailImage.bitmap.height,
        mime: "image/png",
        generatedAt: Date.now()
      }
    });
    return {
      resource: resourceId,
      thumbnail,
      width: jimpImage.bitmap.width,
      height: jimpImage.bitmap.height,
      mimeType: "image/png",
      source: JSON.stringify(params)
    };
  } catch (error) {
    return {
      error: (error == null ? void 0 : error.stack) || (error == null ? void 0 : error.message) || String(error)
    };
  }
}
async function applyMaskToImageImpl(params) {
  const { imageResource, maskResource, invertMask = false } = params;
  if (!imageResource) {
    throw new Error("applyMaskToImage: imageResource is required");
  }
  if (!maskResource) {
    throw new Error("applyMaskToImage: maskResource is required");
  }
  const [{ buffer: imageBuffer }, { buffer: maskBuffer }] = await Promise.all([
    resolveResourceBuffer(imageResource),
    resolveResourceBuffer(maskResource)
  ]);
  if (!(imageBuffer == null ? void 0 : imageBuffer.byteLength)) {
    throw new Error("applyMaskToImage: failed to resolve image buffer");
  }
  if (!(maskBuffer == null ? void 0 : maskBuffer.byteLength)) {
    throw new Error("applyMaskToImage: failed to resolve mask buffer");
  }
  const baseImage = await Jimp.read(bufferExports.Buffer.from(imageBuffer));
  const maskImage = await Jimp.read(bufferExports.Buffer.from(maskBuffer));
  const width = baseImage.width;
  const height = baseImage.height;
  if (!width || !height) {
    throw new Error("applyMaskToImage: base image has invalid dimensions");
  }
  if (maskImage.width !== width || maskImage.height !== height) {
    maskImage.resize({ w: width, h: height });
  }
  const baseData = baseImage.bitmap.data;
  const maskData = maskImage.bitmap.data;
  const totalPixels = width * height;
  for (let idx = 0; idx < totalPixels; idx += 1) {
    const dataIndex = idx * 4;
    let maskValue = maskData[dataIndex];
    if (invertMask) {
      maskValue = 255 - maskValue;
    }
    baseData[dataIndex + 3] = maskValue;
  }
  const outputBuffer = await baseImage.getBuffer(JimpMime.png);
  const resourceId = createResource({
    type: "image",
    data: {
      buffer: new Uint8Array(outputBuffer),
      mime: JimpMime.png
    },
    originalMeta: {
      width,
      height,
      source: "applyMaskToImage",
      imageResource,
      maskResource,
      invertMask,
      createdAt: Date.now()
    }
  });
  const thumbnailImage = baseImage.clone();
  thumbnailImage.scaleToFit({ w: 320, h: 320 });
  const thumbnailBuffer = await thumbnailImage.getBuffer(JimpMime.png);
  const thumbnailBase64 = `data:image/png;base64,${thumbnailBuffer.toString("base64")}`;
  updateResource(resourceId, {
    thumbnailCache: {
      base64: thumbnailBase64,
      width,
      height,
      mime: "image/png",
      generatedAt: Date.now()
    }
  });
  return {
    resource: resourceId,
    thumbnail: thumbnailBase64,
    width,
    height,
    mimeType: JimpMime.png
  };
}
let managedGuides = [];
let currentDocumentId = null;
function clearManagedGuides(document2) {
  try {
    managedGuides.forEach((guide) => {
      try {
        if (guide.parent.id === document2.id) {
          guide.delete();
        }
      } catch (e4) {
      }
    });
  } catch (e4) {
    console.error("clearManagedGuides error:", e4);
  }
  managedGuides = [];
}
function checkDocumentChange() {
  if (photoshop.app.activeDocument && currentDocumentId !== photoshop.app.activeDocument.id) {
    if (currentDocumentId !== null) {
      managedGuides = [];
    }
    currentDocumentId = photoshop.app.activeDocument.id;
  }
}
async function manageGuides(params) {
  if (!photoshop.app.activeDocument) {
    throw new Error(t("photoshop.no_active_document"));
  }
  const document2 = photoshop.app.activeDocument;
  checkDocumentChange();
  switch (params.action) {
    case "create":
      if (!params.rect) {
        throw new Error(t("photoshop.rectangle_coordinates_required"));
      }
      await runNextModalState(async (restorer) => {
        clearManagedGuides(document2);
        const docWidth = document2.width;
        const docHeight = document2.height;
        const clampedRect = BoundaryRectUtils.clampToDocument(params.rect, docWidth, docHeight);
        const left = Math.max(0, Math.min(clampedRect.leftDistance, docWidth));
        const top = Math.max(0, Math.min(clampedRect.topDistance, docHeight));
        const right = Math.max(left, Math.min(docWidth - clampedRect.rightDistance, docWidth));
        const bottom = Math.max(top, Math.min(docHeight - clampedRect.bottomDistance, docHeight));
        const guides = [
          document2.guides.add(photoshop.constants.Direction.VERTICAL, left),
          document2.guides.add(photoshop.constants.Direction.VERTICAL, right),
          document2.guides.add(photoshop.constants.Direction.HORIZONTAL, top),
          document2.guides.add(photoshop.constants.Direction.HORIZONTAL, bottom)
        ];
        managedGuides = guides;
        restorer.add((success) => {
          if (!success) {
            clearManagedGuides(document2);
          }
        });
      }, {
        commandName: t("photoshop.create_guide_frame"),
        document: document2,
        suspendHistory: false
      });
      break;
    case "clear":
      await runNextModalState(async (restorer) => {
        const guidesToRemove = [...managedGuides];
        clearManagedGuides(document2);
        restorer.add((success) => {
          if (!success) {
            managedGuides = guidesToRemove;
          }
        });
      }, {
        commandName: t("photoshop.clear_guide_frame"),
        document: document2,
        suspendHistory: false
      });
      break;
    default:
      throw new Error(t("photoshop.invalid_action", { action: params.action }));
  }
  return { success: true };
}
const getBoundary = getBoundaryImpl;
async function showBoundarySelectionDialog(_params) {
  try {
    const result = await new Promise((resolve2, reject2) => {
      var _a3, _b2, _c2, _d2;
      const activeDocId = mcpMesh.getNode("uxp").store.getState().activeDocumentID;
      const defaultSize = ((_b2 = (_a3 = mcpMesh.getNode("uxp").store.getState()) == null ? void 0 : _a3.sdpppX) == null ? void 0 : _b2["settings.imaging.defaultImagesSizeLimit"]) || 2048;
      const rawSize = (_d2 = (_c2 = mcpMesh.store.getState()) == null ? void 0 : _c2.workBoundaryMaxSizes) == null ? void 0 : _d2[activeDocId];
      const currentSize = typeof rawSize === "number" ? rawSize === 999999 ? 0 : rawSize : defaultSize;
      DialogManagerStore.setState({
        genericDialog: {
          active: true,
          config: boundaryDialogConfig,
          additionalData: {
            imageSize: currentSize
          }
        },
        resolveGenericDialog: resolve2,
        rejectGenericDialog: reject2
      });
    });
    return result;
  } catch (e4) {
    return { cancelled: true };
  } finally {
    DialogManagerStore.setState({
      genericDialog: {
        active: false,
        config: void 0,
        additionalData: void 0
      },
      resolveGenericDialog: () => {
      },
      rejectGenericDialog: () => {
      }
    });
  }
}
async function selectImageSource(_params) {
  var _a3;
  try {
    const boundaryResource = (_a3 = _params.additionalData) == null ? void 0 : _a3.boundaryResource;
    if (!boundaryResource || typeof boundaryResource !== "string") {
      throw new Error("boundaryResource is required for image source dialog");
    }
    const mergedAdditionalData = {
      ..._params.additionalData || {},
      boundaryResource
    };
    const result = await new Promise((resolve2) => {
      DialogManagerStore.setState({
        genericDialog: {
          active: true,
          config: imageSourceDialogConfig,
          additionalData: mergedAdditionalData
        },
        resolveGenericDialog: (value) => resolve2(value),
        rejectGenericDialog: (error) => {
          console.warn("[selectImageSource] dialog cancelled:", (error == null ? void 0 : error.message) ?? error);
          resolve2({ cancelled: true });
        }
      });
    });
    return result;
  } catch (e4) {
    console.error("[selectImageSource] unexpected rejection:", e4);
    return { cancelled: true };
  } finally {
    DialogManagerStore.setState({
      genericDialog: {
        active: false,
        config: void 0,
        additionalData: void 0
      },
      resolveGenericDialog: () => {
      },
      rejectGenericDialog: () => {
      }
    });
  }
}
async function selectContentSource(_params = {}) {
  try {
    const result = await new Promise((resolve2) => {
      DialogManagerStore.setState({
        genericDialog: {
          active: true,
          config: contentSourceDialogConfig,
          additionalData: _params.additionalData
        },
        resolveGenericDialog: (value) => resolve2(value),
        rejectGenericDialog: (error) => {
          console.warn("[selectContentSource] dialog cancelled:", (error == null ? void 0 : error.message) ?? error);
          resolve2({ cancelled: true });
        }
      });
    });
    return result ?? { cancelled: true };
  } catch (e4) {
    console.error("[selectContentSource] unexpected rejection:", e4);
    return { cancelled: true };
  } finally {
    DialogManagerStore.setState({
      genericDialog: {
        active: false,
        config: void 0,
        additionalData: void 0
      },
      resolveGenericDialog: () => {
      },
      rejectGenericDialog: () => {
      }
    });
  }
}
mcpMesh.implementAction("manageGuides", manageGuides);
mcpMesh.implementAction("getBoundary", getBoundary);
mcpMesh.implementAction("getImage", getImageImpl);
mcpMesh.implementAction("getMask", getMaskImpl);
mcpMesh.implementAction("getCurrentLayerIdentify", getCurrentLayerIdentify);
mcpMesh.implementAction("importImage", importImageImpl);
mcpMesh.implementAction("applyMaskToImage", applyMaskToImageImpl);
mcpMesh.implementAction("showBoundarySelectionDialog", showBoundarySelectionDialog);
mcpMesh.implementAction("selectImageSource", selectImageSource);
mcpMesh.implementAction("selectContentSource", selectContentSource);
function getSDPPPUID() {
  let uid = localStorage.getItem("sdppp_uid");
  if (!uid || uid.length != 3) {
    uid = makeid(3);
    localStorage.setItem("sdppp_uid", uid);
  }
  return uid;
}
function makeid(length) {
  let result = "";
  const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  const charactersLength = characters.length;
  let counter = 0;
  while (counter < length) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
    counter += 1;
  }
  return result;
}
const getTheme = async () => {
  const result = await photoshop.action.batchPlay(
    [
      {
        "_obj": "get",
        "_target": [
          { "_property": "kuiBrightnessLevel" },
          { "_ref": "application", "_enum": "ordinal", "_value": "targetEnum" }
        ],
        "_options": { "dialogOptions": "dontDisplay" }
      }
    ],
    { "synchronousExecution": true }
  );
  const pinned = result[0].kuiBrightnessLevel._value;
  return pinned;
};
mcpMesh.store.subscribe((state) => {
  localStorage.setItem("mcpMeshState", JSON.stringify({
    isLogin: state.isLogin,
    token: state.token,
    userInfo: state.userInfo,
    comfyURL: state.comfyURL
  }));
});
const localState = JSON.parse(localStorage.getItem("mcpMeshState") || "{}");
mcpMesh.store.setState({
  uname: getSDPPPUID(),
  activeDocumentID: 0,
  layers: [],
  actions: [],
  theme: "kPanelBrightnessMediumGray",
  locale: uxp.host.uiLocale.startsWith("zh") ? "zh-CN" : "en-US",
  sdpppX,
  comfyWebviewConnectStatus: "disconnected",
  comfyWebviewLoadError: "",
  comfyWebviewLoading: false,
  comfyWebviewVersion: "",
  comfyHTTPCode: 200,
  comfyURL: localState.comfyURL || "",
  sdkWebviewFocusing: false,
  sdkWebviewConnectStatus: "disconnected",
  isLogin: localState.isLogin || false,
  requestingLogin: false,
  loginMessage: "",
  token: localState.token || "",
  userInfo: localState.userInfo || {}
});
async function initializeUtilStates() {
  mcpMesh.store.setState({
    theme: await getTheme()
  });
  changeLanguage(mcpMesh.store.getState().locale);
}
(async () => {
  await initializeUtilStates();
})();
async function intervalCheck() {
  const isLogin = mcpMesh.store.getState().isLogin;
  let _nextCheckTime = 15e3;
  if (isLogin) {
    try {
      const provider = PSUXPInternalStore.getState().loginProvider;
      if (provider) {
        const { loginValid, nextCheckTime } = await provider.intervalCheck(mcpMesh.store.getState().token);
        if (!loginValid) {
          mcpMesh.store.setState({
            isLogin: false,
            token: "",
            userInfo: void 0
          });
        }
        _nextCheckTime = nextCheckTime;
      }
    } catch (e4) {
      console.warn(e4);
    }
  }
  setTimeout(intervalCheck, _nextCheckTime);
}
function startAuthMaintenance() {
  setTimeout(intervalCheck, 4e3);
}
startAuthMaintenance();
function makeLayerIdentify(id, name, level = 0) {
  return "-".repeat(level) + `${name} (id:${id})`;
}
let lastCurrentDocumentID = ((_a2 = photoshop.app.activeDocument) == null ? void 0 : _a2.id) || 0;
let lastCurrentLayerID = ((_b = photoshop.app.activeDocument) == null ? void 0 : _b.activeLayers.map((layer) => layer.id).join(",")) || "";
let selectionAreaID = 0;
let lastSelectionStateIDFrame = "";
let lastFrameSelectionBounds = null;
function getActiveSelectionBounds() {
  try {
    const doc = photoshop.app.activeDocument;
    if (!doc) {
      return null;
    }
    const selection = doc.selection;
    if (!selection) {
      return null;
    }
    const bounds = selection.bounds;
    if (!bounds) {
      return null;
    }
    const left = bounds.left ?? bounds[0];
    const top = bounds.top ?? bounds[1];
    const right = bounds.right ?? bounds[2];
    const bottom = bounds.bottom ?? bounds[3];
    if (left == null || top == null || right == null || bottom == null || right <= left || bottom <= top) {
      return null;
    }
    return { left, top, right, bottom };
  } catch {
    return null;
  }
}
(async () => {
  mcpMesh.store.setState({
    uname: getSDPPPUID()
  });
  updateDocumentState();
})().catch(console.error);
photoshop.action.addNotificationListener(["historyStateChanged"], (args) => {
  if (args.commandID == 5004 || args.commandID == 5002) {
    notifyCanvasStateChange();
    notifyLayerChange();
  }
});
photoshop.action.addNotificationListener(["toolModalStateChanged"], (name, args) => {
  if (args.state._value == "exit" && args.kind._value == "paint") {
    notifyCanvasStateChange();
    notifyLayerChange();
  }
});
photoshop.action.addNotificationListener(["modalStateChanged"], (name, args) => {
  if (args.state._value == "exit") {
    notifyCanvasStateChange();
    notifyLayerChange();
  }
});
photoshop.action.addNotificationListener(["show", "hide", "transform", "fill", "crop"], () => {
  notifyCanvasStateChange();
  notifyLayerChange();
});
photoshop.action.addNotificationListener(["delete", "move", "copyToLayer"], () => {
  updateDocumentState();
  notifyCanvasStateChange();
  notifyLayerChange();
});
photoshop.action.addNotificationListener(["newDocument", "open", "close", "make", "modalJavaScriptScopeExit"], () => {
  updateDocumentState();
});
photoshop.action.addNotificationListener(["set"], (name, args) => {
  var _a3, _b2;
  try {
    if (((_b2 = (_a3 = args == null ? void 0 : args._target) == null ? void 0 : _a3[0]) == null ? void 0 : _b2._property) === "selection") {
      selectionAreaID++;
      notifySelectionStateChange();
    }
  } catch (e4) {
  }
});
function notifyCanvasStateChange() {
  var _a3;
  const historyStates = (_a3 = photoshop.app.activeDocument) == null ? void 0 : _a3.historyStates;
  if (historyStates) {
    mcpMesh.store.setState({
      canvasStateID: historyStates[historyStates.length - 1].id
    });
  }
}
function notifySelectionStateChange() {
  const id = `${selectionAreaID}_${lastCurrentDocumentID}_${lastCurrentLayerID}`;
  mcpMesh.store.setState({ selectionStateID: id });
  return id;
}
function notifyLayerChange() {
  fetchDocuments();
}
function fetchDocuments() {
  try {
    if (!photoshop.app.activeDocument) return;
    const layers = getAllSubLayer(photoshop.app.activeDocument).map((layerAndPath) => {
      const layerId = layerAndPath.layer.id;
      return {
        id: layerId,
        name: layerAndPath.layer.name,
        identify: makeLayerIdentify(layerId, layerAndPath.layer.name, layerAndPath.level)
      };
    });
    if (mcpMesh == null ? void 0 : mcpMesh.store) {
      mcpMesh.store.setState({
        layers
      });
    }
  } catch (e4) {
    console.error("fetchDocuments error:", e4);
  }
}
function updateDocumentState() {
  const activeDocument = photoshop.app.activeDocument;
  if (activeDocument) {
    const currentState = mcpMesh.store.getState();
    if (currentState.activeDocumentID !== activeDocument.id) {
      mcpMesh.store.setState({
        activeDocumentID: activeDocument.id
      });
    }
  }
}
function updateActions() {
  try {
    let allActions = [];
    photoshop.app.actionTree.forEach((actionSet) => {
      actionSet.actions.forEach((action2) => {
        allActions.push(actionSet.name + "/" + action2.name);
      });
    });
    if (mcpMesh == null ? void 0 : mcpMesh.store) {
      const currentActions = mcpMesh.store.getState().actions || [];
      if (currentActions.length != allActions.length || currentActions.some((action2, index2) => action2 != allActions[index2])) {
        mcpMesh.store.setState({
          actions: allActions
        });
      }
    }
  } catch (e4) {
    console.error("actions update error:", e4);
  }
}
function checkCurrentDocument() {
  var _a3, _b2;
  try {
    if ((mcpMesh == null ? void 0 : mcpMesh.store) && typeof mcpMesh.store.getState === "function") {
      const currentState = mcpMesh.store.getState();
      const currentSelectionStateID = (currentState == null ? void 0 : currentState.selectionStateID) ?? "";
      const currentBounds = getActiveSelectionBounds();
      if (currentSelectionStateID !== lastSelectionStateIDFrame) {
        lastSelectionStateIDFrame = currentSelectionStateID;
      } else if (!!currentBounds !== !!lastFrameSelectionBounds || currentBounds && lastFrameSelectionBounds && (currentBounds.left != lastFrameSelectionBounds.left || currentBounds.top != lastFrameSelectionBounds.top || currentBounds.right != lastFrameSelectionBounds.right || currentBounds.bottom != lastFrameSelectionBounds.bottom)) {
        selectionAreaID++;
        lastSelectionStateIDFrame = notifySelectionStateChange();
      }
      lastFrameSelectionBounds = currentBounds;
    }
    const currentDocId = ((_a3 = photoshop.app.activeDocument) == null ? void 0 : _a3.id) || 0;
    const activeLayers = (_b2 = photoshop.app.activeDocument) == null ? void 0 : _b2.activeLayers.map((layer) => layer.id).join(",");
    if (lastCurrentDocumentID != currentDocId) {
      lastCurrentDocumentID = currentDocId;
      mcpMesh.store.setState({
        activeDocumentID: currentDocId
      });
      updateDocumentState();
      fetchDocuments();
      notifySelectionStateChange();
    }
    if (lastCurrentLayerID != activeLayers) {
      lastCurrentLayerID = activeLayers;
      notifyLayerChange();
      notifySelectionStateChange();
    }
  } catch (e4) {
    console.error("checkCurrentDocument error:", e4);
  }
  requestAnimationFrame(checkCurrentDocument);
}
requestAnimationFrame(checkCurrentDocument);
lastSelectionStateIDFrame = notifySelectionStateChange();
lastFrameSelectionBounds = getActiveSelectionBounds();
setInterval(updateActions, 5e3);
setInterval(() => {
  updateDocumentState();
  fetchDocuments();
}, 5e3);
let debounceTimer = null;
let lastScheduledAt = 0;
let lastHandledCanvasStateID = void 0;
async function updateThumbnails() {
  try {
    const uxpState = mcpMesh.store.getState();
    const activeDocumentID = uxpState.activeDocumentID;
    if (!activeDocumentID) return;
    const sdkNode2 = mcpMesh.getNode("sdk");
    const sdkStoreState = sdkNode2.store.getState();
    const boundaryMap = sdkStoreState && sdkStoreState.workBoundaries || {};
    const boundaryRect = boundaryMap[activeDocumentID];
    if (!boundaryRect) {
      return;
    }
  } catch (e4) {
    console.warn("[thumbnail-store-maintain] updateThumbnails error", e4);
  }
}
function scheduleUpdate() {
  const now = Date.now();
  const remaining = 1e3 - (now - lastScheduledAt);
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
  debounceTimer = setTimeout(() => {
    lastScheduledAt = Date.now();
    updateThumbnails();
  }, remaining > 0 ? remaining : 0);
}
mcpMesh.store.subscribe((state, prev) => {
  const curr = state.canvasStateID;
  const prevId = prev == null ? void 0 : prev.canvasStateID;
  if (curr !== prevId && curr !== lastHandledCanvasStateID) {
    lastHandledCanvasStateID = curr;
    scheduleUpdate();
  }
});
scheduleUpdate();
window.addEventListener("message", async (event) => {
  if (event.data.channel === "mcp-mesh-router") {
    const { meshName, action } = event.data;
    const webview = event.source;
    if (meshName === "sdk" && action === "connect") {
      await connectSDK(webview);
      if (sdkConnectTimeout) {
        clearTimeout(sdkConnectTimeout);
        sdkConnectTimeout = null;
      }
      mcpMesh.store.setState({
        sdkWebviewConnectStatus: "connected"
      });
    } else if (meshName === "comfy" && action === "connect") {
      await connectComfy(webview);
      if (comfyConnectTimeout) {
        clearTimeout(comfyConnectTimeout);
        comfyConnectTimeout = null;
      }
      mcpMesh.store.setState({
        comfyWebviewConnectStatus: "connected"
      });
    }
  }
});
let sdkConnectTimeout = null;
function onSDKWebviewLoadStart() {
  mcpMesh.disconnect("sdk");
  mcpMesh.store.setState({
    sdkWebviewConnectStatus: "connecting"
  });
  sdkConnectTimeout = setTimeout(() => {
    mcpMesh.store.setState({
      sdkWebviewConnectStatus: "disconnected"
    });
  }, 8e3);
}
let comfyConnectTimeout = null;
function onComfyWebviewLoadStart() {
  mcpMesh.disconnect("comfy");
  if (!mcpMesh.store.getState().comfyURL) {
    mcpMesh.store.setState({
      comfyWebviewConnectStatus: "disconnected",
      comfyWebviewLoading: false,
      comfyWebviewLoadError: ""
    });
    return;
  }
  mcpMesh.store.setState({
    comfyWebviewConnectStatus: "connecting",
    comfyWebviewLoading: true,
    comfyWebviewLoadError: ""
  });
  if (comfyConnectTimeout) {
    clearTimeout(comfyConnectTimeout);
  }
  comfyConnectTimeout = setTimeout(() => {
    mcpMesh.store.setState({
      comfyWebviewConnectStatus: "disconnected",
      comfyWebviewLoadError: "Connection timed out",
      comfyWebviewLoading: false
    });
  }, 2e4);
}
function onComfyWebviewLoadStop() {
  mcpMesh.store.setState({
    comfyWebviewLoading: false
  });
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  mcpMesh,
  onComfyWebviewLoadStart,
  onComfyWebviewLoadStop,
  onSDKWebviewLoadStart
}, Symbol.toStringTag, { value: "Module" }));
const log$1 = sdpppLogger.extend("AuthingQRCode");
function AuthingQRCode() {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-6 rounded-lg shadow-lg w-full mx-auto", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center mb-6", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h2", { style: { color: "var(--uxp-host-text-color)" }, className: "text-2xl font-bold mb-4", children: "扫码登录" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
        lineNumber: 12,
        columnNumber: 13
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: { color: "var(--uxp-host-text-color-secondary)" }, className: "mb-4", children: "请使用手机扫描下方二维码进行登录" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
        lineNumber: 13,
        columnNumber: 13
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
      lineNumber: 11,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AuthingQRCodeLogic, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
      lineNumber: 16,
      columnNumber: 13
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
      lineNumber: 15,
      columnNumber: 9
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
    lineNumber: 10,
    columnNumber: 12
  }, this);
}
function AuthingQRCodeLogic() {
  const isLogin = useStore(mcpMesh.store, (state) => state.isLogin);
  const requestingLogin = useStore(mcpMesh.store, (state) => state.requestingLogin);
  const [qrcodeURL, setQrcodeURL] = reactExports.useState("");
  const [prevRequestingLogin, setPrevRequestingLogin] = reactExports.useState(false);
  const [qrStatus, setQrStatus] = reactExports.useState("loading");
  const buttonStyle = {
    backgroundColor: "var(--uxp-host-widget-hover-background-color)",
    color: "var(--uxp-host-text-color)",
    border: "1px solid var(--uxp-host-border-color)"
  };
  const containerStyle = {
    backgroundColor: "var(--uxp-host-background-color)"
  };
  const iconContainerStyle = {
    backgroundColor: "var(--uxp-host-widget-hover-background-color)"
  };
  const textColorStyle = {
    color: "var(--uxp-host-text-color)"
  };
  const secondaryTextColorStyle = {
    color: "var(--uxp-host-text-color-secondary)"
  };
  const StatusIcon = ({ children }) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center", style: iconContainerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { className: "w-8 h-8", style: textColorStyle, fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
    lineNumber: 55,
    columnNumber: 13
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
    lineNumber: 54,
    columnNumber: 9
  }, this);
  const generateAndPollQRCode = async () => {
    var _a3;
    setQrStatus("loading");
    setQrcodeURL("");
    try {
      for await (const { qrcodeURL: qrcodeURL2, status, userInfo } of ((_a3 = PSUXPInternalStore.getState().loginProvider) == null ? void 0 : _a3.loginByQRCode()) || []) {
        log$1({ qrcodeURL: qrcodeURL2, status, userInfo });
        setQrcodeURL(qrcodeURL2);
        setQrStatus(status);
        if (status === "success" && userInfo) {
          mcpMesh.store.setState({
            isLogin: true,
            token: userInfo.token || ""
          });
          break;
        } else if (status === "cancel" || status === "expired" || status === "error") {
          break;
        }
      }
    } catch (error) {
      console.error("Failed to generate QR code:", error);
      setQrStatus("error");
    }
  };
  reactExports.useEffect(() => {
    if (!isLogin && requestingLogin && !prevRequestingLogin) {
      generateAndPollQRCode();
    }
    setPrevRequestingLogin(requestingLogin);
  }, [isLogin, requestingLogin]);
  const handleRefresh = () => {
    generateAndPollQRCode();
  };
  const renderQRContent = () => {
    switch (qrStatus) {
      case "loading":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "animate-spin rounded-full h-12 w-12 border-b-2 mx-auto mb-4", style: { borderColor: "var(--uxp-host-text-color)" } }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 105,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: secondaryTextColorStyle, children: "正在生成二维码..." }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 106,
            columnNumber: 29
          }, this)
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 104,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 103,
          columnNumber: 21
        }, this);
      case "ready":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("img", { src: qrcodeURL, alt: "qrcode", className: "w-full h-full" }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 113,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 112,
          columnNumber: 21
        }, this);
      case "scanned":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(StatusIcon, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 121,
            columnNumber: 33
          }, this) }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 120,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: textColorStyle, className: "font-medium mb-2", children: "已扫描" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 123,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: secondaryTextColorStyle, className: "text-sm", children: "请在手机上确认登录" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 124,
            columnNumber: 29
          }, this)
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 119,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 118,
          columnNumber: 21
        }, this);
      case "expired":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(StatusIcon, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 133,
            columnNumber: 33
          }, this) }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 132,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: textColorStyle, className: "font-medium mb-2", children: "二维码已过期" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 135,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: secondaryTextColorStyle, className: "text-sm mb-4", children: "请点击刷新重新生成" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 136,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              onClick: handleRefresh,
              style: buttonStyle,
              className: "px-4 py-2 rounded-lg transition-colors hover:opacity-80 text-sm",
              children: "刷新二维码"
            },
            void 0,
            false,
            {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
              lineNumber: 137,
              columnNumber: 29
            },
            this
          )
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 131,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 130,
          columnNumber: 21
        }, this);
      case "error":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(StatusIcon, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 152,
            columnNumber: 33
          }, this) }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 151,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: textColorStyle, className: "font-medium mb-2", children: "生成失败" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 154,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: secondaryTextColorStyle, className: "text-sm mb-4", children: "请检查网络连接后重试" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 155,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              onClick: handleRefresh,
              style: buttonStyle,
              className: "px-4 py-2 rounded-lg transition-colors hover:opacity-80 text-sm",
              children: "重新生成"
            },
            void 0,
            false,
            {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
              lineNumber: 156,
              columnNumber: 29
            },
            this
          )
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 150,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 149,
          columnNumber: 21
        }, this);
      case "cancel":
        return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-64 h-64 rounded-lg flex items-center justify-center", style: containerStyle, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(StatusIcon, { children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M6 18L18 6M6 6l12 12" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 171,
            columnNumber: 33
          }, this) }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 170,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: textColorStyle, className: "font-medium mb-2", children: "已取消" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 173,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: secondaryTextColorStyle, className: "text-sm mb-4", children: "扫码登录已取消" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
            lineNumber: 174,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            "button",
            {
              onClick: handleRefresh,
              style: buttonStyle,
              className: "px-4 py-2 rounded-lg transition-colors hover:opacity-80 text-sm",
              children: "重新扫码"
            },
            void 0,
            false,
            {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
              lineNumber: 175,
              columnNumber: 29
            },
            this
          )
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 169,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/Login/AuthingQRCode.tsx",
          lineNumber: 168,
          columnNumber: 21
        }, this);
      default:
        return null;
    }
  };
  return renderQRContent();
}
function AuthingLoginDialog() {
  var _a3;
  const requestingLogin = useStore(mcpMesh.store, (state) => state.requestingLogin);
  const isLogin = useStore(mcpMesh.store, (state) => state.isLogin);
  const isGuest = useStore(mcpMesh.store, (state) => state.isGuest);
  const token = useStore(mcpMesh.store, (state) => state.token);
  const userInfo = useStore(mcpMesh.store, (state) => state.userInfo);
  reactExports.useEffect(() => {
    var _a4;
    if (isLogin && token && !userInfo) {
      (_a4 = PSUXPInternalStore.getState().loginProvider) == null ? void 0 : _a4.validateToken(token).then((result) => {
        if (!result.username) {
          throw new Error("Invalid token");
        }
        mcpMesh.store.setState({
          userInfo: {
            username: result.username || "",
            email: result.email || ""
          }
        });
      }).catch((error) => {
        mcpMesh.store.setState({
          isLogin: false,
          userInfo: {},
          token: ""
        });
      });
    }
  }, [isLogin, token, userInfo]);
  const handleLogout = () => {
    mcpMesh.store.setState({
      isLogin: false,
      isGuest: false,
      userInfo: {},
      token: ""
    });
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(BaseDialog, { className: "w-[25rem] h-[30rem]", show: requestingLogin, setShow: () => {
    mcpMesh.store.setState({ requestingLogin: false });
  }, children: isLogin || isGuest ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-6 rounded-lg shadow-lg w-full mx-auto", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center mb-6", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h2", { style: { color: "var(--uxp-host-text-color)" }, className: "text-2xl font-bold mb-2", children: t("auth.login_success") }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
        lineNumber: 56,
        columnNumber: 29
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { style: { color: "var(--uxp-host-text-color-secondary)" }, children: [
        isGuest ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { className: "mb-1", children: t("auth.guest_login_success") }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
          lineNumber: 58,
          columnNumber: 44
        }, this) : (userInfo == null ? void 0 : userInfo.username) && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { className: "mb-1", children: t("auth.username_label", { username: userInfo.username }) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
          lineNumber: 59,
          columnNumber: 37
        }, this),
        !isGuest && (userInfo == null ? void 0 : userInfo.email) && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { className: "mb-1", children: t("auth.email_label", { email: userInfo.email }) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
          lineNumber: 62,
          columnNumber: 37
        }, this)
      ] }, void 0, true, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
        lineNumber: 57,
        columnNumber: 29
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
      lineNumber: 55,
      columnNumber: 25
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "button",
      {
        onClick: handleLogout,
        style: {
          backgroundColor: "var(--uxp-host-widget-hover-background-color)",
          color: "var(--uxp-host-text-color)",
          border: "1px solid var(--uxp-host-border-color)"
        },
        className: "px-6 py-2 rounded-lg transition-colors hover:opacity-80",
        children: t("auth.logout")
      },
      void 0,
      false,
      {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
        lineNumber: 67,
        columnNumber: 29
      },
      this
    ) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
      lineNumber: 66,
      columnNumber: 25
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
    lineNumber: 54,
    columnNumber: 21
  }, this) : ((_a3 = PSUXPInternalStore.getState().loginProvider) == null ? void 0 : _a3.isQRCodeSupported()) ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AuthingQRCode, {}, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
    lineNumber: 81,
    columnNumber: 88
  }, this) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center justify-center h-full", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("p", { style: { color: "var(--uxp-host-text-color)" }, children: t("auth.login_required") }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
    lineNumber: 82,
    columnNumber: 25
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
    lineNumber: 81,
    columnNumber: 108
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AuthingLoginDialog.tsx",
    lineNumber: 49,
    columnNumber: 9
  }, this);
}
function About() {
  const [html, setHtml] = reactExports.useState("");
  reactExports.useEffect(() => {
    const data2 = loadRemoteConfig("sponsors");
    setHtml(data2[getCurrentLanguage() === "zh-CN" ? "zh" : "en"]);
  }, []);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "h-full", dangerouslySetInnerHTML: { __html: html } }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/About/index.tsx",
    lineNumber: 11,
    columnNumber: 12
  }, this);
}
const AboutDialogStore = createStore((set) => ({
  show: false
}));
function AboutDialog() {
  const show = useStore(AboutDialogStore, (state) => state.show);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(BaseDialog, { className: "w-[20rem] h-[40rem] p-8", show, setShow: (show2) => {
    AboutDialogStore.setState({ show: show2 });
  }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-full h-full", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(About, {}, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AboutDialog.tsx",
    lineNumber: 17,
    columnNumber: 13
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AboutDialog.tsx",
    lineNumber: 16,
    columnNumber: 9
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/AboutDialog.tsx",
    lineNumber: 13,
    columnNumber: 12
  }, this);
}
const ComfyConnectDialogStore = createStore(() => ({
  show: false
}));
function openComfyConnectDialog() {
  ComfyConnectDialogStore.setState({ show: true });
}
function closeComfyConnectDialog() {
  ComfyConnectDialogStore.setState({ show: false });
}
function ComfyConnectDialog() {
  const show = useStore(ComfyConnectDialogStore, (state) => state.show);
  const connection = useComfyConnectionState();
  const [inputUrl, setInputUrl] = reactExports.useState("");
  reactExports.useEffect(() => {
    setInputUrl(connection.comfyURL ?? "");
  }, [connection.comfyURL, show]);
  reactExports.useEffect(() => {
    const key2 = "comfy-connect-tail";
    PSUXPInternalStore.setState((state) => {
      const others = state.headerTailElems.filter((elem) => (elem == null ? void 0 : elem.key) !== key2);
      return {
        headerTailElems: [...others, /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(HeaderTailElem$1, {}, key2, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 37,
          columnNumber: 46
        }, this)]
      };
    });
    return () => {
      PSUXPInternalStore.setState((state) => ({
        headerTailElems: state.headerTailElems.filter((elem) => (elem == null ? void 0 : elem.key) !== key2)
      }));
    };
  }, []);
  const handleConnect = reactExports.useCallback(() => {
    const next = inputUrl.trim();
    if (next) {
      connection.doConnect(next);
    }
  }, [connection, inputUrl]);
  const handleDisconnect = reactExports.useCallback(() => {
    connection.doDisconnect();
  }, [connection]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    BaseDialog,
    {
      className: "w-[28rem] p-4",
      show,
      setShow: (value) => {
        if (!value) {
          closeComfyConnectDialog();
        }
      },
      children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-[var(--uxp-host-text-color)]", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 rounded-md mb-2", children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-lg font-semibold mb-3", style: { color: "var(--uxp-host-text-color)" }, children: "连接指定地址" }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 71,
          columnNumber: 21
        }, this),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          AddressBar$1,
          {
            connectState: connection.connectState,
            connectionError: connection.connectionError,
            inputUrl,
            setInputUrl,
            onConnect: handleConnect,
            onDisconnect: handleDisconnect
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
            lineNumber: 74,
            columnNumber: 21
          },
          this
        )
      ] }, void 0, true, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
        lineNumber: 70,
        columnNumber: 17
      }, this) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
        lineNumber: 69,
        columnNumber: 13
      }, this)
    },
    void 0,
    false,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
      lineNumber: 60,
      columnNumber: 9
    },
    this
  );
}
function AddressBar$1({
  connectState,
  connectionError,
  inputUrl,
  setInputUrl,
  onConnect,
  onDisconnect
}) {
  const dotClass = connectState === "connected" ? "bg-emerald-300" : connectState === "connecting" ? "bg-yellow-300" : "bg-rose-300";
  const inputDisabled = connectState === "connected" || connectState === "connecting";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center mb-3", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: `w-3 h-3 rounded-full ${dotClass}` }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
        lineNumber: 114,
        columnNumber: 17
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-textfield",
        {
          id: "comfy-url-field",
          label: "backendURL",
          value: inputUrl,
          placeholder: "http://127.0.0.1:8000",
          onInput: (event) => setInputUrl(event.currentTarget.value),
          ...inputDisabled ? { disabled: true } : {},
          class: "flex-1 m-2"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 115,
          columnNumber: 17
        },
        this
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-action-button",
        {
          id: "comfy-connect-btn",
          onClick: () => {
            if (connectState === "disconnected") {
              onConnect();
            } else {
              onDisconnect();
            }
          },
          class: "px-3 py-2 rounded min-w-[2.5rem] flex items-center justify-center",
          children: connectState !== "disconnected" ? "⊗" : "→"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 124,
          columnNumber: 17
        },
        this
      )
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
      lineNumber: 113,
      columnNumber: 13
    }, this),
    connectionError ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "mt-2", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-red-500 text-sm", children: connectionError }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
      lineNumber: 141,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
      lineNumber: 140,
      columnNumber: 17
    }, this) : null
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
    lineNumber: 112,
    columnNumber: 9
  }, this);
}
function useComfyConnectionState() {
  const comfyURL = useStore(mcpMesh.store, (state) => state.comfyURL);
  const comfyWebviewLoading = useStore(mcpMesh.store, (state) => state.comfyWebviewLoading);
  const comfyWebviewLoadError = useStore(mcpMesh.store, (state) => state.comfyWebviewLoadError);
  const comfyWebviewConnectStatus = useStore(mcpMesh.store, (state) => state.comfyWebviewConnectStatus);
  const comfyWSState = useStore(mcpMesh.getNode("comfy").store, (state) => state.comfyWSState);
  const comfyWebviewVersion = useStore(mcpMesh.store, (state) => state.comfyWebviewVersion);
  return reactExports.useMemo(() => {
    let state = "disconnected";
    let error = "";
    let warning = "";
    if (comfyWebviewLoadError) {
      error = comfyWebviewLoadError;
    } else if (comfyWebviewLoading || comfyWebviewConnectStatus === "connecting") {
      state = "connecting";
    } else if (comfyWSState === "reconnecting") {
      state = "reconnecting";
    } else if (comfyURL) {
      state = "connected";
    }
    if (!error && state === "connected" && comfyWebviewVersion && true && comfyWebviewVersion !== "510") {
      warning = `Comfy 侧 SDPPP 版本（${comfyWebviewVersion}）与插件（${"510"}）不匹配`;
    }
    return {
      comfyURL,
      comfyWebviewVersion,
      connectState: state,
      connectionError: error,
      connectionWarning: warning,
      doConnect: (url) => mcpMesh.actions.setComfyWebviewURL({ url }),
      doDisconnect: () => mcpMesh.actions.setComfyWebviewURL({ url: "" })
    };
  }, [
    comfyURL,
    comfyWebviewConnectStatus,
    comfyWebviewLoadError,
    comfyWebviewLoading,
    comfyWebviewVersion,
    comfyWSState
  ]);
}
function HeaderTailElem$1() {
  const { connectState } = useComfyConnectionState();
  const dotClass = connectState === "connected" ? "bg-emerald-300" : connectState === "connecting" ? "bg-yellow-300" : "bg-rose-300";
  const label = connectState === "connected" ? "comfy已连接" : connectState === "connecting" ? "comfy连接中" : connectState === "reconnecting" ? "comfy重连中" : "comfy未连接";
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      className: "flex items-center mr-2 cursor-pointer",
      onClick: (event) => {
        event.stopPropagation();
        openComfyConnectDialog();
      },
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: `w-3 h-3 rounded-full mr-1 ${dotClass}` }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 221,
          columnNumber: 13
        }, this),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: "text-xs underline", style: { color: "var(--uxp-host-text-color)" }, children: label }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
          lineNumber: 222,
          columnNumber: 13
        }, this)
      ]
    },
    void 0,
    true,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/ComfyConnectDialog.tsx",
      lineNumber: 214,
      columnNumber: 9
    },
    this
  );
}
var Subscribable = class {
  constructor() {
    this.listeners = /* @__PURE__ */ new Set();
    this.subscribe = this.subscribe.bind(this);
  }
  subscribe(listener) {
    this.listeners.add(listener);
    this.onSubscribe();
    return () => {
      this.listeners.delete(listener);
      this.onUnsubscribe();
    };
  }
  hasListeners() {
    return this.listeners.size > 0;
  }
  onSubscribe() {
  }
  onUnsubscribe() {
  }
};
var defaultTimeoutProvider = {
  // We need the wrapper function syntax below instead of direct references to
  // global setTimeout etc.
  //
  // BAD: `setTimeout: setTimeout`
  // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
  //
  // If we use direct references here, then anything that wants to spy on or
  // replace the global setTimeout (like tests) won't work since we'll already
  // have a hard reference to the original implementation at the time when this
  // file was imported.
  setTimeout: (callback, delay) => setTimeout(callback, delay),
  clearTimeout: (timeoutId) => clearTimeout(timeoutId),
  setInterval: (callback, delay) => setInterval(callback, delay),
  clearInterval: (intervalId) => clearInterval(intervalId)
};
var TimeoutManager = (_c = class {
  constructor() {
    // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
    // type at app boot; and if we leave that type, then any new timer provider
    // would need to support ReturnType<typeof setTimeout>, which is infeasible.
    //
    // We settle for type safety for the TimeoutProvider type, and accept that
    // this class is unsafe internally to allow for extension.
    __privateAdd(this, _provider, defaultTimeoutProvider);
    __privateAdd(this, _providerCalled, false);
  }
  setTimeoutProvider(provider) {
    {
      if (__privateGet(this, _providerCalled) && provider !== __privateGet(this, _provider)) {
        console.error(
          `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
          { previous: __privateGet(this, _provider), provider }
        );
      }
    }
    __privateSet(this, _provider, provider);
    {
      __privateSet(this, _providerCalled, false);
    }
  }
  setTimeout(callback, delay) {
    {
      __privateSet(this, _providerCalled, true);
    }
    return __privateGet(this, _provider).setTimeout(callback, delay);
  }
  clearTimeout(timeoutId) {
    __privateGet(this, _provider).clearTimeout(timeoutId);
  }
  setInterval(callback, delay) {
    {
      __privateSet(this, _providerCalled, true);
    }
    return __privateGet(this, _provider).setInterval(callback, delay);
  }
  clearInterval(intervalId) {
    __privateGet(this, _provider).clearInterval(intervalId);
  }
}, _provider = new WeakMap(), _providerCalled = new WeakMap(), _c);
var timeoutManager = new TimeoutManager();
function systemSetTimeoutZero(callback) {
  setTimeout(callback, 0);
}
var isServer = typeof window === "undefined" || "Deno" in globalThis;
function noop() {
}
function functionalUpdate(updater, input) {
  return typeof updater === "function" ? updater(input) : updater;
}
function isValidTimeout(value) {
  return typeof value === "number" && value >= 0 && value !== Infinity;
}
function timeUntilStale(updatedAt, staleTime) {
  return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
}
function resolveStaleTime(staleTime, query) {
  return typeof staleTime === "function" ? staleTime(query) : staleTime;
}
function resolveEnabled(enabled, query) {
  return typeof enabled === "function" ? enabled(query) : enabled;
}
function matchQuery(filters, query) {
  const {
    type: type2 = "all",
    exact,
    fetchStatus,
    predicate,
    queryKey,
    stale
  } = filters;
  if (queryKey) {
    if (exact) {
      if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
        return false;
      }
    } else if (!partialMatchKey(query.queryKey, queryKey)) {
      return false;
    }
  }
  if (type2 !== "all") {
    const isActive = query.isActive();
    if (type2 === "active" && !isActive) {
      return false;
    }
    if (type2 === "inactive" && isActive) {
      return false;
    }
  }
  if (typeof stale === "boolean" && query.isStale() !== stale) {
    return false;
  }
  if (fetchStatus && fetchStatus !== query.state.fetchStatus) {
    return false;
  }
  if (predicate && !predicate(query)) {
    return false;
  }
  return true;
}
function matchMutation(filters, mutation) {
  const { exact, status, predicate, mutationKey } = filters;
  if (mutationKey) {
    if (!mutation.options.mutationKey) {
      return false;
    }
    if (exact) {
      if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
        return false;
      }
    } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
      return false;
    }
  }
  if (status && mutation.state.status !== status) {
    return false;
  }
  if (predicate && !predicate(mutation)) {
    return false;
  }
  return true;
}
function hashQueryKeyByOptions(queryKey, options2) {
  const hashFn = (options2 == null ? void 0 : options2.queryKeyHashFn) || hashKey;
  return hashFn(queryKey);
}
function hashKey(queryKey) {
  return JSON.stringify(
    queryKey,
    (_2, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key2) => {
      result[key2] = val[key2];
      return result;
    }, {}) : val
  );
}
function partialMatchKey(a2, b2) {
  if (a2 === b2) {
    return true;
  }
  if (typeof a2 !== typeof b2) {
    return false;
  }
  if (a2 && b2 && typeof a2 === "object" && typeof b2 === "object") {
    return Object.keys(b2).every((key2) => partialMatchKey(a2[key2], b2[key2]));
  }
  return false;
}
var hasOwn = Object.prototype.hasOwnProperty;
function replaceEqualDeep(a2, b2) {
  if (a2 === b2) {
    return a2;
  }
  const array = isPlainArray(a2) && isPlainArray(b2);
  if (!array && !(isPlainObject(a2) && isPlainObject(b2))) return b2;
  const aItems = array ? a2 : Object.keys(a2);
  const aSize = aItems.length;
  const bItems = array ? b2 : Object.keys(b2);
  const bSize = bItems.length;
  const copy2 = array ? new Array(bSize) : {};
  let equalItems = 0;
  for (let i2 = 0; i2 < bSize; i2++) {
    const key2 = array ? i2 : bItems[i2];
    const aItem = a2[key2];
    const bItem = b2[key2];
    if (aItem === bItem) {
      copy2[key2] = aItem;
      if (array ? i2 < aSize : hasOwn.call(a2, key2)) equalItems++;
      continue;
    }
    if (aItem === null || bItem === null || typeof aItem !== "object" || typeof bItem !== "object") {
      copy2[key2] = bItem;
      continue;
    }
    const v2 = replaceEqualDeep(aItem, bItem);
    copy2[key2] = v2;
    if (v2 === aItem) equalItems++;
  }
  return aSize === bSize && equalItems === aSize ? a2 : copy2;
}
function shallowEqualObjects(a2, b2) {
  if (!b2 || Object.keys(a2).length !== Object.keys(b2).length) {
    return false;
  }
  for (const key2 in a2) {
    if (a2[key2] !== b2[key2]) {
      return false;
    }
  }
  return true;
}
function isPlainArray(value) {
  return Array.isArray(value) && value.length === Object.keys(value).length;
}
function isPlainObject(o2) {
  if (!hasObjectPrototype(o2)) {
    return false;
  }
  const ctor = o2.constructor;
  if (ctor === void 0) {
    return true;
  }
  const prot = ctor.prototype;
  if (!hasObjectPrototype(prot)) {
    return false;
  }
  if (!prot.hasOwnProperty("isPrototypeOf")) {
    return false;
  }
  if (Object.getPrototypeOf(o2) !== Object.prototype) {
    return false;
  }
  return true;
}
function hasObjectPrototype(o2) {
  return Object.prototype.toString.call(o2) === "[object Object]";
}
function sleep(timeout) {
  return new Promise((resolve2) => {
    timeoutManager.setTimeout(resolve2, timeout);
  });
}
function replaceData(prevData, data2, options2) {
  if (typeof options2.structuralSharing === "function") {
    return options2.structuralSharing(prevData, data2);
  } else if (options2.structuralSharing !== false) {
    {
      try {
        return replaceEqualDeep(prevData, data2);
      } catch (error) {
        console.error(
          `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options2.queryHash}]: ${error}`
        );
        throw error;
      }
    }
    return replaceEqualDeep(prevData, data2);
  }
  return data2;
}
function addToEnd(items2, item, max2 = 0) {
  const newItems = [...items2, item];
  return max2 && newItems.length > max2 ? newItems.slice(1) : newItems;
}
function addToStart(items2, item, max2 = 0) {
  const newItems = [item, ...items2];
  return max2 && newItems.length > max2 ? newItems.slice(0, -1) : newItems;
}
var skipToken = Symbol();
function ensureQueryFn(options2, fetchOptions) {
  {
    if (options2.queryFn === skipToken) {
      console.error(
        `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options2.queryHash}'`
      );
    }
  }
  if (!options2.queryFn && (fetchOptions == null ? void 0 : fetchOptions.initialPromise)) {
    return () => fetchOptions.initialPromise;
  }
  if (!options2.queryFn || options2.queryFn === skipToken) {
    return () => Promise.reject(new Error(`Missing queryFn: '${options2.queryHash}'`));
  }
  return options2.queryFn;
}
function shouldThrowError(throwOnError, params) {
  if (typeof throwOnError === "function") {
    return throwOnError(...params);
  }
  return !!throwOnError;
}
var FocusManager = (_d = class extends Subscribable {
  constructor() {
    super();
    __privateAdd(this, _focused);
    __privateAdd(this, _cleanup);
    __privateAdd(this, _setup);
    __privateSet(this, _setup, (onFocus) => {
      if (!isServer && window.addEventListener) {
        const listener = () => onFocus();
        window.addEventListener("visibilitychange", listener, false);
        return () => {
          window.removeEventListener("visibilitychange", listener);
        };
      }
      return;
    });
  }
  onSubscribe() {
    if (!__privateGet(this, _cleanup)) {
      this.setEventListener(__privateGet(this, _setup));
    }
  }
  onUnsubscribe() {
    var _a3;
    if (!this.hasListeners()) {
      (_a3 = __privateGet(this, _cleanup)) == null ? void 0 : _a3.call(this);
      __privateSet(this, _cleanup, void 0);
    }
  }
  setEventListener(setup) {
    var _a3;
    __privateSet(this, _setup, setup);
    (_a3 = __privateGet(this, _cleanup)) == null ? void 0 : _a3.call(this);
    __privateSet(this, _cleanup, setup((focused) => {
      if (typeof focused === "boolean") {
        this.setFocused(focused);
      } else {
        this.onFocus();
      }
    }));
  }
  setFocused(focused) {
    const changed = __privateGet(this, _focused) !== focused;
    if (changed) {
      __privateSet(this, _focused, focused);
      this.onFocus();
    }
  }
  onFocus() {
    const isFocused = this.isFocused();
    this.listeners.forEach((listener) => {
      listener(isFocused);
    });
  }
  isFocused() {
    var _a3;
    if (typeof __privateGet(this, _focused) === "boolean") {
      return __privateGet(this, _focused);
    }
    return ((_a3 = globalThis.document) == null ? void 0 : _a3.visibilityState) !== "hidden";
  }
}, _focused = new WeakMap(), _cleanup = new WeakMap(), _setup = new WeakMap(), _d);
var focusManager = new FocusManager();
function pendingThenable() {
  let resolve2;
  let reject2;
  const thenable = new Promise((_resolve, _reject) => {
    resolve2 = _resolve;
    reject2 = _reject;
  });
  thenable.status = "pending";
  thenable.catch(() => {
  });
  function finalize(data2) {
    Object.assign(thenable, data2);
    delete thenable.resolve;
    delete thenable.reject;
  }
  thenable.resolve = (value) => {
    finalize({
      status: "fulfilled",
      value
    });
    resolve2(value);
  };
  thenable.reject = (reason) => {
    finalize({
      status: "rejected",
      reason
    });
    reject2(reason);
  };
  return thenable;
}
var defaultScheduler = systemSetTimeoutZero;
function createNotifyManager() {
  let queue = [];
  let transactions = 0;
  let notifyFn = (callback) => {
    callback();
  };
  let batchNotifyFn = (callback) => {
    callback();
  };
  let scheduleFn = defaultScheduler;
  const schedule = (callback) => {
    if (transactions) {
      queue.push(callback);
    } else {
      scheduleFn(() => {
        notifyFn(callback);
      });
    }
  };
  const flush = () => {
    const originalQueue = queue;
    queue = [];
    if (originalQueue.length) {
      scheduleFn(() => {
        batchNotifyFn(() => {
          originalQueue.forEach((callback) => {
            notifyFn(callback);
          });
        });
      });
    }
  };
  return {
    batch: (callback) => {
      let result;
      transactions++;
      try {
        result = callback();
      } finally {
        transactions--;
        if (!transactions) {
          flush();
        }
      }
      return result;
    },
    /**
     * All calls to the wrapped function will be batched.
     */
    batchCalls: (callback) => {
      return (...args) => {
        schedule(() => {
          callback(...args);
        });
      };
    },
    schedule,
    /**
     * Use this method to set a custom notify function.
     * This can be used to for example wrap notifications with `React.act` while running tests.
     */
    setNotifyFunction: (fn) => {
      notifyFn = fn;
    },
    /**
     * Use this method to set a custom function to batch notifications together into a single tick.
     * By default React Query will use the batch function provided by ReactDOM or React Native.
     */
    setBatchNotifyFunction: (fn) => {
      batchNotifyFn = fn;
    },
    setScheduler: (fn) => {
      scheduleFn = fn;
    }
  };
}
var notifyManager = createNotifyManager();
var OnlineManager = (_e = class extends Subscribable {
  constructor() {
    super();
    __privateAdd(this, _online, true);
    __privateAdd(this, _cleanup2);
    __privateAdd(this, _setup2);
    __privateSet(this, _setup2, (onOnline) => {
      if (!isServer && window.addEventListener) {
        const onlineListener = () => onOnline(true);
        const offlineListener = () => onOnline(false);
        window.addEventListener("online", onlineListener, false);
        window.addEventListener("offline", offlineListener, false);
        return () => {
          window.removeEventListener("online", onlineListener);
          window.removeEventListener("offline", offlineListener);
        };
      }
      return;
    });
  }
  onSubscribe() {
    if (!__privateGet(this, _cleanup2)) {
      this.setEventListener(__privateGet(this, _setup2));
    }
  }
  onUnsubscribe() {
    var _a3;
    if (!this.hasListeners()) {
      (_a3 = __privateGet(this, _cleanup2)) == null ? void 0 : _a3.call(this);
      __privateSet(this, _cleanup2, void 0);
    }
  }
  setEventListener(setup) {
    var _a3;
    __privateSet(this, _setup2, setup);
    (_a3 = __privateGet(this, _cleanup2)) == null ? void 0 : _a3.call(this);
    __privateSet(this, _cleanup2, setup(this.setOnline.bind(this)));
  }
  setOnline(online) {
    const changed = __privateGet(this, _online) !== online;
    if (changed) {
      __privateSet(this, _online, online);
      this.listeners.forEach((listener) => {
        listener(online);
      });
    }
  }
  isOnline() {
    return __privateGet(this, _online);
  }
}, _online = new WeakMap(), _cleanup2 = new WeakMap(), _setup2 = new WeakMap(), _e);
var onlineManager = new OnlineManager();
function defaultRetryDelay(failureCount) {
  return Math.min(1e3 * 2 ** failureCount, 3e4);
}
function canFetch(networkMode) {
  return (networkMode ?? "online") === "online" ? onlineManager.isOnline() : true;
}
var CancelledError = class extends Error {
  constructor(options2) {
    super("CancelledError");
    this.revert = options2 == null ? void 0 : options2.revert;
    this.silent = options2 == null ? void 0 : options2.silent;
  }
};
function createRetryer(config) {
  let isRetryCancelled = false;
  let failureCount = 0;
  let continueFn;
  const thenable = pendingThenable();
  const isResolved = () => thenable.status !== "pending";
  const cancel = (cancelOptions) => {
    var _a3;
    if (!isResolved()) {
      const error = new CancelledError(cancelOptions);
      reject2(error);
      (_a3 = config.onCancel) == null ? void 0 : _a3.call(config, error);
    }
  };
  const cancelRetry = () => {
    isRetryCancelled = true;
  };
  const continueRetry = () => {
    isRetryCancelled = false;
  };
  const canContinue = () => focusManager.isFocused() && (config.networkMode === "always" || onlineManager.isOnline()) && config.canRun();
  const canStart = () => canFetch(config.networkMode) && config.canRun();
  const resolve2 = (value) => {
    if (!isResolved()) {
      continueFn == null ? void 0 : continueFn();
      thenable.resolve(value);
    }
  };
  const reject2 = (value) => {
    if (!isResolved()) {
      continueFn == null ? void 0 : continueFn();
      thenable.reject(value);
    }
  };
  const pause = () => {
    return new Promise((continueResolve) => {
      var _a3;
      continueFn = (value) => {
        if (isResolved() || canContinue()) {
          continueResolve(value);
        }
      };
      (_a3 = config.onPause) == null ? void 0 : _a3.call(config);
    }).then(() => {
      var _a3;
      continueFn = void 0;
      if (!isResolved()) {
        (_a3 = config.onContinue) == null ? void 0 : _a3.call(config);
      }
    });
  };
  const run = () => {
    if (isResolved()) {
      return;
    }
    let promiseOrValue;
    const initialPromise = failureCount === 0 ? config.initialPromise : void 0;
    try {
      promiseOrValue = initialPromise ?? config.fn();
    } catch (error) {
      promiseOrValue = Promise.reject(error);
    }
    Promise.resolve(promiseOrValue).then(resolve2).catch((error) => {
      var _a3;
      if (isResolved()) {
        return;
      }
      const retry = config.retry ?? (isServer ? 0 : 3);
      const retryDelay = config.retryDelay ?? defaultRetryDelay;
      const delay = typeof retryDelay === "function" ? retryDelay(failureCount, error) : retryDelay;
      const shouldRetry = retry === true || typeof retry === "number" && failureCount < retry || typeof retry === "function" && retry(failureCount, error);
      if (isRetryCancelled || !shouldRetry) {
        reject2(error);
        return;
      }
      failureCount++;
      (_a3 = config.onFail) == null ? void 0 : _a3.call(config, failureCount, error);
      sleep(delay).then(() => {
        return canContinue() ? void 0 : pause();
      }).then(() => {
        if (isRetryCancelled) {
          reject2(error);
        } else {
          run();
        }
      });
    });
  };
  return {
    promise: thenable,
    status: () => thenable.status,
    cancel,
    continue: () => {
      continueFn == null ? void 0 : continueFn();
      return thenable;
    },
    cancelRetry,
    continueRetry,
    canStart,
    start: () => {
      if (canStart()) {
        run();
      } else {
        pause().then(run);
      }
      return thenable;
    }
  };
}
var Removable = (_f = class {
  constructor() {
    __privateAdd(this, _gcTimeout);
  }
  destroy() {
    this.clearGcTimeout();
  }
  scheduleGc() {
    this.clearGcTimeout();
    if (isValidTimeout(this.gcTime)) {
      __privateSet(this, _gcTimeout, timeoutManager.setTimeout(() => {
        this.optionalRemove();
      }, this.gcTime));
    }
  }
  updateGcTime(newGcTime) {
    this.gcTime = Math.max(
      this.gcTime || 0,
      newGcTime ?? (isServer ? Infinity : 5 * 60 * 1e3)
    );
  }
  clearGcTimeout() {
    if (__privateGet(this, _gcTimeout)) {
      timeoutManager.clearTimeout(__privateGet(this, _gcTimeout));
      __privateSet(this, _gcTimeout, void 0);
    }
  }
}, _gcTimeout = new WeakMap(), _f);
var Query = (_g = class extends Removable {
  constructor(config) {
    super();
    __privateAdd(this, _Query_instances);
    __privateAdd(this, _initialState);
    __privateAdd(this, _revertState);
    __privateAdd(this, _cache);
    __privateAdd(this, _client);
    __privateAdd(this, _retryer);
    __privateAdd(this, _defaultOptions);
    __privateAdd(this, _abortSignalConsumed);
    __privateSet(this, _abortSignalConsumed, false);
    __privateSet(this, _defaultOptions, config.defaultOptions);
    this.setOptions(config.options);
    this.observers = [];
    __privateSet(this, _client, config.client);
    __privateSet(this, _cache, __privateGet(this, _client).getQueryCache());
    this.queryKey = config.queryKey;
    this.queryHash = config.queryHash;
    __privateSet(this, _initialState, getDefaultState$1(this.options));
    this.state = config.state ?? __privateGet(this, _initialState);
    this.scheduleGc();
  }
  get meta() {
    return this.options.meta;
  }
  get promise() {
    var _a3;
    return (_a3 = __privateGet(this, _retryer)) == null ? void 0 : _a3.promise;
  }
  setOptions(options2) {
    this.options = { ...__privateGet(this, _defaultOptions), ...options2 };
    this.updateGcTime(this.options.gcTime);
    if (this.state && this.state.data === void 0) {
      const defaultState = getDefaultState$1(this.options);
      if (defaultState.data !== void 0) {
        this.setState(
          successState(defaultState.data, defaultState.dataUpdatedAt)
        );
        __privateSet(this, _initialState, defaultState);
      }
    }
  }
  optionalRemove() {
    if (!this.observers.length && this.state.fetchStatus === "idle") {
      __privateGet(this, _cache).remove(this);
    }
  }
  setData(newData, options2) {
    const data2 = replaceData(this.state.data, newData, this.options);
    __privateMethod(this, _Query_instances, dispatch_fn).call(this, {
      data: data2,
      type: "success",
      dataUpdatedAt: options2 == null ? void 0 : options2.updatedAt,
      manual: options2 == null ? void 0 : options2.manual
    });
    return data2;
  }
  setState(state, setStateOptions) {
    __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state, setStateOptions });
  }
  cancel(options2) {
    var _a3, _b2;
    const promise = (_a3 = __privateGet(this, _retryer)) == null ? void 0 : _a3.promise;
    (_b2 = __privateGet(this, _retryer)) == null ? void 0 : _b2.cancel(options2);
    return promise ? promise.then(noop).catch(noop) : Promise.resolve();
  }
  destroy() {
    super.destroy();
    this.cancel({ silent: true });
  }
  reset() {
    this.destroy();
    this.setState(__privateGet(this, _initialState));
  }
  isActive() {
    return this.observers.some(
      (observer) => resolveEnabled(observer.options.enabled, this) !== false
    );
  }
  isDisabled() {
    if (this.getObserversCount() > 0) {
      return !this.isActive();
    }
    return this.options.queryFn === skipToken || this.state.dataUpdateCount + this.state.errorUpdateCount === 0;
  }
  isStatic() {
    if (this.getObserversCount() > 0) {
      return this.observers.some(
        (observer) => resolveStaleTime(observer.options.staleTime, this) === "static"
      );
    }
    return false;
  }
  isStale() {
    if (this.getObserversCount() > 0) {
      return this.observers.some(
        (observer) => observer.getCurrentResult().isStale
      );
    }
    return this.state.data === void 0 || this.state.isInvalidated;
  }
  isStaleByTime(staleTime = 0) {
    if (this.state.data === void 0) {
      return true;
    }
    if (staleTime === "static") {
      return false;
    }
    if (this.state.isInvalidated) {
      return true;
    }
    return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
  }
  onFocus() {
    var _a3;
    const observer = this.observers.find((x2) => x2.shouldFetchOnWindowFocus());
    observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
    (_a3 = __privateGet(this, _retryer)) == null ? void 0 : _a3.continue();
  }
  onOnline() {
    var _a3;
    const observer = this.observers.find((x2) => x2.shouldFetchOnReconnect());
    observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
    (_a3 = __privateGet(this, _retryer)) == null ? void 0 : _a3.continue();
  }
  addObserver(observer) {
    if (!this.observers.includes(observer)) {
      this.observers.push(observer);
      this.clearGcTimeout();
      __privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer });
    }
  }
  removeObserver(observer) {
    if (this.observers.includes(observer)) {
      this.observers = this.observers.filter((x2) => x2 !== observer);
      if (!this.observers.length) {
        if (__privateGet(this, _retryer)) {
          if (__privateGet(this, _abortSignalConsumed)) {
            __privateGet(this, _retryer).cancel({ revert: true });
          } else {
            __privateGet(this, _retryer).cancelRetry();
          }
        }
        this.scheduleGc();
      }
      __privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer });
    }
  }
  getObserversCount() {
    return this.observers.length;
  }
  invalidate() {
    if (!this.state.isInvalidated) {
      __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" });
    }
  }
  async fetch(options2, fetchOptions) {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2;
    if (this.state.fetchStatus !== "idle" && // If the promise in the retyer is already rejected, we have to definitely
    // re-start the fetch; there is a chance that the query is still in a
    // pending state when that happens
    ((_a3 = __privateGet(this, _retryer)) == null ? void 0 : _a3.status()) !== "rejected") {
      if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
        this.cancel({ silent: true });
      } else if (__privateGet(this, _retryer)) {
        __privateGet(this, _retryer).continueRetry();
        return __privateGet(this, _retryer).promise;
      }
    }
    if (options2) {
      this.setOptions(options2);
    }
    if (!this.options.queryFn) {
      const observer = this.observers.find((x2) => x2.options.queryFn);
      if (observer) {
        this.setOptions(observer.options);
      }
    }
    {
      if (!Array.isArray(this.options.queryKey)) {
        console.error(
          `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`
        );
      }
    }
    const abortController = new AbortController();
    const addSignalProperty = (object) => {
      Object.defineProperty(object, "signal", {
        enumerable: true,
        get: () => {
          __privateSet(this, _abortSignalConsumed, true);
          return abortController.signal;
        }
      });
    };
    const fetchFn = () => {
      const queryFn = ensureQueryFn(this.options, fetchOptions);
      const createQueryFnContext = () => {
        const queryFnContext2 = {
          client: __privateGet(this, _client),
          queryKey: this.queryKey,
          meta: this.meta
        };
        addSignalProperty(queryFnContext2);
        return queryFnContext2;
      };
      const queryFnContext = createQueryFnContext();
      __privateSet(this, _abortSignalConsumed, false);
      if (this.options.persister) {
        return this.options.persister(
          queryFn,
          queryFnContext,
          this
        );
      }
      return queryFn(queryFnContext);
    };
    const createFetchContext = () => {
      const context2 = {
        fetchOptions,
        options: this.options,
        queryKey: this.queryKey,
        client: __privateGet(this, _client),
        state: this.state,
        fetchFn
      };
      addSignalProperty(context2);
      return context2;
    };
    const context = createFetchContext();
    (_b2 = this.options.behavior) == null ? void 0 : _b2.onFetch(context, this);
    __privateSet(this, _revertState, this.state);
    if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_c2 = context.fetchOptions) == null ? void 0 : _c2.meta)) {
      __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_d2 = context.fetchOptions) == null ? void 0 : _d2.meta });
    }
    __privateSet(this, _retryer, createRetryer({
      initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise,
      fn: context.fetchFn,
      onCancel: (error) => {
        if (error instanceof CancelledError && error.revert) {
          this.setState({
            ...__privateGet(this, _revertState),
            fetchStatus: "idle"
          });
        }
        abortController.abort();
      },
      onFail: (failureCount, error) => {
        __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
      },
      onPause: () => {
        __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" });
      },
      onContinue: () => {
        __privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" });
      },
      retry: context.options.retry,
      retryDelay: context.options.retryDelay,
      networkMode: context.options.networkMode,
      canRun: () => true
    }));
    try {
      const data2 = await __privateGet(this, _retryer).start();
      if (data2 === void 0) {
        if (true) {
          console.error(
            `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
          );
        }
        throw new Error(`${this.queryHash} data is undefined`);
      }
      this.setData(data2);
      (_f2 = (_e2 = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _f2.call(_e2, data2, this);
      (_h2 = (_g2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _h2.call(
        _g2,
        data2,
        this.state.error,
        this
      );
      return data2;
    } catch (error) {
      if (error instanceof CancelledError) {
        if (error.silent) {
          return __privateGet(this, _retryer).promise;
        } else if (error.revert) {
          if (this.state.data === void 0) {
            throw error;
          }
          return this.state.data;
        }
      }
      __privateMethod(this, _Query_instances, dispatch_fn).call(this, {
        type: "error",
        error
      });
      (_j2 = (_i2 = __privateGet(this, _cache).config).onError) == null ? void 0 : _j2.call(
        _i2,
        error,
        this
      );
      (_l2 = (_k2 = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _l2.call(
        _k2,
        this.state.data,
        error,
        this
      );
      throw error;
    } finally {
      this.scheduleGc();
    }
  }
}, _initialState = new WeakMap(), _revertState = new WeakMap(), _cache = new WeakMap(), _client = new WeakMap(), _retryer = new WeakMap(), _defaultOptions = new WeakMap(), _abortSignalConsumed = new WeakMap(), _Query_instances = new WeakSet(), dispatch_fn = function(action) {
  const reducer = (state) => {
    switch (action.type) {
      case "failed":
        return {
          ...state,
          fetchFailureCount: action.failureCount,
          fetchFailureReason: action.error
        };
      case "pause":
        return {
          ...state,
          fetchStatus: "paused"
        };
      case "continue":
        return {
          ...state,
          fetchStatus: "fetching"
        };
      case "fetch":
        return {
          ...state,
          ...fetchState(state.data, this.options),
          fetchMeta: action.meta ?? null
        };
      case "success":
        const newState = {
          ...state,
          ...successState(action.data, action.dataUpdatedAt),
          dataUpdateCount: state.dataUpdateCount + 1,
          ...!action.manual && {
            fetchStatus: "idle",
            fetchFailureCount: 0,
            fetchFailureReason: null
          }
        };
        __privateSet(this, _revertState, action.manual ? newState : void 0);
        return newState;
      case "error":
        const error = action.error;
        return {
          ...state,
          error,
          errorUpdateCount: state.errorUpdateCount + 1,
          errorUpdatedAt: Date.now(),
          fetchFailureCount: state.fetchFailureCount + 1,
          fetchFailureReason: error,
          fetchStatus: "idle",
          status: "error"
        };
      case "invalidate":
        return {
          ...state,
          isInvalidated: true
        };
      case "setState":
        return {
          ...state,
          ...action.state
        };
    }
  };
  this.state = reducer(this.state);
  notifyManager.batch(() => {
    this.observers.forEach((observer) => {
      observer.onQueryUpdate();
    });
    __privateGet(this, _cache).notify({ query: this, type: "updated", action });
  });
}, _g);
function fetchState(data2, options2) {
  return {
    fetchFailureCount: 0,
    fetchFailureReason: null,
    fetchStatus: canFetch(options2.networkMode) ? "fetching" : "paused",
    ...data2 === void 0 && {
      error: null,
      status: "pending"
    }
  };
}
function successState(data2, dataUpdatedAt) {
  return {
    data: data2,
    dataUpdatedAt: dataUpdatedAt ?? Date.now(),
    error: null,
    isInvalidated: false,
    status: "success"
  };
}
function getDefaultState$1(options2) {
  const data2 = typeof options2.initialData === "function" ? options2.initialData() : options2.initialData;
  const hasData = data2 !== void 0;
  const initialDataUpdatedAt = hasData ? typeof options2.initialDataUpdatedAt === "function" ? options2.initialDataUpdatedAt() : options2.initialDataUpdatedAt : 0;
  return {
    data: data2,
    dataUpdateCount: 0,
    dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
    error: null,
    errorUpdateCount: 0,
    errorUpdatedAt: 0,
    fetchFailureCount: 0,
    fetchFailureReason: null,
    fetchMeta: null,
    isInvalidated: false,
    status: hasData ? "success" : "pending",
    fetchStatus: "idle"
  };
}
var QueryObserver = (_h = class extends Subscribable {
  constructor(client2, options2) {
    super();
    __privateAdd(this, _QueryObserver_instances);
    __privateAdd(this, _client2);
    __privateAdd(this, _currentQuery);
    __privateAdd(this, _currentQueryInitialState);
    __privateAdd(this, _currentResult);
    __privateAdd(this, _currentResultState);
    __privateAdd(this, _currentResultOptions);
    __privateAdd(this, _currentThenable);
    __privateAdd(this, _selectError);
    __privateAdd(this, _selectFn);
    __privateAdd(this, _selectResult);
    // This property keeps track of the last query with defined data.
    // It will be used to pass the previous data and query to the placeholder function between renders.
    __privateAdd(this, _lastQueryWithDefinedData);
    __privateAdd(this, _staleTimeoutId);
    __privateAdd(this, _refetchIntervalId);
    __privateAdd(this, _currentRefetchInterval);
    __privateAdd(this, _trackedProps, /* @__PURE__ */ new Set());
    this.options = options2;
    __privateSet(this, _client2, client2);
    __privateSet(this, _selectError, null);
    __privateSet(this, _currentThenable, pendingThenable());
    this.bindMethods();
    this.setOptions(options2);
  }
  bindMethods() {
    this.refetch = this.refetch.bind(this);
  }
  onSubscribe() {
    if (this.listeners.size === 1) {
      __privateGet(this, _currentQuery).addObserver(this);
      if (shouldFetchOnMount(__privateGet(this, _currentQuery), this.options)) {
        __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
      } else {
        this.updateResult();
      }
      __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
    }
  }
  onUnsubscribe() {
    if (!this.hasListeners()) {
      this.destroy();
    }
  }
  shouldFetchOnReconnect() {
    return shouldFetchOn(
      __privateGet(this, _currentQuery),
      this.options,
      this.options.refetchOnReconnect
    );
  }
  shouldFetchOnWindowFocus() {
    return shouldFetchOn(
      __privateGet(this, _currentQuery),
      this.options,
      this.options.refetchOnWindowFocus
    );
  }
  destroy() {
    this.listeners = /* @__PURE__ */ new Set();
    __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
    __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
    __privateGet(this, _currentQuery).removeObserver(this);
  }
  setOptions(options2) {
    const prevOptions = this.options;
    const prevQuery = __privateGet(this, _currentQuery);
    this.options = __privateGet(this, _client2).defaultQueryOptions(options2);
    if (this.options.enabled !== void 0 && typeof this.options.enabled !== "boolean" && typeof this.options.enabled !== "function" && typeof resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== "boolean") {
      throw new Error(
        "Expected enabled to be a boolean or a callback that returns a boolean"
      );
    }
    __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
    __privateGet(this, _currentQuery).setOptions(this.options);
    if (prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions)) {
      __privateGet(this, _client2).getQueryCache().notify({
        type: "observerOptionsUpdated",
        query: __privateGet(this, _currentQuery),
        observer: this
      });
    }
    const mounted = this.hasListeners();
    if (mounted && shouldFetchOptionally(
      __privateGet(this, _currentQuery),
      prevQuery,
      this.options,
      prevOptions
    )) {
      __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
    }
    this.updateResult();
    if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || resolveStaleTime(this.options.staleTime, __privateGet(this, _currentQuery)) !== resolveStaleTime(prevOptions.staleTime, __privateGet(this, _currentQuery)))) {
      __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
    }
    const nextRefetchInterval = __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this);
    if (mounted && (__privateGet(this, _currentQuery) !== prevQuery || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) !== resolveEnabled(prevOptions.enabled, __privateGet(this, _currentQuery)) || nextRefetchInterval !== __privateGet(this, _currentRefetchInterval))) {
      __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, nextRefetchInterval);
    }
  }
  getOptimisticResult(options2) {
    const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), options2);
    const result = this.createResult(query, options2);
    if (shouldAssignObserverCurrentProperties(this, result)) {
      __privateSet(this, _currentResult, result);
      __privateSet(this, _currentResultOptions, this.options);
      __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
    }
    return result;
  }
  getCurrentResult() {
    return __privateGet(this, _currentResult);
  }
  trackResult(result, onPropTracked) {
    return new Proxy(result, {
      get: (target, key2) => {
        this.trackProp(key2);
        onPropTracked == null ? void 0 : onPropTracked(key2);
        if (key2 === "promise") {
          this.trackProp("data");
          if (!this.options.experimental_prefetchInRender && __privateGet(this, _currentThenable).status === "pending") {
            __privateGet(this, _currentThenable).reject(
              new Error(
                "experimental_prefetchInRender feature flag is not enabled"
              )
            );
          }
        }
        return Reflect.get(target, key2);
      }
    });
  }
  trackProp(key2) {
    __privateGet(this, _trackedProps).add(key2);
  }
  getCurrentQuery() {
    return __privateGet(this, _currentQuery);
  }
  refetch({ ...options2 } = {}) {
    return this.fetch({
      ...options2
    });
  }
  fetchOptimistic(options2) {
    const defaultedOptions = __privateGet(this, _client2).defaultQueryOptions(options2);
    const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), defaultedOptions);
    return query.fetch().then(() => this.createResult(query, defaultedOptions));
  }
  fetch(fetchOptions) {
    return __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this, {
      ...fetchOptions,
      cancelRefetch: fetchOptions.cancelRefetch ?? true
    }).then(() => {
      this.updateResult();
      return __privateGet(this, _currentResult);
    });
  }
  createResult(query, options2) {
    var _a3;
    const prevQuery = __privateGet(this, _currentQuery);
    const prevOptions = this.options;
    const prevResult = __privateGet(this, _currentResult);
    const prevResultState = __privateGet(this, _currentResultState);
    const prevResultOptions = __privateGet(this, _currentResultOptions);
    const queryChange = query !== prevQuery;
    const queryInitialState = queryChange ? query.state : __privateGet(this, _currentQueryInitialState);
    const { state } = query;
    let newState = { ...state };
    let isPlaceholderData = false;
    let data2;
    if (options2._optimisticResults) {
      const mounted = this.hasListeners();
      const fetchOnMount = !mounted && shouldFetchOnMount(query, options2);
      const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options2, prevOptions);
      if (fetchOnMount || fetchOptionally) {
        newState = {
          ...newState,
          ...fetchState(state.data, query.options)
        };
      }
      if (options2._optimisticResults === "isRestoring") {
        newState.fetchStatus = "idle";
      }
    }
    let { error, errorUpdatedAt, status } = newState;
    data2 = newState.data;
    let skipSelect = false;
    if (options2.placeholderData !== void 0 && data2 === void 0 && status === "pending") {
      let placeholderData;
      if ((prevResult == null ? void 0 : prevResult.isPlaceholderData) && options2.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
        placeholderData = prevResult.data;
        skipSelect = true;
      } else {
        placeholderData = typeof options2.placeholderData === "function" ? options2.placeholderData(
          (_a3 = __privateGet(this, _lastQueryWithDefinedData)) == null ? void 0 : _a3.state.data,
          __privateGet(this, _lastQueryWithDefinedData)
        ) : options2.placeholderData;
      }
      if (placeholderData !== void 0) {
        status = "success";
        data2 = replaceData(
          prevResult == null ? void 0 : prevResult.data,
          placeholderData,
          options2
        );
        isPlaceholderData = true;
      }
    }
    if (options2.select && data2 !== void 0 && !skipSelect) {
      if (prevResult && data2 === (prevResultState == null ? void 0 : prevResultState.data) && options2.select === __privateGet(this, _selectFn)) {
        data2 = __privateGet(this, _selectResult);
      } else {
        try {
          __privateSet(this, _selectFn, options2.select);
          data2 = options2.select(data2);
          data2 = replaceData(prevResult == null ? void 0 : prevResult.data, data2, options2);
          __privateSet(this, _selectResult, data2);
          __privateSet(this, _selectError, null);
        } catch (selectError) {
          __privateSet(this, _selectError, selectError);
        }
      }
    }
    if (__privateGet(this, _selectError)) {
      error = __privateGet(this, _selectError);
      data2 = __privateGet(this, _selectResult);
      errorUpdatedAt = Date.now();
      status = "error";
    }
    const isFetching = newState.fetchStatus === "fetching";
    const isPending = status === "pending";
    const isError = status === "error";
    const isLoading = isPending && isFetching;
    const hasData = data2 !== void 0;
    const result = {
      status,
      fetchStatus: newState.fetchStatus,
      isPending,
      isSuccess: status === "success",
      isError,
      isInitialLoading: isLoading,
      isLoading,
      data: data2,
      dataUpdatedAt: newState.dataUpdatedAt,
      error,
      errorUpdatedAt,
      failureCount: newState.fetchFailureCount,
      failureReason: newState.fetchFailureReason,
      errorUpdateCount: newState.errorUpdateCount,
      isFetched: newState.dataUpdateCount > 0 || newState.errorUpdateCount > 0,
      isFetchedAfterMount: newState.dataUpdateCount > queryInitialState.dataUpdateCount || newState.errorUpdateCount > queryInitialState.errorUpdateCount,
      isFetching,
      isRefetching: isFetching && !isPending,
      isLoadingError: isError && !hasData,
      isPaused: newState.fetchStatus === "paused",
      isPlaceholderData,
      isRefetchError: isError && hasData,
      isStale: isStale(query, options2),
      refetch: this.refetch,
      promise: __privateGet(this, _currentThenable),
      isEnabled: resolveEnabled(options2.enabled, query) !== false
    };
    const nextResult = result;
    if (this.options.experimental_prefetchInRender) {
      const finalizeThenableIfPossible = (thenable) => {
        if (nextResult.status === "error") {
          thenable.reject(nextResult.error);
        } else if (nextResult.data !== void 0) {
          thenable.resolve(nextResult.data);
        }
      };
      const recreateThenable = () => {
        const pending = __privateSet(this, _currentThenable, nextResult.promise = pendingThenable());
        finalizeThenableIfPossible(pending);
      };
      const prevThenable = __privateGet(this, _currentThenable);
      switch (prevThenable.status) {
        case "pending":
          if (query.queryHash === prevQuery.queryHash) {
            finalizeThenableIfPossible(prevThenable);
          }
          break;
        case "fulfilled":
          if (nextResult.status === "error" || nextResult.data !== prevThenable.value) {
            recreateThenable();
          }
          break;
        case "rejected":
          if (nextResult.status !== "error" || nextResult.error !== prevThenable.reason) {
            recreateThenable();
          }
          break;
      }
    }
    return nextResult;
  }
  updateResult() {
    const prevResult = __privateGet(this, _currentResult);
    const nextResult = this.createResult(__privateGet(this, _currentQuery), this.options);
    __privateSet(this, _currentResultState, __privateGet(this, _currentQuery).state);
    __privateSet(this, _currentResultOptions, this.options);
    if (__privateGet(this, _currentResultState).data !== void 0) {
      __privateSet(this, _lastQueryWithDefinedData, __privateGet(this, _currentQuery));
    }
    if (shallowEqualObjects(nextResult, prevResult)) {
      return;
    }
    __privateSet(this, _currentResult, nextResult);
    const shouldNotifyListeners = () => {
      if (!prevResult) {
        return true;
      }
      const { notifyOnChangeProps } = this.options;
      const notifyOnChangePropsValue = typeof notifyOnChangeProps === "function" ? notifyOnChangeProps() : notifyOnChangeProps;
      if (notifyOnChangePropsValue === "all" || !notifyOnChangePropsValue && !__privateGet(this, _trackedProps).size) {
        return true;
      }
      const includedProps = new Set(
        notifyOnChangePropsValue ?? __privateGet(this, _trackedProps)
      );
      if (this.options.throwOnError) {
        includedProps.add("error");
      }
      return Object.keys(__privateGet(this, _currentResult)).some((key2) => {
        const typedKey = key2;
        const changed = __privateGet(this, _currentResult)[typedKey] !== prevResult[typedKey];
        return changed && includedProps.has(typedKey);
      });
    };
    __privateMethod(this, _QueryObserver_instances, notify_fn).call(this, { listeners: shouldNotifyListeners() });
  }
  onQueryUpdate() {
    this.updateResult();
    if (this.hasListeners()) {
      __privateMethod(this, _QueryObserver_instances, updateTimers_fn).call(this);
    }
  }
}, _client2 = new WeakMap(), _currentQuery = new WeakMap(), _currentQueryInitialState = new WeakMap(), _currentResult = new WeakMap(), _currentResultState = new WeakMap(), _currentResultOptions = new WeakMap(), _currentThenable = new WeakMap(), _selectError = new WeakMap(), _selectFn = new WeakMap(), _selectResult = new WeakMap(), _lastQueryWithDefinedData = new WeakMap(), _staleTimeoutId = new WeakMap(), _refetchIntervalId = new WeakMap(), _currentRefetchInterval = new WeakMap(), _trackedProps = new WeakMap(), _QueryObserver_instances = new WeakSet(), executeFetch_fn = function(fetchOptions) {
  __privateMethod(this, _QueryObserver_instances, updateQuery_fn).call(this);
  let promise = __privateGet(this, _currentQuery).fetch(
    this.options,
    fetchOptions
  );
  if (!(fetchOptions == null ? void 0 : fetchOptions.throwOnError)) {
    promise = promise.catch(noop);
  }
  return promise;
}, updateStaleTimeout_fn = function() {
  __privateMethod(this, _QueryObserver_instances, clearStaleTimeout_fn).call(this);
  const staleTime = resolveStaleTime(
    this.options.staleTime,
    __privateGet(this, _currentQuery)
  );
  if (isServer || __privateGet(this, _currentResult).isStale || !isValidTimeout(staleTime)) {
    return;
  }
  const time = timeUntilStale(__privateGet(this, _currentResult).dataUpdatedAt, staleTime);
  const timeout = time + 1;
  __privateSet(this, _staleTimeoutId, timeoutManager.setTimeout(() => {
    if (!__privateGet(this, _currentResult).isStale) {
      this.updateResult();
    }
  }, timeout));
}, computeRefetchInterval_fn = function() {
  return (typeof this.options.refetchInterval === "function" ? this.options.refetchInterval(__privateGet(this, _currentQuery)) : this.options.refetchInterval) ?? false;
}, updateRefetchInterval_fn = function(nextInterval) {
  __privateMethod(this, _QueryObserver_instances, clearRefetchInterval_fn).call(this);
  __privateSet(this, _currentRefetchInterval, nextInterval);
  if (isServer || resolveEnabled(this.options.enabled, __privateGet(this, _currentQuery)) === false || !isValidTimeout(__privateGet(this, _currentRefetchInterval)) || __privateGet(this, _currentRefetchInterval) === 0) {
    return;
  }
  __privateSet(this, _refetchIntervalId, timeoutManager.setInterval(() => {
    if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
      __privateMethod(this, _QueryObserver_instances, executeFetch_fn).call(this);
    }
  }, __privateGet(this, _currentRefetchInterval)));
}, updateTimers_fn = function() {
  __privateMethod(this, _QueryObserver_instances, updateStaleTimeout_fn).call(this);
  __privateMethod(this, _QueryObserver_instances, updateRefetchInterval_fn).call(this, __privateMethod(this, _QueryObserver_instances, computeRefetchInterval_fn).call(this));
}, clearStaleTimeout_fn = function() {
  if (__privateGet(this, _staleTimeoutId)) {
    timeoutManager.clearTimeout(__privateGet(this, _staleTimeoutId));
    __privateSet(this, _staleTimeoutId, void 0);
  }
}, clearRefetchInterval_fn = function() {
  if (__privateGet(this, _refetchIntervalId)) {
    timeoutManager.clearInterval(__privateGet(this, _refetchIntervalId));
    __privateSet(this, _refetchIntervalId, void 0);
  }
}, updateQuery_fn = function() {
  const query = __privateGet(this, _client2).getQueryCache().build(__privateGet(this, _client2), this.options);
  if (query === __privateGet(this, _currentQuery)) {
    return;
  }
  const prevQuery = __privateGet(this, _currentQuery);
  __privateSet(this, _currentQuery, query);
  __privateSet(this, _currentQueryInitialState, query.state);
  if (this.hasListeners()) {
    prevQuery == null ? void 0 : prevQuery.removeObserver(this);
    query.addObserver(this);
  }
}, notify_fn = function(notifyOptions) {
  notifyManager.batch(() => {
    if (notifyOptions.listeners) {
      this.listeners.forEach((listener) => {
        listener(__privateGet(this, _currentResult));
      });
    }
    __privateGet(this, _client2).getQueryCache().notify({
      query: __privateGet(this, _currentQuery),
      type: "observerResultsUpdated"
    });
  });
}, _h);
function shouldLoadOnMount(query, options2) {
  return resolveEnabled(options2.enabled, query) !== false && query.state.data === void 0 && !(query.state.status === "error" && options2.retryOnMount === false);
}
function shouldFetchOnMount(query, options2) {
  return shouldLoadOnMount(query, options2) || query.state.data !== void 0 && shouldFetchOn(query, options2, options2.refetchOnMount);
}
function shouldFetchOn(query, options2, field) {
  if (resolveEnabled(options2.enabled, query) !== false && resolveStaleTime(options2.staleTime, query) !== "static") {
    const value = typeof field === "function" ? field(query) : field;
    return value === "always" || value !== false && isStale(query, options2);
  }
  return false;
}
function shouldFetchOptionally(query, prevQuery, options2, prevOptions) {
  return (query !== prevQuery || resolveEnabled(prevOptions.enabled, query) === false) && (!options2.suspense || query.state.status !== "error") && isStale(query, options2);
}
function isStale(query, options2) {
  return resolveEnabled(options2.enabled, query) !== false && query.isStaleByTime(resolveStaleTime(options2.staleTime, query));
}
function shouldAssignObserverCurrentProperties(observer, optimisticResult) {
  if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
    return true;
  }
  return false;
}
function infiniteQueryBehavior(pages) {
  return {
    onFetch: (context, query) => {
      var _a3, _b2, _c2, _d2, _e2;
      const options2 = context.options;
      const direction = (_c2 = (_b2 = (_a3 = context.fetchOptions) == null ? void 0 : _a3.meta) == null ? void 0 : _b2.fetchMore) == null ? void 0 : _c2.direction;
      const oldPages = ((_d2 = context.state.data) == null ? void 0 : _d2.pages) || [];
      const oldPageParams = ((_e2 = context.state.data) == null ? void 0 : _e2.pageParams) || [];
      let result = { pages: [], pageParams: [] };
      let currentPage = 0;
      const fetchFn = async () => {
        let cancelled = false;
        const addSignalProperty = (object) => {
          Object.defineProperty(object, "signal", {
            enumerable: true,
            get: () => {
              if (context.signal.aborted) {
                cancelled = true;
              } else {
                context.signal.addEventListener("abort", () => {
                  cancelled = true;
                });
              }
              return context.signal;
            }
          });
        };
        const queryFn = ensureQueryFn(context.options, context.fetchOptions);
        const fetchPage = async (data2, param, previous) => {
          if (cancelled) {
            return Promise.reject();
          }
          if (param == null && data2.pages.length) {
            return Promise.resolve(data2);
          }
          const createQueryFnContext = () => {
            const queryFnContext2 = {
              client: context.client,
              queryKey: context.queryKey,
              pageParam: param,
              direction: previous ? "backward" : "forward",
              meta: context.options.meta
            };
            addSignalProperty(queryFnContext2);
            return queryFnContext2;
          };
          const queryFnContext = createQueryFnContext();
          const page = await queryFn(queryFnContext);
          const { maxPages } = context.options;
          const addTo = previous ? addToStart : addToEnd;
          return {
            pages: addTo(data2.pages, page, maxPages),
            pageParams: addTo(data2.pageParams, param, maxPages)
          };
        };
        if (direction && oldPages.length) {
          const previous = direction === "backward";
          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
          const oldData = {
            pages: oldPages,
            pageParams: oldPageParams
          };
          const param = pageParamFn(options2, oldData);
          result = await fetchPage(oldData, param, previous);
        } else {
          const remainingPages = pages ?? oldPages.length;
          do {
            const param = currentPage === 0 ? oldPageParams[0] ?? options2.initialPageParam : getNextPageParam(options2, result);
            if (currentPage > 0 && param == null) {
              break;
            }
            result = await fetchPage(result, param);
            currentPage++;
          } while (currentPage < remainingPages);
        }
        return result;
      };
      if (context.options.persister) {
        context.fetchFn = () => {
          var _a4, _b3;
          return (_b3 = (_a4 = context.options).persister) == null ? void 0 : _b3.call(
            _a4,
            fetchFn,
            {
              client: context.client,
              queryKey: context.queryKey,
              meta: context.options.meta,
              signal: context.signal
            },
            query
          );
        };
      } else {
        context.fetchFn = fetchFn;
      }
    }
  };
}
function getNextPageParam(options2, { pages, pageParams }) {
  const lastIndex = pages.length - 1;
  return pages.length > 0 ? options2.getNextPageParam(
    pages[lastIndex],
    pages,
    pageParams[lastIndex],
    pageParams
  ) : void 0;
}
function getPreviousPageParam(options2, { pages, pageParams }) {
  var _a3;
  return pages.length > 0 ? (_a3 = options2.getPreviousPageParam) == null ? void 0 : _a3.call(options2, pages[0], pages, pageParams[0], pageParams) : void 0;
}
var Mutation = (_i = class extends Removable {
  constructor(config) {
    super();
    __privateAdd(this, _Mutation_instances);
    __privateAdd(this, _client3);
    __privateAdd(this, _observers);
    __privateAdd(this, _mutationCache);
    __privateAdd(this, _retryer2);
    __privateSet(this, _client3, config.client);
    this.mutationId = config.mutationId;
    __privateSet(this, _mutationCache, config.mutationCache);
    __privateSet(this, _observers, []);
    this.state = config.state || getDefaultState();
    this.setOptions(config.options);
    this.scheduleGc();
  }
  setOptions(options2) {
    this.options = options2;
    this.updateGcTime(this.options.gcTime);
  }
  get meta() {
    return this.options.meta;
  }
  addObserver(observer) {
    if (!__privateGet(this, _observers).includes(observer)) {
      __privateGet(this, _observers).push(observer);
      this.clearGcTimeout();
      __privateGet(this, _mutationCache).notify({
        type: "observerAdded",
        mutation: this,
        observer
      });
    }
  }
  removeObserver(observer) {
    __privateSet(this, _observers, __privateGet(this, _observers).filter((x2) => x2 !== observer));
    this.scheduleGc();
    __privateGet(this, _mutationCache).notify({
      type: "observerRemoved",
      mutation: this,
      observer
    });
  }
  optionalRemove() {
    if (!__privateGet(this, _observers).length) {
      if (this.state.status === "pending") {
        this.scheduleGc();
      } else {
        __privateGet(this, _mutationCache).remove(this);
      }
    }
  }
  continue() {
    var _a3;
    return ((_a3 = __privateGet(this, _retryer2)) == null ? void 0 : _a3.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
    this.execute(this.state.variables);
  }
  async execute(variables) {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n, _o, _p, _q, _r, _s, _t;
    const onContinue = () => {
      __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "continue" });
    };
    const mutationFnContext = {
      client: __privateGet(this, _client3),
      meta: this.options.meta,
      mutationKey: this.options.mutationKey
    };
    __privateSet(this, _retryer2, createRetryer({
      fn: () => {
        if (!this.options.mutationFn) {
          return Promise.reject(new Error("No mutationFn found"));
        }
        return this.options.mutationFn(variables, mutationFnContext);
      },
      onFail: (failureCount, error) => {
        __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "failed", failureCount, error });
      },
      onPause: () => {
        __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pause" });
      },
      onContinue,
      retry: this.options.retry ?? 0,
      retryDelay: this.options.retryDelay,
      networkMode: this.options.networkMode,
      canRun: () => __privateGet(this, _mutationCache).canRun(this)
    }));
    const restored = this.state.status === "pending";
    const isPaused = !__privateGet(this, _retryer2).canStart();
    try {
      if (restored) {
        onContinue();
      } else {
        __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "pending", variables, isPaused });
        await ((_b2 = (_a3 = __privateGet(this, _mutationCache).config).onMutate) == null ? void 0 : _b2.call(
          _a3,
          variables,
          this,
          mutationFnContext
        ));
        const context = await ((_d2 = (_c2 = this.options).onMutate) == null ? void 0 : _d2.call(
          _c2,
          variables,
          mutationFnContext
        ));
        if (context !== this.state.context) {
          __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, {
            type: "pending",
            context,
            variables,
            isPaused
          });
        }
      }
      const data2 = await __privateGet(this, _retryer2).start();
      await ((_f2 = (_e2 = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _f2.call(
        _e2,
        data2,
        variables,
        this.state.context,
        this,
        mutationFnContext
      ));
      await ((_h2 = (_g2 = this.options).onSuccess) == null ? void 0 : _h2.call(
        _g2,
        data2,
        variables,
        this.state.context,
        mutationFnContext
      ));
      await ((_j2 = (_i2 = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _j2.call(
        _i2,
        data2,
        null,
        this.state.variables,
        this.state.context,
        this,
        mutationFnContext
      ));
      await ((_l2 = (_k2 = this.options).onSettled) == null ? void 0 : _l2.call(
        _k2,
        data2,
        null,
        variables,
        this.state.context,
        mutationFnContext
      ));
      __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "success", data: data2 });
      return data2;
    } catch (error) {
      try {
        await ((_n = (_m2 = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _n.call(
          _m2,
          error,
          variables,
          this.state.context,
          this,
          mutationFnContext
        ));
        await ((_p = (_o = this.options).onError) == null ? void 0 : _p.call(
          _o,
          error,
          variables,
          this.state.context,
          mutationFnContext
        ));
        await ((_r = (_q = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _r.call(
          _q,
          void 0,
          error,
          this.state.variables,
          this.state.context,
          this,
          mutationFnContext
        ));
        await ((_t = (_s = this.options).onSettled) == null ? void 0 : _t.call(
          _s,
          void 0,
          error,
          variables,
          this.state.context,
          mutationFnContext
        ));
        throw error;
      } finally {
        __privateMethod(this, _Mutation_instances, dispatch_fn2).call(this, { type: "error", error });
      }
    } finally {
      __privateGet(this, _mutationCache).runNext(this);
    }
  }
}, _client3 = new WeakMap(), _observers = new WeakMap(), _mutationCache = new WeakMap(), _retryer2 = new WeakMap(), _Mutation_instances = new WeakSet(), dispatch_fn2 = function(action) {
  const reducer = (state) => {
    switch (action.type) {
      case "failed":
        return {
          ...state,
          failureCount: action.failureCount,
          failureReason: action.error
        };
      case "pause":
        return {
          ...state,
          isPaused: true
        };
      case "continue":
        return {
          ...state,
          isPaused: false
        };
      case "pending":
        return {
          ...state,
          context: action.context,
          data: void 0,
          failureCount: 0,
          failureReason: null,
          error: null,
          isPaused: action.isPaused,
          status: "pending",
          variables: action.variables,
          submittedAt: Date.now()
        };
      case "success":
        return {
          ...state,
          data: action.data,
          failureCount: 0,
          failureReason: null,
          error: null,
          status: "success",
          isPaused: false
        };
      case "error":
        return {
          ...state,
          data: void 0,
          error: action.error,
          failureCount: state.failureCount + 1,
          failureReason: action.error,
          isPaused: false,
          status: "error"
        };
    }
  };
  this.state = reducer(this.state);
  notifyManager.batch(() => {
    __privateGet(this, _observers).forEach((observer) => {
      observer.onMutationUpdate(action);
    });
    __privateGet(this, _mutationCache).notify({
      mutation: this,
      type: "updated",
      action
    });
  });
}, _i);
function getDefaultState() {
  return {
    context: void 0,
    data: void 0,
    error: null,
    failureCount: 0,
    failureReason: null,
    isPaused: false,
    status: "idle",
    variables: void 0,
    submittedAt: 0
  };
}
var MutationCache = (_j = class extends Subscribable {
  constructor(config = {}) {
    super();
    __privateAdd(this, _mutations);
    __privateAdd(this, _scopes);
    __privateAdd(this, _mutationId);
    this.config = config;
    __privateSet(this, _mutations, /* @__PURE__ */ new Set());
    __privateSet(this, _scopes, /* @__PURE__ */ new Map());
    __privateSet(this, _mutationId, 0);
  }
  build(client2, options2, state) {
    const mutation = new Mutation({
      client: client2,
      mutationCache: this,
      mutationId: ++__privateWrapper(this, _mutationId)._,
      options: client2.defaultMutationOptions(options2),
      state
    });
    this.add(mutation);
    return mutation;
  }
  add(mutation) {
    __privateGet(this, _mutations).add(mutation);
    const scope = scopeFor(mutation);
    if (typeof scope === "string") {
      const scopedMutations = __privateGet(this, _scopes).get(scope);
      if (scopedMutations) {
        scopedMutations.push(mutation);
      } else {
        __privateGet(this, _scopes).set(scope, [mutation]);
      }
    }
    this.notify({ type: "added", mutation });
  }
  remove(mutation) {
    if (__privateGet(this, _mutations).delete(mutation)) {
      const scope = scopeFor(mutation);
      if (typeof scope === "string") {
        const scopedMutations = __privateGet(this, _scopes).get(scope);
        if (scopedMutations) {
          if (scopedMutations.length > 1) {
            const index2 = scopedMutations.indexOf(mutation);
            if (index2 !== -1) {
              scopedMutations.splice(index2, 1);
            }
          } else if (scopedMutations[0] === mutation) {
            __privateGet(this, _scopes).delete(scope);
          }
        }
      }
    }
    this.notify({ type: "removed", mutation });
  }
  canRun(mutation) {
    const scope = scopeFor(mutation);
    if (typeof scope === "string") {
      const mutationsWithSameScope = __privateGet(this, _scopes).get(scope);
      const firstPendingMutation = mutationsWithSameScope == null ? void 0 : mutationsWithSameScope.find(
        (m) => m.state.status === "pending"
      );
      return !firstPendingMutation || firstPendingMutation === mutation;
    } else {
      return true;
    }
  }
  runNext(mutation) {
    var _a3;
    const scope = scopeFor(mutation);
    if (typeof scope === "string") {
      const foundMutation = (_a3 = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a3.find((m) => m !== mutation && m.state.isPaused);
      return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve();
    } else {
      return Promise.resolve();
    }
  }
  clear() {
    notifyManager.batch(() => {
      __privateGet(this, _mutations).forEach((mutation) => {
        this.notify({ type: "removed", mutation });
      });
      __privateGet(this, _mutations).clear();
      __privateGet(this, _scopes).clear();
    });
  }
  getAll() {
    return Array.from(__privateGet(this, _mutations));
  }
  find(filters) {
    const defaultedFilters = { exact: true, ...filters };
    return this.getAll().find(
      (mutation) => matchMutation(defaultedFilters, mutation)
    );
  }
  findAll(filters = {}) {
    return this.getAll().filter((mutation) => matchMutation(filters, mutation));
  }
  notify(event) {
    notifyManager.batch(() => {
      this.listeners.forEach((listener) => {
        listener(event);
      });
    });
  }
  resumePausedMutations() {
    const pausedMutations = this.getAll().filter((x2) => x2.state.isPaused);
    return notifyManager.batch(
      () => Promise.all(
        pausedMutations.map((mutation) => mutation.continue().catch(noop))
      )
    );
  }
}, _mutations = new WeakMap(), _scopes = new WeakMap(), _mutationId = new WeakMap(), _j);
function scopeFor(mutation) {
  var _a3;
  return (_a3 = mutation.options.scope) == null ? void 0 : _a3.id;
}
var MutationObserver = (_k = class extends Subscribable {
  constructor(client2, options2) {
    super();
    __privateAdd(this, _MutationObserver_instances);
    __privateAdd(this, _client4);
    __privateAdd(this, _currentResult2);
    __privateAdd(this, _currentMutation);
    __privateAdd(this, _mutateOptions);
    __privateSet(this, _client4, client2);
    this.setOptions(options2);
    this.bindMethods();
    __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
  }
  bindMethods() {
    this.mutate = this.mutate.bind(this);
    this.reset = this.reset.bind(this);
  }
  setOptions(options2) {
    var _a3;
    const prevOptions = this.options;
    this.options = __privateGet(this, _client4).defaultMutationOptions(options2);
    if (!shallowEqualObjects(this.options, prevOptions)) {
      __privateGet(this, _client4).getMutationCache().notify({
        type: "observerOptionsUpdated",
        mutation: __privateGet(this, _currentMutation),
        observer: this
      });
    }
    if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
      this.reset();
    } else if (((_a3 = __privateGet(this, _currentMutation)) == null ? void 0 : _a3.state.status) === "pending") {
      __privateGet(this, _currentMutation).setOptions(this.options);
    }
  }
  onUnsubscribe() {
    var _a3;
    if (!this.hasListeners()) {
      (_a3 = __privateGet(this, _currentMutation)) == null ? void 0 : _a3.removeObserver(this);
    }
  }
  onMutationUpdate(action) {
    __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
    __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this, action);
  }
  getCurrentResult() {
    return __privateGet(this, _currentResult2);
  }
  reset() {
    var _a3;
    (_a3 = __privateGet(this, _currentMutation)) == null ? void 0 : _a3.removeObserver(this);
    __privateSet(this, _currentMutation, void 0);
    __privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
    __privateMethod(this, _MutationObserver_instances, notify_fn2).call(this);
  }
  mutate(variables, options2) {
    var _a3;
    __privateSet(this, _mutateOptions, options2);
    (_a3 = __privateGet(this, _currentMutation)) == null ? void 0 : _a3.removeObserver(this);
    __privateSet(this, _currentMutation, __privateGet(this, _client4).getMutationCache().build(__privateGet(this, _client4), this.options));
    __privateGet(this, _currentMutation).addObserver(this);
    return __privateGet(this, _currentMutation).execute(variables);
  }
}, _client4 = new WeakMap(), _currentResult2 = new WeakMap(), _currentMutation = new WeakMap(), _mutateOptions = new WeakMap(), _MutationObserver_instances = new WeakSet(), updateResult_fn = function() {
  var _a3;
  const state = ((_a3 = __privateGet(this, _currentMutation)) == null ? void 0 : _a3.state) ?? getDefaultState();
  __privateSet(this, _currentResult2, {
    ...state,
    isPending: state.status === "pending",
    isSuccess: state.status === "success",
    isError: state.status === "error",
    isIdle: state.status === "idle",
    mutate: this.mutate,
    reset: this.reset
  });
}, notify_fn2 = function(action) {
  notifyManager.batch(() => {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
      const variables = __privateGet(this, _currentResult2).variables;
      const onMutateResult = __privateGet(this, _currentResult2).context;
      const context = {
        client: __privateGet(this, _client4),
        meta: this.options.meta,
        mutationKey: this.options.mutationKey
      };
      if ((action == null ? void 0 : action.type) === "success") {
        (_b2 = (_a3 = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b2.call(
          _a3,
          action.data,
          variables,
          onMutateResult,
          context
        );
        (_d2 = (_c2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d2.call(
          _c2,
          action.data,
          null,
          variables,
          onMutateResult,
          context
        );
      } else if ((action == null ? void 0 : action.type) === "error") {
        (_f2 = (_e2 = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f2.call(
          _e2,
          action.error,
          variables,
          onMutateResult,
          context
        );
        (_h2 = (_g2 = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h2.call(
          _g2,
          void 0,
          action.error,
          variables,
          onMutateResult,
          context
        );
      }
    }
    this.listeners.forEach((listener) => {
      listener(__privateGet(this, _currentResult2));
    });
  });
}, _k);
var QueryCache = (_l = class extends Subscribable {
  constructor(config = {}) {
    super();
    __privateAdd(this, _queries);
    this.config = config;
    __privateSet(this, _queries, /* @__PURE__ */ new Map());
  }
  build(client2, options2, state) {
    const queryKey = options2.queryKey;
    const queryHash = options2.queryHash ?? hashQueryKeyByOptions(queryKey, options2);
    let query = this.get(queryHash);
    if (!query) {
      query = new Query({
        client: client2,
        queryKey,
        queryHash,
        options: client2.defaultQueryOptions(options2),
        state,
        defaultOptions: client2.getQueryDefaults(queryKey)
      });
      this.add(query);
    }
    return query;
  }
  add(query) {
    if (!__privateGet(this, _queries).has(query.queryHash)) {
      __privateGet(this, _queries).set(query.queryHash, query);
      this.notify({
        type: "added",
        query
      });
    }
  }
  remove(query) {
    const queryInMap = __privateGet(this, _queries).get(query.queryHash);
    if (queryInMap) {
      query.destroy();
      if (queryInMap === query) {
        __privateGet(this, _queries).delete(query.queryHash);
      }
      this.notify({ type: "removed", query });
    }
  }
  clear() {
    notifyManager.batch(() => {
      this.getAll().forEach((query) => {
        this.remove(query);
      });
    });
  }
  get(queryHash) {
    return __privateGet(this, _queries).get(queryHash);
  }
  getAll() {
    return [...__privateGet(this, _queries).values()];
  }
  find(filters) {
    const defaultedFilters = { exact: true, ...filters };
    return this.getAll().find(
      (query) => matchQuery(defaultedFilters, query)
    );
  }
  findAll(filters = {}) {
    const queries = this.getAll();
    return Object.keys(filters).length > 0 ? queries.filter((query) => matchQuery(filters, query)) : queries;
  }
  notify(event) {
    notifyManager.batch(() => {
      this.listeners.forEach((listener) => {
        listener(event);
      });
    });
  }
  onFocus() {
    notifyManager.batch(() => {
      this.getAll().forEach((query) => {
        query.onFocus();
      });
    });
  }
  onOnline() {
    notifyManager.batch(() => {
      this.getAll().forEach((query) => {
        query.onOnline();
      });
    });
  }
}, _queries = new WeakMap(), _l);
var QueryClient = (_m = class {
  constructor(config = {}) {
    __privateAdd(this, _queryCache);
    __privateAdd(this, _mutationCache2);
    __privateAdd(this, _defaultOptions2);
    __privateAdd(this, _queryDefaults);
    __privateAdd(this, _mutationDefaults);
    __privateAdd(this, _mountCount);
    __privateAdd(this, _unsubscribeFocus);
    __privateAdd(this, _unsubscribeOnline);
    __privateSet(this, _queryCache, config.queryCache || new QueryCache());
    __privateSet(this, _mutationCache2, config.mutationCache || new MutationCache());
    __privateSet(this, _defaultOptions2, config.defaultOptions || {});
    __privateSet(this, _queryDefaults, /* @__PURE__ */ new Map());
    __privateSet(this, _mutationDefaults, /* @__PURE__ */ new Map());
    __privateSet(this, _mountCount, 0);
  }
  mount() {
    __privateWrapper(this, _mountCount)._++;
    if (__privateGet(this, _mountCount) !== 1) return;
    __privateSet(this, _unsubscribeFocus, focusManager.subscribe(async (focused) => {
      if (focused) {
        await this.resumePausedMutations();
        __privateGet(this, _queryCache).onFocus();
      }
    }));
    __privateSet(this, _unsubscribeOnline, onlineManager.subscribe(async (online) => {
      if (online) {
        await this.resumePausedMutations();
        __privateGet(this, _queryCache).onOnline();
      }
    }));
  }
  unmount() {
    var _a3, _b2;
    __privateWrapper(this, _mountCount)._--;
    if (__privateGet(this, _mountCount) !== 0) return;
    (_a3 = __privateGet(this, _unsubscribeFocus)) == null ? void 0 : _a3.call(this);
    __privateSet(this, _unsubscribeFocus, void 0);
    (_b2 = __privateGet(this, _unsubscribeOnline)) == null ? void 0 : _b2.call(this);
    __privateSet(this, _unsubscribeOnline, void 0);
  }
  isFetching(filters) {
    return __privateGet(this, _queryCache).findAll({ ...filters, fetchStatus: "fetching" }).length;
  }
  isMutating(filters) {
    return __privateGet(this, _mutationCache2).findAll({ ...filters, status: "pending" }).length;
  }
  /**
   * Imperative (non-reactive) way to retrieve data for a QueryKey.
   * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates.
   *
   * Hint: Do not use this function inside a component, because it won't receive updates.
   * Use `useQuery` to create a `QueryObserver` that subscribes to changes.
   */
  getQueryData(queryKey) {
    var _a3;
    const options2 = this.defaultQueryOptions({ queryKey });
    return (_a3 = __privateGet(this, _queryCache).get(options2.queryHash)) == null ? void 0 : _a3.state.data;
  }
  ensureQueryData(options2) {
    const defaultedOptions = this.defaultQueryOptions(options2);
    const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
    const cachedData = query.state.data;
    if (cachedData === void 0) {
      return this.fetchQuery(options2);
    }
    if (options2.revalidateIfStale && query.isStaleByTime(resolveStaleTime(defaultedOptions.staleTime, query))) {
      void this.prefetchQuery(defaultedOptions);
    }
    return Promise.resolve(cachedData);
  }
  getQueriesData(filters) {
    return __privateGet(this, _queryCache).findAll(filters).map(({ queryKey, state }) => {
      const data2 = state.data;
      return [queryKey, data2];
    });
  }
  setQueryData(queryKey, updater, options2) {
    const defaultedOptions = this.defaultQueryOptions({ queryKey });
    const query = __privateGet(this, _queryCache).get(
      defaultedOptions.queryHash
    );
    const prevData = query == null ? void 0 : query.state.data;
    const data2 = functionalUpdate(updater, prevData);
    if (data2 === void 0) {
      return void 0;
    }
    return __privateGet(this, _queryCache).build(this, defaultedOptions).setData(data2, { ...options2, manual: true });
  }
  setQueriesData(filters, updater, options2) {
    return notifyManager.batch(
      () => __privateGet(this, _queryCache).findAll(filters).map(({ queryKey }) => [
        queryKey,
        this.setQueryData(queryKey, updater, options2)
      ])
    );
  }
  getQueryState(queryKey) {
    var _a3;
    const options2 = this.defaultQueryOptions({ queryKey });
    return (_a3 = __privateGet(this, _queryCache).get(
      options2.queryHash
    )) == null ? void 0 : _a3.state;
  }
  removeQueries(filters) {
    const queryCache = __privateGet(this, _queryCache);
    notifyManager.batch(() => {
      queryCache.findAll(filters).forEach((query) => {
        queryCache.remove(query);
      });
    });
  }
  resetQueries(filters, options2) {
    const queryCache = __privateGet(this, _queryCache);
    return notifyManager.batch(() => {
      queryCache.findAll(filters).forEach((query) => {
        query.reset();
      });
      return this.refetchQueries(
        {
          type: "active",
          ...filters
        },
        options2
      );
    });
  }
  cancelQueries(filters, cancelOptions = {}) {
    const defaultedCancelOptions = { revert: true, ...cancelOptions };
    const promises = notifyManager.batch(
      () => __privateGet(this, _queryCache).findAll(filters).map((query) => query.cancel(defaultedCancelOptions))
    );
    return Promise.all(promises).then(noop).catch(noop);
  }
  invalidateQueries(filters, options2 = {}) {
    return notifyManager.batch(() => {
      __privateGet(this, _queryCache).findAll(filters).forEach((query) => {
        query.invalidate();
      });
      if ((filters == null ? void 0 : filters.refetchType) === "none") {
        return Promise.resolve();
      }
      return this.refetchQueries(
        {
          ...filters,
          type: (filters == null ? void 0 : filters.refetchType) ?? (filters == null ? void 0 : filters.type) ?? "active"
        },
        options2
      );
    });
  }
  refetchQueries(filters, options2 = {}) {
    const fetchOptions = {
      ...options2,
      cancelRefetch: options2.cancelRefetch ?? true
    };
    const promises = notifyManager.batch(
      () => __privateGet(this, _queryCache).findAll(filters).filter((query) => !query.isDisabled() && !query.isStatic()).map((query) => {
        let promise = query.fetch(void 0, fetchOptions);
        if (!fetchOptions.throwOnError) {
          promise = promise.catch(noop);
        }
        return query.state.fetchStatus === "paused" ? Promise.resolve() : promise;
      })
    );
    return Promise.all(promises).then(noop);
  }
  fetchQuery(options2) {
    const defaultedOptions = this.defaultQueryOptions(options2);
    if (defaultedOptions.retry === void 0) {
      defaultedOptions.retry = false;
    }
    const query = __privateGet(this, _queryCache).build(this, defaultedOptions);
    return query.isStaleByTime(
      resolveStaleTime(defaultedOptions.staleTime, query)
    ) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
  }
  prefetchQuery(options2) {
    return this.fetchQuery(options2).then(noop).catch(noop);
  }
  fetchInfiniteQuery(options2) {
    options2.behavior = infiniteQueryBehavior(options2.pages);
    return this.fetchQuery(options2);
  }
  prefetchInfiniteQuery(options2) {
    return this.fetchInfiniteQuery(options2).then(noop).catch(noop);
  }
  ensureInfiniteQueryData(options2) {
    options2.behavior = infiniteQueryBehavior(options2.pages);
    return this.ensureQueryData(options2);
  }
  resumePausedMutations() {
    if (onlineManager.isOnline()) {
      return __privateGet(this, _mutationCache2).resumePausedMutations();
    }
    return Promise.resolve();
  }
  getQueryCache() {
    return __privateGet(this, _queryCache);
  }
  getMutationCache() {
    return __privateGet(this, _mutationCache2);
  }
  getDefaultOptions() {
    return __privateGet(this, _defaultOptions2);
  }
  setDefaultOptions(options2) {
    __privateSet(this, _defaultOptions2, options2);
  }
  setQueryDefaults(queryKey, options2) {
    __privateGet(this, _queryDefaults).set(hashKey(queryKey), {
      queryKey,
      defaultOptions: options2
    });
  }
  getQueryDefaults(queryKey) {
    const defaults = [...__privateGet(this, _queryDefaults).values()];
    const result = {};
    defaults.forEach((queryDefault) => {
      if (partialMatchKey(queryKey, queryDefault.queryKey)) {
        Object.assign(result, queryDefault.defaultOptions);
      }
    });
    return result;
  }
  setMutationDefaults(mutationKey, options2) {
    __privateGet(this, _mutationDefaults).set(hashKey(mutationKey), {
      mutationKey,
      defaultOptions: options2
    });
  }
  getMutationDefaults(mutationKey) {
    const defaults = [...__privateGet(this, _mutationDefaults).values()];
    const result = {};
    defaults.forEach((queryDefault) => {
      if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
        Object.assign(result, queryDefault.defaultOptions);
      }
    });
    return result;
  }
  defaultQueryOptions(options2) {
    if (options2._defaulted) {
      return options2;
    }
    const defaultedOptions = {
      ...__privateGet(this, _defaultOptions2).queries,
      ...this.getQueryDefaults(options2.queryKey),
      ...options2,
      _defaulted: true
    };
    if (!defaultedOptions.queryHash) {
      defaultedOptions.queryHash = hashQueryKeyByOptions(
        defaultedOptions.queryKey,
        defaultedOptions
      );
    }
    if (defaultedOptions.refetchOnReconnect === void 0) {
      defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== "always";
    }
    if (defaultedOptions.throwOnError === void 0) {
      defaultedOptions.throwOnError = !!defaultedOptions.suspense;
    }
    if (!defaultedOptions.networkMode && defaultedOptions.persister) {
      defaultedOptions.networkMode = "offlineFirst";
    }
    if (defaultedOptions.queryFn === skipToken) {
      defaultedOptions.enabled = false;
    }
    return defaultedOptions;
  }
  defaultMutationOptions(options2) {
    if (options2 == null ? void 0 : options2._defaulted) {
      return options2;
    }
    return {
      ...__privateGet(this, _defaultOptions2).mutations,
      ...(options2 == null ? void 0 : options2.mutationKey) && this.getMutationDefaults(options2.mutationKey),
      ...options2,
      _defaulted: true
    };
  }
  clear() {
    __privateGet(this, _queryCache).clear();
    __privateGet(this, _mutationCache2).clear();
  }
}, _queryCache = new WeakMap(), _mutationCache2 = new WeakMap(), _defaultOptions2 = new WeakMap(), _queryDefaults = new WeakMap(), _mutationDefaults = new WeakMap(), _mountCount = new WeakMap(), _unsubscribeFocus = new WeakMap(), _unsubscribeOnline = new WeakMap(), _m);
var jsxRuntime = { exports: {} };
var reactJsxRuntime_development = {};
var hasRequiredReactJsxRuntime_development;
function requireReactJsxRuntime_development() {
  if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
  hasRequiredReactJsxRuntime_development = 1;
  /**
   * @license React
   * react-jsx-runtime.development.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  {
    (function() {
      var React2 = requireReact();
      var REACT_ELEMENT_TYPE = Symbol.for("react.element");
      var REACT_PORTAL_TYPE = Symbol.for("react.portal");
      var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
      var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode");
      var REACT_PROFILER_TYPE = Symbol.for("react.profiler");
      var REACT_PROVIDER_TYPE = Symbol.for("react.provider");
      var REACT_CONTEXT_TYPE = Symbol.for("react.context");
      var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
      var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense");
      var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list");
      var REACT_MEMO_TYPE = Symbol.for("react.memo");
      var REACT_LAZY_TYPE = Symbol.for("react.lazy");
      var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
      var FAUX_ITERATOR_SYMBOL = "@@iterator";
      function getIteratorFn(maybeIterable) {
        if (maybeIterable === null || typeof maybeIterable !== "object") {
          return null;
        }
        var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
        if (typeof maybeIterator === "function") {
          return maybeIterator;
        }
        return null;
      }
      var ReactSharedInternals = React2.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      function error(format2) {
        {
          {
            for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
              args[_key2 - 1] = arguments[_key2];
            }
            printWarning("error", format2, args);
          }
        }
      }
      function printWarning(level, format2, args) {
        {
          var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame;
          var stack = ReactDebugCurrentFrame2.getStackAddendum();
          if (stack !== "") {
            format2 += "%s";
            args = args.concat([stack]);
          }
          var argsWithFormat = args.map(function(item) {
            return String(item);
          });
          argsWithFormat.unshift("Warning: " + format2);
          Function.prototype.apply.call(console[level], console, argsWithFormat);
        }
      }
      var enableScopeAPI = false;
      var enableCacheElement = false;
      var enableTransitionTracing = false;
      var enableLegacyHidden = false;
      var enableDebugTracing = false;
      var REACT_MODULE_REFERENCE;
      {
        REACT_MODULE_REFERENCE = Symbol.for("react.module.reference");
      }
      function isValidElementType(type2) {
        if (typeof type2 === "string" || typeof type2 === "function") {
          return true;
        }
        if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) {
          return true;
        }
        if (typeof type2 === "object" && type2 !== null) {
          if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
          // types supported by any Flight configuration anywhere since
          // we don't know which Flight build this will end up being used
          // with.
          type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) {
            return true;
          }
        }
        return false;
      }
      function getWrappedName(outerType, innerType, wrapperName) {
        var displayName = outerType.displayName;
        if (displayName) {
          return displayName;
        }
        var functionName = innerType.displayName || innerType.name || "";
        return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName;
      }
      function getContextName(type2) {
        return type2.displayName || "Context";
      }
      function getComponentNameFromType(type2) {
        if (type2 == null) {
          return null;
        }
        {
          if (typeof type2.tag === "number") {
            error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.");
          }
        }
        if (typeof type2 === "function") {
          return type2.displayName || type2.name || null;
        }
        if (typeof type2 === "string") {
          return type2;
        }
        switch (type2) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_CONTEXT_TYPE:
              var context = type2;
              return getContextName(context) + ".Consumer";
            case REACT_PROVIDER_TYPE:
              var provider = type2;
              return getContextName(provider._context) + ".Provider";
            case REACT_FORWARD_REF_TYPE:
              return getWrappedName(type2, type2.render, "ForwardRef");
            case REACT_MEMO_TYPE:
              var outerName = type2.displayName || null;
              if (outerName !== null) {
                return outerName;
              }
              return getComponentNameFromType(type2.type) || "Memo";
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return getComponentNameFromType(init2(payload));
              } catch (x2) {
                return null;
              }
            }
          }
        }
        return null;
      }
      var assign = Object.assign;
      var disabledDepth = 0;
      var prevLog;
      var prevInfo;
      var prevWarn;
      var prevError;
      var prevGroup;
      var prevGroupCollapsed;
      var prevGroupEnd;
      function disabledLog() {
      }
      disabledLog.__reactDisabledLog = true;
      function disableLogs() {
        {
          if (disabledDepth === 0) {
            prevLog = console.log;
            prevInfo = console.info;
            prevWarn = console.warn;
            prevError = console.error;
            prevGroup = console.group;
            prevGroupCollapsed = console.groupCollapsed;
            prevGroupEnd = console.groupEnd;
            var props = {
              configurable: true,
              enumerable: true,
              value: disabledLog,
              writable: true
            };
            Object.defineProperties(console, {
              info: props,
              log: props,
              warn: props,
              error: props,
              group: props,
              groupCollapsed: props,
              groupEnd: props
            });
          }
          disabledDepth++;
        }
      }
      function reenableLogs() {
        {
          disabledDepth--;
          if (disabledDepth === 0) {
            var props = {
              configurable: true,
              enumerable: true,
              writable: true
            };
            Object.defineProperties(console, {
              log: assign({}, props, {
                value: prevLog
              }),
              info: assign({}, props, {
                value: prevInfo
              }),
              warn: assign({}, props, {
                value: prevWarn
              }),
              error: assign({}, props, {
                value: prevError
              }),
              group: assign({}, props, {
                value: prevGroup
              }),
              groupCollapsed: assign({}, props, {
                value: prevGroupCollapsed
              }),
              groupEnd: assign({}, props, {
                value: prevGroupEnd
              })
            });
          }
          if (disabledDepth < 0) {
            error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
          }
        }
      }
      var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
      var prefix;
      function describeBuiltInComponentFrame(name, source, ownerFn) {
        {
          if (prefix === void 0) {
            try {
              throw Error();
            } catch (x2) {
              var match = x2.stack.trim().match(/\n( *(at )?)/);
              prefix = match && match[1] || "";
            }
          }
          return "\n" + prefix + name;
        }
      }
      var reentry = false;
      var componentFrameCache;
      {
        var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map;
        componentFrameCache = new PossiblyWeakMap();
      }
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) {
          return "";
        }
        {
          var frame = componentFrameCache.get(fn);
          if (frame !== void 0) {
            return frame;
          }
        }
        var control;
        reentry = true;
        var previousPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher;
        {
          previousDispatcher = ReactCurrentDispatcher.current;
          ReactCurrentDispatcher.current = null;
          disableLogs();
        }
        try {
          if (construct) {
            var Fake = function() {
              throw Error();
            };
            Object.defineProperty(Fake.prototype, "props", {
              set: function() {
                throw Error();
              }
            });
            if (typeof Reflect === "object" && Reflect.construct) {
              try {
                Reflect.construct(Fake, []);
              } catch (x2) {
                control = x2;
              }
              Reflect.construct(fn, [], Fake);
            } else {
              try {
                Fake.call();
              } catch (x2) {
                control = x2;
              }
              fn.call(Fake.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (x2) {
              control = x2;
            }
            fn();
          }
        } catch (sample) {
          if (sample && control && typeof sample.stack === "string") {
            var sampleLines = sample.stack.split("\n");
            var controlLines = control.stack.split("\n");
            var s2 = sampleLines.length - 1;
            var c2 = controlLines.length - 1;
            while (s2 >= 1 && c2 >= 0 && sampleLines[s2] !== controlLines[c2]) {
              c2--;
            }
            for (; s2 >= 1 && c2 >= 0; s2--, c2--) {
              if (sampleLines[s2] !== controlLines[c2]) {
                if (s2 !== 1 || c2 !== 1) {
                  do {
                    s2--;
                    c2--;
                    if (c2 < 0 || sampleLines[s2] !== controlLines[c2]) {
                      var _frame = "\n" + sampleLines[s2].replace(" at new ", " at ");
                      if (fn.displayName && _frame.includes("<anonymous>")) {
                        _frame = _frame.replace("<anonymous>", fn.displayName);
                      }
                      {
                        if (typeof fn === "function") {
                          componentFrameCache.set(fn, _frame);
                        }
                      }
                      return _frame;
                    }
                  } while (s2 >= 1 && c2 >= 0);
                }
                break;
              }
            }
          }
        } finally {
          reentry = false;
          {
            ReactCurrentDispatcher.current = previousDispatcher;
            reenableLogs();
          }
          Error.prepareStackTrace = previousPrepareStackTrace;
        }
        var name = fn ? fn.displayName || fn.name : "";
        var syntheticFrame = name ? describeBuiltInComponentFrame(name) : "";
        {
          if (typeof fn === "function") {
            componentFrameCache.set(fn, syntheticFrame);
          }
        }
        return syntheticFrame;
      }
      function describeFunctionComponentFrame(fn, source, ownerFn) {
        {
          return describeNativeComponentFrame(fn, false);
        }
      }
      function shouldConstruct(Component) {
        var prototype = Component.prototype;
        return !!(prototype && prototype.isReactComponent);
      }
      function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) {
        if (type2 == null) {
          return "";
        }
        if (typeof type2 === "function") {
          {
            return describeNativeComponentFrame(type2, shouldConstruct(type2));
          }
        }
        if (typeof type2 === "string") {
          return describeBuiltInComponentFrame(type2);
        }
        switch (type2) {
          case REACT_SUSPENSE_TYPE:
            return describeBuiltInComponentFrame("Suspense");
          case REACT_SUSPENSE_LIST_TYPE:
            return describeBuiltInComponentFrame("SuspenseList");
        }
        if (typeof type2 === "object") {
          switch (type2.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              return describeFunctionComponentFrame(type2.render);
            case REACT_MEMO_TYPE:
              return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn);
            case REACT_LAZY_TYPE: {
              var lazyComponent = type2;
              var payload = lazyComponent._payload;
              var init2 = lazyComponent._init;
              try {
                return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn);
              } catch (x2) {
              }
            }
          }
        }
        return "";
      }
      var hasOwnProperty = Object.prototype.hasOwnProperty;
      var loggedTypeFailures = {};
      var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame.setExtraStackFrame(null);
          }
        }
      }
      function checkPropTypes(typeSpecs, values, location, componentName, element) {
        {
          var has = Function.call.bind(hasOwnProperty);
          for (var typeSpecName in typeSpecs) {
            if (has(typeSpecs, typeSpecName)) {
              var error$1 = void 0;
              try {
                if (typeof typeSpecs[typeSpecName] !== "function") {
                  var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                  err.name = "Invariant Violation";
                  throw err;
                }
                error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
              } catch (ex) {
                error$1 = ex;
              }
              if (error$1 && !(error$1 instanceof Error)) {
                setCurrentlyValidatingElement(element);
                error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1);
                setCurrentlyValidatingElement(null);
              }
              if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
                loggedTypeFailures[error$1.message] = true;
                setCurrentlyValidatingElement(element);
                error("Failed %s type: %s", location, error$1.message);
                setCurrentlyValidatingElement(null);
              }
            }
          }
        }
      }
      var isArrayImpl = Array.isArray;
      function isArray2(a2) {
        return isArrayImpl(a2);
      }
      function typeName(value) {
        {
          var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag;
          var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          return type2;
        }
      }
      function willCoercionThrow(value) {
        {
          try {
            testStringCoercion(value);
            return false;
          } catch (e4) {
            return true;
          }
        }
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkKeyStringCoercion(value) {
        {
          if (willCoercionThrow(value)) {
            error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value));
            return testStringCoercion(value);
          }
        }
      }
      var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
      var RESERVED_PROPS = {
        key: true,
        ref: true,
        __self: true,
        __source: true
      };
      var specialPropKeyWarningShown;
      var specialPropRefWarningShown;
      function hasValidRef(config) {
        {
          if (hasOwnProperty.call(config, "ref")) {
            var getter = Object.getOwnPropertyDescriptor(config, "ref").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.ref !== void 0;
      }
      function hasValidKey(config) {
        {
          if (hasOwnProperty.call(config, "key")) {
            var getter = Object.getOwnPropertyDescriptor(config, "key").get;
            if (getter && getter.isReactWarning) {
              return false;
            }
          }
        }
        return config.key !== void 0;
      }
      function warnIfStringRefCannotBeAutoConverted(config, self2) {
        {
          if (typeof config.ref === "string" && ReactCurrentOwner.current && self2) ;
        }
      }
      function defineKeyPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingKey = function() {
            if (!specialPropKeyWarningShown) {
              specialPropKeyWarningShown = true;
              error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingKey.isReactWarning = true;
          Object.defineProperty(props, "key", {
            get: warnAboutAccessingKey,
            configurable: true
          });
        }
      }
      function defineRefPropWarningGetter(props, displayName) {
        {
          var warnAboutAccessingRef = function() {
            if (!specialPropRefWarningShown) {
              specialPropRefWarningShown = true;
              error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName);
            }
          };
          warnAboutAccessingRef.isReactWarning = true;
          Object.defineProperty(props, "ref", {
            get: warnAboutAccessingRef,
            configurable: true
          });
        }
      }
      var ReactElement = function(type2, key2, ref2, self2, source, owner, props) {
        var element = {
          // This tag allows us to uniquely identify this as a React Element
          $$typeof: REACT_ELEMENT_TYPE,
          // Built-in properties that belong on the element
          type: type2,
          key: key2,
          ref: ref2,
          props,
          // Record the component responsible for creating this element.
          _owner: owner
        };
        {
          element._store = {};
          Object.defineProperty(element._store, "validated", {
            configurable: false,
            enumerable: false,
            writable: true,
            value: false
          });
          Object.defineProperty(element, "_self", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: self2
          });
          Object.defineProperty(element, "_source", {
            configurable: false,
            enumerable: false,
            writable: false,
            value: source
          });
          if (Object.freeze) {
            Object.freeze(element.props);
            Object.freeze(element);
          }
        }
        return element;
      };
      function jsxDEV(type2, config, maybeKey, source, self2) {
        {
          var propName;
          var props = {};
          var key2 = null;
          var ref2 = null;
          if (maybeKey !== void 0) {
            {
              checkKeyStringCoercion(maybeKey);
            }
            key2 = "" + maybeKey;
          }
          if (hasValidKey(config)) {
            {
              checkKeyStringCoercion(config.key);
            }
            key2 = "" + config.key;
          }
          if (hasValidRef(config)) {
            ref2 = config.ref;
            warnIfStringRefCannotBeAutoConverted(config, self2);
          }
          for (propName in config) {
            if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
              props[propName] = config[propName];
            }
          }
          if (type2 && type2.defaultProps) {
            var defaultProps = type2.defaultProps;
            for (propName in defaultProps) {
              if (props[propName] === void 0) {
                props[propName] = defaultProps[propName];
              }
            }
          }
          if (key2 || ref2) {
            var displayName = typeof type2 === "function" ? type2.displayName || type2.name || "Unknown" : type2;
            if (key2) {
              defineKeyPropWarningGetter(props, displayName);
            }
            if (ref2) {
              defineRefPropWarningGetter(props, displayName);
            }
          }
          return ReactElement(type2, key2, ref2, self2, source, ReactCurrentOwner.current, props);
        }
      }
      var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
      var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
      function setCurrentlyValidatingElement$1(element) {
        {
          if (element) {
            var owner = element._owner;
            var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
            ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
          } else {
            ReactDebugCurrentFrame$1.setExtraStackFrame(null);
          }
        }
      }
      var propTypesMisspellWarningShown;
      {
        propTypesMisspellWarningShown = false;
      }
      function isValidElement(object) {
        {
          return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
        }
      }
      function getDeclarationErrorAddendum() {
        {
          if (ReactCurrentOwner$1.current) {
            var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
            if (name) {
              return "\n\nCheck the render method of `" + name + "`.";
            }
          }
          return "";
        }
      }
      function getSourceInfoErrorAddendum(source) {
        {
          return "";
        }
      }
      var ownerHasKeyUseWarning = {};
      function getCurrentComponentErrorInfo(parentType) {
        {
          var info = getDeclarationErrorAddendum();
          if (!info) {
            var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name;
            if (parentName) {
              info = "\n\nCheck the top-level render call using <" + parentName + ">.";
            }
          }
          return info;
        }
      }
      function validateExplicitKey(element, parentType) {
        {
          if (!element._store || element._store.validated || element.key != null) {
            return;
          }
          element._store.validated = true;
          var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
          if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
            return;
          }
          ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
          var childOwner = "";
          if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
            childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
          }
          setCurrentlyValidatingElement$1(element);
          error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
          setCurrentlyValidatingElement$1(null);
        }
      }
      function validateChildKeys(node2, parentType) {
        {
          if (typeof node2 !== "object") {
            return;
          }
          if (isArray2(node2)) {
            for (var i2 = 0; i2 < node2.length; i2++) {
              var child = node2[i2];
              if (isValidElement(child)) {
                validateExplicitKey(child, parentType);
              }
            }
          } else if (isValidElement(node2)) {
            if (node2._store) {
              node2._store.validated = true;
            }
          } else if (node2) {
            var iteratorFn = getIteratorFn(node2);
            if (typeof iteratorFn === "function") {
              if (iteratorFn !== node2.entries) {
                var iterator = iteratorFn.call(node2);
                var step;
                while (!(step = iterator.next()).done) {
                  if (isValidElement(step.value)) {
                    validateExplicitKey(step.value, parentType);
                  }
                }
              }
            }
          }
        }
      }
      function validatePropTypes(element) {
        {
          var type2 = element.type;
          if (type2 === null || type2 === void 0 || typeof type2 === "string") {
            return;
          }
          var propTypes;
          if (typeof type2 === "function") {
            propTypes = type2.propTypes;
          } else if (typeof type2 === "object" && (type2.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
          // Inner props are checked in the reconciler.
          type2.$$typeof === REACT_MEMO_TYPE)) {
            propTypes = type2.propTypes;
          } else {
            return;
          }
          if (propTypes) {
            var name = getComponentNameFromType(type2);
            checkPropTypes(propTypes, element.props, "prop", name, element);
          } else if (type2.PropTypes !== void 0 && !propTypesMisspellWarningShown) {
            propTypesMisspellWarningShown = true;
            var _name = getComponentNameFromType(type2);
            error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown");
          }
          if (typeof type2.getDefaultProps === "function" && !type2.getDefaultProps.isReactClassApproved) {
            error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
          }
        }
      }
      function validateFragmentProps(fragment) {
        {
          var keys = Object.keys(fragment.props);
          for (var i2 = 0; i2 < keys.length; i2++) {
            var key2 = keys[i2];
            if (key2 !== "children" && key2 !== "key") {
              setCurrentlyValidatingElement$1(fragment);
              error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key2);
              setCurrentlyValidatingElement$1(null);
              break;
            }
          }
          if (fragment.ref !== null) {
            setCurrentlyValidatingElement$1(fragment);
            error("Invalid attribute `ref` supplied to `React.Fragment`.");
            setCurrentlyValidatingElement$1(null);
          }
        }
      }
      var didWarnAboutKeySpread = {};
      function jsxWithValidation(type2, props, key2, isStaticChildren, source, self2) {
        {
          var validType = isValidElementType(type2);
          if (!validType) {
            var info = "";
            if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) {
              info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            }
            var sourceInfo = getSourceInfoErrorAddendum();
            if (sourceInfo) {
              info += sourceInfo;
            } else {
              info += getDeclarationErrorAddendum();
            }
            var typeString;
            if (type2 === null) {
              typeString = "null";
            } else if (isArray2(type2)) {
              typeString = "array";
            } else if (type2 !== void 0 && type2.$$typeof === REACT_ELEMENT_TYPE) {
              typeString = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />";
              info = " Did you accidentally export a JSX literal instead of a component?";
            } else {
              typeString = typeof type2;
            }
            error("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
          }
          var element = jsxDEV(type2, props, key2, source, self2);
          if (element == null) {
            return element;
          }
          if (validType) {
            var children = props.children;
            if (children !== void 0) {
              if (isStaticChildren) {
                if (isArray2(children)) {
                  for (var i2 = 0; i2 < children.length; i2++) {
                    validateChildKeys(children[i2], type2);
                  }
                  if (Object.freeze) {
                    Object.freeze(children);
                  }
                } else {
                  error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
                }
              } else {
                validateChildKeys(children, type2);
              }
            }
          }
          {
            if (hasOwnProperty.call(props, "key")) {
              var componentName = getComponentNameFromType(type2);
              var keys = Object.keys(props).filter(function(k2) {
                return k2 !== "key";
              });
              var beforeExample = keys.length > 0 ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
              if (!didWarnAboutKeySpread[componentName + beforeExample]) {
                var afterExample = keys.length > 0 ? "{" + keys.join(": ..., ") + ": ...}" : "{}";
                error('A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
                didWarnAboutKeySpread[componentName + beforeExample] = true;
              }
            }
          }
          if (type2 === REACT_FRAGMENT_TYPE) {
            validateFragmentProps(element);
          } else {
            validatePropTypes(element);
          }
          return element;
        }
      }
      function jsxWithValidationStatic(type2, props, key2) {
        {
          return jsxWithValidation(type2, props, key2, true);
        }
      }
      function jsxWithValidationDynamic(type2, props, key2) {
        {
          return jsxWithValidation(type2, props, key2, false);
        }
      }
      var jsx = jsxWithValidationDynamic;
      var jsxs = jsxWithValidationStatic;
      reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
      reactJsxRuntime_development.jsx = jsx;
      reactJsxRuntime_development.jsxs = jsxs;
    })();
  }
  return reactJsxRuntime_development;
}
var hasRequiredJsxRuntime;
function requireJsxRuntime() {
  if (hasRequiredJsxRuntime) return jsxRuntime.exports;
  hasRequiredJsxRuntime = 1;
  {
    jsxRuntime.exports = requireReactJsxRuntime_development();
  }
  return jsxRuntime.exports;
}
var jsxRuntimeExports = requireJsxRuntime();
var QueryClientContext = reactExports.createContext(
  void 0
);
var useQueryClient = (queryClient) => {
  const client2 = reactExports.useContext(QueryClientContext);
  if (!client2) {
    throw new Error("No QueryClient set, use QueryClientProvider to set one");
  }
  return client2;
};
var QueryClientProvider = ({
  client: client2,
  children
}) => {
  reactExports.useEffect(() => {
    client2.mount();
    return () => {
      client2.unmount();
    };
  }, [client2]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(QueryClientContext.Provider, { value: client2, children });
};
var IsRestoringContext = reactExports.createContext(false);
var useIsRestoring = () => reactExports.useContext(IsRestoringContext);
IsRestoringContext.Provider;
function createValue() {
  let isReset = false;
  return {
    clearReset: () => {
      isReset = false;
    },
    reset: () => {
      isReset = true;
    },
    isReset: () => {
      return isReset;
    }
  };
}
var QueryErrorResetBoundaryContext = reactExports.createContext(createValue());
var useQueryErrorResetBoundary = () => reactExports.useContext(QueryErrorResetBoundaryContext);
var ensurePreventErrorBoundaryRetry = (options2, errorResetBoundary) => {
  if (options2.suspense || options2.throwOnError || options2.experimental_prefetchInRender) {
    if (!errorResetBoundary.isReset()) {
      options2.retryOnMount = false;
    }
  }
};
var useClearResetErrorBoundary = (errorResetBoundary) => {
  reactExports.useEffect(() => {
    errorResetBoundary.clearReset();
  }, [errorResetBoundary]);
};
var getHasError = ({
  result,
  errorResetBoundary,
  throwOnError,
  query,
  suspense
}) => {
  return result.isError && !errorResetBoundary.isReset() && !result.isFetching && query && (suspense && result.data === void 0 || shouldThrowError(throwOnError, [result.error, query]));
};
var ensureSuspenseTimers = (defaultedOptions) => {
  if (defaultedOptions.suspense) {
    const MIN_SUSPENSE_TIME_MS = 1e3;
    const clamp = (value) => value === "static" ? value : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS);
    const originalStaleTime = defaultedOptions.staleTime;
    defaultedOptions.staleTime = typeof originalStaleTime === "function" ? (...args) => clamp(originalStaleTime(...args)) : clamp(originalStaleTime);
    if (typeof defaultedOptions.gcTime === "number") {
      defaultedOptions.gcTime = Math.max(
        defaultedOptions.gcTime,
        MIN_SUSPENSE_TIME_MS
      );
    }
  }
};
var willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
var shouldSuspend = (defaultedOptions, result) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && result.isPending;
var fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).catch(() => {
  errorResetBoundary.clearReset();
});
function useBaseQuery(options2, Observer, queryClient) {
  var _a3, _b2, _c2, _d2, _e2;
  {
    if (typeof options2 !== "object" || Array.isArray(options2)) {
      throw new Error(
        'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object'
      );
    }
  }
  const isRestoring = useIsRestoring();
  const errorResetBoundary = useQueryErrorResetBoundary();
  const client2 = useQueryClient();
  const defaultedOptions = client2.defaultQueryOptions(options2);
  (_b2 = (_a3 = client2.getDefaultOptions().queries) == null ? void 0 : _a3._experimental_beforeQuery) == null ? void 0 : _b2.call(
    _a3,
    defaultedOptions
  );
  {
    if (!defaultedOptions.queryFn) {
      console.error(
        `[${defaultedOptions.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`
      );
    }
  }
  defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
  ensureSuspenseTimers(defaultedOptions);
  ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
  useClearResetErrorBoundary(errorResetBoundary);
  const isNewCacheEntry = !client2.getQueryCache().get(defaultedOptions.queryHash);
  const [observer] = reactExports.useState(
    () => new Observer(
      client2,
      defaultedOptions
    )
  );
  const result = observer.getOptimisticResult(defaultedOptions);
  const shouldSubscribe = !isRestoring && options2.subscribed !== false;
  reactExports.useSyncExternalStore(
    reactExports.useCallback(
      (onStoreChange) => {
        const unsubscribe = shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop;
        observer.updateResult();
        return unsubscribe;
      },
      [observer, shouldSubscribe]
    ),
    () => observer.getCurrentResult(),
    () => observer.getCurrentResult()
  );
  reactExports.useEffect(() => {
    observer.setOptions(defaultedOptions);
  }, [defaultedOptions, observer]);
  if (shouldSuspend(defaultedOptions, result)) {
    throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
  }
  if (getHasError({
    result,
    errorResetBoundary,
    throwOnError: defaultedOptions.throwOnError,
    query: client2.getQueryCache().get(defaultedOptions.queryHash),
    suspense: defaultedOptions.suspense
  })) {
    throw result.error;
  }
  (_d2 = (_c2 = client2.getDefaultOptions().queries) == null ? void 0 : _c2._experimental_afterQuery) == null ? void 0 : _d2.call(
    _c2,
    defaultedOptions,
    result
  );
  if (defaultedOptions.experimental_prefetchInRender && !isServer && willFetch(result, isRestoring)) {
    const promise = isNewCacheEntry ? (
      // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
      fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
    ) : (
      // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
      (_e2 = client2.getQueryCache().get(defaultedOptions.queryHash)) == null ? void 0 : _e2.promise
    );
    promise == null ? void 0 : promise.catch(noop).finally(() => {
      observer.updateResult();
    });
  }
  return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
}
function useQuery(options2, queryClient) {
  return useBaseQuery(options2, QueryObserver);
}
function useMutation(options2, queryClient) {
  const client2 = useQueryClient();
  const [observer] = reactExports.useState(
    () => new MutationObserver(
      client2,
      options2
    )
  );
  reactExports.useEffect(() => {
    observer.setOptions(options2);
  }, [observer, options2]);
  const result = reactExports.useSyncExternalStore(
    reactExports.useCallback(
      (onStoreChange) => observer.subscribe(notifyManager.batchCalls(onStoreChange)),
      [observer]
    ),
    () => observer.getCurrentResult(),
    () => observer.getCurrentResult()
  );
  const mutate = reactExports.useCallback(
    (variables, mutateOptions) => {
      observer.mutate(variables, mutateOptions).catch(noop);
    },
    [observer]
  );
  if (result.error && shouldThrowError(observer.options.throwOnError, [result.error])) {
    throw result.error;
  }
  return { ...result, mutate, mutateAsync: result.mutate };
}
function createJSONStorage(getStorage, options2) {
  let storage;
  try {
    storage = getStorage();
  } catch (e4) {
    return;
  }
  const persistStorage = {
    getItem: (name) => {
      var _a3;
      const parse = (str2) => {
        if (str2 === null) {
          return null;
        }
        return JSON.parse(str2, void 0);
      };
      const str = (_a3 = storage.getItem(name)) != null ? _a3 : null;
      if (str instanceof Promise) {
        return str.then(parse);
      }
      return parse(str);
    },
    setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, void 0)),
    removeItem: (name) => storage.removeItem(name)
  };
  return persistStorage;
}
const toThenable = (fn) => (input) => {
  try {
    const result = fn(input);
    if (result instanceof Promise) {
      return result;
    }
    return {
      then(onFulfilled) {
        return toThenable(onFulfilled)(result);
      },
      catch(_onRejected) {
        return this;
      }
    };
  } catch (e4) {
    return {
      then(_onFulfilled) {
        return this;
      },
      catch(onRejected) {
        return toThenable(onRejected)(e4);
      }
    };
  }
};
const persistImpl = (config, baseOptions) => (set, get2, api2) => {
  let options2 = {
    storage: createJSONStorage(() => localStorage),
    partialize: (state) => state,
    version: 0,
    merge: (persistedState, currentState) => ({
      ...currentState,
      ...persistedState
    }),
    ...baseOptions
  };
  let hasHydrated = false;
  const hydrationListeners = /* @__PURE__ */ new Set();
  const finishHydrationListeners = /* @__PURE__ */ new Set();
  let storage = options2.storage;
  if (!storage) {
    return config(
      (...args) => {
        console.warn(
          `[zustand persist middleware] Unable to update item '${options2.name}', the given storage is currently unavailable.`
        );
        set(...args);
      },
      get2,
      api2
    );
  }
  const setItem = () => {
    const state = options2.partialize({ ...get2() });
    return storage.setItem(options2.name, {
      state,
      version: options2.version
    });
  };
  const savedSetState = api2.setState;
  api2.setState = (state, replace) => {
    savedSetState(state, replace);
    void setItem();
  };
  const configResult = config(
    (...args) => {
      set(...args);
      void setItem();
    },
    get2,
    api2
  );
  api2.getInitialState = () => configResult;
  let stateFromStorage;
  const hydrate = () => {
    var _a3, _b2;
    if (!storage) return;
    hasHydrated = false;
    hydrationListeners.forEach((cb) => {
      var _a22;
      return cb((_a22 = get2()) != null ? _a22 : configResult);
    });
    const postRehydrationCallback = ((_b2 = options2.onRehydrateStorage) == null ? void 0 : _b2.call(options2, (_a3 = get2()) != null ? _a3 : configResult)) || void 0;
    return toThenable(storage.getItem.bind(storage))(options2.name).then((deserializedStorageValue) => {
      if (deserializedStorageValue) {
        if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options2.version) {
          if (options2.migrate) {
            const migration = options2.migrate(
              deserializedStorageValue.state,
              deserializedStorageValue.version
            );
            if (migration instanceof Promise) {
              return migration.then((result) => [true, result]);
            }
            return [true, migration];
          }
          console.error(
            `State loaded from storage couldn't be migrated since no migrate function was provided`
          );
        } else {
          return [false, deserializedStorageValue.state];
        }
      }
      return [false, void 0];
    }).then((migrationResult) => {
      var _a22;
      const [migrated, migratedState] = migrationResult;
      stateFromStorage = options2.merge(
        migratedState,
        (_a22 = get2()) != null ? _a22 : configResult
      );
      set(stateFromStorage, true);
      if (migrated) {
        return setItem();
      }
    }).then(() => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
      stateFromStorage = get2();
      hasHydrated = true;
      finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
    }).catch((e4) => {
      postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e4);
    });
  };
  api2.persist = {
    setOptions: (newOptions) => {
      options2 = {
        ...options2,
        ...newOptions
      };
      if (newOptions.storage) {
        storage = newOptions.storage;
      }
    },
    clearStorage: () => {
      storage == null ? void 0 : storage.removeItem(options2.name);
    },
    getOptions: () => options2,
    rehydrate: () => hydrate(),
    hasHydrated: () => hasHydrated,
    onHydrate: (cb) => {
      hydrationListeners.add(cb);
      return () => {
        hydrationListeners.delete(cb);
      };
    },
    onFinishHydration: (cb) => {
      finishHydrationListeners.add(cb);
      return () => {
        finishHydrationListeners.delete(cb);
      };
    }
  };
  if (!options2.skipHydration) {
    hydrate();
  }
  return stateFromStorage || configResult;
};
const persist = persistImpl;
class BaseAdapter {
  constructor(config) {
    __publicField2(this, "config");
    this.config = config;
  }
  // 错误处理辅助方法
  createError(message, originalError, code) {
    const error = new Error(message);
    error.provider = this.config.provider;
    error.originalError = originalError;
    error.code = code;
    return error;
  }
}
const API_V2_URLS = {
  INSTANCE_LIST: "https://www.chenyu.cn/api/open/v2/instance/list",
  INSTANCE_CREATE_BY_POD: "https://www.chenyu.cn/api/open/v2/instance/create_by_pod",
  INSTANCE_STARTUP: "https://www.chenyu.cn/api/open/v2/instance/startup",
  INSTANCE_SHUTDOWN: "https://www.chenyu.cn/api/open/v2/instance/shutdown",
  INSTANCE_RESTART: "https://www.chenyu.cn/api/open/v2/instance/restart",
  INSTANCE_DESTROY: "https://www.chenyu.cn/api/open/v2/instance/destroy",
  BALANCE_INFO: "https://www.chenyu.cn/api/open/v2/balance/info"
};
const createChenyu2API = (apikey) => {
  const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${apikey}`
  };
  return {
    getInstanceList: async () => {
      const response = await fetch(API_V2_URLS.INSTANCE_LIST, {
        method: "GET",
        headers
      });
      return response.json();
    },
    createInstanceByPod: async (params) => {
      const response = await fetch(API_V2_URLS.INSTANCE_CREATE_BY_POD, {
        method: "POST",
        headers,
        body: JSON.stringify(params)
      });
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      return response.json();
    },
    startupInstance: async (instanceUuid) => {
      const response = await fetch(API_V2_URLS.INSTANCE_STARTUP, {
        method: "POST",
        headers,
        body: JSON.stringify({ instance_uuid: instanceUuid })
      });
      return response.json();
    },
    shutdownInstance: async (instanceUuid) => {
      const response = await fetch(API_V2_URLS.INSTANCE_SHUTDOWN, {
        method: "POST",
        headers,
        body: JSON.stringify({ instance_uuid: instanceUuid })
      });
      return response.json();
    },
    restartInstance: async (instanceUuid) => {
      const response = await fetch(API_V2_URLS.INSTANCE_RESTART, {
        method: "POST",
        headers,
        body: JSON.stringify({ instance_uuid: instanceUuid })
      });
      return response.json();
    },
    destroyInstance: async (instanceUuid) => {
      const response = await fetch(API_V2_URLS.INSTANCE_DESTROY, {
        method: "POST",
        headers,
        body: JSON.stringify({ instance_uuid: instanceUuid })
      });
      return response.json();
    },
    getBalance: async () => {
      const response = await fetch(API_V2_URLS.BALANCE_INFO, {
        method: "GET",
        headers
      });
      return response.json();
    }
  };
};
const INSTANCE_STATUS = {
  CREATED: 1,
  RUNNING: 2,
  SHUTTING_DOWN: 21,
  SHUTDOWN: 22,
  STARTING_UP: 24,
  RESTARTING: 27
};
const RESPONSE_CODES = {
  SUCCESS: 0,
  NOT_LOGGED_IN: 2,
  SYSTEM_ERROR: -2
};
const InstanceStatus = {
  CREATING: "creating",
  // 创建中
  STARTING: "starting",
  // 启动中
  RUNNING: "running",
  // 运行中
  STOPPING: "stopping",
  // 停止中
  STOPPED: "stopped",
  // 已停止
  DESTROYING: "destroying",
  // 销毁中
  DESTROYED: "destroyed",
  // 已销毁
  ERROR: "error",
  // 错误状态
  UNKNOWN: "unknown"
  // 未知状态
};
class ChenyuAdapter extends BaseAdapter {
  constructor() {
    super(...arguments);
    __publicField2(this, "api", createChenyu2API(this.config.apiKey));
  }
  mapStatus(originalStatus) {
    switch (originalStatus) {
      case INSTANCE_STATUS.CREATED:
        return InstanceStatus.CREATING;
      case INSTANCE_STATUS.RUNNING:
        return InstanceStatus.RUNNING;
      case INSTANCE_STATUS.SHUTTING_DOWN:
        return InstanceStatus.STOPPING;
      case INSTANCE_STATUS.SHUTDOWN:
        return InstanceStatus.STOPPED;
      case INSTANCE_STATUS.STARTING_UP:
        return InstanceStatus.STARTING;
      case INSTANCE_STATUS.RESTARTING:
        return InstanceStatus.STARTING;
      default:
        return InstanceStatus.UNKNOWN;
    }
  }
  async getInstances() {
    try {
      const response = await this.api.getInstanceList();
      if (response.code !== RESPONSE_CODES.SUCCESS) {
        throw this.createError(`Failed to get instances from Chenyu2: ${response.msg} (code: ${response.code})`, response, response.code);
      }
      const instanceList = response.data.instance_list || [];
      const instances = instanceList.map((item) => {
        var _a3;
        return {
          id: item.instance_uuid,
          name: item.title,
          status: this.mapStatus(item.status),
          statusText: this.getStatusText(item.status),
          gpuModel: item.gpu_name,
          gpuCount: item.gpu_nums,
          webUrl: item.server_url.find((url) => url.startsWith("https://")) || "",
          connectURL: ((_a3 = item.server_map.find((sm) => sm.port_type === "http")) == null ? void 0 : _a3.url) || "",
          createTime: item.create_time,
          startTime: item.start_time,
          stopTime: void 0,
          pricePerHour: 0,
          provider: "chenyu",
          raw: item
        };
      });
      return {
        instances,
        total: response.data.total || 0,
        provider: "chenyu"
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError(`Failed to get instances from Chenyu2: ${error.message || error}`, error);
    }
  }
  async getBalance() {
    try {
      const response = await this.api.getBalance();
      if (response.code !== RESPONSE_CODES.SUCCESS) {
        throw this.createError(response.msg || "Unknown error", response, response.code);
      }
      return {
        balance: parseFloat(response.data.balance || "0"),
        currency: response.data.currency || "CNY",
        provider: "chenyu",
        raw: response.data
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to get balance from Chenyu2", error);
    }
  }
  async createInstance(params) {
    try {
      const chenyu2Params = {
        pod_uuid: params.imageId,
        pod_tag: params.imageName || void 0,
        gpu_uuid: params.gpuModel,
        gpu_nums: 1
      };
      const response = await this.api.createInstanceByPod(chenyu2Params);
      if (response.code !== RESPONSE_CODES.SUCCESS) {
        throw this.createError(`Failed to create instance on Chenyu2: ${response.msg} (code: ${response.code})`, response, response.code);
      }
      return {
        instanceId: response.data.instance_uuid,
        success: true,
        message: response.msg,
        provider: "chenyu",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError(`Failed to create instance on Chenyu2: ${error.message || error}`, error);
    }
  }
  async startInstance(instanceId) {
    try {
      const response = await this.api.startupInstance(instanceId);
      return {
        success: response.code === RESPONSE_CODES.SUCCESS,
        message: response.msg,
        provider: "chenyu",
        raw: response
      };
    } catch (error) {
      throw this.createError("Failed to start instance on Chenyu2", error);
    }
  }
  async stopInstance(instanceId) {
    try {
      const response = await this.api.shutdownInstance(instanceId);
      return {
        success: response.code === RESPONSE_CODES.SUCCESS,
        message: response.msg,
        provider: "chenyu",
        raw: response
      };
    } catch (error) {
      throw this.createError("Failed to stop instance on Chenyu2", error);
    }
  }
  async destroyInstance(instanceId) {
    try {
      const response = await this.api.destroyInstance(instanceId);
      return {
        success: response.code === RESPONSE_CODES.SUCCESS,
        message: response.msg,
        provider: "chenyu",
        raw: response
      };
    } catch (error) {
      throw this.createError("Failed to destroy instance on Chenyu2", error);
    }
  }
  async restartInstance(instanceId) {
    try {
      const response = await this.api.restartInstance(instanceId);
      return {
        success: response.code === RESPONSE_CODES.SUCCESS,
        message: response.msg || "Instance restarted successfully",
        provider: "chenyu",
        raw: response
      };
    } catch (error) {
      throw this.createError("Failed to restart instance on Chenyu2", error);
    }
  }
  getStatusText(status) {
    switch (status) {
      case INSTANCE_STATUS.CREATED:
        return "已创建";
      case INSTANCE_STATUS.RUNNING:
        return "运行中";
      case INSTANCE_STATUS.SHUTTING_DOWN:
        return "关机中";
      case INSTANCE_STATUS.SHUTDOWN:
        return "已关机";
      case INSTANCE_STATUS.STARTING_UP:
        return "开机中";
      case INSTANCE_STATUS.RESTARTING:
        return "重启中";
      default:
        return "未知状态";
    }
  }
}
const API_URLS$1 = {
  INSTANCES: "https://api.xiangongyun.com/open/instances",
  INSTANCE_DETAIL: (id) => `https://api.xiangongyun.com/open/instance/${id}`,
  INSTANCE_DESTROY: "https://api.xiangongyun.com/open/instance/destroy",
  INSTANCE_DEPLOY: "https://api.xiangongyun.com/open/instance/deploy",
  INSTANCE_SHUTDOWN_WITH_GPU: "https://api.xiangongyun.com/open/instance/shutdown",
  INSTANCE_SHUTDOWN_WITHOUT_GPU: "https://api.xiangongyun.com/open/instance/shutdown_release_gpu",
  INSTANCE_SHUTDOWN_AND_DESTROY: "https://api.xiangongyun.com/open/instance/shutdown_destroy",
  INSTANCE_START: "https://api.xiangongyun.com/open/instance/boot",
  BALANCE: "https://api.xiangongyun.com/open/balance"
};
const createXiangongAPI = (apikey) => {
  const headers = {
    "Content-Type": "application/json",
    "Authorization": apikey
  };
  return {
    getInstanceList: async () => {
      const response = await fetch(API_URLS$1.INSTANCES, { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getInstanceInfo: async (id) => {
      const response = await fetch(API_URLS$1.INSTANCE_DETAIL(id), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    destroyInstance: async (id) => {
      const response = await fetch(API_URLS$1.INSTANCE_DESTROY, {
        method: "POST",
        headers,
        body: JSON.stringify({ id })
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    deployInstance: async (params) => {
      const response = await fetch(API_URLS$1.INSTANCE_DEPLOY, {
        method: "POST",
        headers,
        body: JSON.stringify(params)
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      return json;
    },
    shutdownWithGPU: async (id) => {
      const response = await fetch(API_URLS$1.INSTANCE_SHUTDOWN_WITH_GPU, {
        method: "POST",
        headers,
        body: JSON.stringify({ id })
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    shutdownWithoutGPU: async (id) => {
      const response = await fetch(API_URLS$1.INSTANCE_SHUTDOWN_WITHOUT_GPU, {
        method: "POST",
        headers,
        body: JSON.stringify({ id })
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    shutdownAndDestroy: async (id) => {
      const response = await fetch(API_URLS$1.INSTANCE_SHUTDOWN_AND_DESTROY, {
        method: "POST",
        headers,
        body: JSON.stringify({ id })
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    startInstance: async (params) => {
      const response = await fetch(API_URLS$1.INSTANCE_START, {
        method: "POST",
        headers,
        body: JSON.stringify(params)
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getBalance: async () => {
      const response = await fetch(API_URLS$1.BALANCE, { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 0 && json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    }
  };
};
class XiangongAdapter extends BaseAdapter {
  constructor() {
    super(...arguments);
    __publicField2(this, "api", createXiangongAPI(this.config.apiKey));
  }
  mapStatus(originalStatus) {
    switch (originalStatus) {
      case "deploying":
        return InstanceStatus.CREATING;
      case "booting":
        return InstanceStatus.STARTING;
      case "running":
        return InstanceStatus.RUNNING;
      case "shutting_down":
        return InstanceStatus.STOPPING;
      case "shutdown":
        return InstanceStatus.STOPPED;
      case "destroying":
        return InstanceStatus.DESTROYING;
      case "destroyed":
        return InstanceStatus.DESTROYED;
      case "saving_image":
      case "freezing":
      case "freeze":
      case "replacing_image":
        return InstanceStatus.UNKNOWN;
      default:
        return InstanceStatus.UNKNOWN;
    }
  }
  async getInstances() {
    try {
      const response = await this.api.getInstanceList();
      if (response.code !== 0 && response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      const instances = response.data.list.map((item) => ({
        id: item.id,
        name: item.name,
        status: this.mapStatus(item.status),
        statusText: item.status,
        gpuModel: item.gpu_model,
        gpuCount: item.gpu_used,
        webUrl: item.web_url,
        connectURL: `https://${item.id}-8188.container.x-gpu.com/`,
        createTime: item.create_timestamp,
        startTime: item.start_timestamp || void 0,
        stopTime: item.stop_timestamp || void 0,
        pricePerHour: item.price_per_hour,
        provider: "xiangong",
        raw: item
      }));
      return {
        instances,
        total: response.data.total,
        provider: "xiangong"
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to get instances from Xiangong", error);
    }
  }
  async getBalance() {
    try {
      const response = await this.api.getBalance();
      if (response.code !== 0 && response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      return {
        balance: response.data.balance,
        currency: "CNY",
        provider: "xiangong",
        raw: response.data
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to get balance from Xiangong", error);
    }
  }
  async createInstance(params) {
    try {
      const xiangongParams = {
        gpu_model: params.gpuModel,
        gpu_count: 1,
        // 默认1个GPU
        data_center_id: 1,
        // 默认数据中心
        image: params.imageId,
        image_type: "community"
      };
      const response = await this.api.deployInstance(xiangongParams);
      if (response.code !== 0 && response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      return {
        instanceId: response.data.id,
        success: true,
        message: response.msg || "Instance created successfully",
        provider: "xiangong",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to create instance on Xiangong", error);
    }
  }
  async startInstance(instanceId) {
    try {
      const response = await this.api.startInstance({ id: instanceId });
      return {
        success: response.code === 0 || response.code === 200,
        message: response.msg || "Instance started successfully",
        provider: "xiangong",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to start instance on Xiangong", error);
    }
  }
  async stopInstance(instanceId) {
    try {
      const response = await this.api.shutdownWithoutGPU(instanceId);
      return {
        success: response.code === 0 || response.code === 200,
        message: response.msg || "Instance stopped successfully",
        provider: "xiangong",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to stop instance on Xiangong", error);
    }
  }
  async destroyInstance(instanceId) {
    try {
      const response = await this.api.shutdownAndDestroy(instanceId);
      return {
        success: response.code === 0 || response.code === 200,
        message: response.msg || "Instance destroyed successfully",
        provider: "xiangong",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to destroy instance on Xiangong", error);
    }
  }
  async restartInstance(instanceId) {
    try {
      const stopResponse = await this.api.shutdownWithGPU(instanceId);
      if (stopResponse.code !== 0 && stopResponse.code !== 200) {
        throw this.createError(stopResponse.msg || "Failed to stop instance", stopResponse, stopResponse.code);
      }
      const maxWaitTime = 3e5;
      const pollInterval = 5e3;
      const startTime = Date.now();
      while (Date.now() - startTime < maxWaitTime) {
        try {
          const instanceInfo = await this.api.getInstanceInfo(instanceId);
          if (instanceInfo.code === 0 || instanceInfo.code === 200) {
            const status = instanceInfo.data.status;
            if (status === "shutdown") {
              break;
            }
            if (status === "destroyed" || status === "freeze") {
              throw this.createError(`Instance entered unexpected state: ${status}`, instanceInfo);
            }
          }
        } catch (error) {
          console.warn(`Failed to get instance info for ${instanceId}:`, error.message);
        }
        await new Promise((resolve2) => setTimeout(resolve2, pollInterval));
      }
      if (Date.now() - startTime >= maxWaitTime) {
        throw this.createError("Timeout waiting for instance to shutdown", { instanceId, maxWaitTime });
      }
      const startResponse = await this.api.startInstance({ id: instanceId });
      return {
        success: startResponse.code === 0 || startResponse.code === 200,
        message: startResponse.msg || "Instance restarted successfully",
        provider: "xiangong",
        raw: { stopResponse, startResponse }
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to restart instance on Xiangong", error);
    }
  }
}
const API_URLS = {
  APPLICATIONS: "https://api.lightcc.cloud/equipment/deviceServer/openApplication",
  APPLICATION_DETAIL: (aId) => `https://api.lightcc.cloud/equipment/deviceServer/openApplicationDetails/${aId}`,
  APPLICATION_CREATE: "https://api.lightcc.cloud/equipment/deviceServer/openCreateApplication",
  APPLICATION_START: (aId) => `https://api.lightcc.cloud/equipment/deviceServer/openRestartApplication/${aId}`,
  APPLICATION_STOP: (aId) => `https://api.lightcc.cloud/equipment/deviceServer/openStopApplication/${aId}`,
  APPLICATION_DESTROY: (aId) => `https://api.lightcc.cloud/equipment/deviceServer/openDestructionApplication/${aId}`,
  APPLICATION_TIMED_STOP: (aId) => `https://api.lightcc.cloud/equipment/deviceServer/openTimedStopApplication/${aId}`,
  APPLICATION_LINKS: (type2, aId) => `https://api.lightcc.cloud/equipment/deviceServer/applicationLinks/${type2}/${aId}`,
  IMAGES: "https://api.lightcc.cloud/system/applicationImage/openListByUser",
  IMAGE_DETAIL: (imageId) => `https://api.lightcc.cloud/system/applicationImage/openGetInfoById/${imageId}`,
  AVAILABLE_GPU: "https://api.lightcc.cloud/equipment/deviceServer/openAvailableGpuConfig",
  GPU_PRICE: "https://api.lightcc.cloud/recharge/charge/getGpuPrice",
  BALANCE: "https://api.lightcc.cloud/recharge/order-info/openSelectBalance"
};
const createLightccAPI = (apikey) => {
  const headers = {
    "Content-Type": "application/json",
    "X-Api-Key": apikey
  };
  return {
    getApplications: async (params) => {
      const url = new URL(API_URLS.APPLICATIONS);
      if (params == null ? void 0 : params.runningState) {
        url.searchParams.append("runningState", params.runningState);
      }
      const response = await fetch(url.toString(), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getApplicationDetail: async (aId) => {
      const response = await fetch(API_URLS.APPLICATION_DETAIL(aId), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    createApplication: async (params) => {
      const response = await fetch(API_URLS.APPLICATION_CREATE, {
        method: "POST",
        headers,
        body: JSON.stringify(params)
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    startApplication: async (aId) => {
      const response = await fetch(API_URLS.APPLICATION_START(aId), {
        method: "POST",
        headers
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    stopApplication: async (aId) => {
      const response = await fetch(API_URLS.APPLICATION_STOP(aId), {
        method: "POST",
        headers
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    destroyApplication: async (aId) => {
      const response = await fetch(API_URLS.APPLICATION_DESTROY(aId), {
        method: "POST",
        headers
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    timedStopApplication: async (aId, stopTime) => {
      const url = new URL(API_URLS.APPLICATION_TIMED_STOP(aId));
      url.searchParams.append("stopTime", stopTime);
      const response = await fetch(url.toString(), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getApplicationLinks: async (type2, aId) => {
      const response = await fetch(API_URLS.APPLICATION_LINKS(type2, aId), {
        method: "POST",
        headers
      });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getImages: async (params) => {
      const url = new URL(API_URLS.IMAGES);
      if (params == null ? void 0 : params.title) {
        url.searchParams.append("title", params.title);
      }
      const response = await fetch(url.toString(), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getImageDetail: async (imageId) => {
      const response = await fetch(API_URLS.IMAGE_DETAIL(imageId), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getAvailableGpu: async (imageId) => {
      const url = new URL(API_URLS.AVAILABLE_GPU);
      url.searchParams.append("imageId", imageId);
      const response = await fetch(url.toString(), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getGpuPrice: async (params) => {
      const url = new URL(API_URLS.GPU_PRICE);
      url.searchParams.append("gpuModel", params.gpuModel);
      url.searchParams.append("gpuCount", params.gpuCount);
      url.searchParams.append("billingMode", params.billingMode);
      url.searchParams.append("cycle", params.cycle);
      const response = await fetch(url.toString(), { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    },
    getBalance: async () => {
      const response = await fetch(API_URLS.BALANCE, { headers });
      if (response.status !== 200) {
        throw new Error(response.statusText);
      }
      const json = await response.json();
      if (json.code !== 200) {
        throw new Error(json.msg);
      }
      return json;
    }
  };
};
class LightccAdapter extends BaseAdapter {
  constructor() {
    super(...arguments);
    __publicField2(this, "api", createLightccAPI(this.config.apiKey));
  }
  mapStatus(originalStatus) {
    switch (originalStatus) {
      case "0":
        return InstanceStatus.CREATING;
      // 创建中
      case "1":
        return InstanceStatus.RUNNING;
      // 运行中
      case "2":
        return InstanceStatus.STOPPED;
      // 关机
      case "3":
        return InstanceStatus.STARTING;
      // 启动中
      case "4":
        return InstanceStatus.STOPPING;
      // 关机中
      case "5":
        return InstanceStatus.UNKNOWN;
      // 未知
      case "6":
        return InstanceStatus.DESTROYED;
      // 销毁
      case "7":
        return InstanceStatus.ERROR;
      // 异常
      case "8":
        return InstanceStatus.STARTING;
      // 重启中
      default:
        return InstanceStatus.UNKNOWN;
    }
  }
  async getInstances() {
    try {
      const response = await this.api.getApplications();
      if (response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      const instances = await Promise.all(
        response.data.map(async (item) => {
          let connectURL = "";
          try {
            const detailResponse = await this.api.getApplicationDetail(item.aId);
            if (detailResponse.code === 200 && detailResponse.data.appLink) {
              connectURL = detailResponse.data.appLink;
            }
          } catch (error) {
            console.warn(`无法获取应用 ${item.aId} 的详情信息:`, error);
          }
          return {
            id: item.aId,
            name: item.aApplicationName || item.imageTitle,
            status: this.mapStatus(item.aStatus),
            statusText: item.aStatus,
            gpuModel: item.gpuModel,
            gpuCount: item.aGpuNumbers,
            webUrl: "",
            // Web URL需要通过详情接口获取，此处留空
            connectURL,
            createTime: new Date(item.createTime).getTime(),
            startTime: item.startTime ? new Date(item.startTime).getTime() : void 0,
            stopTime: item.stopTime ? new Date(item.stopTime).getTime() : void 0,
            pricePerHour: item.sRentalPrice,
            provider: "lightcc",
            raw: item
          };
        })
      );
      return {
        instances,
        total: response.data.length,
        provider: "lightcc"
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to get instances from LightCC", error);
    }
  }
  async getBalance() {
    try {
      const response = await this.api.getBalance();
      if (response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      return {
        balance: response.data.balance,
        currency: "CNY",
        provider: "lightcc",
        raw: response.data
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to get balance from LightCC", error);
    }
  }
  async createInstance(params) {
    try {
      let imageName;
      try {
        const imageDetail = await this.api.getImageDetail(params.imageId);
        imageName = imageDetail.data.fileDirectory;
      } catch (error) {
        console.warn("无法获取镜像详情，使用默认imageName");
        imageName = "default-image";
      }
      const lightccParams = {
        imageName,
        imageId: parseInt(params.imageId),
        gpuModel: params.gpuModel,
        numberOfGPUs: 1,
        // 默认1个GPU
        billingMethod: "0",
        // 默认按量计费
        cycle: "0"
      };
      const response = await this.api.createApplication(lightccParams);
      if (response.code !== 200) {
        throw this.createError(response.msg, response, response.code);
      }
      const instanceId = response.msg || "";
      return {
        instanceId,
        success: true,
        message: "Application created successfully",
        provider: "lightcc",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to create instance on LightCC", error);
    }
  }
  async startInstance(instanceId) {
    try {
      const response = await this.api.startApplication(instanceId);
      return {
        success: response.code === 200,
        message: response.msg,
        provider: "lightcc",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to start instance on LightCC", error);
    }
  }
  async stopInstance(instanceId) {
    try {
      const response = await this.api.stopApplication(instanceId);
      return {
        success: response.code === 200,
        message: response.msg,
        provider: "lightcc",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to stop instance on LightCC", error);
    }
  }
  async destroyInstance(instanceId) {
    try {
      const response = await this.api.destroyApplication(instanceId);
      return {
        success: response.code === 200,
        message: response.msg,
        provider: "lightcc",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to destroy instance on LightCC", error);
    }
  }
  async restartInstance(instanceId) {
    try {
      const response = await this.api.startApplication(instanceId);
      return {
        success: response.code === 200,
        message: response.msg,
        provider: "lightcc",
        raw: response
      };
    } catch (error) {
      if (error.provider) {
        throw error;
      }
      throw this.createError("Failed to restart instance on LightCC", error);
    }
  }
}
function createAdapter(config) {
  switch (config.provider) {
    case "chenyu":
      return new ChenyuAdapter(config);
    case "xiangong":
      return new XiangongAdapter(config);
    case "lightcc":
      return new LightccAdapter(config);
    default:
      throw new Error(`Unsupported provider: ${config.provider}`);
  }
}
class BalanceService {
  constructor(config) {
    this.config = config;
  }
  async getBalance() {
    const adapter = createAdapter(this.config);
    return adapter.getBalance();
  }
}
class InstancesService {
  constructor(config) {
    __publicField2(this, "config");
    this.config = config;
  }
  async getInstances() {
    const adapter = createAdapter(this.config);
    return adapter.getInstances();
  }
}
class CreateInstanceService {
  constructor(config) {
    this.config = config;
  }
  async createInstance(params) {
    const adapter = createAdapter(this.config);
    return adapter.createInstance(params);
  }
}
class DestroyInstanceService {
  constructor(config) {
    __publicField2(this, "config");
    this.config = config;
  }
  async destroyInstance(instanceId) {
    const adapter = createAdapter(this.config);
    return adapter.destroyInstance(instanceId);
  }
}
const destroyInstance = async (config, instanceId) => {
  const service = new DestroyInstanceService(config);
  return service.destroyInstance(instanceId);
};
class StartInstanceService {
  constructor(config) {
    this.config = config;
  }
  async startInstance(instanceId) {
    const adapter = createAdapter(this.config);
    return adapter.startInstance(instanceId);
  }
}
class RestartInstanceService {
  constructor(config) {
    this.config = config;
  }
  async restartInstance(instanceId) {
    const adapter = createAdapter(this.config);
    return adapter.restartInstance(instanceId);
  }
}
const restartInstance = async (config, instanceId) => {
  const service = new RestartInstanceService(config);
  return service.restartInstance(instanceId);
};
objectType$1({
  xiangong: objectType$1({
    apiKey: stringType$1()
  }),
  chenyu: objectType$1({
    apiKey: stringType$1()
  }),
  lightcc: objectType$1({
    apiKey: stringType$1()
  })
});
const AIProviders = createStore()(
  persist(
    (set) => ({
      xiangong: {
        apiKey: ""
      },
      chenyu: {
        apiKey: ""
      },
      lightcc: {
        apiKey: ""
      }
    }),
    {
      name: "ai-providers",
      // name of the item in the storage (must be unique)
      storage: createJSONStorage(() => localStorage)
      // (optional) by default, 'localStorage' is used
    }
  )
);
const cloudControlStore = createStore()((set) => ({
  showConnectDialog: false,
  instanceId: "",
  currentPlatform: "none"
}));
mcpMesh.broadcastReceived("cloudcontroller", ({ action }) => {
  const currentPlatform = cloudControlStore.getState().currentPlatform;
  if (action === "open_dialog") {
    cloudControlStore.setState({
      showConnectDialog: true
    });
  } else if (action === "open_output") {
    const { currentPlatform: currentPlatform2, instanceId } = cloudControlStore.getState();
    if (currentPlatform2 == "xiangong") {
      uxp.shell.openExternal(`https://${instanceId}-8081.container.x-gpu.com/files/`);
    } else if (currentPlatform2 == "chenyu") {
      uxp.shell.openExternal(`https://www.chenyu.cn/console/podExample`);
    } else if (currentPlatform2 == "lightcc") {
      uxp.shell.openExternal(`https://lightcc.cloud/myApp`);
    }
  } else if (action === "reboot") {
    if (currentPlatform !== "none") {
      restartInstance({
        apiKey: AIProviders.getState()[currentPlatform].apiKey,
        provider: currentPlatform
      }, cloudControlStore.getState().instanceId);
    }
  } else if (action === "destroy") {
    if (currentPlatform !== "none") {
      destroyInstance({
        apiKey: AIProviders.getState()[currentPlatform].apiKey,
        provider: currentPlatform
      }, cloudControlStore.getState().instanceId);
    }
  }
});
function useComfyUtils() {
  const comfyWebviewURL = useStore(mcpMesh.store, (state) => state.comfyURL);
  const comfyWebviewLoading = useStore(mcpMesh.store, (state) => state.comfyWebviewLoading);
  const comfyWebviewLoadError = useStore(mcpMesh.store, (state) => state.comfyWebviewLoadError);
  const comfyWebviewConnectStatus = useStore(mcpMesh.store, (state) => state.comfyWebviewConnectStatus);
  useStore(mcpMesh.store, (state) => state.comfyHTTPCode);
  const comfyWebviewVersion = useStore(mcpMesh.store, (state) => state.comfyWebviewVersion);
  const comfyWSState = useStore(mcpMesh.getNode("comfy").store, (state) => state.comfyWSState);
  let connectState = "disconnected";
  let connectionError = "";
  let connectionWarning = "";
  if (comfyWebviewLoadError) {
    connectionError = comfyWebviewLoadError;
    connectState = "disconnected";
  } else if (comfyWebviewLoading) {
    connectState = "connecting";
  } else if (comfyWebviewConnectStatus === "connecting") {
    connectState = "connecting";
  } else if (comfyWSState === "reconnecting") {
    connectState = "reconnecting";
  } else if (comfyWebviewURL) {
    connectionError = "";
    connectState = "connected";
  }
  if (comfyWebviewVersion && comfyWebviewVersion !== "510") {
    connectionWarning = `Comfy侧SDPPP版本与插件不匹配，运行可能有问题`;
  }
  return {
    connectionError,
    connectionWarning,
    connectState,
    doConnect(url, instanceId) {
      mcpMesh.actions.setComfyWebviewURL({ url });
      cloudControlStore.setState({
        instanceId
      });
    },
    doDisconnect() {
      mcpMesh.actions.setComfyWebviewURL({ url: "" });
      cloudControlStore.setState({
        instanceId: ""
      });
    }
  };
}
function useInstances(config) {
  var _a3, _b2, _c2;
  const { apiKey, provider } = config;
  const instanceListQuery = useQuery({
    queryKey: ["instances", apiKey, provider],
    queryFn: async () => {
      const service = new InstancesService(config);
      return service.getInstances();
    },
    enabled: !!apiKey
  });
  return {
    instances: (_a3 = instanceListQuery.data) == null ? void 0 : _a3.instances,
    totalInstances: (_b2 = instanceListQuery.data) == null ? void 0 : _b2.total,
    provider: (_c2 = instanceListQuery.data) == null ? void 0 : _c2.provider,
    instancesError: instanceListQuery.error || void 0,
    instancesLoading: instanceListQuery.isLoading,
    refreshInstances: instanceListQuery.refetch
  };
}
function useCreateInstance(config) {
  const queryClient = useQueryClient();
  const { apiKey, provider } = config;
  const mutation = useMutation({
    mutationFn: async (params) => {
      const service = new CreateInstanceService(config);
      return service.createInstance(params);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["instances", apiKey, provider] });
    }
  });
  return {
    createInstance: mutation.mutateAsync,
    createInstanceLoading: mutation.isPending,
    createInstanceError: mutation.error
  };
}
function useDestroyInstance(config) {
  const queryClient = useQueryClient();
  const { apiKey, provider } = config;
  const mutation = useMutation({
    mutationFn: async (instanceId) => {
      const service = new DestroyInstanceService(config);
      return service.destroyInstance(instanceId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["instances", apiKey, provider] });
    }
  });
  return {
    destroyInstance: mutation.mutateAsync,
    destroyInstanceLoading: mutation.isPending,
    destroyInstanceError: mutation.error
  };
}
function useStartInstance(config) {
  const queryClient = useQueryClient();
  const { apiKey, provider } = config;
  const mutation = useMutation({
    mutationFn: async (instanceId) => {
      const service = new StartInstanceService(config);
      return service.startInstance(instanceId);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["instances", apiKey, provider] });
    }
  });
  return {
    startInstance: mutation.mutateAsync,
    startInstanceLoading: mutation.isPending,
    startInstanceError: mutation.error
  };
}
function useBalance(config) {
  const { apiKey, provider } = config;
  const balanceQuery = useQuery({
    queryKey: ["balance", apiKey, provider],
    queryFn: async () => {
      const service = new BalanceService(config);
      return service.getBalance();
    },
    enabled: !!apiKey
  });
  return {
    balance: balanceQuery.data,
    balanceError: balanceQuery.error || void 0,
    balanceLoading: balanceQuery.isLoading
  };
}
function useXiangong(config) {
  const { apiKey } = config;
  const serviceConfig = { apiKey, provider: "xiangong" };
  const {
    instances,
    totalInstances,
    provider,
    instancesError,
    instancesLoading,
    refreshInstances
  } = useInstances(serviceConfig);
  const {
    createInstance,
    createInstanceLoading,
    createInstanceError
  } = useCreateInstance(serviceConfig);
  const {
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError
  } = useDestroyInstance(serviceConfig);
  const {
    startInstance,
    startInstanceLoading,
    startInstanceError
  } = useStartInstance(serviceConfig);
  const {
    balance,
    balanceError,
    balanceLoading
  } = useBalance(serviceConfig);
  reactExports.useEffect(() => {
    if (!apiKey || balanceError || balanceLoading) {
      return;
    }
    const interval = setInterval(() => {
      refreshInstances();
    }, 5e3);
    return () => clearInterval(interval);
  }, [apiKey, balanceError, balanceLoading, refreshInstances]);
  return {
    // Provider info
    provider,
    // Instance management
    instances,
    totalInstances,
    instancesError,
    instancesLoading,
    refreshInstances,
    // Create instance
    createInstance,
    createInstanceLoading,
    createInstanceError,
    // Destroy instance
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError,
    // Start instance
    startInstance,
    startInstanceLoading,
    startInstanceError,
    // Balance
    balance,
    balanceError,
    balanceLoading
  };
}
function useChenyu(config) {
  const { apiKey } = config;
  const serviceConfig = { apiKey, provider: "chenyu" };
  const {
    instances,
    totalInstances,
    provider,
    instancesError,
    instancesLoading,
    refreshInstances
  } = useInstances(serviceConfig);
  const {
    createInstance,
    createInstanceLoading,
    createInstanceError
  } = useCreateInstance(serviceConfig);
  const {
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError
  } = useDestroyInstance(serviceConfig);
  const {
    startInstance,
    startInstanceLoading,
    startInstanceError
  } = useStartInstance(serviceConfig);
  const {
    balance,
    balanceError,
    balanceLoading
  } = useBalance(serviceConfig);
  reactExports.useEffect(() => {
    if (!apiKey || balanceError || balanceLoading) {
      return;
    }
    const interval = setInterval(() => {
      refreshInstances();
    }, 5e3);
    return () => clearInterval(interval);
  }, [apiKey, balanceError, balanceLoading, refreshInstances]);
  return {
    // Provider info
    provider,
    // Instance management
    instances,
    totalInstances,
    instancesError,
    instancesLoading,
    refreshInstances,
    // Create instance
    createInstance,
    createInstanceLoading,
    createInstanceError,
    // Destroy instance
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError,
    // Start instance
    startInstance,
    startInstanceLoading,
    startInstanceError,
    // Balance
    balance,
    balanceError,
    balanceLoading
  };
}
function useLightCC(config) {
  const { apiKey } = config;
  const serviceConfig = { apiKey, provider: "lightcc" };
  const {
    instances,
    totalInstances,
    provider,
    instancesError,
    instancesLoading,
    refreshInstances
  } = useInstances(serviceConfig);
  const {
    createInstance,
    createInstanceLoading,
    createInstanceError
  } = useCreateInstance(serviceConfig);
  const {
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError
  } = useDestroyInstance(serviceConfig);
  const {
    startInstance,
    startInstanceLoading,
    startInstanceError
  } = useStartInstance(serviceConfig);
  const {
    balance,
    balanceError,
    balanceLoading
  } = useBalance(serviceConfig);
  reactExports.useEffect(() => {
    if (!apiKey || balanceError || balanceLoading) {
      return;
    }
    const interval = setInterval(() => {
      refreshInstances();
    }, 5e3);
    return () => clearInterval(interval);
  }, [apiKey, balanceError, balanceLoading, refreshInstances]);
  return {
    // Provider info
    provider,
    // Instance management
    instances,
    totalInstances,
    instancesError,
    instancesLoading,
    refreshInstances,
    // Create instance
    createInstance,
    createInstanceLoading,
    createInstanceError,
    // Destroy instance
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    destroyInstanceError,
    // Start instance
    startInstance,
    startInstanceLoading,
    startInstanceError,
    // Balance
    balance,
    balanceError,
    balanceLoading
  };
}
function CloudControlProvider({ apiKey, provider }) {
  const xiangongHook = useXiangong(provider === "xiangong" ? { apiKey } : { apiKey: "" });
  const chenyuHook = useChenyu(provider === "chenyu" ? { apiKey } : { apiKey: "" });
  const lightccHook = useLightCC(provider === "lightcc" ? { apiKey } : { apiKey: "" });
  const activeHook = provider === "xiangong" ? xiangongHook : provider === "chenyu" ? chenyuHook : lightccHook;
  const {
    instances,
    instancesLoading,
    balance,
    balanceLoading,
    balanceError,
    createInstance,
    createInstanceLoading,
    destroyInstance: destroyInstance2,
    destroyInstanceLoading,
    startInstance,
    startInstanceLoading,
    refreshInstances
  } = activeHook;
  const sdpppX2 = useStore(mcpMesh.store, (state) => state.sdpppX);
  const { connectState, doConnect, doDisconnect } = useComfyUtils();
  const instanceId = useStore(cloudControlStore, (state) => state.instanceId);
  const [createInstanceError, setCreateInstanceError] = reactExports.useState("");
  const [hoverInstanceId, setHoverInstanceId] = reactExports.useState(null);
  const [connectingInstanceId, setConnectingInstanceId] = reactExports.useState(null);
  const [destroyingInstanceId, setDestroyingInstanceId] = reactExports.useState(null);
  const [isCreatingLocked, setIsCreatingLocked] = reactExports.useState(false);
  const [selectedGpuModel, setSelectedGpuModel] = reactExports.useState("");
  const [gpuSelectionError, setGpuSelectionError] = reactExports.useState("");
  const gpuDropdownRef = reactExports.useRef(null);
  const getInstanceConfig = () => {
    switch (provider) {
      case "xiangong":
        return sdpppX2.cloudControls.xiangong;
      case "chenyu":
        return sdpppX2.cloudControls.chenyu;
      case "lightcc":
        return sdpppX2.cloudControls.lightcc;
      default:
        return {};
    }
  };
  const instanceConfig = reactExports.useMemo(() => {
    const config = getInstanceConfig() || {};
    const cloned = { ...config };
    console.debug("[CloudControl] loaded instance config", { provider, config: cloned });
    return cloned;
  }, [provider, sdpppX2]);
  const gpuModelSource = instanceConfig.gpuModel;
  const gpuModelOptions = reactExports.useMemo(() => {
    if (Array.isArray(gpuModelSource)) {
      const options2 = gpuModelSource.map((item) => {
        if (item && typeof item === "object") {
          const option = item;
          if (typeof option.label === "string" && option.label.trim().length > 0 && typeof option.value === "string" && option.value.trim().length > 0) {
            return {
              label: option.label.trim(),
              value: option.value.trim()
            };
          }
        }
        console.warn("[CloudControl] invalid gpuModel option skipped", {
          provider,
          option: item
        });
        return null;
      }).filter((item) => item !== null);
      console.debug("[CloudControl] gpuModel options parsed", {
        provider,
        options: options2
      });
      return options2.length > 0 ? options2 : void 0;
    }
    return void 0;
  }, [gpuModelSource, provider]);
  reactExports.useEffect(() => {
    if (gpuModelOptions && gpuModelOptions.length > 0) {
      const optionValues = gpuModelOptions.map((option) => option.value);
      setSelectedGpuModel((current) => {
        const nextValue = current && optionValues.includes(current) ? current : optionValues[0];
        console.debug("[CloudControl] gpuModel defaulted/retained", nextValue);
        return nextValue;
      });
      setGpuSelectionError("");
      return;
    }
    if (typeof gpuModelSource === "string" && gpuModelSource.trim().length > 0) {
      setSelectedGpuModel(gpuModelSource);
      setGpuSelectionError("");
      return;
    }
    if (gpuModelSource === void 0) {
      setGpuSelectionError("");
      return;
    }
    setSelectedGpuModel("");
    console.warn("[CloudControl] gpuModel configuration missing or invalid", { provider, gpuModelSource });
    setGpuSelectionError("当前云端配置缺少 GPU 型号，请联系管理员补充。");
  }, [gpuModelOptions, gpuModelSource]);
  const requiresGpuSelection = ((gpuModelOptions == null ? void 0 : gpuModelOptions.length) ?? 0) > 0;
  const createButtonDisabled = createInstanceLoading || isCreatingLocked || requiresGpuSelection && !selectedGpuModel;
  const handleCreateInstance = async () => {
    var _a3;
    if (createInstanceLoading || isCreatingLocked) {
      return;
    }
    if (!selectedGpuModel) {
      setGpuSelectionError(requiresGpuSelection ? "请选择 GPU 型号" : "当前云端配置缺少 GPU 型号，请联系管理员补充。");
      return;
    }
    setIsCreatingLocked(true);
    setCreateInstanceError("");
    setGpuSelectionError("");
    setTimeout(() => {
      setIsCreatingLocked(false);
    }, 3e3);
    try {
      const rawConfig = getInstanceConfig() || {};
      console.debug("[CloudControl] submitting createInstance", {
        provider,
        rawConfig,
        selectedGpuModel
      });
      const resolvedParams = {
        ...rawConfig,
        gpuModel: selectedGpuModel
      };
      const res = await createInstance(resolvedParams);
      setTimeout(() => {
        refreshInstances();
      }, 1e3);
    } catch (error) {
      console.error(error);
      const errorMessage = ((_a3 = error.originalError) == null ? void 0 : _a3.msg) || error.message || "未知错误";
      setCreateInstanceError(errorMessage);
    }
  };
  reactExports.useEffect(() => {
    if (apiKey && balance && !balanceError) {
      if (provider === "xiangong") {
        AIProviders.setState({
          xiangong: { apiKey }
        });
      } else if (provider === "chenyu") {
        AIProviders.setState({
          chenyu: { apiKey }
        });
      } else if (provider === "lightcc") {
        AIProviders.setState({
          lightcc: { apiKey }
        });
      }
      cloudControlStore.setState({
        currentPlatform: provider
      });
      doDisconnect();
    }
  }, [balance, balanceError, apiKey, provider]);
  const getProviderInfo = () => {
    switch (provider) {
      case "xiangong":
        return {
          name: "仙宫云",
          rechargeUrl: "https://www.xiangongyun.com/console/finance/recharge"
        };
      case "chenyu":
        return {
          name: "晨羽智云",
          rechargeUrl: "https://www.chenyu.cn/console/accountDetails?invitationCode=BUD913"
        };
      case "lightcc":
        return {
          name: "LightCC",
          rechargeUrl: "https://lightcc.cloud/voucherCenter?invite_id=m95SDj"
        };
      default:
        return {
          name: "云服务",
          rechargeUrl: ""
        };
    }
  };
  const providerInfo = getProviderInfo();
  const getConnectionUrl = (instanceId2) => {
    const instance2 = instances == null ? void 0 : instances.find((i2) => i2.id === instanceId2);
    if (instance2 == null ? void 0 : instance2.connectURL) {
      return instance2.connectURL;
    }
    switch (provider) {
      case "xiangong":
        return `https://${instanceId2}-8188.container.x-gpu.com/`;
      case "chenyu":
      case "lightcc":
      default:
        return (instance2 == null ? void 0 : instance2.webUrl) || "";
    }
  };
  const handleGpuModelChange = reactExports.useCallback((event) => {
    var _a3, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2;
    const value = (event == null ? void 0 : event.target) && typeof event.target.value === "string" && event.target.value || ((_a3 = event == null ? void 0 : event.target) == null ? void 0 : _a3.selectedItem) && typeof event.target.selectedItem.value === "string" && event.target.selectedItem.value || ((_b2 = event == null ? void 0 : event.detail) == null ? void 0 : _b2.value) && typeof event.detail.value === "string" && event.detail.value || ((_c2 = event == null ? void 0 : event.detail) == null ? void 0 : _c2.item) && typeof event.detail.item.value === "string" && event.detail.item.value || "";
    console.debug("[CloudControl] gpuModel changed", {
      provider,
      targetValue: (_d2 = event == null ? void 0 : event.target) == null ? void 0 : _d2.value,
      selectedItemValue: (_f2 = (_e2 = event == null ? void 0 : event.target) == null ? void 0 : _e2.selectedItem) == null ? void 0 : _f2.value,
      detailValue: (_g2 = event == null ? void 0 : event.detail) == null ? void 0 : _g2.value,
      detailItemValue: (_i2 = (_h2 = event == null ? void 0 : event.detail) == null ? void 0 : _h2.item) == null ? void 0 : _i2.value,
      resolvedValue: value
    });
    setSelectedGpuModel(value);
    if (value) {
      setGpuSelectionError("");
    }
  }, [provider]);
  reactExports.useEffect(() => {
    if (!requiresGpuSelection) {
      return;
    }
    const dropdownEl = gpuDropdownRef.current;
    if (!dropdownEl) {
      return;
    }
    console.debug("[CloudControl] attaching dropdown listeners", { provider });
    const listener = (event) => {
      handleGpuModelChange(event);
    };
    dropdownEl.addEventListener("change", listener);
    dropdownEl.addEventListener("input", listener);
    return () => {
      dropdownEl.removeEventListener("change", listener);
      dropdownEl.removeEventListener("input", listener);
    };
  }, [handleGpuModelChange, requiresGpuSelection, provider]);
  reactExports.useEffect(() => {
    console.debug("[CloudControl] sync request for selected GPU", { provider, selectedGpuModel });
  }, [selectedGpuModel, provider]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 bg-white rounded-lg shadow-sm", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-between items-center mb-4", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center gap-3", children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "sp-action-button",
          {
            onClick: handleCreateInstance,
            variant: "primary",
            ...createButtonDisabled ? { disabled: "" } : {},
            class: "bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded",
            children: createInstanceLoading || isCreatingLocked ? "云端开机中..." : "云端开机"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
            lineNumber: 327,
            columnNumber: 21
          },
          this
        ),
        requiresGpuSelection && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "sp-dropdown",
          {
            ref: gpuDropdownRef,
            placeholder: "选择 GPU 型号",
            style: { width: "160px" },
            children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-menu", { slot: "options", children: gpuModelOptions == null ? void 0 : gpuModelOptions.map(({ label, value }) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
              "sp-menu-item",
              {
                value,
                ...selectedGpuModel === value ? { selected: "" } : {},
                children: label
              },
              value,
              false,
              {
                fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                lineNumber: 343,
                columnNumber: 37
              },
              this
            )) }, void 0, false, {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
              lineNumber: 341,
              columnNumber: 29
            }, this)
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
            lineNumber: 336,
            columnNumber: 25
          },
          this
        )
      ] }, void 0, true, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 326,
        columnNumber: 17
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-sm text-gray-700", children: [
          providerInfo.name,
          "余额: ",
          balanceLoading || !balance ? "加载中..." : balance.balance.toFixed(2),
          " ",
          balance == null ? void 0 : balance.currency
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
          lineNumber: 357,
          columnNumber: 21
        }, this),
        providerInfo.rechargeUrl && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "sp-action-button",
          {
            onClick: () => uxp.shell.openExternal(providerInfo.rechargeUrl),
            variant: "secondary",
            class: "bg-gray-200 hover:bg-gray-300 text-gray-700 px-3 py-1 rounded text-sm",
            children: "充值"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
            lineNumber: 362,
            columnNumber: 29
          },
          this
        ) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
          lineNumber: 361,
          columnNumber: 25
        }, this)
      ] }, void 0, true, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 356,
        columnNumber: 17
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
      lineNumber: 325,
      columnNumber: 13
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "space-y-3", children: [
      gpuSelectionError && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-red-400 text-sm", children: gpuSelectionError }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 374,
        columnNumber: 39
      }, this),
      createInstanceError && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-red-400 text-sm", children: createInstanceError }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 375,
        columnNumber: 41
      }, this),
      (instances == null ? void 0 : instances.length) === 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-gray-500", children: "暂无实例, 请点击创建" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 376,
        columnNumber: 45
      }, this),
      instancesLoading ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-gray-500", children: "加载中..." }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 378,
        columnNumber: 21
      }, this) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "space-y-2", children: instances == null ? void 0 : instances.map((instance2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "div",
        {
          className: "flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors",
          onMouseEnter: () => setHoverInstanceId(instance2.id),
          onMouseLeave: () => setHoverInstanceId(null),
          children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "space-y-1", children: [
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "block text-sm", children: [
                "实例ID: ",
                instance2.id
              ] }, void 0, true, {
                fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                lineNumber: 387,
                columnNumber: 37
              }, this),
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "block text-sm", children: [
                "GPU型号: ",
                instance2.gpuModel,
                " x",
                instance2.gpuCount
              ] }, void 0, true, {
                fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                lineNumber: 388,
                columnNumber: 37
              }, this),
              /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "block text-sm text-gray-700", children: [
                "状态: ",
                statusToText(instance2.status)
              ] }, void 0, true, {
                fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                lineNumber: 391,
                columnNumber: 37
              }, this)
            ] }, void 0, true, {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
              lineNumber: 386,
              columnNumber: 33
            }, this),
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: `flex gap-2 ${hoverInstanceId === instance2.id || instanceId === instance2.id ? "flex" : "hidden"}`, children: [
              instance2.status === "running" && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "div",
                {
                  onClick: async () => {
                    if (connectingInstanceId === instance2.id) return;
                    if (connectState !== "disconnected" && instance2.id === instanceId) {
                      doDisconnect();
                    } else {
                      setConnectingInstanceId(instance2.id);
                      try {
                        const connectUrl = getConnectionUrl(instance2.id);
                        doConnect(connectUrl, instance2.id);
                        cloudControlStore.setState({
                          instanceId: instance2.id
                        });
                        setTimeout(() => {
                          setConnectingInstanceId(null);
                        }, 1e3);
                      } catch (error) {
                        console.error("连接失败:", error);
                        setConnectingInstanceId(null);
                      }
                    }
                  },
                  className: "px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white text-sm rounded cursor-pointer",
                  children: connectingInstanceId === instance2.id ? "连接中..." : connectState !== "disconnected" && instance2.id === instanceId ? "断开连接" : "连接"
                },
                void 0,
                false,
                {
                  fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                  lineNumber: 394,
                  columnNumber: 71
                },
                this
              ),
              (instance2.status === "shutdown" || instance2.status === "stopped") && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "div",
                {
                  onClick: async () => {
                    if (startInstanceLoading) return;
                    try {
                      await startInstance(instance2.id);
                      setTimeout(() => {
                        refreshInstances();
                      }, 1e3);
                    } catch (error) {
                      console.error("启动失败:", error);
                    }
                  },
                  className: "px-3 py-1 bg-green-500 hover:bg-green-600 text-white text-sm rounded cursor-pointer",
                  children: startInstanceLoading ? "启动中..." : "启动"
                },
                void 0,
                false,
                {
                  fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                  lineNumber: 428,
                  columnNumber: 107
                },
                this
              ),
              instance2.status === "running" && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                "div",
                {
                  onClick: async () => {
                    if (destroyingInstanceId === instance2.id || destroyInstanceLoading) return;
                    setDestroyingInstanceId(instance2.id);
                    try {
                      await destroyInstance2(instance2.id);
                      setTimeout(() => {
                        refreshInstances();
                        setDestroyingInstanceId(null);
                      }, 1e3);
                    } catch (error) {
                      console.error("销毁失败:", error);
                      setDestroyingInstanceId(null);
                    }
                  },
                  className: "px-3 py-1 bg-red-500 hover:bg-red-600 text-white text-sm rounded cursor-pointer",
                  children: destroyingInstanceId === instance2.id || destroyInstanceLoading ? "关机中..." : "关机"
                },
                void 0,
                false,
                {
                  fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
                  lineNumber: 445,
                  columnNumber: 71
                },
                this
              )
            ] }, void 0, true, {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
              lineNumber: 393,
              columnNumber: 33
            }, this)
          ]
        },
        instance2.id,
        true,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
          lineNumber: 382,
          columnNumber: 29
        },
        this
      )) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
        lineNumber: 380,
        columnNumber: 21
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
      lineNumber: 373,
      columnNumber: 13
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlProvider.tsx",
    lineNumber: 324,
    columnNumber: 9
  }, this);
}
function statusToText(status) {
  switch (status) {
    case "running":
      return "运行中";
    case "creating":
    case "deploying":
      return "创建中";
    case "starting":
    case "booting":
      return "启动中";
    case "stopping":
    case "shutting_down":
      return "关闭中";
    case "stopped":
    case "shutdown":
      return "已关闭";
    case "destroying":
      return "销毁中";
    case "destroyed":
      return "已销毁";
    case "error":
      return "错误";
    case "unknown":
      return "未知状态";
    default:
      return status;
  }
}
function CloudControlUnified({ apiKey }) {
  const [detectedProvider, setDetectedProvider] = reactExports.useState(null);
  const [isDetecting, setIsDetecting] = reactExports.useState(true);
  reactExports.useEffect(() => {
    const detectProvider = async () => {
      setIsDetecting(true);
      const detectionPromises = [
        // 仙宫云检测
        (async () => {
          try {
            const xiangongAdapter = createAdapter({ apiKey, provider: "xiangong" });
            const result = await xiangongAdapter.getBalance();
            return "xiangong";
          } catch (error) {
            throw error;
          }
        })(),
        // LightCC检测
        (async () => {
          try {
            const lightccAdapter = createAdapter({ apiKey, provider: "lightcc" });
            const result = await lightccAdapter.getBalance();
            return "lightcc";
          } catch (error) {
            throw error;
          }
        })(),
        // 晨羽云检测
        (async () => {
          try {
            const chenyuAdapter = createAdapter({ apiKey, provider: "chenyu" });
            const result = await chenyuAdapter.getBalance();
            return "chenyu";
          } catch (error) {
            throw error;
          }
        })()
      ];
      try {
        const results = await Promise.allSettled(detectionPromises);
        const successfulResult = results.find((result) => result.status === "fulfilled");
        if (successfulResult) {
          setDetectedProvider(successfulResult.value);
        } else {
          console.log("All provider detection failed");
          setDetectedProvider(null);
        }
      } catch (error) {
        console.log("Unexpected error during provider detection", error);
        setDetectedProvider(null);
      }
    };
    if (apiKey) {
      detectProvider().finally(() => setIsDetecting(false));
    }
  }, [apiKey]);
  if (isDetecting) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 bg-white rounded-lg shadow-sm", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-gray-500", children: "正在检测API提供商..." }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 79,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 78,
      columnNumber: 17
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 77,
      columnNumber: 13
    }, this);
  }
  if (!detectedProvider) {
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 bg-white rounded-lg shadow-sm", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-red-500", children: "无法识别API提供商，请检查API密钥是否正确" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 89,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 88,
      columnNumber: 17
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
      lineNumber: 87,
      columnNumber: 13
    }, this);
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CloudControlProvider, { apiKey, provider: detectedProvider }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/CloudControlUnified.tsx",
    lineNumber: 95,
    columnNumber: 12
  }, this);
}
function CloudControl() {
  const xiangongApiKey = useStore(AIProviders, (state) => state.xiangong.apiKey);
  const chenyuApiKey = useStore(AIProviders, (state) => state.chenyu.apiKey);
  const lightccApiKey = useStore(AIProviders, (state) => state.lightcc.apiKey);
  const sdpppX2 = useStore(mcpMesh.store, (state) => state.sdpppX);
  const [tempApiKey, setTempApiKey] = reactExports.useState(xiangongApiKey || chenyuApiKey || lightccApiKey || "");
  const { doDisconnect } = useComfyUtils();
  const hasApiKey = xiangongApiKey || chenyuApiKey || lightccApiKey;
  const handleReset = () => {
    AIProviders.setState({
      xiangong: { apiKey: "" },
      chenyu: { apiKey: "" },
      lightcc: { apiKey: "" }
    });
    setTempApiKey("");
    doDisconnect();
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 rounded-md", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-lg font-semibold mb-3 relative flex items-center justify-between", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-lg font-semibold", style: { color: "var(--uxp-host-text-color)" }, children: hasApiKey ? "连接云端" : "或 连接云端" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
        lineNumber: 33,
        columnNumber: 17
      }, this),
      hasApiKey && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "a",
        {
          style: { color: "var(--uxp-host-text-color-secondary)" },
          className: "text-xs absolute right-0 top-0 cursor-pointer hover:text-gray-700",
          onClick: handleReset,
          children: "重设API令牌或按地址连接"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
          lineNumber: 37,
          columnNumber: 21
        },
        this
      )
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
      lineNumber: 32,
      columnNumber: 13
    }, this),
    !hasApiKey && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center gap-2 mb-3", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-textfield",
        {
          id: "api-key",
          label: "API Key",
          onBlur: (ev) => {
            setTempApiKey(ev.currentTarget.value);
          },
          placeholder: "填入云服务商的API令牌",
          class: "flex-1"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
          lineNumber: 50,
          columnNumber: 25
        },
        this
      ) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
        lineNumber: 49,
        columnNumber: 21
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "space-y-2 mb-3", children: [
        sdpppX2.cloudControls.xiangong && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            className: "text-blue-500 hover:text-blue-700 cursor-pointer block",
            onClick: () => uxp.shell.openExternal("https://www.xiangongyun.com/console/user/accesstoken"),
            children: "如何获取仙宫云API令牌？"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
            lineNumber: 59,
            columnNumber: 59
          },
          this
        ),
        sdpppX2.cloudControls.chenyu && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            className: "text-blue-500 hover:text-blue-700 cursor-pointer block",
            onClick: () => uxp.shell.openExternal("https://www.chenyu.cn/console/apiServer?invitationCode=BUD913"),
            children: "如何获取晨羽云API令牌？"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
            lineNumber: 63,
            columnNumber: 57
          },
          this
        ),
        sdpppX2.cloudControls.lightcc && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "a",
          {
            className: "text-blue-500 hover:text-blue-700 cursor-pointer block",
            onClick: () => uxp.shell.openExternal("https://www.lightcc.cloud/userCenter/?invite_id=m95SDj"),
            children: "如何获取LightCC API令牌？"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
            lineNumber: 67,
            columnNumber: 58
          },
          this
        )
      ] }, void 0, true, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
        lineNumber: 58,
        columnNumber: 21
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
      lineNumber: 48,
      columnNumber: 17
    }, this),
    tempApiKey && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CloudControlUnified, { apiKey: tempApiKey }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
      lineNumber: 75,
      columnNumber: 28
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/CloudControl/index.tsx",
    lineNumber: 31,
    columnNumber: 9
  }, this);
}
function FooterElem() {
  const lastRunTime = useStore(mcpMesh.getNode("comfy").store, (state) => state.lastRunTime);
  const [timeSinceLastRun, setTimeSinceLastRun] = reactExports.useState("从未");
  const [shutdownCountdown, setShutdownCountdown] = reactExports.useState("");
  const [hasShutdown, setHasShutdown] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (!lastRunTime) {
      setTimeSinceLastRun("从未");
      setShutdownCountdown("");
      setHasShutdown(false);
      return;
    }
    setHasShutdown(false);
    const updateTimeDiff = () => {
      const now = Date.now();
      const diff = now - lastRunTime;
      const targetTime = 60 * 60 * 1e3;
      const remainingTime = targetTime - diff;
      if (diff < 6e4) {
        setTimeSinceLastRun("刚刚");
      } else if (diff < 36e5) {
        setTimeSinceLastRun(`${Math.floor(diff / 6e4)}分钟前`);
      } else if (diff < 864e5) {
        setTimeSinceLastRun(`${Math.floor(diff / 36e5)}小时前`);
      } else {
        setTimeSinceLastRun(`${Math.floor(diff / 864e5)}天前`);
      }
      if (remainingTime > 0) {
        const remainingMinutes = Math.floor(remainingTime / 6e4);
        const remainingSeconds = Math.floor(remainingTime % 6e4 / 1e3);
        if (remainingMinutes > 0) {
          setShutdownCountdown(`，还有${remainingMinutes}分${remainingSeconds}秒自动关机`);
        } else {
          setShutdownCountdown(`，还有${remainingSeconds}秒`);
        }
      } else {
        setShutdownCountdown("，即将自动关机");
        setHasShutdown((alreadyShutdown) => {
          if (!alreadyShutdown) {
            const currentPlatform = cloudControlStore.getState().currentPlatform;
            const instanceId = cloudControlStore.getState().instanceId;
            if (currentPlatform !== "none" && instanceId) {
              destroyInstance({
                apiKey: AIProviders.getState()[currentPlatform].apiKey,
                provider: currentPlatform
              }, instanceId);
            }
          }
          return true;
        });
      }
    };
    updateTimeDiff();
    const timer = setInterval(updateTimeDiff, 1e3);
    return () => clearInterval(timer);
  }, [lastRunTime]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-xs text-right", style: { color: "var(--uxp-host-text-color-secondary)" }, children: [
    "上次执行：",
    timeSinceLastRun,
    shutdownCountdown
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
    lineNumber: 79,
    columnNumber: 9
  }, this);
}
function HeaderTailElem() {
  const { connectState } = useComfyUtils();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center mr-2 cursor-pointer", onClick: () => {
    cloudControlStore.setState({
      showConnectDialog: true
    });
  }, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: `w-3 h-3 rounded-full mr-1 ` + (connectState === "connected" ? "bg-emerald-300" : "bg-rose-300") }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 94,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { className: "text-xs underline", style: { color: "var(--uxp-host-text-color)" }, children: connectState === "connected" ? "云端已连接" : "云端未连接" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 96,
      columnNumber: 9
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
    lineNumber: 89,
    columnNumber: 14
  }, this);
}
function ConnectDialog() {
  const showConnectDialog = useStore(cloudControlStore, (state) => state.showConnectDialog);
  const lastRunTime = useStore(mcpMesh.getNode("comfy").store, (state) => state.lastRunTime);
  const platform2 = useStore(cloudControlStore, (state) => state.currentPlatform);
  const instanceId = useStore(cloudControlStore, (state) => state.instanceId);
  const comfyURL = useStore(mcpMesh.store, (state) => state.comfyURL);
  const { connectState } = useComfyUtils();
  reactExports.useEffect(() => {
    if (comfyURL) {
      PSUXPInternalStore.setState({
        headerTailElems: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(HeaderTailElem, {}, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
            lineNumber: 113,
            columnNumber: 21
          }, this)
        ]
      });
    } else {
      PSUXPInternalStore.setState({
        headerTailElems: PSUXPInternalStore.getState().headerTailElems.filter((elem) => elem !== elem)
      });
    }
  }, [comfyURL]);
  reactExports.useEffect(() => {
    if (platform2 !== "none" && connectState === "connected" && instanceId) {
      PSUXPInternalStore.setState({
        footerElems: [/* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(FooterElem, {}, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
          lineNumber: 125,
          columnNumber: 31
        }, this)]
      });
    } else {
      PSUXPInternalStore.setState({
        footerElems: PSUXPInternalStore.getState().footerElems.filter((elem) => elem !== elem)
      });
    }
  }, [platform2, lastRunTime]);
  const xiangongApiKey = useStore(AIProviders, (state) => state.xiangong.apiKey);
  const chenyuApiKey = useStore(AIProviders, (state) => state.chenyu.apiKey);
  const lightccApiKey = useStore(AIProviders, (state) => state.lightcc.apiKey);
  const queryClient = new QueryClient();
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(BaseDialog, { className: "w-[40rem] h-[45rem] p-4", show: showConnectDialog, setShow: () => {
    cloudControlStore.setState({
      showConnectDialog: false
    });
  }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(QueryClientProvider, { client: queryClient, children: [
    !xiangongApiKey && !chenyuApiKey && !lightccApiKey && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 rounded-md mb-4", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-lg font-semibold mb-3", style: { color: "var(--uxp-host-text-color)" }, children: "连接指定地址" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
        lineNumber: 146,
        columnNumber: 17
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AddressBar, {}, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
        lineNumber: 149,
        columnNumber: 17
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 145,
      columnNumber: 68
    }, this),
    (connectState !== "connected" || xiangongApiKey || chenyuApiKey || lightccApiKey) && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(CloudControl, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 153,
      columnNumber: 17
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
    lineNumber: 144,
    columnNumber: 9
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
    lineNumber: 139,
    columnNumber: 12
  }, this);
}
function AddressBar() {
  const { connectionError, connectState, doConnect, doDisconnect } = useComfyUtils();
  const comfyWebviewURL = useStore(mcpMesh.store, (state) => state.comfyURL);
  const [inputUrl, setInputUrl] = reactExports.useState(comfyWebviewURL || "");
  const inputDisable = connectState === "connected" || connectState === "connecting" ? { disabled: true } : {};
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center mb-3", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: `w-3 h-3 rounded-full ${connectState === "connected" ? "bg-emerald-300" : connectState === "connecting" ? "bg-yellow-300" : "bg-rose-300"}` }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
        lineNumber: 166,
        columnNumber: 9
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-textfield",
        {
          id: "url-bar",
          label: "backendURL",
          onInput: (ev) => {
            setInputUrl(ev.currentTarget.value);
          },
          ...inputDisable,
          value: inputUrl,
          placeholder: "http://127.0.0.1:8000",
          class: "flex-1 m-2"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
          lineNumber: 171,
          columnNumber: 9
        },
        this
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-action-button",
        {
          id: "connect-btn",
          onClick: () => {
            if (connectState === "disconnected") {
              cloudControlStore.setState({
                currentPlatform: "none",
                instanceId: ""
              });
              doConnect(inputUrl, "");
            } else {
              doDisconnect();
            }
          },
          class: "px-3 py-2 rounded min-w-[2.5rem] flex items-center justify-center",
          children: connectState !== "disconnected" ? "⊗" : "→"
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
          lineNumber: 180,
          columnNumber: 9
        },
        this
      )
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 165,
      columnNumber: 14
    }, this),
    connectionError ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "mt-2", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-label", { class: "text-red-500 text-sm", children: connectionError }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 201,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
      lineNumber: 200,
      columnNumber: 17
    }, this) : ""
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/src/components/ConnectDialog/index.tsx",
    lineNumber: 165,
    columnNumber: 12
  }, this);
}
async function execute() {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ConnectDialog, {}, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/capabilities/cloudcontroller/@uxp/ps-uxp-dialog-provider.tsx",
    lineNumber: 15,
    columnNumber: 5
  }, this);
}
const pluginCount = 1;
const pluginNames = ["@sdppp/cloudcontroller"];
const pluginFiles = ["capabilities/cloudcontroller/@uxp/ps-uxp-dialog-provider.tsx"];
async function executeAllPlugins() {
  console.log(`🎯 执行 ${pluginCount} 个插件:`);
  pluginNames.forEach((name, index2) => {
    console.log(`   ${index2 + 1}. ${name} (${pluginFiles[index2]})`);
  });
  try {
    const results = await Promise.all([
      execute && await execute()
    ]);
    console.log("✅ 所有插件执行完成");
    return results.filter((r2) => r2 !== void 0);
  } catch (error) {
    console.error("❌ 插件执行失败:", error);
    throw error;
  }
}
const checkerboardSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" style="background:#ffffff"><rect x="0" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="0" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="1" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="2" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="3" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="4" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="5" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="6" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="7" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="8" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="9" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="10" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="11" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="12" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="13" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="14" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="15" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="16" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="17" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="18" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="19" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="20" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="21" y="22" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="1" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="3" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="5" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="7" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="9" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="11" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="13" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="15" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="17" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="19" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="21" width="1" height="1" fill="#e5e5e5"/><rect x="22" y="23" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="0" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="2" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="4" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="6" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="8" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="10" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="12" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="14" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="16" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="18" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="20" width="1" height="1" fill="#e5e5e5"/><rect x="23" y="22" width="1" height="1" fill="#e5e5e5"/></svg>`;
const checkerboardDataUrl = `data:image/svg+xml;base64,${btoa(checkerboardSvg)}`;
function ImageCard(props) {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "div",
    {
      onClick: () => {
        var _a3;
        return (_a3 = props.onClick) == null ? void 0 : _a3.call(props, props.imageId);
      },
      className: `${props.className || "flex-1 min-w-0"} border rounded-lg p-2 flex flex-col items-center cursor-pointer hover:bg-[rgba(127,127,127,0.2)] transition-colors ${props.hidden ? "hidden" : ""}`,
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-36 h-36 rounded-lg mb-2 flex items-center justify-center overflow-hidden", style: {
          backgroundImage: `url("${checkerboardDataUrl}")`,
          backgroundColor: "white",
          backgroundSize: "cover"
        }, children: props.thumbnailLoading ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-full h-full flex items-center justify-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { className: "w-12 h-12 animate-spin", fill: "none", viewBox: "0 0 24 24", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
            lineNumber: 28,
            columnNumber: 29
          }, this),
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
            lineNumber: 29,
            columnNumber: 29
          }, this)
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 27,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 26,
          columnNumber: 21
        }, this) : props.thumbnail ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
          "img",
          {
            src: props.thumbnail,
            alt: props.text,
            className: "w-full h-full object-contain"
          },
          void 0,
          false,
          {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
            lineNumber: 33,
            columnNumber: 21
          },
          this
        ) : /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-full h-full flex items-center justify-center", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { className: "w-16 h-16", fill: "currentColor", viewBox: "0 0 20 20", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { fillRule: "evenodd", d: "M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z", clipRule: "evenodd" }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 41,
          columnNumber: 29
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 40,
          columnNumber: 25
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 39,
          columnNumber: 21
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 20,
          columnNumber: 13
        }, this),
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center text-base whitespace-nowrap", style: { color: "var(--uxp-host-text-color)" }, children: props.text }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 46,
          columnNumber: 13
        }, this),
        props.subtext && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-center text-sm whitespace-nowrap", style: { color: "var(--uxp-host-text-color-secondary)" }, children: props.subtext }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
          lineNumber: 49,
          columnNumber: 31
        }, this)
      ]
    },
    void 0,
    true,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/RequestImageCard.tsx",
      lineNumber: 18,
      columnNumber: 9
    },
    this
  );
}
function ImageSizeControl({
  title: title2,
  enabled,
  size,
  onChange
}) {
  const handleEnabledChange = (e4) => {
    console.log("handleEnabledChange", e4.target.checked, size);
    onChange(e4.target.checked, size);
  };
  const handleSizeChange = (e4) => {
    const value = parseInt(e4.target.value);
    if (!isNaN(value) && value > 0) {
      onChange(enabled, value);
    }
  };
  const handleSizeInput = (e4) => {
    var _a3;
    const value = parseInt((_a3 = e4 == null ? void 0 : e4.target) == null ? void 0 : _a3.value);
    if (!isNaN(value) && value > 0) {
      onChange(enabled, value);
    }
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex flex-col items-center space-y-3 mt-2", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center space-x-3", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("label", { className: "flex items-center space-x-2 cursor-pointer", children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "input",
        {
          type: "checkbox",
          checked: enabled,
          onChange: handleEnabledChange,
          className: "w-4 h-4",
          style: {
            accentColor: "var(--uxp-host-link-text-color)"
          }
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
          lineNumber: 41,
          columnNumber: 21
        },
        this
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("span", { style: { color: "var(--uxp-host-text-color)" }, children: title2 }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
        lineNumber: 50,
        columnNumber: 21
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
      lineNumber: 40,
      columnNumber: 17
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "sp-textfield",
      {
        type: "number",
        value: size,
        onChange: handleSizeChange,
        onInput: handleSizeInput,
        className: "w-40 px-2 py-1 text-sm rounded",
        placeholder: sdpppX["settings.imaging.defaultImagesSizeLimit"].toString(),
        style: {
          backgroundColor: "var(--uxp-host-background-color)",
          color: "var(--uxp-host-text-color)",
          borderColor: "var(--uxp-host-border-color)"
        }
      },
      void 0,
      false,
      {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
        lineNumber: 52,
        columnNumber: 17
      },
      this
    )
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
    lineNumber: 39,
    columnNumber: 13
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/ImageSizeControl.tsx",
    lineNumber: 38,
    columnNumber: 9
  }, this);
}
function CropBySelectionControl({
  title: title2,
  value,
  onChange,
  showKeyboardHint = false
}) {
  const handleClick = (value2) => () => {
    console.log("handleClick", value2);
    onChange(value2);
  };
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex flex-col items-center space-y-3 mt-2", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex space-x-4 h-8 items-center", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-sm font-medium flex items-center", style: { color: "var(--uxp-host-text-color)" }, children: [
      title2,
      showKeyboardHint ? "(Z)" : ""
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
      lineNumber: 25,
      columnNumber: 17
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("sp-radio-group", { children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-radio",
        {
          name: "cropBySelection",
          value: "no",
          checked: value === "no",
          onClick: handleClick("no"),
          class: "p-0 mr-2",
          style: {
            accentColor: "var(--uxp-host-link-text-color)",
            color: "var(--uxp-host-text-color)"
          },
          children: t("image.crop.none")
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
          lineNumber: 29,
          columnNumber: 21
        },
        this
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-radio",
        {
          name: "cropBySelection",
          value: "negative",
          checked: value === "negative",
          onClick: handleClick("negative"),
          class: "p-0 mr-2",
          style: {
            accentColor: "var(--uxp-host-link-text-color)"
          },
          children: t("image.crop.inpaint")
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
          lineNumber: 40,
          columnNumber: 21
        },
        this
      ),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
        "sp-radio",
        {
          name: "cropBySelection",
          value: "positive",
          checked: value === "positive",
          onClick: handleClick("positive"),
          class: "p-0 mr-2",
          style: {
            accentColor: "var(--uxp-host-link-text-color)"
          },
          children: t("image.crop.outpaint")
        },
        void 0,
        false,
        {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
          lineNumber: 50,
          columnNumber: 21
        },
        this
      )
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
      lineNumber: 28,
      columnNumber: 17
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
    lineNumber: 24,
    columnNumber: 13
  }, this) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/components/ImageRequest/CropBySelectionControl.tsx",
    lineNumber: 23,
    columnNumber: 9
  }, this);
}
sdpppLogger.extend("GenericImageSelectionDialog");
let thumbnailChain = Promise.resolve();
function GenericImageCard(props) {
  var _a3, _b2, _c2, _d2;
  const [thumbnail, setThumbnail] = reactExports.useState(null);
  const [loading, setLoading] = reactExports.useState(false);
  const prevActiveRef = reactExports.useRef(false);
  const generateThumbnail = reactExports.useCallback(async () => {
    const config = props.option.thumbnailConfig;
    if (!config) return;
    setLoading(true);
    setThumbnail(null);
    thumbnailChain = thumbnailChain.catch(() => {
    }).then(async () => {
      try {
        if (config.reverse) {
        }
        const cropBySelection = config.boundary === "selection" ? config.reverse ? "negative" : "positive" : "no";
        const result = await getImageImpl({
          content: config.content,
          boundary: config.boundary,
          imageSize: 192,
          imageQuality: 1,
          cropBySelection
        });
        const resourceId = result == null ? void 0 : result.resource;
        let thumb = (result == null ? void 0 : result.thumbnail) || null;
        if (!thumb && resourceId) {
          try {
            const thumbRes = await mcpMesh.actions.getThumbnail({ resource: resourceId, maxSize: 192 });
            thumb = (thumbRes == null ? void 0 : thumbRes.thumbnail) ?? thumb;
          } catch (error) {
            console.warn("getThumbnail fallback failed", error);
          }
        }
        setThumbnail(thumb || null);
        if (resourceId) {
          deleteResource(resourceId);
        }
      } catch (error) {
        console.warn("Failed to generate thumbnail for", props.option.id, error);
      } finally {
        setLoading(false);
      }
    });
    await thumbnailChain;
  }, [props.option]);
  const [hasInitialized, setHasInitialized] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (!hasInitialized && props.active) {
      setHasInitialized(true);
      generateThumbnail();
    }
  }, [props.active, hasInitialized, generateThumbnail, props.option.id]);
  reactExports.useEffect(() => {
    const currentActive = props.active;
    if (!prevActiveRef.current && currentActive || currentActive && !thumbnail && !loading) {
      generateThumbnail();
    }
    prevActiveRef.current = currentActive;
  }, [props.active, generateThumbnail, thumbnail, loading]);
  const hasSelection = ((_b2 = (_a3 = photoshop.app.activeDocument) == null ? void 0 : _a3.selection) == null ? void 0 : _b2.bounds) !== null;
  const hasActiveLayers = ((_d2 = (_c2 = photoshop.app.activeDocument) == null ? void 0 : _c2.activeLayers) == null ? void 0 : _d2.length) > 0;
  const hidden = props.option.visibility && (props.option.visibility.requiresSelection && !hasSelection || props.option.visibility.requiresActiveLayers && !hasActiveLayers);
  const displayText = props.option.text + (props.option.keyboardShortcut && props.contentWebviewFocusing ? `(${props.option.keyboardShortcut})` : "");
  if (props.option.variant === "wide") {
    if (hidden) {
      return null;
    }
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        onClick: () => props.onClick(props.option.id),
        className: "w-[36rem] max-w-full border rounded-lg p-5 flex flex-col items-center justify-center cursor-pointer hover:bg-[rgba(127,127,127,0.2)] transition-colors",
        style: { color: "var(--uxp-host-text-color)" },
        children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-lg font-medium text-center", children: displayText }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
            lineNumber: 178,
            columnNumber: 17
          }, this),
          props.option.subtext && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-sm mt-1 text-center", style: { color: "var(--uxp-host-text-color-secondary)" }, children: props.option.subtext }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
            lineNumber: 180,
            columnNumber: 21
          }, this)
        ]
      },
      void 0,
      true,
      {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
        lineNumber: 173,
        columnNumber: 13
      },
      this
    );
  }
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    ImageCard,
    {
      text: displayText,
      subtext: props.option.subtext,
      hidden,
      onClick: () => props.onClick(props.option.id),
      imageId: props.option.id,
      thumbnail,
      thumbnailLoading: loading
    },
    void 0,
    false,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
      lineNumber: 189,
      columnNumber: 9
    },
    this
  );
}
function GenericImageSelectionDialog({ config }) {
  const genericDialogState = useStore(DialogManagerStore, (state) => state.genericDialog);
  const isGenericDialog = genericDialogState.active && genericDialogState.config === config;
  const contentWebviewFocusing = useStore(mcpMesh.store, (state) => state.sdkWebviewFocusing);
  const active = useStore(
    DialogManagerStore,
    isGenericDialog ? (state) => state.genericDialog.active : config.storeConfig.activeSelector
  );
  const resolve2 = useStore(
    DialogManagerStore,
    isGenericDialog ? (state) => state.resolveGenericDialog : config.storeConfig.resolveSelector
  );
  const reject2 = useStore(
    DialogManagerStore,
    isGenericDialog ? (state) => state.rejectGenericDialog : config.storeConfig.rejectSelector
  );
  const storeAdditionalData = config.storeConfig.additionalSelectors && !isGenericDialog ? Object.entries(config.storeConfig.additionalSelectors).reduce((acc, [key2, selector]) => {
    acc[key2] = useStore(DialogManagerStore, selector);
    return acc;
  }, {}) : {};
  const genericAdditionalData = useStore(
    DialogManagerStore,
    (state) => isGenericDialog ? state.genericDialog.additionalData : void 0
  );
  const additionalData = isGenericDialog ? genericAdditionalData || {} : storeAdditionalData;
  const handleOptionClick = reactExports.useCallback(async (optionId) => {
    try {
      const result = await config.onSelect(optionId, additionalData);
      resolve2(result);
    } catch (error) {
      reject2(error);
    }
  }, [config.onSelect, additionalData, resolve2, reject2]);
  const handleOptionClickRef = reactExports.useRef(handleOptionClick);
  handleOptionClickRef.current = handleOptionClick;
  reactExports.useEffect(() => {
    if (!config.keyboardMapping) return;
    DialogManagerStore.setState({
      keyboardHandlers: [
        ...DialogManagerStore.getState().keyboardHandlers,
        (keyCode) => {
          if (!active) return false;
          if (keyCode === "Escape") {
            reject2(new Error("canceled"));
            return true;
          }
          const mappedAction = config.keyboardMapping[keyCode];
          if (mappedAction) {
            if (typeof mappedAction === "function") {
              mappedAction();
            } else {
              handleOptionClickRef.current(mappedAction);
            }
            return true;
          }
          return false;
        }
      ]
    });
  }, [active, config.keyboardMapping, config.dialogType, reject2]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    BaseDialog,
    {
      className: config.className || "w-[40rem] h-[45rem]",
      show: active,
      setShow: () => reject2(new Error("canceled")),
      children: [
        /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "p-4 rounded-lg shadow-lg w-full mx-auto", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex flex-col items-center space-y-6", children: [
          /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h2", { className: "text-xl font-semibold text-center", style: { color: "var(--uxp-host-text-color)" }, children: config.title }, void 0, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
            lineNumber: 290,
            columnNumber: 21
          }, this),
          config.optionRows.map((row, rowIndex) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-center space-x-4", children: row.map((option) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
            GenericImageCard,
            {
              option,
              active,
              additionalData,
              contentWebviewFocusing,
              onClick: handleOptionClick
            },
            option.id,
            false,
            {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
              lineNumber: 298,
              columnNumber: 33
            },
            this
          )) }, rowIndex, false, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
            lineNumber: 296,
            columnNumber: 25
          }, this)),
          config.controls && config.controls.length > 0 && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-center space-x-4", style: { color: "var(--uxp-host-text-color-secondary)" }, children: t("common.options_separator") }, void 0, false, {
              fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
              lineNumber: 313,
              columnNumber: 29
            }, this),
            config.controls.map((control, index2) => {
              var _a3, _b2, _c2;
              if (control.type === "imageSize") {
                const imageSizeValue = additionalData.imageSize || 0;
                const defaultSize = ((_a3 = control.config) == null ? void 0 : _a3.defaultSize) || 512;
                return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  ImageSizeControl,
                  {
                    title: control.title,
                    enabled: imageSizeValue > 0,
                    size: imageSizeValue || defaultSize,
                    onChange: (enabled, size) => {
                      var _a4, _b3;
                      if (isGenericDialog) {
                        DialogManagerStore.setState((prev) => ({
                          ...prev,
                          genericDialog: {
                            ...prev.genericDialog,
                            additionalData: {
                              ...prev.genericDialog.additionalData || {},
                              imageSize: enabled ? size : 0
                            }
                          }
                        }));
                      } else {
                        (_b3 = (_a4 = control.config) == null ? void 0 : _a4.onChange) == null ? void 0 : _b3.call(_a4, enabled, size);
                      }
                    }
                  },
                  index2,
                  false,
                  {
                    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
                    lineNumber: 323,
                    columnNumber: 41
                  },
                  this
                );
              } else if (control.type === "cropBySelection") {
                const cropValue = additionalData.cropBySelection || "no";
                const hasSelection = ((_c2 = (_b2 = photoshop.app.activeDocument) == null ? void 0 : _b2.selection) == null ? void 0 : _c2.bounds) !== null;
                if (!hasSelection) return null;
                return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
                  CropBySelectionControl,
                  {
                    title: control.title,
                    value: cropValue,
                    onChange: (value) => {
                      var _a4, _b3;
                      if (isGenericDialog) {
                        DialogManagerStore.setState((prev) => ({
                          ...prev,
                          genericDialog: {
                            ...prev.genericDialog,
                            additionalData: {
                              ...prev.genericDialog.additionalData || {},
                              cropBySelection: value
                            }
                          }
                        }));
                      } else {
                        (_b3 = (_a4 = control.config) == null ? void 0 : _a4.onChange) == null ? void 0 : _b3.call(_a4, value);
                      }
                    },
                    showKeyboardHint: contentWebviewFocusing
                  },
                  index2,
                  false,
                  {
                    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
                    lineNumber: 355,
                    columnNumber: 41
                  },
                  this
                );
              }
              return null;
            })
          ] }, void 0, true, {
            fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
            lineNumber: 312,
            columnNumber: 25
          }, this)
        ] }, void 0, true, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
          lineNumber: 289,
          columnNumber: 17
        }, this) }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
          lineNumber: 288,
          columnNumber: 13
        }, this),
        !contentWebviewFocusing && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex justify-center", style: { color: "var(--uxp-host-text-color-secondary)" }, children: t("image.shortcut_focus_required") }, void 0, false, {
          fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
          lineNumber: 387,
          columnNumber: 17
        }, this)
      ]
    },
    void 0,
    true,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Dialogs/GenericImageSelectionDialog.tsx",
      lineNumber: 283,
      columnNumber: 9
    },
    this
  );
}
function DialogManager() {
  const [pluginDialogs, setPluginDialogs] = reactExports.useState([]);
  const genericDialogConfig = useStore(DialogManagerStore, (state) => state.genericDialog.config);
  reactExports.useEffect(() => {
    {
      executeAllPlugins().then((results) => {
        setPluginDialogs(results);
      });
    }
  }, []);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(jsxDevRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AuthingLoginDialog, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
      lineNumber: 25,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(AboutDialog, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
      lineNumber: 26,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ComfyConnectDialog, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
      lineNumber: 27,
      columnNumber: 9
    }, this),
    genericDialogConfig && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(GenericImageSelectionDialog, { config: genericDialogConfig }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
      lineNumber: 30,
      columnNumber: 13
    }, this),
    pluginDialogs.map((dialog, index2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(React.Fragment, { children: dialog }, index2, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
      lineNumber: 33,
      columnNumber: 13
    }, this))
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/DialogManager.tsx",
    lineNumber: 23,
    columnNumber: 12
  }, this);
}
const log = sdpppLogger.extend("ContentWebviewManager");
function ContentWebviewManager({
  contentWebviewRef
}) {
  const majorVersion = parseInt(uxp.host.version.split(".")[0]);
  reactExports.useEffect(() => {
    if (!contentWebviewRef.current) return;
    const contentWebview = contentWebviewRef.current;
    if (contentWebview) {
      let webviewUrl = "./webview/content.html";
      if (sdpppX.__CWURL__) {
        webviewUrl = sdpppX.__CWURL__;
      }
      if (!sdpppX.__CWURL__ && !isNaN(majorVersion) && majorVersion < 26) {
        webviewUrl = sdpppX.__25URL__ || "https://sdppp.zombee.tech/ps2024/warn.html";
      }
      log("content webviewUrl", webviewUrl);
      contentWebview.setAttribute("src", webviewUrl);
      contentWebview.addEventListener("loadstart", () => {
        onSDKWebviewLoadStart();
      });
      contentWebview.addEventListener("loadstop", () => {
      });
      contentWebview.addEventListener("focus", () => {
        mcpMesh.store.setState({
          sdkWebviewFocusing: true
        });
        PSUXPInternalStore.setState({
          contentWebviewLastFocusTime: Date.now()
        });
      });
      contentWebview.addEventListener("blur", () => {
        mcpMesh.store.setState({
          sdkWebviewFocusing: false
        });
        PSUXPInternalStore.setState({
          contentWebviewLastFocusTime: Date.now()
        });
      });
    }
  }, [contentWebviewRef]);
  return null;
}
function ComfyWebviewManager() {
  const webviewRef = reactExports.useRef(null);
  const webviewURL = useStore(mcpMesh.store, (state) => state.comfyURL);
  const comfyWebviewNeedRefresh = useStore(PSUXPInternalStore, (state) => state.comfyWebviewNeedRefresh);
  const [urlTimestamp, setUrlTimestamp] = reactExports.useState(0);
  reactExports.useEffect(() => {
    if (comfyWebviewNeedRefresh) {
      PSUXPInternalStore.setState({
        comfyWebviewNeedRefresh: false
      });
      setUrlTimestamp(Date.now());
    }
  }, [comfyWebviewNeedRefresh]);
  reactExports.useEffect(() => {
    const webview = webviewRef.current;
    if (!webview) return;
    const handleLoadStop = (e4) => {
      onComfyWebviewLoadStop();
    };
    const handleLoadError = (e4) => {
      const errorMessage = e4.message || e4.type || "Load error occurred";
      mcpMesh.store.setState({
        comfyWebviewLoadError: errorMessage,
        comfyWebviewLoading: false
      });
    };
    const handleLoadStart = () => {
      onComfyWebviewLoadStart();
      mcpMesh.store.setState({
        comfyWebviewVersion: "",
        comfyHTTPCode: 200
      });
    };
    webview.addEventListener("loadstop", handleLoadStop);
    webview.addEventListener("loaderror", handleLoadError);
    webview.addEventListener("loadstart", handleLoadStart);
    return () => {
      webview.removeEventListener("loadstop", handleLoadStop);
      webview.removeEventListener("loaderror", handleLoadError);
      webview.removeEventListener("loadstart", handleLoadStart);
    };
  }, []);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { style: {
    width: "1024px",
    height: "400px",
    ...sdpppX.__WEBVIEW_DEBUG__ ? {} : { position: "absolute" },
    right: "-10000px",
    bottom: "-10000px"
  }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
    "webview",
    {
      ref: webviewRef,
      src: webviewURL ? webviewURL + "?timestamp=" + urlTimestamp : "about:blank",
      style: {
        position: "relative",
        width: "100%",
        height: "100%"
      }
    },
    void 0,
    false,
    {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/ComfyWebviewManager.tsx",
      lineNumber: 68,
      columnNumber: 13
    },
    this
  ) }, void 0, false, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/ComfyWebviewManager.tsx",
    lineNumber: 61,
    columnNumber: 9
  }, this);
}
function SDPPPProvider({ children, contentWebviewRef }) {
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(SDPPPContext.Provider, { value: {
    dialogs: []
  }, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(DialogManager, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/provider.tsx",
      lineNumber: 14,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ContentWebviewManager, { contentWebviewRef }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/provider.tsx",
      lineNumber: 15,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(ComfyWebviewManager, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/provider.tsx",
      lineNumber: 16,
      columnNumber: 9
    }, this),
    children
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/providers/provider.tsx",
    lineNumber: 11,
    columnNumber: 12
  }, this);
}
const SDPPPContext = reactExports.createContext({
  dialogs: []
});
class UserIcon extends React.Component {
  render() {
    const size = this.props.size || 1;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { slot: "icon", className: "sdppp-icon", onClick: this.props.onClick, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { width: 20 * size, height: 20 * size, viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M14 7A7 7 0 110 7a7 7 0 0114 0zM2.671 11.155c.696-1.006 2.602-1.816 3.194-1.91.226-.036.232-.658.232-.658s-.665-.658-.81-1.544c-.39 0-.63-.94-.241-1.272a2.578 2.578 0 00-.012-.13c-.066-.607-.28-2.606 1.965-2.606 2.246 0 2.031 2 1.966 2.606l-.012.13c.39.331.149 1.272-.24 1.272-.146.886-.81 1.544-.81 1.544s.004.622.23.658c.593.094 2.5.904 3.195 1.91a6 6 0 10-8.657 0z", fill: "currentColor" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/UserIcon.tsx",
      lineNumber: 16,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/UserIcon.tsx",
      lineNumber: 15,
      columnNumber: 17
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/UserIcon.tsx",
      lineNumber: 10,
      columnNumber: 13
    }, this);
  }
}
class RefreshIcon extends React.Component {
  render() {
    const size = this.props.size || 1;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { slot: "icon", className: "sdppp-icon", onClick: this.props.onClick, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { width: 20 * size, height: 20 * size, viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { fill: "currentColor", d: "M7.092.5H7a6.5 6.5 0 106.41 7.583.5.5 0 10-.986-.166A5.495 5.495 0 017 12.5a5.5 5.5 0 010-11h.006a5.5 5.5 0 014.894 3H10a.5.5 0 000 1h3a.5.5 0 00.5-.5V2a.5.5 0 00-1 0v1.535A6.495 6.495 0 007.092.5z" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/RefreshIcon.tsx",
      lineNumber: 12,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/RefreshIcon.tsx",
      lineNumber: 11,
      columnNumber: 17
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/RefreshIcon.tsx",
      lineNumber: 10,
      columnNumber: 13
    }, this);
  }
}
class BackIcon extends React.Component {
  render() {
    const size = this.props.size || 1;
    return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { slot: "icon", className: "sdppp-icon", onClick: this.props.onClick, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("svg", { width: 20 * size, height: 20 * size, xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("path", { fill: "currentColor", fillRule: "evenodd", clipRule: "evenodd", d: "M9.53 2.47a.75.75 0 0 1 0 1.06L4.81 8.25H15a6.75 6.75 0 0 1 0 13.5h-3a.75.75 0 0 1 0-1.5h3a5.25 5.25 0 1 0 0-10.5H4.81l4.72 4.72a.75.75 0 1 1-1.06 1.06l-6-6a.75.75 0 0 1 0-1.06l6-6a.75.75 0 0 1 1.06 0Z" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/Back.tsx",
      lineNumber: 12,
      columnNumber: 21
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/Back.tsx",
      lineNumber: 11,
      columnNumber: 17
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Icons/Back.tsx",
      lineNumber: 10,
      columnNumber: 13
    }, this);
  }
}
function Header() {
  const headerTitle = useStore(PSUXPInternalStore, (state) => state.headerTitle);
  const headerTailElems = useStore(PSUXPInternalStore, (state) => state.headerTailElems);
  const agentConfigDialogRef = reactExports.useRef(null);
  const theme = useStore(mcpMesh.store, (state) => state.theme);
  const sdkNode2 = mcpMesh.getNode("sdk");
  const backwardable = useStore(sdkNode2.store, (state) => state.backwardable);
  const refreshable = useStore(sdkNode2.store, (state) => state.refreshable);
  const loginable = useStore(sdkNode2.store, (state) => state.loginable);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center px-1 h-[35px]", children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center cursor-pointer", onClick: () => {
      AboutDialogStore.setState({ show: true });
    }, children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("img", { width: 55, src: theme == "kPanelBrightnessDarkGray" || theme == "kPanelBrightnessMediumGray" ? "./icons/sdppp_D@2x.png" : "./icons/sdppp_L@2x.png", alt: "logo", className: "w-8 h-8" }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 26,
        columnNumber: 13
      }, this),
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("h1", { className: "text-sm font-bold m-0 ml-1 text-[var(--uxp-host-text-color)]", children: headerTitle }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 30,
        columnNumber: 13
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
      lineNumber: 23,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex-1 text-[var(--uxp-host-text-color)] h-full flex flex-row text-xs rounded relative pb-0.5 justify-end", onClick: () => {
      var _a3;
      (_a3 = agentConfigDialogRef.current) == null ? void 0 : _a3.show();
    }, children: [
      /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex flex-row align-center", children: headerTailElems.map((elem, index2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center justify-center", children: elem }, index2, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 40,
        columnNumber: 21
      }, this)) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 38,
        columnNumber: 13
      }, this),
      backwardable && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-5 mr-1 h-full flex items-center justify-center cursor-pointer", onClick: () => {
        sdkNode2.actions.backward({});
      }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(BackIcon, { size: 0.8 }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 48,
        columnNumber: 17
      }, this) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 45,
        columnNumber: 30
      }, this),
      refreshable && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-5 mr-1 h-full flex items-center justify-center cursor-pointer", onClick: () => {
        sdkNode2.actions.refresh({});
      }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(RefreshIcon, { size: 0.8 }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 53,
        columnNumber: 17
      }, this) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 50,
        columnNumber: 29
      }, this),
      loginable && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "w-5 h-full flex items-center justify-center cursor-pointer", onClick: () => {
        mcpMesh.store.setState({
          requestingLogin: true
        });
      }, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(UserIcon, { size: 0.8 }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 60,
        columnNumber: 17
      }, this) }, void 0, false, {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
        lineNumber: 55,
        columnNumber: 27
      }, this)
    ] }, void 0, true, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
      lineNumber: 35,
      columnNumber: 9
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Header/index.tsx",
    lineNumber: 21,
    columnNumber: 12
  }, this);
}
const sdkNode = mcpMesh.getNode("sdk");
const uxpNode = mcpMesh;
function compareVersions(version1, version2) {
  const [v1Base, v1Pre] = version1.split("-");
  const [v2Base, v2Pre] = version2.split("-");
  const v1Parts = v1Base.split(".").map(Number);
  const v2Parts = v2Base.split(".").map(Number);
  const maxLength = Math.max(v1Parts.length, v2Parts.length);
  for (let i2 = 0; i2 < maxLength; i2++) {
    const v1Part = v1Parts[i2] || 0;
    const v2Part = v2Parts[i2] || 0;
    if (v1Part > v2Part) return 1;
    if (v1Part < v2Part) return -1;
  }
  if (v1Pre && v2Pre) {
    return v1Pre.localeCompare(v2Pre);
  } else if (v1Pre && !v2Pre) {
    return -1;
  } else if (!v1Pre && v2Pre) {
    return 1;
  }
  return 0;
}
function Footer() {
  const footerElems = useStore(PSUXPInternalStore, (state) => state.footerElems);
  const banners = useStore(sdkNode.store, (state) => state.bannerData);
  const locale = useStore(uxpNode.store, (state) => state.locale);
  const tenantId = useStore(uxpNode.store, (state) => {
    var _a3;
    return (_a3 = state.sdpppX) == null ? void 0 : _a3.tenantid;
  });
  const [currentBannerIndex, setCurrentBannerIndex] = reactExports.useState(0);
  const footerBanners = Array.isArray(banners) ? banners.filter((banner) => {
    if (banner.type !== "footer") return false;
    if (!banner.rule) return true;
    const ruleParts = banner.rule.split(",");
    let ruleVersion = "";
    let ruleLocale = null;
    for (const part of ruleParts) {
      const [key2, value] = part.split(":");
      if (key2 === "version") ruleVersion = value;
      if (key2 === "locale") ruleLocale = value;
    }
    if (ruleVersion) {
      if (tenantId) {
        return false;
      }
      const currentVersion = PSUXPInternalStore.getState().manifestVersion;
      if (currentVersion && compareVersions(currentVersion, ruleVersion) >= 0) {
        return false;
      }
    }
    if (ruleLocale && ruleLocale !== locale) {
      return false;
    }
    return true;
  }) : [];
  reactExports.useEffect(() => {
    if (footerBanners.length <= 0) return;
    const interval = setInterval(() => {
      setCurrentBannerIndex((prev) => (prev + 1) % footerBanners.length);
    }, 3e3);
    return () => clearInterval(interval);
  }, [footerBanners.length]);
  const handleBannerClick = async (link) => {
    if (link) {
      await uxpNode.actions.openExternalLink({ url: link });
    }
  };
  const currentBanner = footerBanners[currentBannerIndex];
  const hasCustomFooter = Array.isArray(footerElems) && footerElems.length > 0;
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "flex items-center justify-end gap-2 mx-2 h-[16px]", children: [
    hasCustomFooter && footerElems.map((elem, index2) => /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "text-xs", style: { color: "var(--uxp-host-text-color-secondary)" }, children: elem }, index2, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Footer/index.tsx",
      lineNumber: 112,
      columnNumber: 17
    }, this)),
    !hasCustomFooter && currentBanner && /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(
      "div",
      {
        className: "underline cursor-pointer text-xs",
        style: {
          color: "var(--uxp-host-text-color-secondary)"
        },
        onClick: () => handleBannerClick(currentBanner.link),
        children: currentBanner.name_chn
      },
      void 0,
      false,
      {
        fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Footer/index.tsx",
        lineNumber: 117,
        columnNumber: 17
      },
      this
    )
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/components/Footer/index.tsx",
    lineNumber: 110,
    columnNumber: 9
  }, this);
}
function Main() {
  const contentWebviewRef = reactExports.useRef(null);
  const loaded = useStore(mcpMesh.store, (state) => state.sdkWebviewConnectStatus === "connected");
  const [loadedAfter1s, setLoadedAfter1s] = reactExports.useState(false);
  const [contentWebviewIdleFor5Minutes, setContentWebviewIdleFor5Minutes] = reactExports.useState(false);
  const uxpPanelLastMouseOverTime = useStore(PSUXPInternalStore, (state) => state.uxpPanelLastMouseOverTime);
  const contentWebviewLastFocusTime = useStore(PSUXPInternalStore, (state) => state.contentWebviewLastFocusTime);
  reactExports.useEffect(() => {
    const timer = setTimeout(() => {
      setLoadedAfter1s(true);
    }, 1e3);
    const interval = setInterval(() => {
      const lastFocusTime = PSUXPInternalStore.getState().contentWebviewLastFocusTime;
      const lastMouseOverTime = PSUXPInternalStore.getState().uxpPanelLastMouseOverTime;
      const sdkWebviewFocusing = mcpMesh.store.getState().sdkWebviewFocusing;
      const timeout = 5 * 1e3 * 60;
      const lastActiveTime = Math.max(lastFocusTime, lastMouseOverTime);
      if (!sdkWebviewFocusing && lastActiveTime > 0 && Date.now() - lastActiveTime > timeout) {
        sdpppLogger.log("contentWebviewIdleFor5Minutes", lastFocusTime, lastMouseOverTime, Date.now() - lastActiveTime, timeout);
        setContentWebviewIdleFor5Minutes(true);
      }
    }, 5e3);
    return () => {
      clearTimeout(timer);
      clearInterval(interval);
    };
  }, [loaded]);
  reactExports.useEffect(() => {
    setContentWebviewIdleFor5Minutes(false);
  }, [uxpPanelLastMouseOverTime, contentWebviewLastFocusTime]);
  return /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("div", { className: "h-full w-full flex flex-col", onMouseOver: () => {
    PSUXPInternalStore.setState({
      uxpPanelLastMouseOverTime: Date.now()
    });
  }, children: [
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(SDPPPProvider, { contentWebviewRef, children: /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Header, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
      lineNumber: 49,
      columnNumber: 13
    }, this) }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
      lineNumber: 48,
      columnNumber: 9
    }, this),
    !loadedAfter1s || contentWebviewIdleFor5Minutes ? /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(About, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
      lineNumber: 51,
      columnNumber: 62
    }, this) : null,
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV("webview", { className: "w-full flex-1", ref: contentWebviewRef, id: "content_webview" }, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
      lineNumber: 52,
      columnNumber: 9
    }, this),
    /* @__PURE__ */ jsxDevRuntimeExports.jsxDEV(Footer, {}, void 0, false, {
      fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
      lineNumber: 53,
      columnNumber: 9
    }, this)
  ] }, void 0, true, {
    fileName: "/apdcephfs/woafs/_GITHUB_/sdppp-sixi/internals/ps-uxp/src/tsx/Main.tsx",
    lineNumber: 43,
    columnNumber: 12
  }, this);
}
sdpppX.__start__ = async (root) => {
  await initPlugins();
  await init$1();
  clientExports.createRoot(root).render(reactExports.createElement(Main));
};
})(window);